|
@@ -204,6 +204,56 @@ serve(async (req) => {
|
|
|
|
|
|
|
|
console.log('Call log stored successfully:', data.id)
|
|
console.log('Call log stored successfully:', data.id)
|
|
|
|
|
|
|
|
|
|
+ // Update subscription usage if call had duration
|
|
|
|
|
+ if (message.durationSeconds && message.durationSeconds > 0) {
|
|
|
|
|
+ const minutesConsumed = message.durationSeconds / 60
|
|
|
|
|
+ console.log(`Updating subscription usage: ${minutesConsumed.toFixed(2)} minutes for store ${storeId}`)
|
|
|
|
|
+
|
|
|
|
|
+ // Get current subscription
|
|
|
|
|
+ const { data: subscription, error: subError } = await supabase
|
|
|
|
|
+ .from('store_subscriptions')
|
|
|
|
|
+ .select('id, minutes_used, minutes_included, status')
|
|
|
|
|
+ .eq('store_id', storeId)
|
|
|
|
|
+ .single()
|
|
|
|
|
+
|
|
|
|
|
+ if (subError || !subscription) {
|
|
|
|
|
+ console.error('No subscription found for store:', storeId, subError)
|
|
|
|
|
+ } else if (subscription.status === 'cancelled' || subscription.status === 'expired') {
|
|
|
|
|
+ console.log('Subscription is not active, skipping usage update:', subscription.status)
|
|
|
|
|
+ } else {
|
|
|
|
|
+ // Update minutes_used in store_subscriptions
|
|
|
|
|
+ const { error: updateError } = await supabase
|
|
|
|
|
+ .from('store_subscriptions')
|
|
|
|
|
+ .update({
|
|
|
|
|
+ minutes_used: (subscription.minutes_used || 0) + minutesConsumed
|
|
|
|
|
+ })
|
|
|
|
|
+ .eq('id', subscription.id)
|
|
|
|
|
+
|
|
|
|
|
+ if (updateError) {
|
|
|
|
|
+ console.error('Error updating subscription usage:', updateError)
|
|
|
|
|
+ } else {
|
|
|
|
|
+ console.log(`Subscription usage updated: ${(subscription.minutes_used || 0) + minutesConsumed} total minutes used`)
|
|
|
|
|
+
|
|
|
|
|
+ // Log usage in subscription_usage_log
|
|
|
|
|
+ const { error: logError } = await supabase
|
|
|
|
|
+ .from('subscription_usage_log')
|
|
|
|
|
+ .insert({
|
|
|
|
|
+ subscription_id: subscription.id,
|
|
|
|
|
+ store_id: storeId,
|
|
|
|
|
+ call_log_id: data.id,
|
|
|
|
|
+ minutes_consumed: minutesConsumed,
|
|
|
|
|
+ source_type: 'included' // For now, all usage comes from included minutes
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ if (logError) {
|
|
|
|
|
+ console.error('Error logging subscription usage:', logError)
|
|
|
|
|
+ } else {
|
|
|
|
|
+ console.log('Subscription usage logged successfully')
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
// Trigger analytics processing (non-blocking)
|
|
// Trigger analytics processing (non-blocking)
|
|
|
const analyticsApiKey = Deno.env.get('ANALYTICS_INTERNAL_API_KEY')
|
|
const analyticsApiKey = Deno.env.get('ANALYTICS_INTERNAL_API_KEY')
|
|
|
if (analyticsApiKey && message.transcript) {
|
|
if (analyticsApiKey && message.transcript) {
|