Skip to content

Commit aad4fa7

Browse files
I see this error with the app, reported by NextJS, please fix it. The er
1 parent 2573318 commit aad4fa7

File tree

3 files changed

+81
-9
lines changed

3 files changed

+81
-9
lines changed

src/components/companies-client-page.tsx

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ function CompanyTableRow({ company, type }: { company: any, type: 'managed' | 'i
1515
return (
1616
<TableRow>
1717
<TableCell>
18-
<div className="font-medium">{company.name}</div>
18+
<div className="font-medium">{company.name} ({company.ticker})</div>
1919
<div className="text-sm text-muted-foreground">{company.industry}</div>
2020
</TableCell>
2121
{type === 'managed' && (
@@ -40,16 +40,22 @@ function CompanyTableRow({ company, type }: { company: any, type: 'managed' | 'i
4040
<Link href={`/companies/${company.id}`}>Détails</Link>
4141
</Button>
4242
{type === 'invested' && (
43-
<SellSharesDialog
43+
company.isListed ? (
44+
<Button asChild variant="secondary" size="sm">
45+
<Link href={`/trading/${company.ticker}`}>Trader</Link>
46+
</Button>
47+
) : (
48+
<SellSharesDialog
4449
companyId={company.id}
4550
companyName={company.name}
4651
sharePrice={company.sharePrice}
4752
sharesHeld={company.sharesHeld}
48-
>
49-
<Button size="sm" variant="destructive">Vendre</Button>
50-
</SellSharesDialog>
53+
>
54+
<Button size="sm" variant="destructive">Vendre</Button>
55+
</SellSharesDialog>
56+
)
5157
)}
52-
{type !== 'managed' && (
58+
{type !== 'managed' && !company.isListed && (
5359
<InvestDialog company={company as CompanyWithDetails}>
5460
<Button size="sm">Investir</Button>
5561
</InvestDialog>

src/lib/actions/companies.ts

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,10 @@ export async function createCompany(values: z.infer<typeof createCompanySchema>)
7171
revalidatePath('/');
7272
return result;
7373
} catch (error: any) {
74+
console.error("Error creating company:", error);
7475
if (error?.code === '23505' && error.constraint === 'companies_name_key') {
7576
return { error: "Une entreprise avec ce nom existe déjà." };
7677
}
77-
console.error("Error creating company:", error);
7878
return { error: error.message || "Une erreur est survenue lors de la création de l'entreprise." };
7979
}
8080
}
@@ -312,6 +312,67 @@ export async function investInCompany(companyId: number, amount: number): Promis
312312
}
313313
}
314314

315+
export async function sellShares(companyId: number, quantity: number): Promise<{ success?: string; error?: string }> {
316+
const session = await getSession();
317+
if (!session?.id) {
318+
return { error: "Vous devez être connecté pour vendre des parts." };
319+
}
320+
321+
try {
322+
const result = await db.transaction(async (tx) => {
323+
const company = await tx.query.companies.findFirst({
324+
where: eq(companies.id, companyId)
325+
});
326+
if (!company) throw new Error("Entreprise non trouvée.");
327+
if (company.isListed) throw new Error("Les actions des entreprises cotées doivent être vendues sur le marché.");
328+
329+
const sharePrice = parseFloat(company.sharePrice);
330+
if (quantity <= 0) throw new Error("La quantité doit être positive.");
331+
332+
const userShareHolding = await tx.query.companyShares.findFirst({
333+
where: and(eq(companyShares.userId, session.id), eq(companyShares.companyId, companyId))
334+
});
335+
const sharesHeld = parseFloat(userShareHolding?.quantity || '0');
336+
if (sharesHeld < quantity) throw new Error("Vous ne possédez pas assez de parts.");
337+
338+
const proceeds = sharePrice * quantity;
339+
const companyCash = parseFloat(company.cash);
340+
if(companyCash < proceeds) throw new Error("La trésorerie de l'entreprise est insuffisante pour racheter ces parts.");
341+
342+
const user = await tx.query.users.findFirst({ where: eq(users.id, session.id), columns: { cash: true } });
343+
if (!user) throw new Error("Utilisateur non trouvé.");
344+
345+
const newTotalShares = parseFloat(company.totalShares) - quantity;
346+
347+
await tx.update(users).set({ cash: (parseFloat(user.cash) + proceeds).toFixed(2) }).where(eq(users.id, session.id));
348+
await tx.update(companies).set({
349+
cash: (companyCash - proceeds).toFixed(2),
350+
totalShares: newTotalShares.toString(),
351+
}).where(eq(companies.id, companyId));
352+
353+
const newSharesHeld = sharesHeld - quantity;
354+
if (newSharesHeld < 1e-9) {
355+
await tx.delete(companyShares).where(eq(companyShares.id, userShareHolding!.id));
356+
} else {
357+
await tx.update(companyShares).set({ quantity: newSharesHeld.toString() }).where(eq(companyShares.id, userShareHolding!.id));
358+
}
359+
360+
return { success: `Vous avez vendu ${quantity.toFixed(4)} parts de ${company.name} pour ${proceeds.toFixed(2)}$.` };
361+
});
362+
363+
revalidatePath('/companies');
364+
revalidatePath(`/companies/${companyId}`);
365+
revalidatePath('/portfolio');
366+
revalidatePath('/profile');
367+
revalidatePath('/');
368+
return result;
369+
370+
} catch (error: any) {
371+
return { error: error.message || "Une erreur est survenue lors de la vente." };
372+
}
373+
}
374+
375+
315376
export async function addCashToCompany(companyId: number, amount: number): Promise<{ success?: string; error?: string }> {
316377
const session = await getSession();
317378
if (!session?.id) return { error: "Vous devez être connecté." };
@@ -440,7 +501,7 @@ export async function searchUsersForCompany(companyId: number, query: string): P
440501

441502
const potentialUsers = await db.query.users.findMany({
442503
where: and(
443-
notInArray(users.id, existingMemberIds),
504+
notInArray(users.id, existingMemberIds.length > 0 ? existingMemberIds : [0]),
444505
or(
445506
ilike(users.displayName, `%${query}%`),
446507
ilike(users.email, `%${query}%`)

src/lib/actions/portfolio.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,13 @@ export async function sellAssetAction(ticker: string, quantity: number): Promise
265265
if (sharesHeld < quantity) throw new Error("Vous ne possédez pas assez de parts pour cette vente.");
266266
if (parseFloat(company.cash) < tradeValue) throw new Error("La trésorerie de l'entreprise est insuffisante pour racheter ces parts.");
267267

268+
const newTotalShares = parseFloat(company.totalShares) - quantity;
269+
268270
// Debit company, credit user
269-
await tx.update(companies).set({ cash: (parseFloat(company.cash) - tradeValue).toFixed(2) }).where(eq(companies.id, company.id));
271+
await tx.update(companies).set({
272+
cash: (parseFloat(company.cash) - tradeValue).toFixed(2),
273+
totalShares: newTotalShares.toString(),
274+
}).where(eq(companies.id, company.id));
270275
await tx.update(users).set({ cash: (parseFloat(user.cash) + tradeValue).toFixed(2) }).where(eq(users.id, session.id));
271276

272277
// Remove shares from user

0 commit comments

Comments
 (0)