@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.d.mts CHANGED
@@ -24,7 +24,17 @@ interface usePBMTypes {
24
24
  }
25
25
  interface IProduct {
26
26
  ean: string;
27
- quantity: number;
27
+ quantity?: number;
28
+ sku?: string;
29
+ skuId?: string;
30
+ price?: number;
31
+ listPrice?: number;
32
+ stockBalance?: number;
33
+ productName?: string;
34
+ productId?: string;
35
+ availabilityText?: string;
36
+ brandName?: string;
37
+ categoryName?: string;
28
38
  }
29
39
 
30
40
  interface PBMStore extends usePBMTypes {
package/dist/index.d.ts CHANGED
@@ -24,7 +24,17 @@ interface usePBMTypes {
24
24
  }
25
25
  interface IProduct {
26
26
  ean: string;
27
- quantity: number;
27
+ quantity?: number;
28
+ sku?: string;
29
+ skuId?: string;
30
+ price?: number;
31
+ listPrice?: number;
32
+ stockBalance?: number;
33
+ productName?: string;
34
+ productId?: string;
35
+ availabilityText?: string;
36
+ brandName?: string;
37
+ categoryName?: string;
28
38
  }
29
39
 
30
40
  interface PBMStore extends usePBMTypes {
package/dist/index.js CHANGED
@@ -141,7 +141,7 @@ var GetProductByEAN = async ({ PRODUCT_EAN }) => {
141
141
  }
142
142
  });
143
143
  const dataResponse = await response.json();
