@agrada_digital/pbm 0.0.56 → 0.0.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -103,7 +103,7 @@ var GetProductByEAN = async ({ PRODUCT_EAN }) => {
103
103
  }
104
104
  });
105
105
  const dataResponse = await response.json();
106
- if (!dataResponse.sucesso) {
106
+ if (!dataResponse.success) {
107
107
  throw new Error(dataResponse.message || "Failed to fetch authorization");
108
108
  }
109
109
  return dataResponse;
@@ -112,22 +112,27 @@ var GetProductByEAN = async ({ PRODUCT_EAN }) => {
112
112
  // src/components/Footer/index.tsx
113
113
  import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
114
114
  function Footer() {
115
- const [industryLogo, setIndustryLogo] = useState(void 0);
116
- const { targetProduct } = usePBMStore();
115
+ const [industryLogo, setIndustryLogo] = useState(null);
116
+ const { targetProduct, setTargetProduct } = usePBMStore();
117
117
  useEffect(() => {
118
118
  const fetchProductByEan = async () => {
119
- if (!targetProduct) return;
119
+ if (!targetProduct?.ean) return;
120
120
  try {
121
121
  const response = await GetProductByEAN({ PRODUCT_EAN: targetProduct.ean });
122
- if (response.sucesso && response.dados) {
123
- setIndustryLogo(response.dados.pbm.imageLink);
122
+ if (response.success && response.data) {
123
+ setIndustryLogo(response.data.pbm.imageLink);
124
+ const { pbm, sku, ...targetProductNewData } = response.data;
125
+ setTargetProduct({
126
+ ...targetProduct,
127
+ ...targetProductNewData
128
+ });
124
129
  }
125
130
  } catch (error) {
126
131
  console.error(error);
127
132
  }
128
133
  };
129
134
  fetchProductByEan();
130
- }, [targetProduct]);
135
+ }, [targetProduct?.ean]);
131
136
  return /* @__PURE__ */ jsx3("footer", { className: "w-full h-auto relative", id: "footer_pbm", children: /* @__PURE__ */ jsxs2("section", { className: classNames2("flex items-center w-full h-auto gap-4", { "justify-center": industryLogo, "justify-start": !industryLogo }), children: [
132
137
  /* @__PURE__ */ jsxs2("section", { className: "w-4/5 h-auto", children: [
133
138
  /* @__PURE__ */ jsx3("h3", { className: "text-start font-semibold text-sm", children: "Economize com o benef\xEDcio do laborat\xF3rio." }),
@@ -150,7 +155,7 @@ var Footer_default = Footer;
150
155
 
151
156
  // src/schema/validation-schema.ts
152
157
  import { z } from "zod";
153
- var validationSchema = z.strictObject({
158
+ var validationSchema = z.object({
154
159
  securityNumber: z.string({
155
160
  required_error: "CPF \xE9 obrigat\xF3rio."
156
161
  }).refine((doc) => {
@@ -160,7 +165,7 @@ var validationSchema = z.strictObject({
160
165
  const replacedDoc = doc.replace(/\D/g, "");
161
166
  return !!Number(replacedDoc);
162
167
  }, "CPF deve conter apenas n\xFAmeros."),
163
- coupon: z.string().min(0)
168
+ coupon: z.string({ required_error: "Cupom / ID do Cart\xE3o obrigat\xF3rio." }).optional()
164
169
  });
165
170
 
166
171
  // src/utils/format.ts
@@ -231,14 +236,21 @@ function Form({ setLoading }) {
231
236
  handleSubmit,
232
237
  register,
233
238
  setValue,
239
+ clearErrors,
240
+ unregister,
234
241
  formState: { errors }
235
242
  } = useForm({
236
243
  resolver: zodResolver(validationSchema),
244
+ mode: "onSubmit",
237
245
  defaultValues: {
238
- securityNumber: securityNumber || ""
246
+ securityNumber: securityNumber || "",
247
+ coupon: ""
239
248
  }
240
249
  });
241
250
  const onSubmitDefault = async (values) => {
251
+ if (!showCoupoField) {
252
+ setValue("coupon", void 0, { shouldValidate: false });
253
+ }
242
254
  setLoading(true);
243
255
  try {
244
256
  if (targetProduct === null) {
@@ -247,7 +259,7 @@ function Form({ setLoading }) {
247
259
  }
248
260
  const response = await ValidateDocument({
249
261
  document: values.securityNumber.replace(/\D/g, ""),
250
- products: [{ ean: targetProduct.ean, quantity: targetProduct.quantity }]
262
+ products: [{ ean: targetProduct.ean, quantity: 1 }]
251
263
  });
252
264
  if (response.success) {
253
265
  const status = {
@@ -271,7 +283,7 @@ function Form({ setLoading }) {
271
283
  onSubmit: handleSubmit(onSubmitDefault),
272
284
  className: classNames4(
273
285
  "w-full h-auto flex items-center justify-center mb-0 transition-all duration-150",
274
- { "mb-4": errors.securityNumber || errors.coupon, "gap-2": showCoupoField }
286
+ { "mb-4": errors.securityNumber || errors.coupon && showCoupoField, "gap-2": showCoupoField }
275
287
  ),
276
288
  id: "form_security_number_pbm",
277
289
  children: [
@@ -325,12 +337,12 @@ function Form({ setLoading }) {
325
337
  { "outline outline-red-600": errors.coupon, "rounded-full": showCoupoField }
326
338
  ),
327
339
  placeholder: "Cupom / ID do Cart\xE3o",
328
- required: true,
329
- maxLength: 14,
330
340
  ...register("coupon", {
341
+ required: showCoupoField ? "Cupom / ID do Cart\xE3o obrigat\xF3rio." : false,
342
+ shouldUnregister: !showCoupoField,
331
343
  onChange: (e) => {
332
344
  setValue("coupon", e.target.value, {
333
- shouldValidate: true
345
+ shouldValidate: showCoupoField
334
346
  });
335
347
  }
336
348
  }),
@@ -360,7 +372,14 @@ function Form({ setLoading }) {
360
372
  Button_default,
361
373
  {
362
374
  className: "bg-transparent p-0 pl-2 w-auto h-auto text-zinc-600 underline cursor-pointer hover:text-zinc-900 hover:bg-transparent flex items-center justify-start gap-1",
363
- onClick: () => setShowCoupoField(!showCoupoField),
375
+ onClick: () => {
376
+ const newValue = !showCoupoField;
377
+ setShowCoupoField(newValue);
378
+ if (!newValue) {
379
+ unregister("coupon");
380
+ clearErrors("coupon");
381
+ }
382
+ },
364
383
  id: "check_benefits_button",
365
384
  children: [
366
385
  /* @__PURE__ */ jsx5("span", { children: !showCoupoField ? "Possui cupom?" : "N\xE3o possui cupom?" }),
@@ -398,32 +417,7 @@ function Loading({ textColor }) {
398
417
  var Loading_default = Loading;
399
418
 
400
419
  // src/components/BenefitsTable/index.tsx
401
- import { useState as useState3 } from "react";
402
-
403
- // src/mocks/benefits.ts
404
- var BENEFITS_ITEMS = [
405
- {
406
- id: 1,
407
- ean: "001",
408
- authorizedQuantity: 1,
409
- discountValue: 4800,
410
- discountPercentual: 2400
411
- },
412
- {
413
- id: 2,
414
- ean: "002",
415
- authorizedQuantity: 2,
416
- discountValue: 4800,
417
- discountPercentual: 2400
418
- },
419
- {
420
- id: 3,
421
- ean: "003",
422
- authorizedQuantity: 3,
423
- discountValue: 9400,
424
- discountPercentual: 4700
425
- }
426
- ];
420
+ import { useEffect as useEffect3, useState as useState3 } from "react";
427
421
 
428
422
  // src/components/UI/Title/index.tsx
429
423
  import classNames5 from "classnames";
@@ -449,13 +443,13 @@ var Title_default = Title;
449
443
  import { Badge, BadgeCheck } from "lucide-react";
450
444
  import { useCallback, useEffect as useEffect2 } from "react";
451
445
  import { jsx as jsx8, jsxs as jsxs5 } from "react/jsx-runtime";
452
- function Item({ data, onChange, checked, originalProductPrice }) {
446
+ function Item({ data, onChange, checked }) {
453
447
  const { setAvailableDiscountSelected, securityNumber } = usePBMStore();
454
448
  const ID_INPUT = "unity_quantity_" + data.authorizedQuantity;
455
- const decimalDiscount = data.discountPercentual / 1e4;
456
- const unitDiscountValue = originalProductPrice * decimalDiscount;
449
+ const decimalDiscount = data.discountPercentual / 100;
450
+ const unitDiscountValue = data.grossPrice * decimalDiscount;
457
451
  const discountValue = unitDiscountValue * data.authorizedQuantity;
458
- const totalPriceProductWithDiscountBenefit = originalProductPrice * data.authorizedQuantity - discountValue;
452
+ const totalPriceProductWithDiscountBenefit = data.grossPrice * data.authorizedQuantity - discountValue;
459
453
  const updateStorageData = useCallback(() => {
460
454
  if (checked) {
461
455
  const roundToTwoDecimals = (value) => Math.round(value * 100) / 100;
@@ -527,13 +521,103 @@ function Item({ data, onChange, checked, originalProductPrice }) {
527
521
  }
528
522
  var Item_default = Item;
529
523
 
524
+ // src/services/benefits-without-document.ts
525
+ import Cookies3 from "js-cookie";
526
+ var CheckBenefistWithoutDocument = async ({ products }) => {
527
+ const API_URL = import.meta.env.VITE_API_URL;
528
+ if (!API_URL) {
529
+ throw new Error("API URL is not defined in environment variables");
530
+ }
531
+ const AUTH_TOKEN = Cookies3.get("pbm-token");
532
+ if (!AUTH_TOKEN) {
533
+ throw new Error("Token is not defined in cookies or is expired");
534
+ }
535
+ const response = await fetch(`${API_URL}/products/genericBenefit`, {
536
+ method: "POST",
537
+ headers: {
538
+ Authorization: `Bearer ${AUTH_TOKEN}`,
539
+ "Content-Type": "application/json"
540
+ },
541
+ body: JSON.stringify({ products })
542
+ });
543
+ const dataResponse = await response.json();
544
+ if (!dataResponse.success) {
545
+ throw new Error(dataResponse.message || "Failed to fetch benefits without document");
546
+ }
547
+ return dataResponse;
548
+ };
549
+
530
550
  // src/components/BenefitsTable/index.tsx
531
551
  import { jsx as jsx9, jsxs as jsxs6 } from "react/jsx-runtime";
532
- function BenefitsTable({
533
- originalProductPrice
534
- }) {
535
- const { securityNumber, setState } = usePBMStore();
552
+ function BenefitsTable() {
553
+ const { securityNumber, setState, targetProduct } = usePBMStore();
536
554
  const [selectedDiscout, setSelectedDiscount] = useState3(null);
555
+ const [loading, setLoading] = useState3(true);
556
+ const [benefitsItems, setBenefitsItems] = useState3();
557
+ useEffect3(() => {
558
+ const fetchDicountsWithoutDocument = async () => {
559
+ if (!targetProduct?.productId) {
560
+ console.error("PBMLOG: Product ID is not defined on targetProduct");
561
+ return;
562
+ }
563
+ if (!targetProduct.ean) {
564
+ console.error("PBMLOG: EAN is not defined on targetProduct");
565
+ return;
566
+ }
567
+ if (!targetProduct.listPrice) {
568
+ console.error("PBMLOG: List Price is not defined on targetProduct");
569
+ return;
570
+ }
571
+ if (!targetProduct.price) {
572
+ console.error("PBMLOG: Price is not defined on targetProduct");
573
+ return;
574
+ }
575
+ try {
576
+ const data = {
577
+ productId: Number(targetProduct.productId),
578
+ ean: targetProduct.ean,
579
+ requestedQuantity: 1,
580
+ listPrice: targetProduct.listPrice,
581
+ netPrice: targetProduct.price
582
+ };
583
+ const response = await CheckBenefistWithoutDocument({ products: [data] });
584
+ if (response.success && response.data) {
585
+ setBenefitsItems(response.data);
586
+ } else {
587
+ setBenefitsItems(void 0);
588
+ }
589
+ } catch (error) {
590
+ setBenefitsItems(void 0);
591
+ console.error(error);
592
+ } finally {
593
+ setLoading(false);
594
+ }
595
+ };
596
+ const fetchDiscountWithDocument = async () => {
597
+ console.log("consulta feita com documento");
598
+ };
599
+ securityNumber ? fetchDiscountWithDocument() : fetchDicountsWithoutDocument();
600
+ }, []);
601
+ if (loading) {
602
+ return /* @__PURE__ */ jsxs6("main", { className: "flex items-center justify-center gap-4", id: "loading_pbm", children: [
603
+ /* @__PURE__ */ jsx9(
604
+ "div",
605
+ {
606
+ "data-testid": "test_id_spin",
607
+ className: "w-8 h-8 border-4 border-t-gray-700 border-gray-300 rounded-full animate-spin",
608
+ id: "loading_spin"
609
+ }
610
+ ),
611
+ /* @__PURE__ */ jsx9(
612
+ "p",
613
+ {
614
+ className: "text-sm font-semibold text-start text-zinc-900",
615
+ id: "loading_label",
616
+ children: "Buscando beneficios dispon\xEDveis..."
617
+ }
618
+ )
619
+ ] });
620
+ }
537
621
  return /* @__PURE__ */ jsxs6(
538
622
  "section",
539
623
  {
@@ -541,31 +625,34 @@ function BenefitsTable({
541
625
  id: "benefits_table_pbm",
542
626
  children: [
543
627
  /* @__PURE__ */ jsx9(Title_default, { children: "Descontos dispon\xEDveis:" }),
544
- /* @__PURE__ */ jsx9(
628
+ /* @__PURE__ */ jsxs6(
545
629
  "form",
546
630
  {
547
631
  className: "flex flex-col items-center justify-start w-full gap-3",
548
632
  id: "form_benefits_table_pbm",
549
- children: BENEFITS_ITEMS.map((item, index) => {
550
- const ID_INPUT = "unity_quantity_" + item.authorizedQuantity;
551
- return /* @__PURE__ */ jsx9(
552
- Item_default,
553
- {
554
- data: item,
555
- checked: selectedDiscout === ID_INPUT,
556
- onChange: () => setSelectedDiscount(ID_INPUT),
557
- originalProductPrice
558
- },
559
- index
560
- );
561
- })
633
+ children: [
634
+ !benefitsItems && /* @__PURE__ */ jsx9("p", { className: "text-sm font-semibold text-start text-zinc-900", id: "benefits_empty_pbm", children: "N\xE3o foi poss\xEDvel encontrar benef\xEDcios para esse produto." }),
635
+ benefitsItems && benefitsItems.map((item, index) => {
636
+ const ID_INPUT = "unity_quantity_" + item.authorizedQuantity;
637
+ return /* @__PURE__ */ jsx9(
638
+ Item_default,
639
+ {
640
+ data: item,
641
+ checked: selectedDiscout === ID_INPUT,
642
+ onChange: () => setSelectedDiscount(ID_INPUT)
643
+ },
644
+ index
645
+ );
646
+ }),
647
+ benefitsItems && /* @__PURE__ */ jsx9("p", { className: "w-full text-sm font-semibold text-center text-zinc-600", id: "benefits_empty_pbm", children: benefitsItems[0].informativeMessage })
648
+ ]
562
649
  }
563
650
  ),
564
651
  !securityNumber && /* @__PURE__ */ jsxs6(
565
652
  Button_default,
566
653
  {
567
654
  onClick: () => setState("isEmpty"),
568
- className: "bg-transparent p-0 pl-2 w-auto h-auto text-zinc-600 cursor-pointer hover:text-zinc-900 hover:bg-transparent text-start",
655
+ className: "bg-transparent p-0 w-auto h-auto text-zinc-600 cursor-pointer hover:text-zinc-900 hover:bg-transparent text-start",
569
656
  id: "unauthorized_benefits_button",
570
657
  children: [
571
658
  "Aten\xE7\xE3o: n\xE3o \xE9 poss\xEDvel utilizar os benef\xEDcos sem realizar a consulta do cpf, por favor",
@@ -715,7 +802,7 @@ function SecurityNumberInvalid({ textColor }) {
715
802
  var SecurityNumberInvalid_default = SecurityNumberInvalid;
716
803
 
717
804
  // src/PBM.tsx
718
- import { useCallback as useCallback2, useEffect as useEffect3, useState as useState5 } from "react";
805
+ import { useCallback as useCallback2, useEffect as useEffect4, useState as useState5 } from "react";
719
806
 
720
807
  // src/components/UI/Link/index.tsx
721
808
  import classNames8 from "classnames";
@@ -776,7 +863,7 @@ function SecurityNumberRegitered({ textColor }) {
776
863
  var SecurityNumberRegitered_default = SecurityNumberRegitered;
777
864
 
778
865
  // src/services/authorization.ts
779
- import Cookies3 from "js-cookie";
866
+ import Cookies4 from "js-cookie";
780
867
  var GetAuthorization = async ({ clientID }) => {
781
868
  const API_URL = import.meta.env.VITE_API_URL;
782
869
  const STORE_ID = import.meta.env.VITE_STORE_ID;
@@ -793,22 +880,22 @@ var GetAuthorization = async ({ clientID }) => {
793
880
  "Content-Type": "application/json"
794
881
  },
795
882
  body: JSON.stringify({
796
- StoreID: STORE_ID,
797
- StoreName: STORE_NAME,
798
- ClientID: clientID
883
+ storeId: STORE_ID,
884
+ storeName: STORE_NAME,
885
+ clientId: clientID
799
886
  })
800
887
  });
801
888
  const dataResponse = await response.json();
802
889
  if (!dataResponse.success) {
803
890
  throw new Error(dataResponse.message || "Failed to fetch authorization");
804
891
  }
805
- Cookies3.set("pbm-token", dataResponse.data.Token, {
806
- expires: dataResponse.data.ExpiresIn / (60 * 60),
892
+ Cookies4.set("pbm-token", dataResponse.data.token, {
893
+ expires: dataResponse.data.expiresIn / (60 * 60),
807
894
  secure: true,
808
895
  sameSite: "Strict"
809
896
  });
810
- Cookies3.set("pbm-token-refresh", dataResponse.data.RefreshToken, {
811
- expires: dataResponse.data.RefreshExpiresIn / (60 * 60),
897
+ Cookies4.set("pbm-token-refresh", dataResponse.data.refreshToken, {
898
+ expires: dataResponse.data.refreshExpiresIn / (60 * 60),
812
899
  secure: true,
813
900
  sameSite: "Strict"
814
901
  });
@@ -828,9 +915,9 @@ function PBM({
828
915
  );
829
916
  const [loading, setLoading] = useState5(false);
830
917
  const { setState, state, setTargetProduct } = usePBMStore();
831
- useEffect3(() => {
918
+ useEffect4(() => {
832
919
  if (eanProduct) {
833
- setTargetProduct({ ean: eanProduct, quantity: 1 });
920
+ setTargetProduct({ ean: eanProduct });
834
921
  }
835
922
  }, [eanProduct, setTargetProduct]);
836
923
  const handleAuthorizationRequest = useCallback2(async () => {
@@ -843,7 +930,7 @@ function PBM({
843
930
  console.error("Error fetching authorization:", error);
844
931
  }
845
932
  }, [clientID]);
846
- useEffect3(() => {
933
+ useEffect4(() => {
847
934
  handleAuthorizationRequest();
848
935
  }, [handleAuthorizationRequest]);
849
936
  return /* @__PURE__ */ jsxs10(Container_default, { variant: "main", children: [
@@ -867,7 +954,7 @@ function PBM({
867
954
  state === "isEmpty" && loading && /* @__PURE__ */ jsx15(Loading_default, {}),
868
955
  state === "isInvalid" && !loading && /* @__PURE__ */ jsx15(SecurityNumberInvalid_default, {}),
869
956
  state === "isRegistered" && !loading && /* @__PURE__ */ jsx15(SecurityNumberRegitered_default, {}),
870
- state === "isActivated" && !loading && /* @__PURE__ */ jsx15(BenefitsTable_default, { originalProductPrice: formatedOriginalProductPrice })
957
+ state === "isActivated" && !loading && /* @__PURE__ */ jsx15(BenefitsTable_default, {})
871
958
  ] }),
872
959
  /* @__PURE__ */ jsx15(Footer_default, {})
873
960
  ] });