Skip to content

Commit

Permalink
feat: create obiz commande
Browse files Browse the repository at this point in the history
  • Loading branch information
ClementNumericite committed Nov 6, 2024
1 parent 309d4ba commit 16fc470
Show file tree
Hide file tree
Showing 5 changed files with 143 additions and 48 deletions.
6 changes: 2 additions & 4 deletions webapp/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
## [0.51.2](https://github.com/SocialGouv/carte-jeune-engage/compare/v0.51.1...v0.51.2) (2024-11-05)


### Bug Fixes

* seed offers published param ([ad7b8bf](https://github.com/SocialGouv/carte-jeune-engage/commit/ad7b8bfd8a5462946b27e64e30b5af413f1c6825))
- seed offers published param ([ad7b8bf](https://github.com/SocialGouv/carte-jeune-engage/commit/ad7b8bfd8a5462946b27e64e30b5af413f1c6825))

## [0.51.1](https://github.com/SocialGouv/carte-jeune-engage/compare/v0.51.0...v0.51.1) (2024-11-05)


### Bug Fixes

* generate types & published to false on obiz integration ([f816ca6](https://github.com/SocialGouv/carte-jeune-engage/commit/f816ca6d4e4abbcba74b23cb2a840259dc5d328b))
- generate types & published to false on obiz integration ([f816ca6](https://github.com/SocialGouv/carte-jeune-engage/commit/f816ca6d4e4abbcba74b23cb2a840259dc5d328b))

# [0.51.0](https://github.com/SocialGouv/carte-jeune-engage/compare/v0.50.1...v0.51.0) (2024-11-05)

Expand Down
60 changes: 50 additions & 10 deletions webapp/src/pages/dashboard/obiz-offer-variable.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Box, Button, Flex } from "@chakra-ui/react";
import { Box, Button, Center, Flex, Heading } from "@chakra-ui/react";
import { Dispatch, SetStateAction, useState } from "react";
import LoadingLoader from "~/components/LoadingLoader";
import DiscountAmountBlock from "~/components/obiz/DiscountAmountBlock";
import RecapOrder from "~/components/obiz/RecapOrder";
import BackButton from "~/components/ui/BackButton";
Expand All @@ -12,26 +13,30 @@ const ObizOfferVariableContent = ({
amount,
setAmount,
offer,
article,
createOrder,
}: {
step: "amount" | "summary";
setStep: Dispatch<SetStateAction<"amount" | "summary">>;
amount: number;
setAmount: Dispatch<SetStateAction<number>>;
offer: OfferIncluded | undefined;
createOrder: any;
article: NonNullable<OfferIncluded["articles"]> extends Array<infer T>
? T
: never;
offer: OfferIncluded;
createOrder: () => void;
}) => {
switch (step) {
case "amount":
return (
<>
<Box mt={8}>
<DiscountAmountBlock
discount={5}
discount={article.reductionPercentage}
amount={amount}
setAmount={setAmount}
minAmount={5}
maxAmount={100}
minAmount={article.minimumPrice || 0}
maxAmount={article.maximumPrice || 1000}
/>
</Box>
<Button mt={10} onClick={() => setStep("summary")}>
Expand All @@ -44,7 +49,11 @@ const ObizOfferVariableContent = ({
return (
<>
<Box mt={8}>
<RecapOrder discount={5} amount={amount} offer={offer} />
<RecapOrder
discount={article.reductionPercentage}
amount={amount}
offer={offer}
/>
</Box>
<Button mt={10} onClick={() => createOrder()}>
Passer au paiement
Expand All @@ -58,13 +67,37 @@ export default function ObizOfferVariable() {
const [amount, setAmount] = useState(0);
const [step, setStep] = useState<"amount" | "summary">("amount");

const { mutate: createTestOrder } = api.order.createOrder.useMutation();
const { mutate: createTestOrder, isLoading: isCreateOrderLoading } =
api.order.createOrder.useMutation();

const { data: offerResult } = api.offer.getById.useQuery({
id: 1,
id: 6,
});
const { data: offer } = offerResult || {};

if (!offer || !offer.articles) return;

const availableArticles = offer.articles.filter((a) => !!a.available);
const article = availableArticles.find((a) => a.kind === "variable_price");

if (!article) return;

if (isCreateOrderLoading) {
return (
<Center
h="full"
w="full"
flexDirection={"column"}
justifyContent={"center"}
>
<LoadingLoader />
<Heading textAlign={"center"} mt={6} size="md" fontWeight={900}>
Votre commande est en cours de traitement...
</Heading>
</Center>
);
}

return (
<Flex flexDir="column" mt={10} px={8}>
<BackButton onClick={() => setStep("amount")} />
Expand All @@ -74,7 +107,14 @@ export default function ObizOfferVariable() {
amount={amount}
setAmount={setAmount}
offer={offer}
createOrder={createTestOrder}
article={article}
createOrder={() => {
createTestOrder({
offer_id: offer.id,
article_reference: article.reference,
input_value: amount,
});
}}
/>
</Flex>
);
Expand Down
42 changes: 37 additions & 5 deletions webapp/src/server/api/routers/order.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,53 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { createTRPCRouter, userProtectedProcedure } from "~/server/api/trpc";
import { createOrderPayload, obiz_signature } from "~/utils/obiz";
import { createOrderPayload } from "~/utils/obiz";

export const orderRouter = createTRPCRouter({
createOrder: userProtectedProcedure
// .input(z.object({ user_id: z.number(), client_id: z.number() }))
.input(
z.object({
offer_id: z.number(),
article_reference: z.string(),
input_value: z.number().optional(),
})
)
.mutation(async ({ ctx, input }) => {
// const { user_id, client_id } = input;
const { offer_id, article_reference, input_value } = input;

const order_payload = createOrderPayload();
const user = await ctx.payload.findByID({
collection: "users",
id: ctx.session.id,
});

const offer = await ctx.payload.findByID({
collection: "offers",
id: offer_id,
});

const article = (offer.articles || [])
.filter((a) => !!a.available)
.find((a) => a.reference === article_reference);

if (!article) {
throw new TRPCError({
code: "NOT_FOUND",
message: `Article with reference "${article_reference}" not found in offer ${offer.id}`,
});
}

const order_payload = createOrderPayload(user, "CARTECADEAU");

try {
const [result] = await ctx.soapObizClient.CREATION_COMMANDE_ARRAYAsync({
CE_ID: process.env.OBIZ_PARTNER_ID,
...order_payload,
});
console.log(JSON.stringify(result, null, 2));

const commandeNumero =
result.CREATION_COMMANDE_ARRAYResult.diffgram.NewDataSet.Commande
.commandes_numero;
console.log("Commande number:", commandeNumero);
} catch (error) {
console.error(error);
}
Expand Down
68 changes: 39 additions & 29 deletions webapp/src/utils/obiz.ts
Original file line number Diff line number Diff line change
@@ -1,73 +1,84 @@
import { User } from "~/payload/payload-types";
import { extractAddressInformations } from "./tools";

var crypto = require("crypto");

export const obiz_signature = crypto
.createHash("sha512")
.update(`${process.env.OBIZ_PARTNER_ID}+${process.env.OBIZ_SECRET}`)
.digest("hex") as string;

export const createOrderPayload = () => {
export const createOrderPayload = (
user: User,
kind: "CARTECADEAU" | "EBILLET"
) => {
const { street_address, city, zip_code } = extractAddressInformations(
user.address || ""
);

const signature = crypto
.createHash("sha512")
.update(
`CARTECADEAU+${process.env.OBIZ_PARTNER_ID}+CB[email protected]+Cje+Test+Taverny+${process.env.OBIZ_SECRET}`
`${kind}+${user.id.toString()}+CB +${street_address}+Maison+${zip_code}+${user.userEmail || user.email}+${user.lastName || "Inconnu"}+${user.firstName || "Inconnu"}+${city}+${process.env.OBIZ_SECRET}`
)
.digest("hex") as string;

return {
SIGNATURE: signature,
TABLE_CE: {
string: [
"dcb1600d-9a0d-447e-9f84-8dc45e6c0668",
process.env.OBIZ_PARTNER_ID,
"Numéricité",
"Homme",
"Nom",
"Test",
"",
"",
"",
"[email protected]",
"",
"",
"",
"95150",
"Taverny",
"",
"",
"",
"",
"",
"",
"",
],
},
TABLE_UTILISATEUR: {
string: [
"id-test-cje",
user.id.toString(),
"",
"",
"Cje",
"Test",
"0600000000",
"0600000000",
user.lastName || "Inconnu",
user.firstName || "Inconnu",
user.phone_number,
user.phone_number,
"",
"[email protected]",
"Bureau",
"10 rue de la paix",
user.userEmail || user.email,
"Maison",
street_address,
"",
"95150",
"Taverny",
zip_code,
city,
"France",
"12/09/2000",
user.birthDate || "01/01/1970",
],
},
TABLE_COMMANDE: {
string: [
"0",
"0",
"cb",
"CB ",
"0",
"CARTECADEAU",
kind,
"",
"2 rue de la societe",
"Test",
"10 rue de la paix",
"Batiment A",
"95150",
"Taverny",
"",
"Adresse de facturation",
street_address,
"",
zip_code,
city,
"FRANCE",
"",
"", // url_retour_ok
"", // url_retour_ko
Expand All @@ -79,6 +90,5 @@ export const createOrderPayload = () => {
"",
],
},
SIGNATURE: signature,
};
};
15 changes: 15 additions & 0 deletions webapp/src/utils/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,18 @@ export function cleanHtml(html: string): string {
.replace(/§BR§\s*§BR§+/g, "§BR§")
.replace(/§BR§/g, "<br>");
}

export function extractAddressInformations(address: string) {
const regex = /^(.+?),\s*([^0-9]+?)\s+(\d+)$/;
const match = address.match(regex);

if (!match) {
throw new Error("Invalid address format");
}

return {
street_address: match[1].trim(),
city: match[2].trim(),
zip_code: match[3],
};
}

0 comments on commit 16fc470

Please sign in to comment.