@clickmax/checkout-react 12.5.17 → 12.5.19

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.js CHANGED
@@ -79,6 +79,38 @@ function readError(status, body) {
79
79
  }
80
80
 
81
81
 
82
+ const getGetCheckoutSocialProofUrl = (params)=>{
83
+ const normalizedParams = new URLSearchParams();
84
+ Object.entries(params || {}).forEach(([key, value])=>{
85
+ if (value !== undefined) {
86
+ normalizedParams.append(key, value === null ? 'null' : String(value));
87
+ }
88
+ });
89
+ const stringifiedParams = normalizedParams.toString();
90
+ return stringifiedParams.length > 0 ? `/checkout/offer/social-proof?${stringifiedParams}` : `/checkout/offer/social-proof`;
91
+ };
92
+ const getCheckoutSocialProof = async (params, options)=>{
93
+ return http(getGetCheckoutSocialProofUrl(params), {
94
+ ...options,
95
+ method: 'GET'
96
+ });
97
+ };
98
+ const getGetCheckoutRecentActivityUrl = (params)=>{
99
+ const normalizedParams = new URLSearchParams();
100
+ Object.entries(params || {}).forEach(([key, value])=>{
101
+ if (value !== undefined) {
102
+ normalizedParams.append(key, value === null ? 'null' : String(value));
103
+ }
104
+ });
105
+ const stringifiedParams = normalizedParams.toString();
106
+ return stringifiedParams.length > 0 ? `/checkout/offer/recent-activity?${stringifiedParams}` : `/checkout/offer/recent-activity`;
107
+ };
108
+ const getCheckoutRecentActivity = async (params, options)=>{
109
+ return http(getGetCheckoutRecentActivityUrl(params), {
110
+ ...options,
111
+ method: 'GET'
112
+ });
113
+ };
82
114
  const getOfferCheckoutUrl = ()=>{
83
115
  return `/checkout/offer`;
84
116
  };
@@ -268,6 +300,58 @@ const validateCheckoutCoupon = async (validateCheckoutCouponBody, options)=>{
268
300
  body: JSON.stringify(validateCheckoutCouponBody)
269
301
  });
270
302
  };
303
+ const getCheckCheckoutOfferEligibilityUrl = ()=>{
304
+ return `/checkout/offer/eligibility`;
305
+ };
306
+ const checkCheckoutOfferEligibility = async (checkCheckoutOfferEligibilityBody, options)=>{
307
+ const getHeaders = (h)=>{
308
+ if (!h) return {};
309
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
310
+ if (Symbol.iterator in h) {
311
+ return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
312
+ }
313
+ const headers = {};
314
+ for (const [name, value] of Object.entries(h)){
315
+ if (value !== undefined) headers[name] = value;
316
+ }
317
+ return headers;
318
+ };
319
+ return http(getCheckCheckoutOfferEligibilityUrl(), {
320
+ ...options,
321
+ method: 'POST',
322
+ headers: {
323
+ 'Content-Type': 'application/json',
324
+ ...getHeaders(options?.headers)
325
+ },
326
+ body: JSON.stringify(checkCheckoutOfferEligibilityBody)
327
+ });
328
+ };
329
+ const getFindCheckoutAutoCouponUrl = ()=>{
330
+ return `/checkout/coupon/auto`;
331
+ };
332
+ const findCheckoutAutoCoupon = async (findCheckoutAutoCouponBody, options)=>{
333
+ const getHeaders = (h)=>{
334
+ if (!h) return {};
335
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
336
+ if (Symbol.iterator in h) {
337
+ return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
338
+ }
339
+ const headers = {};
340
+ for (const [name, value] of Object.entries(h)){
341
+ if (value !== undefined) headers[name] = value;
342
+ }
343
+ return headers;
344
+ };
345
+ return http(getFindCheckoutAutoCouponUrl(), {
346
+ ...options,
347
+ method: 'POST',
348
+ headers: {
349
+ 'Content-Type': 'application/json',
350
+ ...getHeaders(options?.headers)
351
+ },
352
+ body: JSON.stringify(findCheckoutAutoCouponBody)
353
+ });
354
+ };
271
355
  const getGetCheckoutPricingUrl = ()=>{
272
356
  return `/checkout/pricing`;
273
357
  };
@@ -354,6 +438,10 @@ function publicOfferQuery({ bumps, bumpTitle, mode, ...rest }) {
354
438
  }),
355
439
  getPurchaseStatus: (jobId, options)=>getCheckoutStatus(jobId, call(options)),
356
440
  getPurchaseDetails: (transactionId, options)=>getCheckoutDetails(transactionId, call(options)),
441
+ getSocialProof: (params, options)=>getCheckoutSocialProof(params, call(options)),
442
+ getRecentActivity: (params, options)=>getCheckoutRecentActivity(params, call(options)),
443
+ findAutoCoupon: async (body, options)=>(await findCheckoutAutoCoupon(body, call(options))).coupon,
444
+ checkEligibility: (body, options)=>checkCheckoutOfferEligibility(body, call(options)),
357
445
  trackLead: async (body, options)=>{
358
446
  await trackCheckoutLeads(body, call(options));
359
447
  },
@@ -741,9 +829,43 @@ const PT_BR = {
741
829
  purchaseTimeout: 'A compra está demorando. Confira seu e-mail antes de tentar de novo.',
742
830
  pixExpired: 'O código pix expirou. Gere outro.',
743
831
  offerBuyerNotEligible: 'Esta oferta não está disponível para este e-mail.',
832
+ checkoutUnavailableTitle: 'Produto temporariamente indisponível',
833
+ checkoutUnavailable: 'Este produto não está disponível para compra no momento. Para mais informações, entre em contato com o suporte do vendedor',
834
+ offerPendingApproval: 'O checkout estará liberado para vendas assim que o produto for aprovado pela moderação.',
835
+ trialUnavailable: 'Este e-mail já usou o período de teste deste produto. A primeira cobrança será feita hoje.',
836
+ affiliateAccountNotice: 'Ao comprar, você ganha uma conta Clickmax gratuita para indicar este produto e ganhar comissão.',
744
837
  includedInOrder: 'Incluído no seu pedido',
745
838
  specialOffer: 'Oferta especial',
746
- specialOffers: 'Ofertas especiais'
839
+ specialOffers: 'Ofertas especiais',
840
+ perMonth: '/mês',
841
+ perYear: '/ano',
842
+ perQuarter: '/trimestre',
843
+ perSemester: '/semestre',
844
+ freeTrial: 'Grátis por {days} dias.',
845
+ postTrialPrice: 'Após este período, o valor da sua assinatura será de {price}.',
846
+ postTrialInstallments: 'Após este período, sua assinatura será cobrada em {installments}x de {value} ({price}).',
847
+ chargeLimit: 'Assinatura com {count} cobranças, contando a de hoje. Depois ela encerra sozinha.',
848
+ chargeLimitSingle: 'Cobrança única: a assinatura não renova.',
849
+ bumpTrialHighlight: '{free} por {days} dias',
850
+ bumpTrialAfter: 'Depois, {price}',
851
+ socialProofRegion: 'Atividade na oferta',
852
+ socialProofClose: 'Fechar avisos',
853
+ socialProofExtraItem: 'um item extra',
854
+ socialProofViewsOne: '**1 visualização** {window}',
855
+ socialProofViewsOther: '**{n} visualizações** {window}',
856
+ socialProofPurchasesOne: '**1 pessoa** comprou {window}',
857
+ socialProofPurchasesOther: '**{n} pessoas** compraram {window}',
858
+ socialProofOrderBumpOne: '**1 pessoa** também levou {item} {window}',
859
+ socialProofOrderBumpOther: '**{n} pessoas** também levaram {item} {window}',
860
+ socialProofWindow10m: 'nos últimos 10 min',
861
+ socialProofWindow1h: 'na última hora',
862
+ socialProofWindow12h: 'nas últimas 12h',
863
+ socialProofWindow24h: 'nas últimas 24h',
864
+ socialProofWindow48h: 'nas últimas 48h',
865
+ socialProofWindow7d: 'nos últimos 7 dias',
866
+ socialProofActionPurchase: 'comprou',
867
+ socialProofActionPix: 'gerou um Pix',
868
+ socialProofActionBoleto: 'gerou um boleto'
747
869
  };
