@@ -19,6 +19,8 @@ export async function createCompany(values: z.infer<typeof createCompanySchema>)
1919 if ( ! session ?. id ) {
2020 return { error : "Vous devez être connecté pour créer une entreprise." } ;
2121 }
22+
23+ const creationCost = 1000 ;
2224
2325 const validatedFields = createCompanySchema . safeParse ( values ) ;
2426 if ( ! validatedFields . success ) {
@@ -27,13 +29,26 @@ export async function createCompany(values: z.infer<typeof createCompanySchema>)
2729 const { name, industry, description } = validatedFields . data ;
2830
2931 try {
30- await db . transaction ( async ( tx ) => {
31- // Create the company
32+ const result = await db . transaction ( async ( tx ) => {
33+ const user = await tx . query . users . findFirst ( { where : eq ( users . id , session . id ) , columns : { cash : true } } ) ;
34+ if ( ! user ) throw new Error ( "Utilisateur non trouvé." ) ;
35+
36+ const userCash = parseFloat ( user . cash ) ;
37+ if ( userCash < creationCost ) throw new Error ( `Fonds insuffisants. La création d'une entreprise coûte ${ creationCost . toLocaleString ( ) } $.` ) ;
38+
39+ // Deduct cost from user
40+ const newUserCash = userCash - creationCost ;
41+ await tx . update ( users ) . set ( { cash : newUserCash . toFixed ( 2 ) } ) . where ( eq ( users . id , session . id ) ) ;
42+
43+ // Create the company with initial treasury
3244 const [ newCompany ] = await tx . insert ( companies ) . values ( {
3345 name,
3446 industry,
3547 description,
3648 creatorId : session . id ,
49+ cash : creationCost . toFixed ( 2 ) ,
50+ totalShares : '10000.00000000' ,
51+ sharePrice : '0.10'
3752 } ) . returning ( ) ;
3853
3954 // Add the creator as the CEO
@@ -42,17 +57,20 @@ export async function createCompany(values: z.infer<typeof createCompanySchema>)
4257 userId : session . id ,
4358 role : 'ceo' ,
4459 } ) ;
60+
61+ return { success : `L'entreprise "${ name } " a été créée avec succès ! ${ creationCost . toLocaleString ( ) } $ ont été transférés à la trésorerie.` } ;
4562 } ) ;
4663
4764 revalidatePath ( '/companies' ) ;
48- return { success : `L'entreprise "${ name } " a été créée avec succès !` } ;
65+ revalidatePath ( '/portfolio' ) ;
66+ return result ;
4967 } catch ( error : any ) {
5068 // Check for unique constraint violation
5169 if ( error ?. code === '23505' ) {
5270 return { error : "Une entreprise avec ce nom existe déjà." } ;
5371 }
5472 console . error ( "Error creating company:" , error ) ;
55- return { error : "Une erreur est survenue lors de la création de l'entreprise." } ;
73+ return { error : error . message || "Une erreur est survenue lors de la création de l'entreprise." } ;
5674 }
5775}
5876
@@ -128,7 +146,7 @@ export async function getCompanyById(companyId: number) {
128146 const companyCash = parseFloat ( company . cash ) ;
129147 const companyValue = companyCash + portfolioValue ;
130148 const totalShares = parseFloat ( company . totalShares ) ;
131- const sharePrice = totalShares > 0 ? companyValue / totalShares : 0 ;
149+ const sharePrice = totalShares > 0 ? companyValue / totalShares : parseFloat ( company . sharePrice ) ;
132150
133151 return {
134152 ...company ,
@@ -165,33 +183,17 @@ export async function investInCompany(companyId: number, amount: number): Promis
165183 if ( ! user ) throw new Error ( "Utilisateur non trouvé." ) ;
166184 if ( parseFloat ( user . cash ) < amount ) throw new Error ( "Fonds insuffisants." ) ;
167185
168- const company = await tx . query . companies . findFirst ( {
169- where : eq ( companies . id , companyId ) ,
170- with : { holdings : true }
171- } ) ;
172- if ( ! company ) throw new Error ( "Entreprise non trouvée." ) ;
173-
174- const allAssets = await tx . query . assets . findMany ( ) ;
175- const priceMap = allAssets . reduce ( ( map , asset ) => {
176- map [ asset . ticker ] = parseFloat ( asset . price ) ;
177- return map ;
178- } , { } as Record < string , number > ) ;
179-
180- const portfolioValue = company . holdings . reduce ( ( sum , holding ) => {
181- const currentPrice = priceMap [ holding . ticker ] || parseFloat ( holding . avgCost ) ;
182- return sum + ( parseFloat ( holding . quantity ) * currentPrice ) ;
183- } , 0 ) ;
184-
185- const companyValue = parseFloat ( company . cash ) + portfolioValue ;
186- const totalShares = parseFloat ( company . totalShares ) ;
187- const preInvestmentSharePrice = totalShares > 0 ? companyValue / totalShares : parseFloat ( company . sharePrice ) ;
186+ const companyData = await getCompanyById ( companyId ) ;
187+ if ( ! companyData ) throw new Error ( "Entreprise non trouvée." ) ;
188+
189+ const preInvestmentSharePrice = companyData . sharePrice ;
188190
189191 if ( amount <= 0 ) throw new Error ( "Le montant de l'investissement doit être positif." ) ;
190192 if ( preInvestmentSharePrice <= 0 ) throw new Error ( "Le prix de l'action est nul, l'investissement est impossible." ) ;
191193
192194 const sharesToBuy = amount / preInvestmentSharePrice ;
193- const newCompanyCash = parseFloat ( company . cash ) + amount ;
194- const newTotalShares = totalShares + sharesToBuy ;
195+ const newCompanyCash = companyData . cash + amount ;
196+ const newTotalShares = companyData . totalShares + sharesToBuy ;
195197
196198 await tx . update ( users ) . set ( { cash : ( parseFloat ( user . cash ) - amount ) . toFixed ( 2 ) } ) . where ( eq ( users . id , session . id ) ) ;
197199 await tx . update ( companies ) . set ( {
@@ -216,7 +218,7 @@ export async function investInCompany(companyId: number, amount: number): Promis
216218 } ) ;
217219 }
218220
219- return { success : `Vous avez investi ${ amount . toFixed ( 2 ) } $ dans ${ company . name } !` } ;
221+ return { success : `Vous avez investi ${ amount . toFixed ( 2 ) } $ dans ${ companyData . name } !` } ;
220222 } ) ;
221223
222224 revalidatePath ( `/companies/${ companyId } ` ) ;
@@ -343,3 +345,37 @@ export async function sellAssetForCompany(companyId: number, holdingId: number,
343345 return { error : error . message || "Une erreur est survenue lors de la vente." } ;
344346 }
345347}
348+
349+
350+ export async function addCashToCompany ( companyId : number , amount : number ) : Promise < { success ?: string ; error ?: string } > {
351+ const session = await getSession ( ) ;
352+ if ( ! session ?. id ) return { error : "Vous devez être connecté." } ;
353+ if ( amount <= 0 ) return { error : "Le montant doit être positif." } ;
354+
355+ try {
356+ const result = await db . transaction ( async ( tx ) => {
357+ const member = await tx . query . companyMembers . findFirst ( { where : and ( eq ( companyMembers . companyId , companyId ) , eq ( companyMembers . userId , session . id ) ) } ) ;
358+ if ( ! member || member . role !== 'ceo' ) throw new Error ( "Seul le PDG peut ajouter des fonds à la trésorerie." ) ;
359+
360+ const user = await tx . query . users . findFirst ( { where : eq ( users . id , session . id ) , columns : { cash : true } } ) ;
361+ if ( ! user ) throw new Error ( "Utilisateur non trouvé." ) ;
362+ if ( parseFloat ( user . cash ) < amount ) throw new Error ( "Fonds personnels insuffisants." ) ;
363+
364+ const company = await tx . query . companies . findFirst ( { where : eq ( companies . id , companyId ) , columns : { cash : true } } ) ;
365+ if ( ! company ) throw new Error ( "Entreprise non trouvée." ) ;
366+
367+ await tx . update ( users ) . set ( { cash : ( parseFloat ( user . cash ) - amount ) . toFixed ( 2 ) } ) . where ( eq ( users . id , session . id ) ) ;
368+ await tx . update ( companies ) . set ( { cash : ( parseFloat ( company . cash ) + amount ) . toFixed ( 2 ) } ) . where ( eq ( companies . id , companyId ) ) ;
369+
370+ return { success : `${ amount . toFixed ( 2 ) } $ ajoutés à la trésorerie de l'entreprise.` } ;
371+ } ) ;
372+
373+ revalidatePath ( `/companies/${ companyId } ` ) ;
374+ revalidatePath ( '/portfolio' ) ;
375+ revalidatePath ( '/profile' ) ;
376+ return result ;
377+
378+ } catch ( error : any ) {
379+ return { error : error . message || "Une erreur est survenue." } ;
380+ }
381+ }
0 commit comments