fix conflict duplicates

This commit is contained in:
Danel Kungla
2025-09-24 18:45:29 +03:00
parent c7298d2b7e
commit 6c6e7a6847
8 changed files with 29 additions and 120 deletions

View File

@@ -1,10 +1,5 @@
'use server'; 'use server';
import { MontonioOrderToken } from '@/app/home/(user)/_components/cart/types';
import { loadCurrentUserAccount } from '@/app/home/(user)/_lib/server/load-user-account';
import { placeOrder, retrieveCart } from '@lib/data/cart';
import { listProductTypes } from '@lib/data/products';
import type { StoreOrder } from '@medusajs/types';
import { MontonioOrderToken } from '@/app/home/(user)/_components/cart/types'; import { MontonioOrderToken } from '@/app/home/(user)/_components/cart/types';
import { loadCurrentUserAccount } from '@/app/home/(user)/_lib/server/load-user-account'; import { loadCurrentUserAccount } from '@/app/home/(user)/_lib/server/load-user-account';
import { placeOrder, retrieveCart } from '@lib/data/cart'; import { placeOrder, retrieveCart } from '@lib/data/cart';
@@ -12,37 +7,26 @@ import { listProductTypes } from '@lib/data/products';
import type { StoreOrder } from '@medusajs/types'; import type { StoreOrder } from '@medusajs/types';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { z } from 'zod'; import { z } from 'zod';
import { AccountWithParams } from '@kit/accounts/types/accounts';
import { createNotificationsApi } from '@kit/notifications/api'; import { createNotificationsApi } from '@kit/notifications/api';
import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client'; import { getSupabaseServerAdminClient } from '@kit/supabase/server-admin-client';
import { createI18nServerInstance } from '~/lib/i18n/i18n.server'; import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
import { import { bookAppointment } from '~/lib/services/connected-online.service';
bookAppointment,
} from '~/lib/services/connected-online.service';
import { FailureReason } from '~/lib/types/connected-online';
import { createAnalysisOrder, getAnalysisOrder } from '~/lib/services/order.service';
import { sendOrderToMedipost } from '~/lib/services/medipost/medipostPrivateMessage.service'; import { sendOrderToMedipost } from '~/lib/services/medipost/medipostPrivateMessage.service';
import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service'; import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service';
import { AccountWithParams } from '@kit/accounts/types/accounts'; import {
createAnalysisOrder,
getAnalysisOrder,
} from '~/lib/services/order.service';
import { getOrderedTtoServices } from '~/lib/services/reservation.service'; import { getOrderedTtoServices } from '~/lib/services/reservation.service';
import { FailureReason } from '~/lib/types/connected-online';
const ANALYSIS_PACKAGES_TYPE_HANDLE = 'analysis-packages'; const ANALYSIS_PACKAGES_TYPE_HANDLE = 'analysis-packages';
const ANALYSIS_TYPE_HANDLE = 'synlab-analysis'; const ANALYSIS_TYPE_HANDLE = 'synlab-analysis';
const MONTONIO_PAID_STATUS = 'PAID'; const MONTONIO_PAID_STATUS = 'PAID';
const env = () =>
z
.object({
emailSender: z
.string({
error: 'EMAIL_SENDER is required',
})
.min(1),
siteUrl: z
.string({
error: 'NEXT_PUBLIC_SITE_URL is required',
})
.min(1),
isEnabledDispatchOnMontonioCallback: z.boolean({
const env = () => const env = () =>
z z
.object({ .object({
@@ -66,13 +50,6 @@ const env = () =>
isEnabledDispatchOnMontonioCallback: isEnabledDispatchOnMontonioCallback:
process.env.MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK === 'true', process.env.MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK === 'true',
}); });
})
.parse({
emailSender: process.env.EMAIL_SENDER,
siteUrl: process.env.NEXT_PUBLIC_SITE_URL!,
isEnabledDispatchOnMontonioCallback:
process.env.MEDIPOST_ENABLE_DISPATCH_ON_MONTONIO_CALLBACK === 'true',
});
const sendEmail = async ({ const sendEmail = async ({
account, account,
@@ -86,17 +63,9 @@ const sendEmail = async ({
analysisPackageName: string; analysisPackageName: string;
partnerLocationName: string; partnerLocationName: string;
language: string; language: string;
account: Pick<AccountWithParams, 'name' | 'id'>;
email: string;
analysisPackageName: string;
partnerLocationName: string;
language: string;
}) => { }) => {
const client = getSupabaseServerAdminClient(); const client = getSupabaseServerAdminClient();
try { try {
const { renderSynlabAnalysisPackageEmail } = await import(
'@kit/email-templates'
);
const { renderSynlabAnalysisPackageEmail } = await import( const { renderSynlabAnalysisPackageEmail } = await import(
'@kit/email-templates' '@kit/email-templates'
); );
@@ -133,7 +102,6 @@ const sendEmail = async ({
throw new Error(`Failed to send email, message=${error}`); throw new Error(`Failed to send email, message=${error}`);
} }
}; };
};
async function decodeOrderToken(orderToken: string) { async function decodeOrderToken(orderToken: string) {
const secretKey = process.env.MONTONIO_SECRET_KEY as string; const secretKey = process.env.MONTONIO_SECRET_KEY as string;
@@ -144,7 +112,6 @@ async function decodeOrderToken(orderToken: string) {
if (decoded.paymentStatus !== MONTONIO_PAID_STATUS) { if (decoded.paymentStatus !== MONTONIO_PAID_STATUS) {
throw new Error('Payment not successful'); throw new Error('Payment not successful');
throw new Error('Payment not successful');
} }
return decoded; return decoded;
@@ -154,12 +121,10 @@ async function getCartByOrderToken(decoded: MontonioOrderToken) {
const [, , cartId] = decoded.merchantReferenceDisplay.split(':'); const [, , cartId] = decoded.merchantReferenceDisplay.split(':');
if (!cartId) { if (!cartId) {
throw new Error('Cart ID not found'); throw new Error('Cart ID not found');
throw new Error('Cart ID not found');
} }
const cart = await retrieveCart(cartId); const cart = await retrieveCart(cartId);
if (!cart) { if (!cart) {
throw new Error('Cart not found'); throw new Error('Cart not found');
throw new Error('Cart not found');
} }
return cart; return cart;
} }
@@ -206,17 +171,12 @@ async function sendAnalysisPackageOrderEmail({
email, email,
analysisPackageOrder, analysisPackageOrder,
}: { }: {
account: AccountWithParams;
email: string;
account: AccountWithParams; account: AccountWithParams;
email: string; email: string;
analysisPackageOrder: { analysisPackageOrder: {
partnerLocationName: string; partnerLocationName: string;
analysisPackageName: string; analysisPackageName: string;
}; };
partnerLocationName: string;
analysisPackageName: string;
};
}) { }) {
const { language } = await createI18nServerInstance(); const { language } = await createI18nServerInstance();
const { analysisPackageName, partnerLocationName } = analysisPackageOrder; const { analysisPackageName, partnerLocationName } = analysisPackageOrder;
@@ -238,15 +198,18 @@ export async function processMontonioCallback(orderToken: string) {
const { account } = await loadCurrentUserAccount(); const { account } = await loadCurrentUserAccount();
if (!account) { if (!account) {
throw new Error('Account not found in context'); throw new Error('Account not found in context');
throw new Error('Account not found in context');
} }
try { try {
const decoded = await decodeOrderToken(orderToken); const decoded = await decodeOrderToken(orderToken);
const cart = await getCartByOrderToken(decoded); const cart = await getCartByOrderToken(decoded);
const medusaOrder = await placeOrder(cart.id, { revalidateCacheTags: false }); const medusaOrder = await placeOrder(cart.id, {
const orderedAnalysisElements = await getOrderedAnalysisIds({ medusaOrder }); revalidateCacheTags: false,
});
const orderedAnalysisElements = await getOrderedAnalysisIds({
medusaOrder,
});
const orderContainsSynlabItems = !!orderedAnalysisElements?.length; const orderContainsSynlabItems = !!orderedAnalysisElements?.length;
@@ -272,7 +235,8 @@ export async function processMontonioCallback(orderToken: string) {
const orderResult = await getOrderResultParameters(medusaOrder); const orderResult = await getOrderResultParameters(medusaOrder);
const { medusaOrderId, email, analysisPackageOrder, analysisItemsOrder } = orderResult; const { medusaOrderId, email, analysisPackageOrder, analysisItemsOrder } =
orderResult;
const orderedTtoServices = await getOrderedTtoServices({ medusaOrder }); const orderedTtoServices = await getOrderedTtoServices({ medusaOrder });
let bookServiceResults: { let bookServiceResults: {
@@ -314,7 +278,6 @@ export async function processMontonioCallback(orderToken: string) {
} }
} else { } else {
console.error('Missing email to send order result email', orderResult); console.error('Missing email to send order result email', orderResult);
console.error('Missing email to send order result email', orderResult);
} }
if (env().isEnabledDispatchOnMontonioCallback && orderContainsSynlabItems) { if (env().isEnabledDispatchOnMontonioCallback && orderContainsSynlabItems) {
@@ -334,7 +297,6 @@ export async function processMontonioCallback(orderToken: string) {
return { success: true, orderId }; return { success: true, orderId };
} catch (error) { } catch (error) {
console.error('Failed to place order', error);
console.error('Failed to place order', error); console.error('Failed to place order', error);
throw new Error(`Failed to place order, message=${error}`); throw new Error(`Failed to place order, message=${error}`);
} }

View File

@@ -2,20 +2,15 @@ import { use } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
import { createI18nServerInstance } from '@/lib/i18n/i18n.server'; import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page'; import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
import { Button } from '@kit/ui/button'; import { toArray } from '@kit/shared/utils';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
import { Alert, AlertDescription } from '@kit/ui/shadcn/alert'; import { Alert, AlertDescription } from '@kit/ui/shadcn/alert';
import { AlertTitle } from '@kit/ui/shadcn/alert'; import { AlertTitle } from '@kit/ui/shadcn/alert';
import { Trans } from '@kit/ui/trans'; import { Trans } from '@kit/ui/trans';
import { FailureReason } from '~/lib/types/connected-online';
import { toArray } from '~/lib/utils';
export async function generateMetadata() { export async function generateMetadata() {
const { t } = await createI18nServerInstance(); const { t } = await createI18nServerInstance();

View File

@@ -25,7 +25,6 @@ export async function generateMetadata() {
async function CartPage() { async function CartPage() {
const cart = await retrieveCart().catch((error) => { const cart = await retrieveCart().catch((error) => {
console.error('Failed to retrieve cart', error);
console.error('Failed to retrieve cart', error); console.error('Failed to retrieve cart', error);
return notFound(); return notFound();
}); });
@@ -75,11 +74,6 @@ async function CartPage() {
synlabAnalyses={synlabAnalyses} synlabAnalyses={synlabAnalyses}
ttoServiceItems={ttoServiceItems} ttoServiceItems={ttoServiceItems}
/> />
<Cart
cart={cart}
synlabAnalyses={synlabAnalyses}
ttoServiceItems={ttoServiceItems}
/>
</PageBody> </PageBody>
); );
} }

View File

@@ -1,16 +1,11 @@
import React from 'react'; import React from 'react';
import React from 'react';
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
import { createI18nServerInstance } from '@/lib/i18n/i18n.server'; import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
import { listProductTypes } from '@lib/data/products'; import { listProductTypes } from '@lib/data/products';
import { Divider } from '@medusajs/ui'; import { Divider } from '@medusajs/ui';
import { pathsConfig } from '@kit/shared/config';
import { Divider } from '@medusajs/ui';
import { pathsConfig } from '@kit/shared/config'; import { pathsConfig } from '@kit/shared/config';
import { PageBody } from '@kit/ui/makerkit/page'; import { PageBody } from '@kit/ui/makerkit/page';
import { Trans } from '@kit/ui/trans'; import { Trans } from '@kit/ui/trans';
@@ -92,7 +87,6 @@ async function OrdersPage() {
/> />
</React.Fragment> </React.Fragment>
); );
);
})} })}
{analysisOrders.length === 0 && ( {analysisOrders.length === 0 && (
<h5 className="mt-6"> <h5 className="mt-6">

View File

@@ -45,6 +45,7 @@ export const BookingProvider: React.FC<{
const updateTimeSlots = async (serviceIds: number[]) => { const updateTimeSlots = async (serviceIds: number[]) => {
setIsLoadingTimeSlots(true); setIsLoadingTimeSlots(true);
try { try {
console.log('serviceIds', serviceIds, selectedLocationId);
const response = await getAvailableTimeSlotsForDisplay( const response = await getAvailableTimeSlotsForDisplay(
serviceIds, serviceIds,
selectedLocationId, selectedLocationId,

View File

@@ -1,14 +1,4 @@
'use client'; 'use client';
'use client';
import { useState } from 'react';
import { handleNavigateToPayment } from '@/lib/services/medusaCart.service';
import { formatCurrency } from '@/packages/shared/src/utils';
import { initiatePaymentSession } from '@lib/data/cart';
import { StoreCart, StoreCartLineItem } from '@medusajs/types';
import { Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useState } from 'react'; import { useState } from 'react';
@@ -36,7 +26,6 @@ export default function Cart({
synlabAnalyses, synlabAnalyses,
ttoServiceItems, ttoServiceItems,
}: { }: {
cart: StoreCart | null;
cart: StoreCart | null; cart: StoreCart | null;
synlabAnalyses: StoreCartLineItem[]; synlabAnalyses: StoreCartLineItem[];
ttoServiceItems: EnrichedCartItem[]; ttoServiceItems: EnrichedCartItem[];
@@ -44,12 +33,10 @@ export default function Cart({
const { const {
i18n: { language }, i18n: { language },
} = useTranslation(); } = useTranslation();
const {
i18n: { language },
} = useTranslation();
const [isInitiatingSession, setIsInitiatingSession] = useState(false); const [isInitiatingSession, setIsInitiatingSession] = useState(false);
const [unavailableLineItemIds, setUnavailableLineItemIds] = useState<string[]>() const [unavailableLineItemIds, setUnavailableLineItemIds] =
useState<string[]>();
const items = cart?.items ?? []; const items = cart?.items ?? [];
@@ -57,10 +44,6 @@ export default function Cart({
return ( return (
<div className="content-container py-5 lg:px-4"> <div className="content-container py-5 lg:px-4">
<div> <div>
<div
className="flex flex-col items-center justify-center"
data-testid="empty-cart-message"
>
<div <div
className="flex flex-col items-center justify-center" className="flex flex-col items-center justify-center"
data-testid="empty-cart-message" data-testid="empty-cart-message"
@@ -85,12 +68,15 @@ export default function Cart({
if (response.payment_collection) { if (response.payment_collection) {
const { payment_sessions } = response.payment_collection; const { payment_sessions } = response.payment_collection;
const paymentSessionId = payment_sessions![0]!.id; const paymentSessionId = payment_sessions![0]!.id;
const result = await handleNavigateToPayment({ language, paymentSessionId }); const result = await handleNavigateToPayment({
language,
paymentSessionId,
});
if (result.url) { if (result.url) {
window.location.href = result.url; window.location.href = result.url;
} }
if (result.unavailableLineItemIds) { if (result.unavailableLineItemIds) {
setUnavailableLineItemIds(result.unavailableLineItemIds) setUnavailableLineItemIds(result.unavailableLineItemIds);
} }
} else { } else {
setIsInitiatingSession(false); setIsInitiatingSession(false);
@@ -117,9 +103,6 @@ export default function Cart({
</div> </div>
{hasCartItems && ( {hasCartItems && (
<> <>
<div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4">
<div className="w-full sm:mr-[42px] sm:w-auto">
<p className="text-muted-foreground ml-0 text-sm font-bold">
<div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4"> <div className="flex gap-x-4 px-4 pt-2 sm:justify-end sm:px-6 sm:pt-4">
<div className="w-full sm:mr-[42px] sm:w-auto"> <div className="w-full sm:mr-[42px] sm:w-auto">
<p className="text-muted-foreground ml-0 text-sm font-bold"> <p className="text-muted-foreground ml-0 text-sm font-bold">
@@ -127,7 +110,6 @@ export default function Cart({
</p> </p>
</div> </div>
<div className={`sm:mr-[112px] sm:w-[50px]`}> <div className={`sm:mr-[112px] sm:w-[50px]`}>
<p className="text-right text-sm">
<p className="text-right text-sm"> <p className="text-right text-sm">
{formatCurrency({ {formatCurrency({
value: cart.subtotal, value: cart.subtotal,
@@ -137,9 +119,6 @@ export default function Cart({
</p> </p>
</div> </div>
</div> </div>
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
<div className="w-full sm:mr-[42px] sm:w-auto">
<p className="text-muted-foreground ml-0 text-sm font-bold">
<div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4"> <div className="flex gap-x-4 px-4 py-2 sm:justify-end sm:px-6 sm:py-4">
<div className="w-full sm:mr-[42px] sm:w-auto"> <div className="w-full sm:mr-[42px] sm:w-auto">
<p className="text-muted-foreground ml-0 text-sm font-bold"> <p className="text-muted-foreground ml-0 text-sm font-bold">
@@ -147,7 +126,6 @@ export default function Cart({
</p> </p>
</div> </div>
<div className={`sm:mr-[112px] sm:w-[50px]`}> <div className={`sm:mr-[112px] sm:w-[50px]`}>
<p className="text-right text-sm">
<p className="text-right text-sm"> <p className="text-right text-sm">
{formatCurrency({ {formatCurrency({
value: cart.discount_total, value: cart.discount_total,
@@ -157,9 +135,6 @@ export default function Cart({
</p> </p>
</div> </div>
</div> </div>
<div className="flex gap-x-4 px-4 sm:justify-end sm:px-6">
<div className="w-full sm:mr-[42px] sm:w-auto">
<p className="ml-0 text-sm font-bold">
<div className="flex gap-x-4 px-4 sm:justify-end sm:px-6"> <div className="flex gap-x-4 px-4 sm:justify-end sm:px-6">
<div className="w-full sm:mr-[42px] sm:w-auto"> <div className="w-full sm:mr-[42px] sm:w-auto">
<p className="ml-0 text-sm font-bold"> <p className="ml-0 text-sm font-bold">
@@ -167,7 +142,6 @@ export default function Cart({
</p> </p>
</div> </div>
<div className={`sm:mr-[112px] sm:w-[50px]`}> <div className={`sm:mr-[112px] sm:w-[50px]`}>
<p className="text-right text-sm">
<p className="text-right text-sm"> <p className="text-right text-sm">
{formatCurrency({ {formatCurrency({
value: cart.total, value: cart.total,
@@ -180,10 +154,8 @@ export default function Cart({
</> </>
)} )}
<div className="flex flex-col gap-x-4 gap-y-6 py-4 sm:flex-row sm:py-8">
<div className="flex flex-col gap-x-4 gap-y-6 py-4 sm:flex-row sm:py-8"> <div className="flex flex-col gap-x-4 gap-y-6 py-4 sm:flex-row sm:py-8">
{IS_DISCOUNT_SHOWN && ( {IS_DISCOUNT_SHOWN && (
<Card className="flex w-full flex-col justify-between sm:w-1/2">
<Card className="flex w-full flex-col justify-between sm:w-1/2"> <Card className="flex w-full flex-col justify-between sm:w-1/2">
<CardHeader className="pb-4"> <CardHeader className="pb-4">
<h5> <h5>
@@ -197,7 +169,6 @@ export default function Cart({
)} )}
{isLocationsShown && ( {isLocationsShown && (
<Card className="flex w-full flex-col justify-between sm:w-1/2">
<Card className="flex w-full flex-col justify-between sm:w-1/2"> <Card className="flex w-full flex-col justify-between sm:w-1/2">
<CardHeader className="pb-4"> <CardHeader className="pb-4">
<h5> <h5>
@@ -219,14 +190,6 @@ export default function Cart({
</div> </div>
<div> <div>
<Button
className="h-10"
onClick={initiatePayment}
disabled={isInitiatingSession}
>
{isInitiatingSession && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
<Button <Button
className="h-10" className="h-10"
onClick={initiatePayment} onClick={initiatePayment}

View File

@@ -31,8 +31,8 @@ const env = () =>
.min(1), .min(1),
}) })
.parse({ .parse({
medusaBackendPublicUrl: process.env.MEDUSA_BACKEND_PUBLIC_URL!, medusaBackendPublicUrl: 'http://webhook.site:3000',
siteUrl: process.env.NEXT_PUBLIC_SITE_URL!, siteUrl: 'http://webhook.site:3000',
}); });
export async function handleAddToCart({ export async function handleAddToCart({

View File

@@ -15,7 +15,7 @@ export const listRegions = async () => {
.fetch<{ regions: HttpTypes.StoreRegion[] }>(`/store/regions`, { .fetch<{ regions: HttpTypes.StoreRegion[] }>(`/store/regions`, {
method: 'GET', method: 'GET',
next, next,
cache: 'force-cache', // cache: 'force-cache',
}) })
.then(({ regions }) => regions) .then(({ regions }) => regions)
.catch(medusaError); .catch(medusaError);