@@ -18,16 +18,70 @@ export async function updateWorkflowRunCounts(workflowId: string, runs: number =
1818 throw new Error ( `Workflow ${ workflowId } not found` )
1919 }
2020
21- const response = await fetch ( `/api/workflows/${ workflowId } /stats?runs=${ runs } ` , {
22- method : 'POST' ,
23- } )
21+ // Get the origin from the environment or use direct DB update as fallback
22+ const origin =
23+ process . env . NEXT_PUBLIC_APP_URL ||
24+ ( typeof window !== 'undefined' ? window . location . origin : '' )
2425
25- if ( ! response . ok ) {
26- const error = await response . json ( )
27- throw new Error ( error . error || 'Failed to update workflow stats' )
28- }
26+ if ( origin ) {
27+ // Use absolute URL with origin
28+ const response = await fetch ( `${ origin } /api/workflows/${ workflowId } /stats?runs=${ runs } ` , {
29+ method : 'POST' ,
30+ } )
31+
32+ if ( ! response . ok ) {
33+ const error = await response . json ( )
34+ throw new Error ( error . error || 'Failed to update workflow stats' )
35+ }
36+
37+ return response . json ( )
38+ } else {
39+ logger . warn ( `No origin available, updating workflow stats directly via DB` )
40+
41+ // Update workflow directly through database
42+ await db
43+ . update ( workflowTable )
44+ . set ( {
45+ runCount : workflow . runCount + runs ,
46+ lastRunAt : new Date ( ) ,
47+ } )
48+ . where ( eq ( workflowTable . id , workflowId ) )
2949
30- return response . json ( )
50+ // Update user stats if needed
51+ if ( workflow . userId ) {
52+ const userStatsRecord = await db
53+ . select ( )
54+ . from ( userStats )
55+ . where ( eq ( userStats . userId , workflow . userId ) )
56+ . limit ( 1 )
57+
58+ if ( userStatsRecord . length === 0 ) {
59+ // Create new record
60+ await db . insert ( userStats ) . values ( {
61+ id : crypto . randomUUID ( ) ,
62+ userId : workflow . userId ,
63+ totalManualExecutions : runs ,
64+ totalApiCalls : 0 ,
65+ totalWebhookTriggers : 0 ,
66+ totalScheduledExecutions : 0 ,
67+ totalTokensUsed : 0 ,
68+ totalCost : '0.00' ,
69+ lastActive : new Date ( ) ,
70+ } )
71+ } else {
72+ // Update existing record
73+ await db
74+ . update ( userStats )
75+ . set ( {
76+ totalManualExecutions : userStatsRecord [ 0 ] . totalManualExecutions + runs ,
77+ lastActive : new Date ( ) ,
78+ } )
79+ . where ( eq ( userStats . userId , workflow . userId ) )
80+ }
81+ }
82+
83+ return { success : true , runsAdded : runs }
84+ }
3185 } catch ( error ) {
3286 logger . error ( `Error updating workflow run counts:` , error )
3387 throw error
0 commit comments