748
870
  const EN = {
749
871
  required: 'Required',
@@ -763,9 +885,43 @@ const EN = {
763
885
  purchaseTimeout: 'The purchase is taking long. Check your email before trying again.',
764
886
  pixExpired: 'The pix code expired. Generate a new one.',
765
887
  offerBuyerNotEligible: 'This offer is not available for this email.',
888
+ checkoutUnavailableTitle: 'Product temporarily unavailable',
889
+ checkoutUnavailable: 'This product is not available for purchase at the moment. For more information, please contact the seller support',
890
+ offerPendingApproval: 'The checkout opens for sales as soon as the product is approved.',
891
+ trialUnavailable: 'This email has already used the free trial for this product. The first charge happens today.',
892
+ affiliateAccountNotice: 'By purchasing, you get a free Clickmax account to recommend this product and earn commission.',
766
893
  includedInOrder: 'Included in your order',
767
894
  specialOffer: 'Special offer',
768
- specialOffers: 'Special offers'
895
+ specialOffers: 'Special offers',
896
+ perMonth: '/month',
897
+ perYear: '/year',
898
+ perQuarter: '/quarter',
899
+ perSemester: '/semester',
900
+ freeTrial: 'Free for {days} days.',
901
+ postTrialPrice: 'After this period, your subscription will be {price}.',
902
+ postTrialInstallments: 'After this period, your subscription will be charged in {installments}x of {value} ({price}).',
903
+ chargeLimit: 'Subscription with {count} charges, including today’s. After that it ends on its own.',
904
+ chargeLimitSingle: 'Single charge: the subscription does not renew.',
905
+ bumpTrialHighlight: '{free} for {days} days',
906
+ bumpTrialAfter: 'Then {price}',
907
+ socialProofRegion: 'Offer activity',
908
+ socialProofClose: 'Close notifications',
909
+ socialProofExtraItem: 'an extra item',
910
+ socialProofViewsOne: '**1 view** {window}',
911
+ socialProofViewsOther: '**{n} views** {window}',
912
+ socialProofPurchasesOne: '**1 person** purchased {window}',
913
+ socialProofPurchasesOther: '**{n} people** purchased {window}',
914
+ socialProofOrderBumpOne: '**1 person** also added {item} {window}',
915
+ socialProofOrderBumpOther: '**{n} people** also added {item} {window}',
916
+ socialProofWindow10m: 'in the last 10 min',
917
+ socialProofWindow1h: 'in the last hour',
918
+ socialProofWindow12h: 'in the last 12 hours',
919
+ socialProofWindow24h: 'in the last 24 hours',
920
+ socialProofWindow48h: 'in the last 48 hours',
921
+ socialProofWindow7d: 'in the last 7 days',
922
+ socialProofActionPurchase: 'bought',
923
+ socialProofActionPix: 'generated a Pix',
924
+ socialProofActionBoleto: 'generated a boleto'
769
925
  };
770
926
  const ES = {
771
927
  required: 'Campo obligatorio',
@@ -785,9 +941,43 @@ const ES = {
785
941
  purchaseTimeout: 'La compra está tardando. Revisa tu correo antes de intentar de nuevo.',
786
942
  pixExpired: 'El código pix expiró. Genera otro.',
787
943
  offerBuyerNotEligible: 'Esta oferta no está disponible para este correo.',
944
+ checkoutUnavailableTitle: 'Producto temporalmente no disponible',
945
+ checkoutUnavailable: 'Este producto no está disponible para la compra en este momento. Para más información, contacta al soporte del vendedor',
946
+ offerPendingApproval: 'El checkout se habilitará para ventas en cuanto se apruebe el producto.',
947
+ trialUnavailable: 'Este correo ya usó el período de prueba de este producto. El primer cobro se hace hoy.',
948
+ affiliateAccountNotice: 'Al comprar, recibes una cuenta Clickmax gratuita para recomendar este producto y ganar comisión.',
788
949
  includedInOrder: 'Incluido en tu pedido',
789
950
  specialOffer: 'Oferta especial',
790
- specialOffers: 'Ofertas especiales'
951
+ specialOffers: 'Ofertas especiales',
952
+ perMonth: '/mes',
953
+ perYear: '/año',
954
+ perQuarter: '/trimestre',
955
+ perSemester: '/semestre',
956
+ freeTrial: 'Gratis por {days} días.',
957
+ postTrialPrice: 'Después de este período, tu suscripción costará {price}.',
958
+ postTrialInstallments: 'Después de este período, tu suscripción se cobrará en {installments}x de {value} ({price}).',
959
+ chargeLimit: 'Suscripción con {count} cobros, incluido el de hoy. Después termina sola.',
960
+ chargeLimitSingle: 'Cobro único: la suscripción no se renueva.',
961
+ bumpTrialHighlight: '{free} por {days} días',
962
+ bumpTrialAfter: 'Después, {price}',
963
+ socialProofRegion: 'Actividad en la oferta',
964
+ socialProofClose: 'Cerrar avisos',
965
+ socialProofExtraItem: 'un artículo extra',
966
+ socialProofViewsOne: '**1 visualización** {window}',
967
+ socialProofViewsOther: '**{n} visualizaciones** {window}',
968
+ socialProofPurchasesOne: '**1 persona** compró {window}',
969
+ socialProofPurchasesOther: '**{n} personas** compraron {window}',
970
+ socialProofOrderBumpOne: '**1 persona** también llevó {item} {window}',
971
+ socialProofOrderBumpOther: '**{n} personas** también llevaron {item} {window}',
972
+ socialProofWindow10m: 'en los últimos 10 min',
973
+ socialProofWindow1h: 'en la última hora',
974
+ socialProofWindow12h: 'en las últimas 12 h',
975
+ socialProofWindow24h: 'en las últimas 24 h',
976
+ socialProofWindow48h: 'en las últimas 48 h',
977
+ socialProofWindow7d: 'en los últimos 7 días',
978
+ socialProofActionPurchase: 'compró',
979
+ socialProofActionPix: 'generó un Pix',
980
+ socialProofActionBoleto: 'generó un boleto'
791
981
  };
792
982
  const BY_LOCALE = {
793
983
  'pt-BR': PT_BR,
@@ -821,6 +1011,330 @@ const LANGUAGE = {
821
1011
  }).format(cents / 100);
822
1012
  }
823
1013
 
1014
+ /**
1015
+ * A generated pix lives only in React state: without this, reloading the page goes back to the
1016
+ * form, polling stops and `onApproved` never fires, so the funnel does not move on (the sale itself
1017
+ * still lands through the webhook). Mirrors the standard checkout.
1018
+ *
1019
+ * `sessionStorage` on purpose: it survives a reload in the same tab and never shows one buyer's
1020
+ * pix to another person on the same browser. Keyed by page path and offer, so two checkouts of the
1021
+ * same offer on different pages do not share a pix. Only read in effects (never during render).
1022
+ */ const VERSION = 1;
1023
+ /** Without an expiry from the API, the longest the backend allows (Pix Automático, 30 min). */ const FALLBACK_TTL_MS = 30 * 60000;
1024
+ function storageKey(offerHash) {
1025
+ if (typeof window === 'undefined') return undefined;
1026
+ return `cx.checkout.pix:${window.location.pathname}:${offerHash}`;
1027
+ }
1028
+ function storage() {
1029
+ try {
1030
+ return window.sessionStorage;
1031
+ } catch {
1032
+ // Blocked storage (private mode, third-party iframe): no restore, the checkout still works.
1033
+ return undefined;
1034
+ }
1035
+ }
1036
+ const isRecord = (value)=>typeof value === 'object' && value !== null;
1037
+ /** Saves only what the pix screen shows; nothing about the buyer. */ function savePendingPix(offerHash, pix) {
1038
+ const key = storageKey(offerHash);
1039
+ if (!key) return;
1040
+ const { transactionId, code, qrcodeUrl, totalAmount, expiresAt } = pix;
1041
+ try {
1042
+ storage()?.setItem(key, JSON.stringify({
1043
+ v: VERSION,
1044
+ savedAt: Date.now(),
1045
+ pix: {
1046
+ transactionId,
1047
+ code,
1048
+ qrcodeUrl,
1049
+ totalAmount,
1050
+ expiresAt: expiresAt?.toISOString()
1051
+ }
1052
+ }));
1053
+ } catch {
1054
+ // Quota or blocked storage: no restore.
1055
+ }
1056
+ }
1057
+ function clearPendingPix(offerHash) {
1058
+ const key = storageKey(offerHash);
1059
+ if (!key) return;
1060
+ try {
1061
+ storage()?.removeItem(key);
1062
+ } catch {
1063
+ // idem
1064
+ }
1065
+ }
1066
+ /** The pending pix of this page and offer while it is still payable; drops stale entries. */ function readPendingPix(offerHash, now = Date.now()) {
1067
+ const key = storageKey(offerHash);
1068
+ if (!key) return undefined;
1069
+ let raw;
1070
+ try {
1071
+ raw = storage()?.getItem(key);
1072
+ } catch {
1073
+ return undefined;
1074
+ }
1075
+ if (!raw) return undefined;
1076
+ const pix = parse(raw, now);
1077
+ if (!pix) clearPendingPix(offerHash);
1078
+ return pix;
1079
+ }
1080
+ /** Rebuilt field by field: nothing from storage reaches the screen without its type checked. */ function parse(raw, now) {
1081
+ let data;
1082
+ try {
1083
+ data = JSON.parse(raw);
1084
+ } catch {
1085
+ return undefined;
1086
+ }
1087
+ if (!isRecord(data) || data.v !== VERSION) return undefined;
1088
+ // `savedAt` drives the fallback expiry; NaN or Infinity would keep a dead pix on screen.
1089
+ if (typeof data.savedAt !== 'number' || !Number.isFinite(data.savedAt) || data.savedAt < 0) {
1090
+ return undefined;
1091
+ }
1092
+ const { pix } = data;
1093
+ if (!isRecord(pix)) return undefined;
1094
+ const { transactionId, code, qrcodeUrl, totalAmount, expiresAt } = pix;
1095
+ if (typeof transactionId !== 'string' || typeof code !== 'string' || typeof qrcodeUrl !== 'string' || typeof totalAmount !== 'number' || !Number.isInteger(totalAmount) || expiresAt !== undefined && typeof expiresAt !== 'string') {
1096
+ return undefined;
1097
+ }
1098
+ const expiry = expiresAt ? Date.parse(expiresAt) : Number.NaN;
1099
+ const deadline = Number.isNaN(expiry) ? data.savedAt + FALLBACK_TTL_MS : expiry;
1100
+ if (now >= deadline) return undefined;
1101
+ return {
1102
+ transactionId,
1103
+ code,
1104
+ qrcodeUrl,
1105
+ totalAmount,
1106
+ expiresAt: Number.isNaN(expiry) ? undefined : new Date(expiry),
1107
+ restored: true
1108
+ };
1109
+ }
1110
+
1111
+
1112
+ /** Replaces `{name}` tokens of a message. Unknown tokens stay as typed. */ function fillMessage(template, values) {
1113
+ return template.replace(/\{(\w+)\}/g, (token, name)=>Object.hasOwn(values, name) ? String(values[name]) : token);
1114
+ }
1115
+ /**
1116
+ * Suffix of a recurring price ("/mês"). `semi-annually` is how the database spells it and
1117
+ * `semiannual` shows up on older offers; both mean every six months. An unknown frequency gets no
1118
+ * suffix: imprecise is better than a wrong "/month".
1119
+ */ function perFrequency(messages, frequency) {
1120
+ switch(frequency){
1121
+ case 'monthly':
1122
+ return messages.perMonth;
1123
+ case 'yearly':
1124
+ return messages.perYear;
1125
+ case 'quarterly':
1126
+ return messages.perQuarter;
1127
+ case 'semi-annually':
1128
+ case 'semiannual':
1129
+ return messages.perSemester;
1130
+ default:
1131
+ return '';
1132
+ }
1133
+ }
1134
+ /** Charge limit notice; `undefined` when the subscription renews until canceled. */ function chargeLimitText(messages, maxCharges) {
1135
+ if (maxCharges == null) return undefined;
1136
+ if (maxCharges === 1) return messages.chargeLimitSingle;
1137
+ return fillMessage(messages.chargeLimit, {
1138
+ count: maxCharges
1139
+ });
1140
+ }
1141
+ /**
1142
+ * "After this period..." sentence of a free trial. It follows the installment the buyer picked
1143
+ * (count, installment value and cycle total) or the cash price at 1x, and the suffix follows the
1144
+ * frequency, so an annual plan never reads "/month".
1145
+ */ function postTrialText(messages, locale, input) {
1146
+ const { cashValue, installment, installmentValue, per } = input;
1147
+ if (installment <= 1 || !installmentValue) {
1148
+ return fillMessage(messages.postTrialPrice, {
1149
+ price: `${formatMoney(cashValue, locale)}${per}`
1150
+ });
1151
+ }
1152
+ return fillMessage(messages.postTrialInstallments, {
1153
+ installments: installment,
1154
+ value: formatMoney(installmentValue, locale),
1155
+ price: `${formatMoney(installmentValue * installment, locale)}${per}`
1156
+ });
1157
+ }
1158
+ // The seller's editor suggests the token in their own language ({dias}/{days}, {preço}/{price}),
1159
+ // and people typing by hand drop the accent; every spelling resolves to the same value.
1160
+ const DAYS_TOKEN = /\{(dias|días|days)\}/gi;
1161
+ const PRICE_TOKEN = /\{(preço|preco|precio|price)\}/gi;
1162
+ /**
1163
+ * Texts of an order bump with a free trial: the highlight ("R$ 0,00 por 30 dias") and the later
1164
+ * charge ("Depois, R$ 497,00/mês"). Seller texts (`configs.orderBump.trialTexts[bumpId]`) win
1165
+ * over the defaults; their price token already carries the frequency suffix.
1166
+ */ function bumpTrialTexts(messages, locale, input) {
1167
+ const priceText = `${formatMoney(input.price, locale)}${perFrequency(messages, input.frequency)}`;
1168
+ const resolve = (template)=>template.replace(DAYS_TOKEN, String(input.days)).replace(PRICE_TOKEN, priceText);
1169
+ return {
1170
+ highlight: resolve(input.custom?.highlight?.trim() || fillMessage(messages.bumpTrialHighlight, {
1171
+ free: formatMoney(0, locale),
1172
+ days: '{days}'
1173
+ })),
1174
+ after: resolve(input.custom?.after?.trim() || messages.bumpTrialAfter)
1175
+ };
1176
+ }
1177
+
1178
+ // Same rules as the standard checkout (`entities/social-proof` in pages/payments). The minimum
1179
+ // per type and the window are applied by the API; the client orders, caps and rotates.
1180
+ // Purchases first: the strongest proof.
1181
+ const TYPE_ORDER = [
1182
+ 'purchases',
1183
+ 'views',
1184
+ 'orderBumpPurchases'
1185
+ ];
1186
+ /** Counts in display order, capped at `maxBalloons`. */ function orderCounts(items, maxBalloons) {
1187
+ return [
1188
+ ...items
1189
+ ].sort((a, b)=>TYPE_ORDER.indexOf(a.type) - TYPE_ORDER.indexOf(b.type)).slice(0, Number.isFinite(maxBalloons) ? Math.max(0, maxBalloons) : 0);
1190
+ }
1191
+ /**
1192
+ * Next balloon: the newest activity not shown yet, otherwise the next count. Picked when it is
1193
+ * shown, so an event that arrives by polling takes the next slot. `maxBalloons` caps the total.
1194
+ */ function pickNext(input) {
1195
+ const { counts, activity, seenIds, countsShown, maxBalloons } = input;
1196
+ if (seenIds.length + countsShown >= maxBalloons) return undefined;
1197
+ const fresh = activity.find((entry)=>!seenIds.includes(entry.id));
1198
+ if (fresh) return {
1199
+ kind: 'activity',
1200
+ activity: fresh
1201
+ };
1202
+ const item = counts[countsShown];
1203
+ return item && {
1204
+ kind: 'count',
1205
+ item
1206
+ };
1207
+ }
1208
+ // Same key as the standard checkout: closing the balloons there or here hides them in both.
1209
+ const dismissedKey = (offerHash)=>`cx-social-proof-dismissed:${offerHash}`;
1210
+ function readDismissed(offerHash) {
1211
+ try {
1212
+ return sessionStorage.getItem(dismissedKey(offerHash)) !== null;
1213
+ } catch {
1214
+ return false;
1215
+ }
1216
+ }
1217
+ function writeDismissed(offerHash) {
1218
+ try {
1219
+ sessionStorage.setItem(dismissedKey(offerHash), '1');
1220
+ } catch {
1221
+ // Blocked storage: the balloons stay closed only on this page.
1222
+ }
1223
+ }
1224
+ const MAX_ITEM_NAME = 28;
1225
+ function textFromParts(parts) {
1226
+ return parts.map((part)=>part.text).join('');
1227
+ }
1228
+ /** Splits `**bold**` markers of a message into parts. */ function toParts(template) {
1229
+ return template.split('**').map((text, index)=>({
1230
+ text,
1231
+ strong: index % 2 === 1
1232
+ })).filter((part)=>part.text !== '');
1233
+ }
1234
+ const WINDOW_MESSAGE = {
1235
+ '10m': 'socialProofWindow10m',
1236
+ '1h': 'socialProofWindow1h',
1237
+ '12h': 'socialProofWindow12h',
1238
+ '24h': 'socialProofWindow24h',
1239
+ '48h': 'socialProofWindow48h',
1240
+ '7d': 'socialProofWindow7d'
1241
+ };
1242
+ const COUNT_MESSAGE = {
1243
+ views: [
1244
+ 'socialProofViewsOne',
1245
+ 'socialProofViewsOther'
1246
+ ],
1247
+ purchases: [
1248
+ 'socialProofPurchasesOne',
1249
+ 'socialProofPurchasesOther'
1250
+ ],
1251
+ orderBumpPurchases: [
1252
+ 'socialProofOrderBumpOne',
1253
+ 'socialProofOrderBumpOther'
1254
+ ]
1255
+ };
1256
+ const ACTION_MESSAGE = {
1257
+ purchase: 'socialProofActionPurchase',
1258
+ pix: 'socialProofActionPix',
1259
+ boleto: 'socialProofActionBoleto'
1260
+ };
1261
+ /**
1262
+ * Balloon of a count. `bumpName` is the name of the offer's only order bump; with more than one,
1263
+ * the text falls back to "an extra item".
1264
+ */ function countBalloon(item, messages, bumpName, id) {
1265
+ const [one, other] = COUNT_MESSAGE[item.type];
1266
+ // `window` comes from the API: without the own-key check, `constructor` would read the prototype.
1267
+ const windowText = Object.hasOwn(WINDOW_MESSAGE, item.window) ? messages[WINDOW_MESSAGE[item.window]] : item.window;
1268
+ // A `*` in the bump name would close the bold too early.
1269
+ const chars = Array.from(bumpName?.replaceAll('*', '') ?? '');
1270
+ const itemName = chars.length > MAX_ITEM_NAME ? `${chars.slice(0, MAX_ITEM_NAME).join('')}…` : chars.join('');
1271
+ const template = messages[item.count === 1 ? one : other].replace('{n}', ()=>String(item.count)).replace('{window}', ()=>windowText).replace('{item}', ()=>itemName || messages.socialProofExtraItem);
1272
+ const parts = toParts(template);
1273
+ return {
1274
+ id,
1275
+ kind: 'count',
1276
+ icon: item.type,
1277
+ parts,
1278
+ text: textFromParts(parts),
1279
+ place: undefined,
1280
+ time: undefined
1281
+ };
1282
+ }
1283
+ function countryName(code, locale) {
1284
+ try {
1285
+ return new Intl.DisplayNames([
1286
+ locale
1287
+ ], {
1288
+ type: 'region'
1289
+ }).of(code);
1290
+ } catch {
1291
+ // Not an ISO alpha-2 code: the country drops out instead of breaking the balloon.
1292
+ return undefined;
1293
+ }
1294
+ }
1295
+ // Browser time zone. pt-BR "09h47" (as the standard checkout), en "1:21 PM", es "13:21".
1296
+ function formatTime(iso, locale) {
1297
+ const date = new Date(iso);
1298
+ if (locale === 'en') {
1299
+ return new Intl.DateTimeFormat('en-US', {
1300
+ hour: 'numeric',
1301
+ minute: '2-digit'
1302
+ }).format(date);
1303
+ }
1304
+ const time = new Intl.DateTimeFormat(locale, {
1305
+ hour: '2-digit',
1306
+ minute: '2-digit',
1307
+ hourCycle: 'h23'
1308
+ }).format(date);
1309
+ return locale === 'pt-BR' ? time.replace(':', 'h') : time;
1310
+ }
1311
+ /** Balloon of a recent purchase or charge. The name already comes masked from the API. */ function activityBalloon(activity, messages, locale) {
1312
+ const country = activity.country ? countryName(activity.country, locale) : undefined;
1313
+ const place = [
1314
+ activity.city,
1315
+ country
1316
+ ].filter(Boolean).join(', ');
1317
+ const parts = [
1318
+ {
1319
+ text: activity.name,
1320
+ strong: true
1321
+ },
1322
+ {
1323
+ text: ` ${messages[ACTION_MESSAGE[activity.action]]}`,
1324
+ strong: false
1325
+ }
1326
+ ];
1327
+ return {
1328
+ id: activity.id,
1329
+ kind: 'activity',
1330
+ icon: activity.action,
1331
+ parts,
1332
+ text: textFromParts(parts),
1333
+ place: place || undefined,
1334
+ time: formatTime(activity.occurredAt, locale)
1335
+ };
1336
+ }
1337
+
824
1338
  /** Digits only. */ function onlyDigits(value) {
825
1339
  return value.replace(/\D/g, '');
826
1340
  }
@@ -950,6 +1464,35 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
950
1464
  return errors;
951
1465
  }
