@@ -14,6 +14,7 @@ export type NewSale = Omit<
1414 "id" | "payments" | "created_at" | "updatedAt" | "clientName" | "totalAmount"
1515> & {
1616 totalAmount ?: number ;
17+ createdAt ?: string ;
1718} ;
1819
1920/**
@@ -23,6 +24,41 @@ export async function createSaleAction(sale: NewSale) {
2324 try {
2425 const supabase = getSupabaseAdmin ( ) ;
2526
27+ // Fetch appointment start time if linked
28+ let inheritedCreatedAt = sale . createdAt || new Date ( ) . toISOString ( ) ;
29+ if ( sale . appointmentId ) {
30+ try {
31+ const appointmentId = parseInt ( sale . appointmentId , 10 ) ;
32+ if ( isNaN ( appointmentId ) ) {
33+ console . warn (
34+ `Invalid appointmentId provided to createSaleAction: ${ sale . appointmentId } `
35+ ) ;
36+ } else {
37+ const { data : appt , error : apptErr } = await supabase
38+ . from ( "appointments" )
39+ . select ( "start_time" )
40+ . eq ( "id" , appointmentId )
41+ . single ( ) ;
42+
43+ if ( apptErr ) {
44+ console . warn (
45+ `Failed to fetch appointment ${ appointmentId } : ${ apptErr . message } `
46+ ) ;
47+ } else if ( appt ?. start_time ) {
48+ inheritedCreatedAt = appt . start_time ;
49+ console . log (
50+ `Sale linked to appointment ${ appointmentId } : using start_time ${ appt . start_time } `
51+ ) ;
52+ }
53+ }
54+ } catch ( appointmentFetchError ) {
55+ console . error (
56+ "Error fetching appointment for sale creation:" ,
57+ appointmentFetchError
58+ ) ;
59+ }
60+ }
61+
2662 // Get default commission
2763 const { data : settingData } = await supabase
2864 . from ( "app_settings" )
@@ -48,6 +84,7 @@ export async function createSaleAction(sale: NewSale) {
4884 total_amount : computedTotal ,
4985 status : sale . status || "pending" ,
5086 notes : sale . notes || null ,
87+ created_at : inheritedCreatedAt ,
5188 } ,
5289 ] )
5390 . select ( "*" )
0 commit comments