144
- if (!dataResponse.sucesso) {
144
+ if (!dataResponse.success) {
145
145
  throw new Error(dataResponse.message || "Failed to fetch authorization");
146
146
  }
147
147
  return dataResponse;
@@ -150,22 +150,27 @@ var GetProductByEAN = async ({ PRODUCT_EAN }) => {
150
150
  // src/components/Footer/index.tsx
151
151
  var import_jsx_runtime3 = require("react/jsx-runtime");
152
152
  function Footer() {
153
- const [industryLogo, setIndustryLogo] = (0, import_react2.useState)(void 0);
154
- const { targetProduct } = usePBMStore();
153
+ const [industryLogo, setIndustryLogo] = (0, import_react2.useState)(null);
154
+ const { targetProduct, setTargetProduct } = usePBMStore();
155
155
  (0, import_react2.useEffect)(() => {
156
156
  const fetchProductByEan = async () => {
157
- if (!targetProduct) return;
157
+ if (!targetProduct?.ean) return;
158
158
  try {
159
159
  const response = await GetProductByEAN({ PRODUCT_EAN: targetProduct.ean });
160
- if (response.sucesso && response.dados) {
161
- setIndustryLogo(response.dados.pbm.imageLink);
160
+ if (response.success && response.data) {
161
+ setIndustryLogo(response.data.pbm.imageLink);
162
+ const { pbm, sku, ...targetProductNewData } = response.data;
163
+ setTargetProduct({
164
+ ...targetProduct,
165
+ ...targetProductNewData
166
+ });
162
167
  }
163
168
  } catch (error) {
164
169
  console.error(error);
165
170
  }
166
171
  };
167
172
  fetchProductByEan();
168
- }, [targetProduct]);
173
+ }, [targetProduct?.ean]);
169
174
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("footer", { className: "w-full h-auto relative", id: "footer_pbm", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: (0, import_classnames2.default)("flex items-center w-full h-auto gap-4", { "justify-center": industryLogo, "justify-start": !industryLogo }), children: [
170
175
  /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "w-4/5 h-auto", children: [
171
176
  /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h3", { className: "text-start font-semibold text-sm", children: "Economize com o benef\xEDcio do laborat\xF3rio." }),
@@ -188,7 +193,7 @@ var Footer_default = Footer;
188
193
 
189
194
  // src/schema/validation-schema.ts
190
195
  var import_zod = require("zod");
191
- var validationSchema = import_zod.z.strictObject({
196
+ var validationSchema = import_zod.z.object({
192
197
  securityNumber: import_zod.z.string({
193
198
  required_error: "CPF \xE9 obrigat\xF3rio."
194
199
  }).refine((doc) => {
@@ -198,7 +203,7 @@ var validationSchema = import_zod.z.strictObject({
198
203
  const replacedDoc = doc.replace(/\D/g, "");
199
204
  return !!Number(replacedDoc);
200
205
  }, "CPF deve conter apenas n\xFAmeros."),
201
- coupon: import_zod.z.string().min(0)
206
+ coupon: import_zod.z.string({ required_error: "Cupom / ID do Cart\xE3o obrigat\xF3rio." }).optional()
202
207
  });
203
208
 
204
209
  // src/utils/format.ts
@@ -270,14 +275,21 @@ function Form({ setLoading }) {
270
275
  handleSubmit,
271
276
  register,
272
277
  setValue,
278
+ clearErrors,
279
+ unregister,
273
280
  formState: { errors }
274
281
  } = (0, import_react_hook_form.useForm)({
275
282
  resolver: (0, import_zod2.zodResolver)(validationSchema),
283
+ mode: "onSubmit",
276
284
  defaultValues: {
277
- securityNumber: securityNumber || ""
285
+ securityNumber: securityNumber || "",
286
+ coupon: ""
278
287
  }
279
288
  });
280
289
  const onSubmitDefault = async (values) => {
290
+ if (!showCoupoField) {
291
+ setValue("coupon", void 0, { shouldValidate: false });
292
+ }
281
293
  setLoading(true);
282
294
  try {
283
295
  if (targetProduct === null) {
@@ -286,7 +298,7 @@ function Form({ setLoading }) {
286
298
  }
287
299
  const response = await ValidateDocument({
288
300
  document: values.securityNumber.replace(/\D/g, ""),
289
- products: [{ ean: targetProduct.ean, quantity: targetProduct.quantity }]
301
+ products: [{ ean: targetProduct.ean, quantity: 1 }]
290
302
  });
291
303
  if (response.success) {
292
304
  const status = {
@@ -310,7 +322,7 @@ function Form({ setLoading }) {
310
322
  onSubmit: handleSubmit(onSubmitDefault),
311
323
  className: (0, import_classnames4.default)(
312
324
  "w-full h-auto flex items-center justify-center mb-0 transition-all duration-150",
313
- { "mb-4": errors.securityNumber || errors.coupon, "gap-2": showCoupoField }
325
+ { "mb-4": errors.securityNumber || errors.coupon && showCoupoField, "gap-2": showCoupoField }
314
326
  ),
315
327
  id: "form_security_number_pbm",
316
328
  children: [
@@ -364,12 +376,12 @@ function Form({ setLoading }) {
364
376
  { "outline outline-red-600": errors.coupon, "rounded-full": showCoupoField }
365
377
  ),
366
378
  placeholder: "Cupom / ID do Cart\xE3o",
367
- required: true,
368
- maxLength: 14,
369
379
  ...register("coupon", {
380
+ required: showCoupoField ? "Cupom / ID do Cart\xE3o obrigat\xF3rio." : false,
381
+ shouldUnregister: !showCoupoField,
370
382
  onChange: (e) => {
371
383
  setValue("coupon", e.target.value, {
372
- shouldValidate: true
384
+ shouldValidate: showCoupoField
373
385
  });
374
386
  }
375
387
  }),
@@ -399,7 +411,14 @@ function Form({ setLoading }) {
399
411
  Button_default,
400
412
  {
401
413
  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",
402
- onClick: () => setShowCoupoField(!showCoupoField),
414
+ onClick: () => {
415
+ const newValue = !showCoupoField;
416
+ setShowCoupoField(newValue);
417
+ if (!newValue) {
418
+ unregister("coupon");
419
+ clearErrors("coupon");
420
+ }
421
+ },
403
422
  id: "check_benefits_button",
404
423
  children: [
405
424
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { children: !showCoupoField ? "Possui cupom?" : "N\xE3o possui cupom?" }),
@@ -439,31 +458,6 @@ var Loading_default = Loading;
439
458
  // src/components/BenefitsTable/index.tsx
440
459
  var import_react5 = require("react");
441
460
 
442
- // src/mocks/benefits.ts
443
- var BENEFITS_ITEMS = [
444
- {
445
- id: 1,
446
- ean: "001",
447
- authorizedQuantity: 1,
448
- discountValue: 4800,
449
- discountPercentual: 2400
450
- },
451
- {
452
- id: 2,
453
- ean: "002",
454
- authorizedQuantity: 2,
455
- discountValue: 4800,
456
- discountPercentual: 2400
457
- },
458
- {
459
- id: 3,
460
- ean: "003",
461
- authorizedQuantity: 3,
462
- discountValue: 9400,
463
- discountPercentual: 4700
464
- }
465
- ];
466
-
467
461
  // src/components/UI/Title/index.tsx
468
462
  var import_classnames5 = __toESM(require("classnames"));
469
463
  var import_jsx_runtime7 = require("react/jsx-runtime");
@@ -488,13 +482,13 @@ var Title_default = Title;
488
482
  var import_lucide_react2 = require("lucide-react");
489
483
  var import_react4 = require("react");
490
484
  var import_jsx_runtime8 = require("react/jsx-runtime");
491
- function Item({ data, onChange, checked, originalProductPrice }) {
485
+ function Item({ data, onChange, checked }) {
492
486
  const { setAvailableDiscountSelected, securityNumber } = usePBMStore();
493
487
  const ID_INPUT = "unity_quantity_" + data.authorizedQuantity;
494
- const decimalDiscount = data.discountPercentual / 1e4;
495
- const unitDiscountValue = originalProductPrice * decimalDiscount;
488
+ const decimalDiscount = data.discountPercentual / 100;
489
+ const unitDiscountValue = data.grossPrice * decimalDiscount;
496
490
  const discountValue = unitDiscountValue * data.authorizedQuantity;
497
- const totalPriceProductWithDiscountBenefit = originalProductPrice * data.authorizedQuantity - discountValue;
491
+ const totalPriceProductWithDiscountBenefit = data.grossPrice * data.authorizedQuantity - discountValue;
498
492
  const updateStorageData = (0, import_react4.useCallback)(() => {
499
493
  if (checked) {
500
494
  const roundToTwoDecimals = (value) => Math.round(value * 100) / 100;
@@ -566,13 +560,104 @@ function Item({ data, onChange, checked, originalProductPrice }) {
566
560
  }
567
561
  var Item_default = Item;
568
562
 
563
+ // src/services/benefits-without-document.ts
564
+ var import_js_cookie3 = __toESM(require("js-cookie"));
565
+ var import_meta3 = {};
566
+ var CheckBenefistWithoutDocument = async ({ products }) => {
567
+ const API_URL = import_meta3.env.VITE_API_URL;
568
+ if (!API_URL) {
569
+ throw new Error("API URL is not defined in environment variables");
570
+ }
571
+ const AUTH_TOKEN = import_js_cookie3.default.get("pbm-token");
572
+ if (!AUTH_TOKEN) {
573
+ throw new Error("Token is not defined in cookies or is expired");
574
+ }
575
+ const response = await fetch(`${API_URL}/products/genericBenefit`, {
576
+ method: "POST",
577
+ headers: {
578
+ Authorization: `Bearer ${AUTH_TOKEN}`,
579
+ "Content-Type": "application/json"
580
+ },
581
+ body: JSON.stringify({ products })
582
+ });
583
+ const dataResponse = await response.json();
584
+ if (!dataResponse.success) {
585
+ throw new Error(dataResponse.message || "Failed to fetch benefits without document");
586
+ }
587
+ return dataResponse;
588
+ };
589
+
569
590
  // src/components/BenefitsTable/index.tsx
570
591
  var import_jsx_runtime9 = require("react/jsx-runtime");
571
- function BenefitsTable({
572
- originalProductPrice
573
- }) {
574
- const { securityNumber, setState } = usePBMStore();
592
+ function BenefitsTable() {
593
+ const { securityNumber, setState, targetProduct } = usePBMStore();
575
594
  const [selectedDiscout, setSelectedDiscount] = (0, import_react5.useState)(null);
595
+ const [loading, setLoading] = (0, import_react5.useState)(true);
596
+ const [benefitsItems, setBenefitsItems] = (0, import_react5.useState)();
597
+ (0, import_react5.useEffect)(() => {
598
+ const fetchDicountsWithoutDocument = async () => {
599
+ if (!targetProduct?.productId) {
600
+ console.error("PBMLOG: Product ID is not defined on targetProduct");
601
+ return;
602
+ }
603
+ if (!targetProduct.ean) {
604
+ console.error("PBMLOG: EAN is not defined on targetProduct");
605
+ return;
606
+ }
607
+ if (!targetProduct.listPrice) {
608
+ console.error("PBMLOG: List Price is not defined on targetProduct");
609
+ return;
610
+ }
611
+ if (!targetProduct.price) {
612
+ console.error("PBMLOG: Price is not defined on targetProduct");
613
+ return;
614
+ }
615
+ try {
616
+ const data = {
617
+ productId: Number(targetProduct.productId),
618
+ ean: targetProduct.ean,
619
+ requestedQuantity: 1,
620
+ listPrice: targetProduct.listPrice,
621
+ netPrice: targetProduct.price
622
+ };
623
+ const response = await CheckBenefistWithoutDocument({ products: [data] });
624
+ if (response.success && response.data) {
625
+ setBenefitsItems(response.data);
626
+ } else {
627
+ setBenefitsItems(void 0);
628
+ }
629
+ } catch (error) {
630
+ setBenefitsItems(void 0);
631
+ console.error(error);
632
+ } finally {
633
+ setLoading(false);
634
+ }
635
+ };
636
+ const fetchDiscountWithDocument = async () => {
637
+ console.log("consulta feita com documento");
638
+ };
639
+ securityNumber ? fetchDiscountWithDocument() : fetchDicountsWithoutDocument();
640
+ }, []);
641
+ if (loading) {
642
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("main", { className: "flex items-center justify-center gap-4", id: "loading_pbm", children: [
643
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
644
+ "div",
645
+ {
646
+ "data-testid": "test_id_spin",
647
+ className: "w-8 h-8 border-4 border-t-gray-700 border-gray-300 rounded-full animate-spin",
648
+ id: "loading_spin"
649
+ }
650
+ ),
651
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
652
+ "p",
653
+ {
654
+ className: "text-sm font-semibold text-start text-zinc-900",
655
+ id: "loading_label",
656
+ children: "Buscando beneficios dispon\xEDveis..."
657
+ }
658
+ )
659
+ ] });
660
+ }
576
661
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
577
662
  "section",
578
663
  {
@@ -580,31 +665,34 @@ function BenefitsTable({
580
665
  id: "benefits_table_pbm",
581
666
  children: [
582
667
  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Title_default, { children: "Descontos dispon\xEDveis:" }),
583
- /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
668
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
584
669
  "form",
585
670
  {
586
671
  className: "flex flex-col items-center justify-start w-full gap-3",
587
672
  id: "form_benefits_table_pbm",
588
- children: BENEFITS_ITEMS.map((item, index) => {
589
- const ID_INPUT = "unity_quantity_" + item.authorizedQuantity;
590
- return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
591
- Item_default,
592
- {
593
- data: item,
594
- checked: selectedDiscout === ID_INPUT,
595
- onChange: () => setSelectedDiscount(ID_INPUT),
596
- originalProductPrice
597
- },
598
- index
599
- );
600
- })
673
+ children: [
674
+ !benefitsItems && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("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." }),
675
+ benefitsItems && benefitsItems.map((item, index) => {
676
+ const ID_INPUT = "unity_quantity_" + item.authorizedQuantity;
677
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
678
+ Item_default,
679
+ {
680
+ data: item,
681
+ checked: selectedDiscout === ID_INPUT,
682
+ onChange: () => setSelectedDiscount(ID_INPUT)
683
+ },
684
+ index
685
+ );
686
+ }),
687
+ benefitsItems && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("p", { className: "w-full text-sm font-semibold text-center text-zinc-600", id: "benefits_empty_pbm", children: benefitsItems[0].informativeMessage })
688
+ ]
601
689
  }
602
690
  ),
603
691
  !securityNumber && /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
604
692
  Button_default,
605
693
  {
606
694
  onClick: () => setState("isEmpty"),
607
- 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",
695
+ className: "bg-transparent p-0 w-auto h-auto text-zinc-600 cursor-pointer hover:text-zinc-900 hover:bg-transparent text-start",
608
696
  id: "unauthorized_benefits_button",
609
697
  children: [
610
698
  "Aten\xE7\xE3o: n\xE3o \xE9 poss\xEDvel utilizar os benef\xEDcos sem realizar a consulta do cpf, por favor",
@@ -815,12 +903,12 @@ function SecurityNumberRegitered({ textColor }) {
815
903
  var SecurityNumberRegitered_default = SecurityNumberRegitered;
816
904
 
817
905
  // src/services/authorization.ts
818
- var import_js_cookie3 = __toESM(require("js-cookie"));
819
- var import_meta3 = {};
906
+ var import_js_cookie4 = __toESM(require("js-cookie"));
907
+ var import_meta4 = {};
820
908
  var GetAuthorization = async ({ clientID }) => {
821
- const API_URL = import_meta3.env.VITE_API_URL;
822
- const STORE_ID = import_meta3.env.VITE_STORE_ID;
823
- const STORE_NAME = import_meta3.env.VITE_STORE_NAME;
909
+ const API_URL = import_meta4.env.VITE_API_URL;
910
+ const STORE_ID = import_meta4.env.VITE_STORE_ID;
911
+ const STORE_NAME = import_meta4.env.VITE_STORE_NAME;
824
912
  if (!API_URL) {
825
913
  throw new Error("API URL is not defined in environment variables");
826
914
  }
@@ -833,22 +921,22 @@ var GetAuthorization = async ({ clientID }) => {
833
921
  "Content-Type": "application/json"
834
922
  },
835
923
  body: JSON.stringify({
836
- StoreID: STORE_ID,
837
- StoreName: STORE_NAME,
838
- ClientID: clientID
924
+ storeId: STORE_ID,
925
+ storeName: STORE_NAME,
926
+ clientId: clientID
839
927
  })
840
928
  });
841
929
  const dataResponse = await response.json();
842
930
  if (!dataResponse.success) {
843
931
  throw new Error(dataResponse.message || "Failed to fetch authorization");
844
932
  }
845
- import_js_cookie3.default.set("pbm-token", dataResponse.data.Token, {
846
- expires: dataResponse.data.ExpiresIn / (60 * 60),
933
+ import_js_cookie4.default.set("pbm-token", dataResponse.data.token, {
934
+ expires: dataResponse.data.expiresIn / (60 * 60),
847
935
  secure: true,
848
936
  sameSite: "Strict"
849
937
  });
850
- import_js_cookie3.default.set("pbm-token-refresh", dataResponse.data.RefreshToken, {
851
- expires: dataResponse.data.RefreshExpiresIn / (60 * 60),
938
+ import_js_cookie4.default.set("pbm-token-refresh", dataResponse.data.refreshToken, {
939
+ expires: dataResponse.data.refreshExpiresIn / (60 * 60),
852
940
  secure: true,
853
941
  sameSite: "Strict"
854
942
  });
@@ -870,7 +958,7 @@ function PBM({
870
958
  const { setState, state, setTargetProduct } = usePBMStore();
871
959
  (0, import_react7.useEffect)(() => {
872
960
  if (eanProduct) {
873
- setTargetProduct({ ean: eanProduct, quantity: 1 });
961
+ setTargetProduct({ ean: eanProduct });
874
962
  }
875
963
  }, [eanProduct, setTargetProduct]);
876
964
  const handleAuthorizationRequest = (0, import_react7.useCallback)(async () => {
@@ -907,7 +995,7 @@ function PBM({
907
995
  state === "isEmpty" && loading && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Loading_default, {}),
908
996
  state === "isInvalid" && !loading && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(SecurityNumberInvalid_default, {}),
909
997
  state === "isRegistered" && !loading && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(SecurityNumberRegitered_default, {}),
910
- state === "isActivated" && !loading && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(BenefitsTable_default, { originalProductPrice: formatedOriginalProductPrice })
998
+ state === "isActivated" && !loading && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(BenefitsTable_default, {})
911
999
  ] }),
912
1000
  /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Footer_default, {})
913
1001
  ] });