952
1466
 
1467
+ const LOOKUP_TIMEOUT_MS = 8000;
1468
+ /**
1469
+ * Default lookup: ViaCEP, the public service the standard checkout uses. Called straight from the
1470
+ * browser (no payments route), so it works on any host.
1471
+ */ const viaCepLookup = async (zipCode, { signal })=>{
1472
+ // A hung ViaCEP must not leave the address form in `loading` forever.
1473
+ const response = await fetch(`https://viacep.com.br/ws/${encodeURIComponent(zipCode)}/json/`, {
1474
+ signal: AbortSignal.any([
1475
+ signal,
1476
+ AbortSignal.timeout(LOOKUP_TIMEOUT_MS)
1477
+ ])
1478
+ });
1479
+ if (!response.ok) throw new Error(`ViaCEP answered ${response.status}`);
1480
+ const data = await response.json();
1481
+ // ViaCEP answers 200 with `{ erro: true }` for a zip code that does not exist.
1482
+ if (typeof data !== 'object' || data === null || 'erro' in data) return undefined;
1483
+ const text = (key)=>{
1484
+ const value = data[key];
1485
+ return typeof value === 'string' && value ? value : undefined;
1486
+ };
1487
+ return {
1488
+ street: text('logradouro'),
1489
+ neighborhood: text('bairro'),
1490
+ city: text('localidade'),
1491
+ state: text('uf')
1492
+ };
1493
+ };
1494
+
1495
+
953
1496
 
954
1497
 
955
1498
 
@@ -1077,6 +1620,7 @@ async function waitForJob(state, jobId) {
1077
1620
  method: 'pix',
1078
1621
  isUpsell: state.offer.isOTO
1079
1622
  };
1623
+ clearPendingPix(state.offer.hash);
1080
1624
  state.setSubmission((value)=>({
1081
1625
  ...value,
1082
1626
  status: 'approved'
@@ -1113,6 +1657,7 @@ async function waitForJob(state, jobId) {
1113
1657
  message
1114
1658
  };
1115
1659
  };
1660
+ if (state.purchaseBlocked) return fail(state.purchaseBlocked);
1116
1661
  if (!method || !state.methods.includes(method)) return fail(state.messages.methodUnavailable);
1117
1662
  if (!state.validate()) return {
1118
1663
  status: 'invalid'
@@ -1189,6 +1734,7 @@ async function waitForJob(state, jobId) {
1189
1734
  boleto: undefined,
1190
1735
  transactionId: response.id
1191
1736
  }));
1737
+ if (state.persistPendingPix) savePendingPix(state.offer.hash, pix);
1192
1738
  state.callbacks.onPixGenerated?.(pix);
1193
1739
  void watchPix(state, response.id, response.totalAmount);
1194
1740
  return {
@@ -1605,6 +2151,10 @@ function buyerSnapshot(input) {
1605
2151
 
1606
2152
 
1607
2153
 
2154
+
2155
+
2156
+
2157
+
1608
2158
  /** Base URL used when the provider gets no `transport`: the same-domain proxy of a site. */ const DEFAULT_PAYMENTS_BASE_URL = '/__clickmax/payments';
1609
2159
  const CheckoutContext = /*#__PURE__*/ createContext(null);
1610
2160
  /** Reads the checkout. Throws outside `CheckoutProvider`. */ function useCheckout() {
@@ -1622,6 +2172,12 @@ const EMPTY_ADDRESS = {
1622
2172
  state: '',
1623
2173
  country: 'BR'
1624
2174
  };
2175
+ const provider_EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
2176
+ const NO_IDS = [];
2177
+ /** Same rule as the server's coupon discount, used only to compare with an automatic coupon. */ function couponDiscount(coupon, base) {
2178
+ const value = coupon.discountValue ?? 0;
2179
+ return coupon.discountType === 'percentage' ? Math.round(base * (value / 100)) : Math.min(value, base);
2180
+ }
1625
2181
  const IDLE_SUBMISSION = {
1626
2182
  status: 'idle',
1627
2183
  error: undefined,
@@ -1662,7 +2218,7 @@ function staticInstallments(offer) {
1662
2218
  * session id, affiliate status), the server pricing and an initial coupon, and only the parts that
1663
2219
  * depend on them re-render.
1664
2220
  */ function CheckoutProvider(props) {
1665
- const { offer, transport, paymentsOrigin, location: locationProp, locale = 'pt-BR', messages: messageOverrides, initialPricing, requireEmailConfirmation = false, children } = props;
2221
+ const { offer, transport, paymentsOrigin, location: locationProp, locale = 'pt-BR', messages: messageOverrides, initialPricing, requireEmailConfirmation = false, restorePendingPix = true, children } = props;
1666
2222
  const location = locationProp ?? {};
1667
2223
  const baseUrl = transport?.baseUrl ?? DEFAULT_PAYMENTS_BASE_URL;
1668
2224
  const api = useMemo(()=>createCheckoutApi({
@@ -1773,6 +2329,7 @@ function staticInstallments(offer) {
1773
2329
  phone: current.phone || `+${telephone.countryCode} ${telephone.areaCode}${telephone.number}`,
1774
2330
  document: current.document || (oneClickData.document ?? '')
1775
2331
  }));
2332
+ if (address.zipCode) lookedUpZip.current = onlyDigits(address.zipCode);
1776
2333
  setAddressValues((current)=>current.zipCode ? current : {
1777
2334
  zipCode: address.zipCode ?? '',
1778
2335
  street: address.street ?? '',
@@ -1816,6 +2373,123 @@ function staticInstallments(offer) {
1816
2373
  addressValues,
1817
2374
  messages
1818
2375
  ]);
2376
+ // Zip code lookup. A zip code that came with saved one-click data is not looked up again, so
2377
+ // the buyer's own street is not replaced by the generic one of the zip code.
2378
+ const zipCodeLookup = props.zipCodeLookup === undefined ? viaCepLookup : props.zipCodeLookup;
2379
+ const lookupZip = onlyDigits(addressValues.zipCode);
2380
+ const lookedUpZip = useRef('');
2381
+ const [zipLookup, setZipLookup] = useState({
2382
+ status: 'idle'
2383
+ });
2384
+ useEffect(()=>{
2385
+ if (!zipCodeLookup || isForeign || !addressRequired) return;
2386
+ if (lookupZip.length !== 8 || lookupZip === lookedUpZip.current) return;
2387
+ const controller = new AbortController();
2388
+ const timer = setTimeout(()=>{
2389
+ lookedUpZip.current = lookupZip;
2390
+ setZipLookup({
2391
+ status: 'loading'
2392
+ });
2393
+ zipCodeLookup(lookupZip, {
2394
+ signal: controller.signal
2395
+ }).then((found)=>{
2396
+ // A custom lookup may ignore the signal: a stale answer must not fill the new zip code.
2397
+ if (controller.signal.aborted) return;
2398
+ setZipLookup({
2399
+ status: found ? 'success' : 'error'
2400
+ });
2401
+ if (!found) return;
2402
+ const filled = Object.fromEntries(Object.entries(found).filter(([, value])=>value));
2403
+ setAddressValues((current)=>({
2404
+ ...current,
2405
+ ...filled
2406
+ }));
2407
+ setAddressErrors((current)=>({
2408
+ ...current,
2409
+ ...Object.fromEntries(Object.keys(filled).map((key)=>[
2410
+ key,
2411
+ undefined
2412
+ ]))
2413
+ }));
2414
+ }).catch(()=>{
2415
+ if (controller.signal.aborted) return;
2416
+ // Typing the address by hand still works; a later edit of the zip code retries.
2417
+ lookedUpZip.current = '';
2418
+ setZipLookup({
2419
+ status: 'error'
2420
+ });
2421
+ });
2422
+ }, 300);
2423
+ return ()=>{
2424
+ clearTimeout(timer);
2425
+ controller.abort();
2426
+ };
2427
+ }, [
2428
+ zipCodeLookup,
2429
+ isForeign,
2430
+ addressRequired,
2431
+ lookupZip
2432
+ ]);
2433
+ // endregion
2434
+ // region Settled email and eligibility
2435
+ // The email the automatic coupon and the audience check run against. It settles 600 ms after
2436
+ // typing stops, so a keystroke fires no request; an incomplete email keeps the last valid one
2437
+ // (the coupon must not blink while the buyer fixes a letter), an empty field clears it.
2438
+ const typedEmail = personalDataActive ? personalValues.email.trim().toLowerCase() : oneClickData?.email.trim().toLowerCase() ?? '';
2439
+ const [settledEmail, setSettledEmail] = useState('');
2440
+ useEffect(()=>{
2441
+ if (!typedEmail) {
2442
+ setSettledEmail('');
2443
+ return;
2444
+ }
2445
+ if (!provider_EMAIL.test(typedEmail)) return;
2446
+ const timer = setTimeout(()=>setSettledEmail(typedEmail), 600);
2447
+ return ()=>clearTimeout(timer);
2448
+ }, [
2449
+ typedEmail
2450
+ ]);
2451
+ const restrictedBumpIds = useMemo(()=>offer.orderBumps.filter((bump)=>bump.isAudienceRestricted).map((bump)=>bump.id), [
2452
+ offer.orderBumps
2453
+ ]);
2454
+ // A trial is once per buyer and product: an email that used it is charged right away.
2455
+ const hasTrial = Boolean(offer.methods.recurrence?.gracePeriod);
2456
+ const checksEligibility = offer.isAudienceRestricted || restrictedBumpIds.length > 0 || hasTrial;
2457
+ const [eligibilityAnswer, setEligibilityAnswer] = useState(undefined);
2458
+ useEffect(()=>{
2459
+ if (!checksEligibility || !settledEmail) return;
2460
+ const controller = new AbortController();
2461
+ api.checkEligibility({
2462
+ offerHash: offer.hash,
2463
+ buyerEmail: settledEmail,
2464
+ orderBumpIds: restrictedBumpIds
2465
+ }, {
2466
+ signal: controller.signal
2467
+ }).then((data)=>setEligibilityAnswer({
2468
+ offer: offer.hash,
2469
+ email: settledEmail,
2470
+ data
2471
+ })).catch(()=>{
2472
+ // No answer blocks nothing: the purchase route refuses an ineligible buyer anyway.
2473
+ });
2474
+ return ()=>controller.abort();
2475
+ }, [
2476
+ api,
2477
+ offer.hash,
2478
+ checksEligibility,
2479
+ settledEmail,
2480
+ restrictedBumpIds
2481
+ ]);
2482
+ // An answer counts only for the offer and email it was asked for: the host may swap the offer.
2483
+ const eligibilityData = settledEmail && eligibilityAnswer?.email === settledEmail && eligibilityAnswer.offer === offer.hash ? eligibilityAnswer.data : undefined;
2484
+ const eligibility = useMemo(()=>({
2485
+ offerBlocked: offer.isAudienceRestricted && eligibilityData?.eligible === false,
2486
+ ineligibleBumpIds: eligibilityData?.ineligibleOrderBumpIds ?? NO_IDS,
2487
+ trialAvailable: !(hasTrial && eligibilityData?.trialAvailable === false)
2488
+ }), [
2489
+ offer.isAudienceRestricted,
2490
+ eligibilityData,
2491
+ hasTrial
2492
+ ]);
1819
2493
  // endregion
1820
2494
  // region Order bumps
1821
2495
  const requiredBumpIds = useMemo(()=>offer.configs?.orderBump.required.filter((id)=>offer.orderBumps.some((b)=>b.id === id)) ?? [], [
@@ -1823,15 +2497,19 @@ function staticInstallments(offer) {
1823
2497
  offer.orderBumps
1824
2498
  ]);
1825
2499
  const [optionalBumpIds, setOptionalBumpIds] = useState([]);
2500
+ // A bump outside the buyer's audience leaves the order, required or not: the purchase would
2501
+ // refuse it, and the buyer can still buy the offer without it.
1826
2502
  const selectedBumpIds = useMemo(()=>[
1827
- ...requiredBumpIds,
1828
- ...optionalBumpIds.filter((id)=>!requiredBumpIds.includes(id))
2503
+ ...requiredBumpIds.filter((id)=>!eligibility.ineligibleBumpIds.includes(id)),
2504
+ ...optionalBumpIds.filter((id)=>!requiredBumpIds.includes(id) && !eligibility.ineligibleBumpIds.includes(id))
1829
2505
  ], [
1830
2506
  requiredBumpIds,
1831
- optionalBumpIds
2507
+ optionalBumpIds,
2508
+ eligibility.ineligibleBumpIds
1832
2509
  ]);
1833
2510
  const toggleBump = useCallback((id, selected)=>{
1834
2511
  if (requiredBumpIds.includes(id)) return;
2512
+ if (selected !== false && eligibility.ineligibleBumpIds.includes(id)) return;
1835
2513
  setOptionalBumpIds((current)=>{
1836
2514
  const isSelected = current.includes(id);
1837
2515
  const next = selected ?? !isSelected;
@@ -1842,16 +2520,18 @@ function staticInstallments(offer) {
1842
2520
  ] : current.filter((value)=>value !== id);
1843
2521
  });
1844
2522
  }, [
1845
- requiredBumpIds
2523
+ requiredBumpIds,
2524
+ eligibility.ineligibleBumpIds
1846
2525
  ]);
1847
2526
  // endregion
1848
2527
  // region Coupon and pricing
1849
2528
  const [couponCode, setCouponCode] = useState(undefined);
2529
+ const [couponSource, setCouponSource] = useState(undefined);
1850
2530
  const [couponStatus, setCouponStatus] = useState('idle');
1851
2531
  const [couponResult, setCouponResult] = useState(undefined);
1852
2532
  const couponRequest = useRef(0);
1853
- const buyerEmail = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(personalValues.email.trim()) ? personalValues.email.trim().toLowerCase() : oneClickData?.email;
1854
- const applyCoupon = useCallback(async (code)=>{
2533
+ const buyerEmail = provider_EMAIL.test(personalValues.email.trim()) ? personalValues.email.trim().toLowerCase() : oneClickData?.email;
2534
+ const applyCouponFrom = useCallback(async (code, source)=>{
1855
2535
  const normalized = code.trim().toUpperCase();
1856
2536
  if (!normalized) return false;
1857
2537
  const request = ++couponRequest.current;
@@ -1867,11 +2547,13 @@ function staticInstallments(offer) {
1867
2547
  setCouponResult(result);
1868
2548
  setCouponStatus(result.valid ? 'valid' : 'invalid');
1869
2549
  setCouponCode(result.valid ? normalized : undefined);
2550
+ setCouponSource(result.valid ? source : undefined);
1870
2551
  return result.valid;
1871
2552
  } catch {
1872
2553
  if (request === couponRequest.current) {
1873
2554
  setCouponStatus('invalid');
1874
2555
  setCouponCode(undefined);
2556
+ setCouponSource(undefined);
1875
2557
  }
1876
2558
  return false;
1877
2559
  }
@@ -1880,23 +2562,106 @@ function staticInstallments(offer) {
1880
2562
  offer.hash,
1881
2563
  buyerEmail
1882
2564
  ]);
1883
- const removeCoupon = useCallback(()=>{
2565
+ const applyCoupon = useCallback((code)=>applyCouponFrom(code, 'manual'), [
2566
+ applyCouponFrom
2567
+ ]);
2568
+ const clearCoupon = useCallback(()=>{
1884
2569
  couponRequest.current++;
1885
2570
  setCouponCode(undefined);
2571
+ setCouponSource(undefined);
1886
2572
  setCouponResult(undefined);
1887
2573
  setCouponStatus('idle');
1888
2574
  }, []);
2575
+ // The buyer removing an automatic coupon keeps it off for that email.
2576
+ const dismissedAutoEmail = useRef('');
2577
+ const removeCoupon = useCallback(()=>{
2578
+ if (couponSource === 'auto') dismissedAutoEmail.current = settledEmail;
2579
+ clearCoupon();
2580
+ }, [
2581
+ couponSource,
2582
+ settledEmail,
2583
+ clearCoupon
2584
+ ]);
1889
2585
  // A coupon from the link is applied once, after hydration (it is per visit, not per page).
1890
2586
  const initialCoupon = location.couponCode;
1891
2587
  const appliedInitialCoupon = useRef(false);
1892
2588
  useEffect(()=>{
1893
2589
  if (appliedInitialCoupon.current || !initialCoupon || !offer.showCoupon) return;
1894
2590
  appliedInitialCoupon.current = true;
1895
- void applyCoupon(initialCoupon);
2591
+ void applyCouponFrom(initialCoupon, 'link');
1896
2592
  }, [
1897
2593
  initialCoupon,
1898
2594
  offer.showCoupon,
1899
- applyCoupon
2595
+ applyCouponFrom
2596
+ ]);
2597
+ // Automatic coupon: each settled email asks the server for the best coupon the seller reserved
2598
+ // for it. The effect below decides whether it replaces the coupon already applied.
2599
+ const [autoCandidate, setAutoCandidate] = useState(undefined);
2600
+ useEffect(()=>{
2601
+ if (!settledEmail) return;
2602
+ const controller = new AbortController();
2603
+ api.findAutoCoupon({
2604
+ offerHash: offer.hash,
2605
+ buyerEmail: settledEmail
2606
+ }, {
2607
+ signal: controller.signal
2608
+ }).then((coupon)=>setAutoCandidate({
2609
+ offer: offer.hash,
2610
+ email: settledEmail,
2611
+ coupon
2612
+ })).catch(()=>{
2613
+ // A failure only means no automatic discount.
2614
+ if (!controller.signal.aborted) setAutoCandidate({
2615
+ offer: offer.hash,
2616
+ email: settledEmail,
2617
+ coupon: null
2618
+ });
2619
+ });
2620
+ return ()=>controller.abort();
2621
+ }, [
2622
+ api,
2623
+ offer.hash,
2624
+ settledEmail
2625
+ ]);
2626
+ useEffect(()=>{
2627
+ if (!autoCandidate || autoCandidate.email !== settledEmail || autoCandidate.offer !== offer.hash) return;
2628
+ if (couponStatus === 'validating') return;
2629
+ const applied = couponStatus === 'valid' && couponCode !== undefined;
2630
+ const candidate = autoCandidate.coupon;
2631
+ if (!candidate) {
2632
+ // Switched to an email with no right to it: drop the discount that was only for the last.
2633
+ if (applied && couponSource === 'auto') clearCoupon();
2634
+ return;
2635
+ }
2636
+ if (dismissedAutoEmail.current === settledEmail) return;
2637
+ if (applied) {
2638
+ if (couponSource === 'auto' && couponCode === candidate.code) return;
2639
+ if (couponSource !== 'auto') {
2640
+ // A typed or link coupon still waiting for the email check: let that check decide.
2641
+ if (couponResult?.pendingBuyerCheck) return;
2642
+ if (couponResult && couponDiscount(couponResult, offerPrice(offer)) >= candidate.discount) return;
2643
+ }
2644
+ }
2645
+ couponRequest.current++;
2646
+ setCouponCode(candidate.code);
2647
+ setCouponSource('auto');
2648
+ setCouponResult({
2649
+ valid: true,
2650
+ code: candidate.code,
2651
+ discountType: candidate.discountType,
2652
+ discountValue: candidate.discountValue,
2653
+ pendingBuyerCheck: false
2654
+ });
2655
+ setCouponStatus('valid');
2656
+ }, [
2657
+ autoCandidate,
2658
+ settledEmail,
2659
+ couponStatus,
2660
+ couponCode,
2661
+ couponSource,
2662
+ couponResult,
2663
+ offer,
2664
+ clearCoupon
1900
2665
  ]);
1901
2666
  const [pricing, setPricing] = useState({
1902
2667
  status: initialPricing ? 'success' : 'idle',
@@ -2034,6 +2799,20 @@ function staticInstallments(offer) {
2034
2799
  const [cardHolderName, setCardHolderName] = useState('');
2035
2800
  const [card, registerCard] = useState(undefined);
2036
2801
  // endregion
2802
+ // region Recurrence
2803
+ const offerRecurrence = 'recurrence' in offer.methods ? offer.methods.recurrence : undefined;
2804
+ const recurrence = useMemo(()=>offerRecurrence ? {
2805
+ frequency: offerRecurrence.frequency,
2806
+ interval: offerRecurrence.interval,
2807
+ // A buyer who already used the product's trial pays today, like the standard checkout.
2808
+ gracePeriod: eligibility.trialAvailable ? offerRecurrence.gracePeriod : 0,
2809
+ tolerancePeriod: offerRecurrence.tolerancePeriod,
2810
+ maxCharges: offerRecurrence.maxCharges ?? null
2811
+ } : undefined, [
2812
+ offerRecurrence,
2813
+ eligibility.trialAvailable
2814
+ ]);
2815
+ // endregion
2037
2816
  const tracking = useCheckoutTracking({
2038
2817
  api,
2039
2818
  offer,
@@ -2107,14 +2886,27 @@ function staticInstallments(offer) {
2107
2886
  recurrenceFrequency: bump.recurrenceFrequency,
2108
2887
  selected: selectedBumpIds.includes(bump.id),
2109
2888
  required: requiredBumpIds.includes(bump.id),
2110
- disabled: method ? !bump.paymentMethods[method] : false
2889
+ ineligible: eligibility.ineligibleBumpIds.includes(bump.id),
2890
+ disabled: eligibility.ineligibleBumpIds.includes(bump.id) || (method ? !bump.paymentMethods[method] : false),
2891
+ trial: bump.gracePeriod > 0 ? {
2892
+ days: bump.gracePeriod,
2893
+ ...bumpTrialTexts(messages, locale, {
2894
+ custom: offer.configs?.orderBump.trialTexts?.[bump.id],
2895
+ days: bump.gracePeriod,
2896
+ price: bumpPrice(bump),
2897
+ frequency: bump.recurrenceFrequency
2898
+ })
2899
+ } : undefined
2111
2900
  }));
2112
2901
  }, [
2113
2902
  offer,
2114
2903
  pricing.data?.items,
2115
2904
  selectedBumpIds,
2116
2905
  requiredBumpIds,
2117
- method
2906
+ method,
2907
+ eligibility,
2908
+ messages,
2909
+ locale
2118
2910
  ]);
2119
2911
  const requiredBumps = useMemo(()=>bumpItems.filter((bump)=>bump.required), [
2120
2912
  bumpItems
@@ -2125,6 +2917,45 @@ function staticInstallments(offer) {
2125
2917
  // Empty title falls back to the translated default: older pages have no title.
2126
2918
  const bumpTitle = offer.configs?.orderBump.title?.trim() || (optionalBumps.length > 1 ? messages.specialOffers : messages.specialOffer);
2127
2919
  // endregion
2920
+ // region Availability and notices
2921
+ const availability = useMemo(()=>({
2922
+ status: offer.isSellerPending || offer.isOfferUnavailable ? 'unavailable' : offer.isAnyOfferPending ? 'pendingApproval' : 'available',
2923
+ supportEmail: offer.supportEmail || undefined
2924
+ }), [
2925
+ offer.isSellerPending,
2926
+ offer.isOfferUnavailable,
2927
+ offer.isAnyOfferPending,
2928
+ offer.supportEmail
2929
+ ]);
2930
+ const notices = useMemo(()=>{
2931
+ const list = [];
2932
+ const notice = (kind, message, extra = {})=>list.push({
2933
+ kind,
2934
+ message,
2935
+ title: undefined,
2936
+ supportEmail: undefined,
2937
+ ...extra
2938
+ });
2939
+ if (availability.status === 'unavailable') {
2940
+ notice('unavailable', messages.checkoutUnavailable, {
2941
+ title: messages.checkoutUnavailableTitle,
2942
+ supportEmail: availability.supportEmail
2943
+ });
2944
+ } else if (availability.status === 'pendingApproval') {
2945
+ notice('pendingApproval', messages.offerPendingApproval);
2946
+ }
2947
+ if (eligibility.offerBlocked) notice('offerIneligible', messages.offerBuyerNotEligible);
2948
+ else if (!eligibility.trialAvailable) notice('trialUnavailable', messages.trialUnavailable);
2949
+ if (offer.showAffiliateAccountNotice) notice('affiliateAccount', messages.affiliateAccountNotice);
2950
+ return list;
2951
+ }, [
2952
+ availability,
2953
+ eligibility,
2954
+ offer.showAffiliateAccountNotice,
2955
+ messages
2956
+ ]);
2957
+ const purchaseBlocked = availability.status === 'unavailable' ? messages.checkoutUnavailableTitle : availability.status === 'pendingApproval' ? messages.offerPendingApproval : eligibility.offerBlocked ? messages.offerBuyerNotEligible : undefined;
2958
+ // endregion
2128
2959
  // region Submit
2129
2960
  const [submission, setSubmissionState] = useState(IDLE_SUBMISSION);
2130
2961
  // Mirrors `submission` synchronously so a running purchase (pix polling) can tell whether the
@@ -2150,6 +2981,8 @@ function staticInstallments(offer) {
2150
2981
  callbacks,
2151
2982
  getRecaptchaToken: ()=>propsRef.current.getRecaptchaToken?.() ?? Promise.resolve(''),
2152
2983
  pixPollIntervalMs: positiveFinite(props.pixPollIntervalMs, 5000),
2984
+ persistPendingPix: restorePendingPix,
2985
+ purchaseBlocked,
2153
2986
  affiliateHash,
2154
2987
  oneClick: oneClickData,
2155
2988
  personalDataActive,
@@ -2182,12 +3015,54 @@ function staticInstallments(offer) {
2182
3015
  }, []);
2183
3016
  const reset = useCallback(()=>{
2184
3017
  attempts.current++;
3018
+ clearPendingPix(offer.hash);
2185
3019
  setSubmission(()=>IDLE_SUBMISSION);
2186
3020
  }, [
2187
3021
  attempts,
3022
+ setSubmission,
3023
+ offer.hash
3024
+ ]);
3025
+ // Back to the pix generated before a reload, after hydration (storage is browser-only). It does
3026
+ // not fire `onPixGenerated` again; polling resumes and `onApproved` fires once it is paid.
3027
+ useEffect(()=>{
3028
+ if (!restorePendingPix) return;
3029
+ const pix = readPendingPix(offer.hash);
3030
+ const state = stateRef.current;
3031
+ if (!pix || !state || submissionRef.current.status !== 'idle') return;
3032
+ setSubmission(()=>({
3033
+ ...IDLE_SUBMISSION,
3034
+ status: 'pix_pending',
3035
+ pix,
3036
+ transactionId: pix.transactionId
3037
+ }));
3038
+ void watchPix(state, pix.transactionId, pix.totalAmount);
3039
+ }, [
3040
+ restorePendingPix,
3041
+ offer.hash,
2188
3042
  setSubmission
2189
3043
  ]);
2190
3044
  // endregion
3045
+ // region Social proof
3046
+ const [socialProofDismissed, setSocialProofDismissed] = useState(false);
3047
+ // sessionStorage only after hydration (SSR contract); a new offer reads its own key.
3048
+ useEffect(()=>setSocialProofDismissed(readDismissed(offer.hash)), [
3049
+ offer.hash
3050
+ ]);
3051
+ // Once the payment is sent no balloon may show again, even after `reset` (as the standard
3052
+ // checkout): a balloon over a pix code or a refusal message distracts at the worst moment.
3053
+ const [paymentStarted, setPaymentStarted] = useState(false);
3054
+ useEffect(()=>{
3055
+ if (submission.status !== 'idle') setPaymentStarted(true);
3056
+ }, [
3057
+ submission.status
3058
+ ]);
3059
+ const dismissSocialProof = useCallback(()=>{
3060
+ writeDismissed(offer.hash);
3061
+ setSocialProofDismissed(true);
3062
+ }, [
3063
+ offer.hash
3064
+ ]);
3065
+ // endregion
2191
3066
  const value = {
2192
3067
  offer,
2193
3068
  api,
@@ -2235,7 +3110,8 @@ function staticInstallments(offer) {
2235
3110
  }));
2236
3111
  },
2237
3112
  validate: validateAddressFields,
2238
- required: addressRequired
3113
+ required: addressRequired,
3114
+ lookup: zipLookup
2239
3115
  },
2240
3116
  bumps: {
2241
3117
  items: bumpItems,
@@ -2246,9 +3122,15 @@ function staticInstallments(offer) {
2246
3122
  toggle: toggleBump
2247
3123
  },
2248
3124
  pricing,
3125
+ recurrence,
2249
3126
  summary,
3127
+ availability,
3128
+ eligibility,
3129
+ notices,
3130
+ purchaseBlocked,
2250
3131
  coupon: {
2251
3132
  code: couponCode,
3133
+ source: couponSource,
2252
3134
  status: couponStatus,
2253
3135
  result: couponResult,
2254
3136
  apply: applyCoupon,
@@ -2280,6 +3162,11 @@ function staticInstallments(offer) {
2280
3162
  registerCard,
2281
3163
  cardInteracted: tracking.cardFocused
2282
3164
  },
3165
+ socialProof: {
3166
+ enabled: Boolean(offer.socialProof?.enabled),
3167
+ stopped: socialProofDismissed || paymentStarted,
3168
+ dismiss: dismissSocialProof
3169
+ },
2283
3170
  submission,
2284
3171
  submit,
2285
3172
  reset,
@@ -2386,6 +3273,8 @@ const ELEMENTS_LOCALE = {
2386
3273
 
2387
3274
 
2388
3275
 
3276
+
3277
+
2389
3278
  /** Formats cents with the checkout locale. */ function useFormatMoney() {
2390
3279
  const { locale } = useCheckout();
2391
3280
  return useCallback((cents)=>formatMoney(cents, locale), [
@@ -2393,7 +3282,7 @@ const ELEMENTS_LOCALE = {
2393
3282
  ]);
2394
3283
  }
2395
3284
  /** Main item and price of the offer. */ function useOfferItem() {
2396
- const { offer, pricing, payment } = useCheckout();
3285
+ const { offer, pricing, payment, messages, recurrence } = useCheckout();
2397
3286
  const format = useFormatMoney();
2398
3287
  const main = pricing.data?.items.find((item)=>item.type === 'main');
2399
3288
  const price = main?.effectivePrice ?? offer.newPrice ?? offer.originalPrice;
@@ -2413,7 +3302,32 @@ const ELEMENTS_LOCALE = {
2413
3302
  installment: last.installment,
2414
3303
  value: last.value,
2415
3304
  formattedValue: format(last.value)
2416
- } : undefined
3305
+ } : undefined,
3306
+ highlightInstallment: offer.highlightInstallment,
3307
+ perFrequency: recurrence ? perFrequency(messages, recurrence.frequency) : '',
3308
+ freeTrialDays: recurrence?.gracePeriod ?? 0
3309
+ };
3310
+ }
3311
+ /** Period, free trial and charge limit of a recurring offer; `undefined` for one-time offers. */ function useRecurrence() {
3312
+ const { recurrence, messages, locale, payment } = useCheckout();
3313
+ const item = useOfferItem();
3314
+ if (!recurrence) return undefined;
3315
+ const per = perFrequency(messages, recurrence.frequency);
3316
+ const selected = payment.installments.find((option)=>option.installment === payment.installment);
3317
+ const hasTrial = recurrence.gracePeriod > 0;
3318
+ return {
3319
+ ...recurrence,
3320
+ perFrequency: per,
3321
+ trialText: hasTrial ? fillMessage(messages.freeTrial, {
3322
+ days: recurrence.gracePeriod
3323
+ }) : undefined,
3324
+ postTrialText: hasTrial ? postTrialText(messages, locale, {
3325
+ cashValue: item.price,
3326
+ installment: payment.method === 'credit' ? payment.installment : 1,
3327
+ installmentValue: selected?.value,
3328
+ per
3329
+ }) : undefined,
3330
+ chargeLimitText: chargeLimitText(messages, recurrence.maxCharges)
2417
3331
  };
2418
3332
  }
2419
3333
  /** Order bumps and their selection. */ function useOrderBumps() {
@@ -2458,12 +3372,13 @@ const ELEMENTS_LOCALE = {
2458
3372
  };
2459
3373
  }
2460
3374
  /** Purchase state and the function that submits it. */ function useSubmit() {
2461
- const { submit, reset, submission } = useCheckout();
3375
+ const { submit, reset, submission, purchaseBlocked } = useCheckout();
2462
3376
  return {
2463
3377
  submit,
2464
3378
  reset,
2465
3379
  submission,
2466
- isSubmitting: submission.status === 'submitting' || submission.status === 'processing'
3380
+ isSubmitting: submission.status === 'submitting' || submission.status === 'processing',
3381
+ blocked: purchaseBlocked
2467
3382
  };
2468
3383
  }
2469
3384
  /**
@@ -2536,6 +3451,7 @@ const ELEMENTS_LOCALE = {
2536
3451
  ]);
2537
3452
  return {
2538
3453
  pix,
3454
+ restored: Boolean(pix?.restored),
2539
3455
  secondsLeft: pix?.expiresAt && Number.isFinite(left) ? left : undefined,
2540
3456
  expired: Boolean(pix?.expiresAt) && left === 0,
2541
3457
  copy,
@@ -2571,6 +3487,168 @@ const ELEMENTS_LOCALE = {
2571
3487
  decline
2572
3488
  };
2573
3489
  }
3490
+ // Timings of the standard checkout: first balloon after 8 s, 5 s on screen, 10 s between them.
3491
+ const SOCIAL_PROOF_FIRST_DELAY_MS = 8000;
3492
+ const SOCIAL_PROOF_GAP_MS = 10000;
3493
+ const SOCIAL_PROOF_VISIBLE_MS = 5000;
3494
+ const SOCIAL_PROOF_EXIT_MS = 200;
3495
+ const RECENT_ACTIVITY_REFETCH_MS = 15000;
3496
+ /**
3497
+ * Social proof balloons of the offer, one at a time: recent purchases first (newest first), then
3498
+ * the counts (purchases, views, order bumps), up to the seller's maximum of balloons. Window and
3499
+ * minimum per type are applied by the API.
3500
+ *
3501
+ * Fetches the counts once per visit and the recent activity every 15 s, both after hydration and
3502
+ * only while mounted, so render it once per page (`SocialProof` does). Pauses while the tab is
3503
+ * hidden, and stops for good when the buyer closes it or sends the payment.
3504
+ */ function useSocialProof() {
3505
+ const { offer, api, isHydrated, messages, locale, socialProof } = useCheckout();
3506
+ const config = offer.socialProof;
3507
+ const active = isHydrated && socialProof.enabled && !socialProof.stopped;
3508
+ const activityOn = Boolean(config?.recentActivity?.enabled);
3509
+ const maxBalloons = config?.maxBalloons ?? 0;
3510
+ const [counts, setCounts] = useState([]);
3511
+ useEffect(()=>{
3512
+ if (!active) return;
3513
+ const controller = new AbortController();
3514
+ api.getSocialProof({
3515
+ offer: offer.hash
3516
+ }, {
3517
+ signal: controller.signal
3518
+ })// Failure = no count balloons; the checkout goes on.
3519
+ .then((data)=>setCounts(data.items)).catch(()=>{});
3520
+ return ()=>controller.abort();
3521
+ // Once per offer: the numbers do not refresh with the page open.
3522
+ }, [
3523
+ active,
3524
+ api,
3525
+ offer.hash
3526
+ ]);
3527
+ const [activity, setActivity] = useState([]);
3528
+ useEffect(()=>{
3529
+ if (!active || !activityOn) return;
3530
+ const controller = new AbortController();
3531
+ let timer;
3532
+ // The next request starts only after the previous one settles, so a slow answer can never
3533
+ // land after (and overwrite) a newer one.
3534
+ const load = ()=>api.getRecentActivity({
3535
+ offer: offer.hash
3536
+ }, {
3537
+ signal: controller.signal
3538
+ }).then((data)=>setActivity(data.items)).catch(()=>{}).finally(()=>{
3539
+ if (!controller.signal.aborted) timer = setTimeout(load, RECENT_ACTIVITY_REFETCH_MS);
3540
+ });
3541
+ void load();
3542
+ return ()=>{
3543
+ clearTimeout(timer);
3544
+ controller.abort();
3545
+ };
3546
+ }, [
3547
+ active,
3548
+ activityOn,
3549
+ api,
3550
+ offer.hash
3551
+ ]);
3552
+ const [hidden, setHidden] = useState(false);
3553
+ useEffect(()=>{
3554
+ if (!active) return;
3555
+ const update = ()=>setHidden(document.hidden);
3556
+ update();
3557
+ document.addEventListener('visibilitychange', update);
3558
+ return ()=>document.removeEventListener('visibilitychange', update);
3559
+ }, [
3560
+ active
3561
+ ]);
3562
+ const [progress, setProgress] = useState({
3563
+ seenIds: [],
3564
+ countsShown: 0,
3565
+ current: null
3566
+ });
3567
+ const [phase, setPhase] = useState('waiting');
3568
+ // A host that swaps the offer without remounting starts the balloons over: counts, activity and
3569
+ // progress of the previous offer must not show (or hide events) in the new checkout.
3570
+ const [stateHash, setStateHash] = useState(offer.hash);
3571
+ if (stateHash !== offer.hash) {
3572
+ setStateHash(offer.hash);
3573
+ setCounts([]);
3574
+ setActivity([]);
3575
+ setProgress({
3576
+ seenIds: [],
3577
+ countsShown: 0,
3578
+ current: null
3579
+ });
3580
+ setPhase('waiting');
3581
+ }
3582
+ const [engaged, setEngaged] = useState(false);
3583
+ useEffect(()=>{
3584
+ if (phase === 'waiting') setEngaged(false);
3585
+ }, [
3586
+ phase
3587
+ ]);
3588
+ const ordered = orderCounts(counts, maxBalloons);
3589
+ const { seenIds, countsShown, current } = progress;
3590
+ const shown = seenIds.length + countsShown;
3591
+ const next = pickNext({
3592
+ counts: ordered,
3593
+ activity,
3594
+ seenIds,
3595
+ countsShown,
3596
+ maxBalloons
3597
+ });
3598
+ // No next while waiting = queue done for now; a new event from polling reopens it.
3599
+ const paused = !active || hidden || phase === 'waiting' && !next || phase === 'visible' && engaged;
3600
+ const duration = phase === 'waiting' ? shown === 0 ? SOCIAL_PROOF_FIRST_DELAY_MS : SOCIAL_PROOF_GAP_MS : phase === 'visible' ? SOCIAL_PROOF_VISIBLE_MS : SOCIAL_PROOF_EXIT_MS;
3601
+ const step = ()=>{
3602
+ if (phase === 'waiting' && next) {
3603
+ setProgress(next.kind === 'activity' ? {
3604
+ seenIds: [
3605
+ ...seenIds,
3606
+ next.activity.id
3607
+ ],
3608
+ countsShown,
3609
+ current: next
3610
+ } : {
3611
+ seenIds,
3612
+ countsShown: countsShown + 1,
3613
+ current: next
3614
+ });
3615
+ setPhase('visible');
3616
+ } else if (phase === 'visible') setPhase('leaving');
3617
+ else setPhase('waiting');
3618
+ };
3619
+ // Pausable timeout: hovering or a hidden tab keeps the time left of the current step.
3620
+ const stepRef = useRef(step);
3621
+ stepRef.current = step;
3622
+ const remaining = useRef(duration);
3623
+ const stepKey = `${shown}-${phase}`;
3624
+ const lastKey = useRef(null);
3625
+ useEffect(()=>{
3626
+ if (lastKey.current !== stepKey) {
3627
+ lastKey.current = stepKey;
3628
+ remaining.current = duration;
3629
+ }
3630
+ if (paused) return;
3631
+ const startedAt = Date.now();
3632
+ const timer = setTimeout(()=>stepRef.current(), remaining.current);
3633
+ return ()=>{
3634
+ clearTimeout(timer);
3635
+ remaining.current -= Date.now() - startedAt;
3636
+ };
3637
+ }, [
3638
+ stepKey,
3639
+ paused,
3640
+ duration
3641
+ ]);
3642
+ const bumpName = offer.orderBumps.length === 1 ? offer.orderBumps[0]?.name : undefined;
3643
+ const balloon = active && phase !== 'waiting' && current ? current.kind === 'count' ? countBalloon(current.item, messages, bumpName, `count-${current.item.type}`) : activityBalloon(current.activity, messages, locale) : undefined;
3644
+ return {
3645
+ enabled: socialProof.enabled && !socialProof.stopped,
3646
+ balloon,
3647
+ leaving: phase === 'leaving',
3648
+ setEngaged,
3649
+ dismiss: socialProof.dismiss
3650
+ };
3651
+ }
2574
3652
 
2575
3653
 
2576
3654
 
@@ -2597,32 +3675,100 @@ const ELEMENTS_LOCALE = {
2597
3675
  "data-cx-checkout": "offer-description",
2598
3676
  children: item.description
2599
3677
  }) : null,
2600
- /*#__PURE__*/ jsx(Price, {})
3678
+ /*#__PURE__*/ jsx(Price, {}),
3679
+ /*#__PURE__*/ jsx(Recurrence, {})
2601
3680
  ]
2602
3681
  });
2603
3682
  }
2604
- /** Price of the offer, with the original price struck through when there is a discount. */ function Price({ className, children }) {
3683
+ /**
3684
+ * Price of the offer, with the original price struck through when there is a discount. A
3685
+ * subscription carries its suffix ("/mês"); during a free trial the price today is zero. When the
3686
+ * seller highlights the installment, it leads and the cash price follows (`data-highlight`).
3687
+ */ function Price({ className, children }) {
2605
3688
  const item = useOfferItem();
3689
+ const format = useFormatMoney();
2606
3690
  if (children) return children(item);
3691
+ const per = item.perFrequency;
3692
+ const installments = item.maxInstallment && item.maxInstallment.installment > 1 ? item.maxInstallment : undefined;
3693
+ if (item.freeTrialDays > 0) {
3694
+ return /*#__PURE__*/ jsx("div", {
3695
+ className: className,
3696
+ "data-cx-checkout": "price",
3697
+ "data-trial": "true",
3698
+ children: /*#__PURE__*/ jsx("strong", {
3699
+ "data-cx-checkout": "price-current",
3700
+ children: format(0)
3701
+ })
3702
+ });
3703
+ }
3704
+ const cash = /*#__PURE__*/ jsxs("strong", {
3705
+ "data-cx-checkout": "price-current",
3706
+ children: [
3707
+ item.formattedPrice,
3708
+ per
3709
+ ]
3710
+ });
3711
+ const split = installments ? /*#__PURE__*/ jsxs("span", {
3712
+ "data-cx-checkout": "price-installments",
3713
+ children: [
3714
+ installments.installment,
3715
+ "x ",
3716
+ installments.formattedValue
3717
+ ]
3718
+ }) : null;
3719
+ const highlight = Boolean(installments) && item.highlightInstallment;
2607
3720
  return /*#__PURE__*/ jsxs("div", {
2608
3721
  className: className,
2609
3722
  "data-cx-checkout": "price",
3723
+ "data-highlight": highlight || undefined,
2610
3724
  children: [
2611
- item.hasDiscount ? /*#__PURE__*/ jsx("s", {
3725
+ item.hasDiscount ? /*#__PURE__*/ jsxs("s", {
2612
3726
  "data-cx-checkout": "price-original",
2613
- children: item.formattedOriginalPrice
3727
+ children: [
3728
+ item.formattedOriginalPrice,
3729
+ per
3730
+ ]
2614
3731
  }) : null,
2615
- /*#__PURE__*/ jsx("strong", {
2616
- "data-cx-checkout": "price-current",
2617
- children: item.formattedPrice
2618
- }),
2619
- item.maxInstallment && item.maxInstallment.installment > 1 ? /*#__PURE__*/ jsxs("span", {
2620
- "data-cx-checkout": "price-installments",
3732
+ highlight ? /*#__PURE__*/ jsxs(Fragment, {
3733
+ children: [
3734
+ split,
3735
+ cash
3736
+ ]
3737
+ }) : /*#__PURE__*/ jsxs(Fragment, {
2621
3738
  children: [
2622
- item.maxInstallment.installment,
2623
- "x ",
2624
- item.maxInstallment.formattedValue
3739
+ cash,
3740
+ split
2625
3741
  ]
3742
+ })
3743
+ ]
3744
+ });
3745
+ }
3746
+ /**
3747
+ * Subscription terms: the free trial with what is charged after it (following the selected
3748
+ * installment) and the charge limit. Renders nothing for one-time offers or a subscription with
3749
+ * neither.
3750
+ */ function Recurrence({ className, children }) {
3751
+ const recurrence = useRecurrence();
3752
+ if (!recurrence) return null;
3753
+ if (children) return children(recurrence);
3754
+ if (!recurrence.trialText && !recurrence.chargeLimitText) return null;
3755
+ return /*#__PURE__*/ jsxs("div", {
3756
+ className: className,
3757
+ "data-cx-checkout": "recurrence",
3758
+ children: [
3759
+ recurrence.trialText ? /*#__PURE__*/ jsxs("p", {
3760
+ "data-cx-checkout": "recurrence-trial",
3761
+ children: [
3762
+ /*#__PURE__*/ jsx("strong", {
3763
+ children: recurrence.trialText
3764
+ }),
3765
+ " ",
3766
+ recurrence.postTrialText
3767
+ ]
3768
+ }) : null,
3769
+ recurrence.chargeLimitText ? /*#__PURE__*/ jsx("p", {
3770
+ "data-cx-checkout": "recurrence-charge-limit",
3771
+ children: recurrence.chargeLimitText
2626
3772
  }) : null
2627
3773
  ]
2628
3774
  });
@@ -2717,7 +3863,19 @@ function OrderBumpContent({ bump }) {
2717
3863
  "data-cx-checkout": "order-bump-description",
2718
3864
  children: bump.description
2719
3865
  }) : null,
2720
- /*#__PURE__*/ jsx("span", {
3866
+ bump.trial ? /*#__PURE__*/ jsxs(Fragment, {
3867
+ children: [
3868
+ /*#__PURE__*/ jsx("span", {
3869
+ "data-cx-checkout": "order-bump-price",
3870
+ "data-trial": "true",
3871
+ children: bump.trial.highlight
3872
+ }),
3873
+ /*#__PURE__*/ jsx("span", {
3874
+ "data-cx-checkout": "order-bump-trial-after",
3875
+ children: bump.trial.after
3876
+ })
3877
+ ]
3878
+ }) : /*#__PURE__*/ jsx("span", {
2721
3879
  "data-cx-checkout": "order-bump-price",
2722
3880
  children: bump.formattedPrice
2723
3881
  })
@@ -2899,11 +4057,12 @@ const ADDRESS_LABELS = {
2899
4057
  * Address of the buyer. Renders nothing when the offer does not ask for one (and while a
2900
4058
  * returning buyer buys with saved data). Physical offers quote freight from the zip code.
2901
4059
  */ function AddressFields({ className, labels, children }) {
2902
- const { values, errors, setValue, required } = useAddress();
4060
+ const { values, errors, setValue, required, lookup } = useAddress();
2903
4061
  const fields = useFieldFactory(values, errors, setValue, ADDRESS_META);
2904
4062
  if (children) return children({
2905
4063
  fields,
2906
- required
4064
+ required,
4065
+ lookup
2907
4066
  });
2908
4067
  if (!required) return null;
2909
4068
  const text = {
@@ -2913,6 +4072,8 @@ const ADDRESS_LABELS = {
2913
4072
  return /*#__PURE__*/ jsx("div", {
2914
4073
  className: className,
2915
4074
  "data-cx-checkout": "address",
4075
+ "aria-busy": lookup.status === 'loading',
4076
+ "data-lookup": lookup.status,
2916
4077
  children: [
2917
4078
  'zipCode',
2918
4079
  'street',
@@ -3143,11 +4304,14 @@ const METHOD_LABELS = {
3143
4304
  ]
3144
4305
  });
3145
4306
  }
3146
- /** Coupon input. Renders nothing when the offer does not accept coupons. */ function CouponField({ className, children }) {
4307
+ /**
4308
+ * Coupon input. Renders nothing when the offer does not accept coupons, except for a coupon the
4309
+ * offer applied on its own for the buyer's email, which still shows (and still counts).
4310
+ */ function CouponField({ className, children }) {
3147
4311
  const coupon = useCoupon();
3148
4312
  const [draft, setDraft] = useState('');
3149
4313
  if (children) return children(coupon);
3150
- if (!coupon.enabled) return null;
4314
+ if (!coupon.enabled && coupon.source !== 'auto') return null;
3151
4315
  if (coupon.code) {
3152
4316
  return /*#__PURE__*/ jsxs("div", {
3153
4317
  className: className,
@@ -3203,6 +4367,62 @@ const METHOD_LABELS = {
3203
4367
  ]
3204
4368
  });
3205
4369
  }
4370
+ /**
4371
+ * Social proof balloons ("12 people bought in the last 24 hours", "***dro B. R. bought"), one at
4372
+ * a time, with a close button that hides them for the visit. Renders nothing when the seller turned
4373
+ * social proof off or after the buyer closed it or sent the payment. Positioning is the page's:
4374
+ * the default markup is a live region (`data-cx-checkout="social-proof"`) to place where it fits.
4375
+ * Render it once per page.
4376
+ */ function SocialProof({ className, children }) {
4377
+ const state = useSocialProof();
4378
+ const { messages } = useCheckout();
4379
+ if (!state.enabled) return null;
4380
+ if (children) return children(state);
4381
+ const { balloon } = state;
4382
+ // The region stays mounted (even empty) so screen readers announce each new balloon.
4383
+ return /*#__PURE__*/ jsx("div", {
4384
+ className: className,
4385
+ role: "status",
4386
+ "aria-live": "polite",
4387
+ "aria-label": messages.socialProofRegion,
4388
+ "data-cx-checkout": "social-proof",
4389
+ children: balloon ? // biome-ignore lint/a11y/noStaticElementInteractions: hover and focus only hold the balloon on screen; the close button is the only control
4390
+ /*#__PURE__*/ jsxs("div", {
4391
+ "data-cx-checkout": "social-proof-balloon",
4392
+ "data-kind": balloon.kind,
4393
+ "data-icon": balloon.icon,
4394
+ "data-leaving": state.leaving,
4395
+ onPointerEnter: ()=>state.setEngaged(true),
4396
+ onPointerLeave: ()=>state.setEngaged(false),
4397
+ onFocus: ()=>state.setEngaged(true),
4398
+ onBlur: (event)=>{
4399
+ if (!event.currentTarget.contains(event.relatedTarget)) state.setEngaged(false);
4400
+ },
4401
+ children: [
4402
+ /*#__PURE__*/ jsx("p", {
4403
+ "data-cx-checkout": "social-proof-text",
4404
+ children: balloon.parts.map((part, index)=>part.strong ? /*#__PURE__*/ jsx("strong", {
4405
+ children: part.text
4406
+ }, index) : part.text)
4407
+ }),
4408
+ balloon.time ? /*#__PURE__*/ jsxs("p", {
4409
+ "data-cx-checkout": "social-proof-meta",
4410
+ children: [
4411
+ balloon.place ? `${balloon.place} · ` : null,
4412
+ balloon.time
4413
+ ]
4414
+ }) : null,
4415
+ /*#__PURE__*/ jsx("button", {
4416
+ type: "button",
4417
+ "aria-label": messages.socialProofClose,
4418
+ "data-cx-checkout": "social-proof-close",
4419
+ onClick: state.dismiss,
4420
+ children: "\xd7"
4421
+ })
4422
+ ]
4423
+ }, balloon.id) : null
4424
+ });
4425
+ }
3206
4426
  /** Submits the purchase with the selected method. */ function SubmitButton({ className, label = 'Finalizar compra', children }) {
3207
4427
  const state = useSubmit();
3208
4428
  if (children) return children(state);
@@ -3210,7 +4430,7 @@ const METHOD_LABELS = {
3210
4430
  type: "button",
3211
4431
  className: className,
3212
4432
  "data-cx-checkout": "submit",
3213
- disabled: state.isSubmitting,
4433
+ disabled: state.isSubmitting || Boolean(state.blocked),
3214
4434
  "aria-busy": state.isSubmitting,
3215
4435
  onClick: ()=>void state.submit(),
3216
4436
  children: label
@@ -3231,9 +4451,53 @@ const METHOD_LABELS = {
3231
4451
  children: state.message
3232
4452
  });
3233
4453
  }
4454
+ /**
4455
+ * Notices about the offer and the buyer: offer not for sale (with the seller's support email),
4456
+ * offer waiting for approval, email outside the offer's audience, free trial already used, and
4457
+ * the free account an affiliate-split purchase creates. Renders nothing when there is none.
4458
+ *
4459
+ * `unavailable` and `pendingApproval` come from the public offer and render on the server; the
4460
+ * others appear once the buyer's email is checked. The submit button stays disabled while the
4461
+ * offer is not for sale or the email is outside its audience.
4462
+ */ function CheckoutNotices({ className, children }) {
4463
+ const { notices } = useCheckout();
4464
+ if (children) return children({
4465
+ notices
4466
+ });
4467
+ if (notices.length === 0) return null;
4468
+ return /*#__PURE__*/ jsx("div", {
4469
+ className: className,
4470
+ "data-cx-checkout": "notices",
4471
+ children: notices.map((notice)=>/*#__PURE__*/ jsxs("div", {
4472
+ role: notice.kind === 'unavailable' || notice.kind === 'offerIneligible' ? 'alert' : 'status',
4473
+ "data-cx-checkout": "notice",
4474
+ "data-kind": notice.kind,
4475
+ children: [
4476
+ notice.title ? /*#__PURE__*/ jsx("strong", {
4477
+ "data-cx-checkout": "notice-title",
4478
+ children: notice.title
4479
+ }) : null,
4480
+ /*#__PURE__*/ jsxs("p", {
4481
+ children: [
4482
+ notice.message,
4483
+ notice.supportEmail ? /*#__PURE__*/ jsxs(Fragment, {
4484
+ children: [
4485
+ ': ',
4486
+ /*#__PURE__*/ jsx("a", {
4487
+ href: `mailto:${notice.supportEmail}`,
4488
+ children: notice.supportEmail
4489
+ })
4490
+ ]
4491
+ }) : notice.title ? '.' : null
4492
+ ]
4493
+ })
4494
+ ]
4495
+ }, notice.kind))
4496
+ });
4497
+ }
3234
4498
  /** Buys the one-time offer. A returning buyer with a saved card buys with one click. */ function UpsellAcceptButton({ className, label = 'Sim, quero aproveitar', children }) {
3235
4499
  const upsell = useUpsell();
3236
- const { isSubmitting } = useSubmit();
4500
+ const { isSubmitting, blocked } = useSubmit();
3237
4501
  if (children) return children({
3238
4502
  ...upsell,
3239
4503
  isSubmitting
@@ -3242,7 +4506,7 @@ const METHOD_LABELS = {
3242
4506
  type: "button",
3243
4507
  className: className,
3244
4508
  "data-cx-checkout": "upsell-accept",
3245
- disabled: isSubmitting,
4509
+ disabled: isSubmitting || Boolean(blocked),
3246
4510
  "aria-busy": isSubmitting,
3247
4511
  onClick: ()=>void upsell.accept(),
3248
4512
  children: label
@@ -3272,4 +4536,5 @@ const METHOD_LABELS = {
3272
4536
 
3273
4537
 
3274
4538
 
3275
- export { AddressFields, BoletoPayment, CardFields, CheckoutApiError, CheckoutError, CheckoutProvider, ClickmaxElementsError, CountdownTimer, CouponField, DEFAULT_PAYMENTS_BASE_URL, FreightOptions, Installments, OfferItem, OrderBumps, OrderSummary, PaymentMethods, PersonalDataFields, PixPayment, Price, SubmitButton, UpsellAcceptButton, UpsellDeclineButton, createCheckoutApi, formatMoney, isValidDocument, parseTelephone, useAddress, useBoleto, useCheckout, useCountdown, useCoupon, useFormatMoney, useFreight, useOfferItem, useOrderBumps, usePayment, usePersonalData, usePix, useSubmit, useSummary, useUpsell };
4539
+
4540
+ export { AddressFields, BoletoPayment, CardFields, CheckoutApiError, CheckoutError, CheckoutNotices, CheckoutProvider, ClickmaxElementsError, CountdownTimer, CouponField, DEFAULT_PAYMENTS_BASE_URL, FreightOptions, Installments, OfferItem, OrderBumps, OrderSummary, PaymentMethods, PersonalDataFields, PixPayment, Price, Recurrence, SocialProof, SubmitButton, UpsellAcceptButton, UpsellDeclineButton, createCheckoutApi, formatMoney, isValidDocument, parseTelephone, useAddress, useBoleto, useCheckout, useCountdown, useCoupon, useFormatMoney, useFreight, useOfferItem, useOrderBumps, usePayment, usePersonalData, usePix, useRecurrence, useSocialProof, useSubmit, useSummary, useUpsell, viaCepLookup };