@greatapps/common 1.1.748 → 1.1.750
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/components/layouts/AiCreditsOfferGate.mjs +105 -0
- package/dist/components/layouts/AiCreditsOfferGate.mjs.map +1 -0
- package/dist/components/modals/AccountFrozenModal.mjs.map +1 -1
- package/dist/components/modals/promo/AiCreditsOfferModal/AiCreditsOfferModal.mjs +276 -0
- package/dist/components/modals/promo/AiCreditsOfferModal/AiCreditsOfferModal.mjs.map +1 -0
- package/dist/components/modals/promo/AiCreditsOfferModal/components/LoseOfferDialog.mjs +55 -0
- package/dist/components/modals/promo/AiCreditsOfferModal/components/LoseOfferDialog.mjs.map +1 -0
- package/dist/components/modals/promo/AiCreditsOfferModal/components/OfferIllustration.mjs +78 -0
- package/dist/components/modals/promo/AiCreditsOfferModal/components/OfferIllustration.mjs.map +1 -0
- package/dist/components/modals/promo/AiCreditsOfferModal/components/OfferPaymentField.mjs +60 -0
- package/dist/components/modals/promo/AiCreditsOfferModal/components/OfferPaymentField.mjs.map +1 -0
- package/dist/components/modals/promo/AiCreditsOfferModal/index.mjs +5 -0
- package/dist/components/modals/promo/AiCreditsOfferModal/index.mjs.map +1 -0
- package/dist/components/navigation/SubscriptionBanner.mjs.map +1 -1
- package/dist/handlers.mjs +5 -1
- package/dist/handlers.mjs.map +1 -1
- package/dist/i18n/messages/en-us.mjs +32 -0
- package/dist/i18n/messages/en-us.mjs.map +1 -1
- package/dist/i18n/messages/es-es.mjs +32 -0
- package/dist/i18n/messages/es-es.mjs.map +1 -1
- package/dist/i18n/messages/pt-br.mjs +32 -0
- package/dist/i18n/messages/pt-br.mjs.map +1 -1
- package/dist/index.mjs +73 -43
- package/dist/index.mjs.map +1 -1
- package/dist/modules/auth/utils/assert-account-not-frozen.mjs.map +1 -1
- package/dist/modules/auth/utils/get-user-context.mjs +2 -1
- package/dist/modules/auth/utils/get-user-context.mjs.map +1 -1
- package/dist/modules/cards/hooks/cards.hook.mjs +3 -2
- package/dist/modules/cards/hooks/cards.hook.mjs.map +1 -1
- package/dist/modules/ia-credits/constants/ai-credits-offer.constants.mjs +28 -0
- package/dist/modules/ia-credits/constants/ai-credits-offer.constants.mjs.map +1 -0
- package/dist/modules/ia-credits/handlers/get-offer-eligibility.handler.mjs +19 -0
- package/dist/modules/ia-credits/handlers/get-offer-eligibility.handler.mjs.map +1 -0
- package/dist/modules/ia-credits/handlers/purchase-ia-credits.handler.mjs +33 -0
- package/dist/modules/ia-credits/handlers/purchase-ia-credits.handler.mjs.map +1 -0
- package/dist/modules/ia-credits/hooks/purchase-ia-credits.hook.mjs +29 -0
- package/dist/modules/ia-credits/hooks/purchase-ia-credits.hook.mjs.map +1 -0
- package/dist/modules/ia-credits/hooks/use-offer-eligibility.hook.mjs +18 -0
- package/dist/modules/ia-credits/hooks/use-offer-eligibility.hook.mjs.map +1 -0
- package/dist/modules/ia-credits/services/ia-credits.service.mjs +67 -0
- package/dist/modules/ia-credits/services/ia-credits.service.mjs.map +1 -1
- package/dist/modules/ia-credits/types/ai-credits-offer.type.mjs +34 -0
- package/dist/modules/ia-credits/types/ai-credits-offer.type.mjs.map +1 -0
- package/dist/modules/ia-credits/utils/offer-stage-cookie.mjs +43 -0
- package/dist/modules/ia-credits/utils/offer-stage-cookie.mjs.map +1 -0
- package/dist/modules/subscriptions/constants/subscription.constants.mjs.map +1 -1
- package/dist/modules/subscriptions/utils/get-account-freeze-date.mjs.map +1 -1
- package/dist/modules/subscriptions/utils/get-account-freeze-state.mjs.map +1 -1
- package/dist/store/useAiCreditsOfferModal.mjs +14 -0
- package/dist/store/useAiCreditsOfferModal.mjs.map +1 -0
- package/package.json +3 -1
- package/src/components/layouts/AiCreditsOfferGate.tsx +199 -0
- package/src/components/modals/AccountFrozenModal.tsx +0 -25
- package/src/components/modals/promo/AiCreditsOfferModal/AiCreditsOfferModal.tsx +401 -0
- package/src/components/modals/promo/AiCreditsOfferModal/components/LoseOfferDialog.tsx +97 -0
- package/src/components/modals/promo/AiCreditsOfferModal/components/OfferIllustration.tsx +121 -0
- package/src/components/modals/promo/AiCreditsOfferModal/components/OfferPaymentField.tsx +91 -0
- package/src/components/modals/promo/AiCreditsOfferModal/index.ts +1 -0
- package/src/components/navigation/SubscriptionBanner.tsx +0 -8
- package/src/handlers.ts +2 -0
- package/src/i18n/messages/en-us.ts +33 -0
- package/src/i18n/messages/es-es.ts +33 -0
- package/src/i18n/messages/pt-br.ts +33 -0
- package/src/index.ts +26 -0
- package/src/modules/auth/utils/assert-account-not-frozen.ts +0 -9
- package/src/modules/auth/utils/get-user-context.ts +3 -0
- package/src/modules/cards/hooks/cards.hook.ts +6 -1
- package/src/modules/ia-credits/constants/ai-credits-offer.constants.ts +41 -0
- package/src/modules/ia-credits/handlers/get-offer-eligibility.handler.ts +24 -0
- package/src/modules/ia-credits/handlers/purchase-ia-credits.handler.ts +42 -0
- package/src/modules/ia-credits/hooks/purchase-ia-credits.hook.ts +43 -0
- package/src/modules/ia-credits/hooks/use-offer-eligibility.hook.ts +28 -0
- package/src/modules/ia-credits/services/ia-credits.service.ts +92 -0
- package/src/modules/ia-credits/types/ai-credits-offer.type.ts +87 -0
- package/src/modules/ia-credits/utils/offer-stage-cookie.ts +70 -0
- package/src/modules/subscriptions/constants/subscription.constants.ts +0 -5
- package/src/modules/subscriptions/utils/get-account-freeze-date.ts +0 -13
- package/src/modules/subscriptions/utils/get-account-freeze-state.ts +0 -7
- package/src/store/useAiCreditsOfferModal.ts +24 -0
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useRef } from "react";
|
|
3
|
+
import { useAuth } from "../../providers/auth.provider";
|
|
4
|
+
import { useIsDefaultWhitelabel, useWhitelabel } from "../../providers/whitelabel.provider";
|
|
5
|
+
import { useActiveSubscription } from "../../modules/subscriptions/hooks/find-active-subscription.hook";
|
|
6
|
+
import { hasActivePaidSubscription } from "../../modules/subscriptions/utils/has-active-paid-subscription";
|
|
7
|
+
import { ADDON_IDS } from "../../modules/subscriptions/constants/addons.constants";
|
|
8
|
+
import { useCurrencyFormatter } from "../../modules/accounts/hooks/use-currency-formatter.hook";
|
|
9
|
+
import { useRequiredBillingData } from "../../modules/accounts/hooks/use-required-billing-data.hook";
|
|
10
|
+
import { useCards } from "../../modules/cards/hooks/cards.hook";
|
|
11
|
+
import { useIaCredits } from "../../modules/ia-credits/hooks/ia-credits.hook";
|
|
12
|
+
import { useAiCreditsOfferEligibility } from "../../modules/ia-credits/hooks/use-offer-eligibility.hook";
|
|
13
|
+
import {
|
|
14
|
+
AI_CREDITS_FIRST_PURCHASE_OFFER,
|
|
15
|
+
AI_CREDITS_OFFER_MAX_REPEATS,
|
|
16
|
+
AiCreditsOfferStage
|
|
17
|
+
} from "../../modules/ia-credits/constants/ai-credits-offer.constants";
|
|
18
|
+
import {
|
|
19
|
+
readOfferStageCookie,
|
|
20
|
+
writeOfferStageCookie
|
|
21
|
+
} from "../../modules/ia-credits/utils/offer-stage-cookie";
|
|
22
|
+
import { useAiCreditsOfferModal } from "../../store/useAiCreditsOfferModal";
|
|
23
|
+
import { useModalManager } from "../../store/useModalManager";
|
|
24
|
+
const OPEN_DELAY_MS = 1e3;
|
|
25
|
+
function resolveCandidateStage(summary) {
|
|
26
|
+
if (summary.totalCredits === 0 && summary.usedCredits === 0) {
|
|
27
|
+
return AiCreditsOfferStage.CAMPAIGN_SHOWN;
|
|
28
|
+
}
|
|
29
|
+
if (summary.availableCredits === 0 || summary.totalCredits === 0) {
|
|
30
|
+
return AiCreditsOfferStage.ZERO_SHOWN;
|
|
31
|
+
}
|
|
32
|
+
const usedRatio = summary.usedCredits / summary.totalCredits;
|
|
33
|
+
if (usedRatio >= 0.9) return AiCreditsOfferStage.EXHAUSTED_SHOWN;
|
|
34
|
+
if (usedRatio >= 0.5) return AiCreditsOfferStage.HALF_SHOWN;
|
|
35
|
+
if (summary.usedCredits >= 1) return AiCreditsOfferStage.FIRST_USE_SHOWN;
|
|
36
|
+
return AiCreditsOfferStage.CAMPAIGN_SHOWN;
|
|
37
|
+
}
|
|
38
|
+
function AiCreditsOfferGate({ suppressWhen = false }) {
|
|
39
|
+
const { activeModal } = useModalManager();
|
|
40
|
+
const { openModal } = useAiCreditsOfferModal();
|
|
41
|
+
const { user } = useAuth();
|
|
42
|
+
const isDefaultWl = useIsDefaultWhitelabel();
|
|
43
|
+
const { whitelabel } = useWhitelabel();
|
|
44
|
+
const { data: subscriptionData } = useActiveSubscription();
|
|
45
|
+
const { currency } = useCurrencyFormatter();
|
|
46
|
+
const { summary, isLoading: isCreditsLoading } = useIaCredits();
|
|
47
|
+
const { isRequired: isBillingDataRequired } = useRequiredBillingData();
|
|
48
|
+
const hasArmedRef = useRef(false);
|
|
49
|
+
const isProfileIncomplete = user != null && (!user.name || !user.last_name);
|
|
50
|
+
const subscription = subscriptionData?.data?.[0] ?? null;
|
|
51
|
+
const accountId = user?.id_account;
|
|
52
|
+
const canManageBilling = user?.profile === "owner" || user?.profile === "admin";
|
|
53
|
+
const currentAiCredits = subscription?.items?.find((item) => item.id_addon === ADDON_IDS.AI)?.quantity ?? 0;
|
|
54
|
+
const isFirstPurchase = !hasActivePaidSubscription(subscription) && !subscription?.charged;
|
|
55
|
+
const passesClientCutoff = isDefaultWl && currency === "brl" && canManageBilling && accountId != null && isFirstPurchase && currentAiCredits < AI_CREDITS_FIRST_PURCHASE_OFFER.credits;
|
|
56
|
+
const { data: eligibilityData } = useAiCreditsOfferEligibility({ enabled: passesClientCutoff });
|
|
57
|
+
const cardsQuery = useCards({ enabled: passesClientCutoff });
|
|
58
|
+
useEffect(() => {
|
|
59
|
+
if (hasArmedRef.current) return;
|
|
60
|
+
if (suppressWhen || activeModal) return;
|
|
61
|
+
if (isBillingDataRequired || isProfileIncomplete) return;
|
|
62
|
+
if (!passesClientCutoff || isCreditsLoading) return;
|
|
63
|
+
if (!eligibilityData || !eligibilityData.eligible || accountId == null) return;
|
|
64
|
+
if (!cardsQuery.isSuccess || cardsQuery.data.data.length > 0) return;
|
|
65
|
+
const candidateStage = resolveCandidateStage(summary);
|
|
66
|
+
const cookie = readOfferStageCookie(accountId);
|
|
67
|
+
const alreadyShownThisSession = cookie.lastSessionIat === eligibilityData.sessionIssuedAt;
|
|
68
|
+
if (alreadyShownThisSession) return;
|
|
69
|
+
const isRepeatableStage = candidateStage === AiCreditsOfferStage.CAMPAIGN_SHOWN || candidateStage === AiCreditsOfferStage.ZERO_SHOWN;
|
|
70
|
+
const isRepeating = isRepeatableStage && candidateStage === cookie.stage;
|
|
71
|
+
const shouldOpen = candidateStage > cookie.stage || isRepeating;
|
|
72
|
+
if (!shouldOpen) return;
|
|
73
|
+
const repeatCount = isRepeating ? cookie.repeatCount + 1 : 0;
|
|
74
|
+
if (isRepeating && cookie.repeatCount >= AI_CREDITS_OFFER_MAX_REPEATS) return;
|
|
75
|
+
hasArmedRef.current = true;
|
|
76
|
+
const timer = setTimeout(() => {
|
|
77
|
+
writeOfferStageCookie(
|
|
78
|
+
accountId,
|
|
79
|
+
{ stage: candidateStage, lastSessionIat: eligibilityData.sessionIssuedAt, repeatCount },
|
|
80
|
+
whitelabel?.domain
|
|
81
|
+
);
|
|
82
|
+
openModal();
|
|
83
|
+
}, OPEN_DELAY_MS);
|
|
84
|
+
return () => clearTimeout(timer);
|
|
85
|
+
}, [
|
|
86
|
+
accountId,
|
|
87
|
+
activeModal,
|
|
88
|
+
cardsQuery.data,
|
|
89
|
+
cardsQuery.isSuccess,
|
|
90
|
+
eligibilityData,
|
|
91
|
+
isBillingDataRequired,
|
|
92
|
+
isCreditsLoading,
|
|
93
|
+
isProfileIncomplete,
|
|
94
|
+
openModal,
|
|
95
|
+
passesClientCutoff,
|
|
96
|
+
suppressWhen,
|
|
97
|
+
summary,
|
|
98
|
+
whitelabel?.domain
|
|
99
|
+
]);
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
export {
|
|
103
|
+
AiCreditsOfferGate
|
|
104
|
+
};
|
|
105
|
+
//# sourceMappingURL=AiCreditsOfferGate.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/components/layouts/AiCreditsOfferGate.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect, useRef } from 'react';\nimport { useAuth } from '../../providers/auth.provider';\nimport { useIsDefaultWhitelabel, useWhitelabel } from '../../providers/whitelabel.provider';\nimport { useActiveSubscription } from '../../modules/subscriptions/hooks/find-active-subscription.hook';\nimport { hasActivePaidSubscription } from '../../modules/subscriptions/utils/has-active-paid-subscription';\nimport { ADDON_IDS } from '../../modules/subscriptions/constants/addons.constants';\nimport { useCurrencyFormatter } from '../../modules/accounts/hooks/use-currency-formatter.hook';\nimport { useRequiredBillingData } from '../../modules/accounts/hooks/use-required-billing-data.hook';\nimport { useCards } from '../../modules/cards/hooks/cards.hook';\nimport { useIaCredits } from '../../modules/ia-credits/hooks/ia-credits.hook';\nimport { useAiCreditsOfferEligibility } from '../../modules/ia-credits/hooks/use-offer-eligibility.hook';\nimport {\n AI_CREDITS_FIRST_PURCHASE_OFFER,\n AI_CREDITS_OFFER_MAX_REPEATS,\n AiCreditsOfferStage,\n} from '../../modules/ia-credits/constants/ai-credits-offer.constants';\nimport {\n readOfferStageCookie,\n writeOfferStageCookie,\n} from '../../modules/ia-credits/utils/offer-stage-cookie';\nimport { useAiCreditsOfferModal } from '../../store/useAiCreditsOfferModal';\nimport { useModalManager } from '../../store/useModalManager';\nimport type { IaCreditsSummary } from '../../modules/ia-credits/types';\n\n/** Espera pedida pelo produto: a oferta entra 1s depois de o gatilho decidir, não junto. */\nconst OPEN_DELAY_MS = 1000;\n\n/**\n * Estágio que os créditos ATUAIS da conta sustentam, na escada do Diogo — sempre o mais alto que os\n * números batem (ordem de checagem: ZERO > EXHAUSTED > HALF > FIRST_USE > CAMPAIGN).\n *\n * `totalCredits === 0` (lote mensal expirado, ainda sem renovar) cai em ZERO, não em divisão por\n * zero — mesma régua do `availableCredits === 0`.\n */\nfunction resolveCandidateStage(\n summary: Pick<IaCreditsSummary, 'totalCredits' | 'usedCredits' | 'availableCredits'>\n): AiCreditsOfferStage {\n // Conta que ainda NÃO recebeu lote nenhum (medido em produção: o free só ganha o primeiro lote\n // meses depois do cadastro) não é o mesmo que conta que gastou tudo. Sem esta distinção o\n // recém-cadastrado entrava direto em ZERO_SHOWN, o degrau mais alto, e como a escada só sobe os\n // gatilhos de uso — primeira geração, 50%, 90% — nunca mais disparavam para ele.\n if (summary.totalCredits === 0 && summary.usedCredits === 0) {\n return AiCreditsOfferStage.CAMPAIGN_SHOWN;\n }\n if (summary.availableCredits === 0 || summary.totalCredits === 0) {\n return AiCreditsOfferStage.ZERO_SHOWN;\n }\n const usedRatio = summary.usedCredits / summary.totalCredits;\n if (usedRatio >= 0.9) return AiCreditsOfferStage.EXHAUSTED_SHOWN;\n if (usedRatio >= 0.5) return AiCreditsOfferStage.HALF_SHOWN;\n if (summary.usedCredits >= 1) return AiCreditsOfferStage.FIRST_USE_SHOWN;\n return AiCreditsOfferStage.CAMPAIGN_SHOWN;\n}\n\nexport interface AiCreditsOfferGateProps {\n /**\n * Overlay local do host, fora do `useModalManager` compartilhado (ex.: geração de IA em\n * progresso, `InsufficientCreditsModal` do editor) — a oferta não empilha em cima nem espera a\n * vez enquanto `true`; ela volta a tentar no próximo render em que a condição cair, porque o\n * estágio só é gravado quando o modal realmente abre.\n */\n suppressWhen?: boolean;\n}\n\n/**\n * Quem decide se a oferta de primeira compra de créditos de IA aparece, e em qual estágio (gatilhos\n * do Diogo — ver Asana ID-1217333331953496). Mora no root layout de cada app, ao lado dos outros\n * gates de modal.\n *\n * Precisa passar por, nesta ordem:\n *\n * 1. **Corte barato do cliente.** Whitelabel padrão + conta em BRL + `owner`/`admin` + primeira\n * compra de verdade (sem assinatura paga vigente, sem NENHUMA cobrança no histórico) + menos de\n * 500 créditos já contratados. Evita bater no backend pra quem obviamente não se qualifica.\n * 2. **Elegibilidade do servidor**, com FAIL CLOSED: erro, timeout ou ainda carregando conta como\n * inelegível — sem confirmação do backend não existe oferta (ele é quem sabe se a conta já\n * consumiu a oferta em QUALQUER assinatura, cross-cancelamento incluso).\n * 2.1. **Cartão salvo, também FAIL CLOSED.** O card exige as duas condições juntas — plano\n * elegível E ainda sem cartão. O backend valida isso na elegibilidade, mas o gate confere de\n * novo com `useCards`: sem confirmação de que a lista veio vazia, não abre (evita a corrida em\n * que alguém cadastra o cartão pelo CTA e desiste antes de confirmar, e o cache local de\n * elegibilidade ainda não invalidou).\n * 3. **Estágio candidato**, derivado dos créditos atuais (`resolveCandidateStage`).\n * 4. **Escada monotônica do cookie `ai-credits-offer-stage`**: só abre se o candidato é MAIOR que o\n * estágio gravado, OU se o candidato é CAMPAIGN/ZERO — os dois únicos que reapresentam, e só\n * numa sessão de login nova (`sessionIssuedAt` ≠ `lastSessionIat`). A repetição respeita\n * `AI_CREDITS_OFFER_MAX_REPEATS`: a campanha é agressiva de propósito (vale inclusive para quem\n * acabou de se cadastrar), mas não pode virar o mesmo pop em toda sessão para sempre.\n * 5. **Máx. 1 apresentação por sessão de login.** Sai de graça da regra acima: se o cookie já tem\n * `lastSessionIat` igual ao da sessão atual, NADA abre — nem uma escalada de estágio dentro da\n * mesma sessão (ex.: FIRST_USE → HALF → EXHAUSTED na mesma geração, no Free de 10 créditos).\n */\nexport function AiCreditsOfferGate({ suppressWhen = false }: AiCreditsOfferGateProps) {\n const { activeModal } = useModalManager();\n const { openModal } = useAiCreditsOfferModal();\n const { user } = useAuth();\n const isDefaultWl = useIsDefaultWhitelabel();\n const { whitelabel } = useWhitelabel();\n const { data: subscriptionData } = useActiveSubscription();\n const { currency } = useCurrencyFormatter();\n const { summary, isLoading: isCreditsLoading } = useIaCredits();\n const { isRequired: isBillingDataRequired } = useRequiredBillingData();\n const hasArmedRef = useRef(false);\n\n /* Modais bloqueantes que NÃO passam pelo `useModalManager` — cada um controla a própria abertura\n * com estado local, então `activeModal` não os enxerga e a oferta subiria por cima:\n * - `RequiredBillingDataModal` (lib), aberto por `useRequiredBillingData().isRequired`;\n * - `CompleteProfileGuard` (app de contas), aberto quando falta nome ou sobrenome.\n * Checar a condição de origem, e não o modal em si, é o que funciona para os três apps sem que\n * cada um precise lembrar de passar `suppressWhen`. */\n const isProfileIncomplete = user != null && (!user.name || !user.last_name);\n\n const subscription = subscriptionData?.data?.[0] ?? null;\n const accountId = user?.id_account;\n const canManageBilling = user?.profile === 'owner' || user?.profile === 'admin';\n const currentAiCredits =\n subscription?.items?.find((item) => item.id_addon === ADDON_IDS.AI)?.quantity ?? 0;\n const isFirstPurchase = !hasActivePaidSubscription(subscription) && !subscription?.charged;\n\n const passesClientCutoff =\n isDefaultWl &&\n currency === 'brl' &&\n canManageBilling &&\n accountId != null &&\n isFirstPurchase &&\n currentAiCredits < AI_CREDITS_FIRST_PURCHASE_OFFER.credits;\n\n // Só consulta o servidor depois do corte barato: quem não passa aqui nunca veria a oferta, e a\n // consulta custa duas chamadas no gapps-r3-api.\n const { data: eligibilityData } = useAiCreditsOfferEligibility({ enabled: passesClientCutoff });\n const cardsQuery = useCards({ enabled: passesClientCutoff });\n\n useEffect(() => {\n if (hasArmedRef.current) return;\n if (suppressWhen || activeModal) return;\n if (isBillingDataRequired || isProfileIncomplete) return;\n if (!passesClientCutoff || isCreditsLoading) return;\n // Fail closed: sem resposta do servidor (carregando, erro, ou reason preenchido), não abre.\n if (!eligibilityData || !eligibilityData.eligible || accountId == null) return;\n // Fail closed: sem confirmação de que a lista de cartões carregou vazia, não abre — o backend\n // já valida \"sem cartão\" na elegibilidade, isto é a segunda camada do lado do cliente.\n if (!cardsQuery.isSuccess || cardsQuery.data.data.length > 0) return;\n\n const candidateStage = resolveCandidateStage(summary);\n const cookie = readOfferStageCookie(accountId);\n\n const alreadyShownThisSession = cookie.lastSessionIat === eligibilityData.sessionIssuedAt;\n if (alreadyShownThisSession) return;\n\n const isRepeatableStage =\n candidateStage === AiCreditsOfferStage.CAMPAIGN_SHOWN ||\n candidateStage === AiCreditsOfferStage.ZERO_SHOWN;\n\n const isRepeating = isRepeatableStage && candidateStage === cookie.stage;\n\n const shouldOpen = candidateStage > cookie.stage || isRepeating;\n if (!shouldOpen) return;\n\n // Subir de estágio zera o contador: o teto limita a insistência DENTRO de um estágio, não a\n // escada inteira. Sem isso, uma conta que já gastou o teto na campanha nunca veria a oferta no\n // momento em que ela mais importa (crédito no fim).\n const repeatCount = isRepeating ? cookie.repeatCount + 1 : 0;\n if (isRepeating && cookie.repeatCount >= AI_CREDITS_OFFER_MAX_REPEATS) return;\n\n // Arma uma única vez por montagem: sem isso, qualquer re-render limparia o timer pendente.\n hasArmedRef.current = true;\n\n const timer = setTimeout(() => {\n // O estágio é gravado junto com a abertura (e não antes): fechar a aba durante o delay não\n // pode queimar a apresentação.\n writeOfferStageCookie(\n accountId,\n { stage: candidateStage, lastSessionIat: eligibilityData.sessionIssuedAt, repeatCount },\n whitelabel?.domain\n );\n openModal();\n }, OPEN_DELAY_MS);\n\n return () => clearTimeout(timer);\n }, [\n accountId,\n activeModal,\n cardsQuery.data,\n cardsQuery.isSuccess,\n eligibilityData,\n isBillingDataRequired,\n isCreditsLoading,\n isProfileIncomplete,\n openModal,\n passesClientCutoff,\n suppressWhen,\n summary,\n whitelabel?.domain,\n ]);\n\n return null;\n}\n"],"mappings":";AAEA,SAAS,WAAW,cAAc;AAClC,SAAS,eAAe;AACxB,SAAS,wBAAwB,qBAAqB;AACtD,SAAS,6BAA6B;AACtC,SAAS,iCAAiC;AAC1C,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,8BAA8B;AACvC,SAAS,gBAAgB;AACzB,SAAS,oBAAoB;AAC7B,SAAS,oCAAoC;AAC7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;AAIhC,MAAM,gBAAgB;AAStB,SAAS,sBACP,SACq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{"version":3,"sources":["../../../src/components/modals/AccountFrozenModal.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n IconLock,\n IconFile,\n IconFolder,\n IconWorld,\n IconInfoCircle,\n type IconProps,\n} from '@tabler/icons-react';\nimport type { ComponentType } from 'react';\nimport { useTranslations } from 'next-intl';\nimport { Button } from '../ui/buttons/Button';\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogTitle,\n} from '../ui/overlay/Dialog';\nimport { Tooltip, TooltipContent, TooltipTrigger } from '../ui/overlay/Tooltip';\nimport { useWhitelabelUrls, useExternalContracting } from '../../providers/whitelabel.provider';\nimport { useModalManager } from '../../store/useModalManager';\nimport { formatShortDate } from '../../infra/utils/date';\n\n/* Os 9 recursos do card agrupados nos 3 grupos que o usuário reconhece na plataforma.\n * Um ícone por grupo; o texto mora no catálogo. */\n/* Chaves LITERAIS, não `resources.${key}.title`: o catálogo dos apps consumidores tipa\n * translate() com a união de chaves, e a template string não resolve nessa união — o TS cai\n * na sobrecarga de 2-3 argumentos e o build do consumidor quebra (a common sozinha não\n * acusa). */\nconst RESOURCE_GROUPS = [\n {\n icon: IconFile,\n titleKey: 'common.subscription.frozen.modal.resources.pages.title',\n descriptionKey: 'common.subscription.frozen.modal.resources.pages.description',\n },\n {\n icon: IconFolder,\n titleKey: 'common.subscription.frozen.modal.resources.projects.title',\n descriptionKey: 'common.subscription.frozen.modal.resources.projects.description',\n },\n {\n icon: IconWorld,\n titleKey: 'common.subscription.frozen.modal.resources.domains.title',\n descriptionKey: 'common.subscription.frozen.modal.resources.domains.description',\n },\n] as const satisfies readonly {\n icon: ComponentType<IconProps>;\n titleKey: string;\n descriptionKey: string;\n}[];\n\n/* `freezeDate` no data = ainda VAI congelar (véspera); sem ele = já congelado.\n *\n * A LISTA só aparece quando o usuário PEDIU por ela, clicando em \"Detalhes\" no banner\n * (`showResources`). Na modal que abre sozinha ao entrar numa conta bloqueada fica só o\n * recado curto e o botão. */\ninterface FrozenModalData {\n freezeDate?: Date | string | null;\n showResources?: boolean;\n}\n\nexport default function AccountFrozenModal() {\n const translate = useTranslations();\n const { activeModal, closeModal, modalData } = useModalManager();\n const isOpen = activeModal === 'accountFrozenModal';\n const { accountsUrl } = useWhitelabelUrls();\n const { redirectToExternal } = useExternalContracting();\n\n const data = modalData as FrozenModalData | undefined;\n const freezeDate = data?.freezeDate ?? null;\n const isWarning = Boolean(freezeDate);\n const showResources = Boolean(data?.showResources);\n\n const title = isWarning\n ? translate('common.subscription.frozen.modal.warningTitle', {\n freezeDate: formatShortDate(freezeDate ? new Date(freezeDate) : null),\n })\n : translate('common.subscription.frozen.modal.title');\n\n /* Sem a lista o texto tem que fechar sozinho; com a lista ele a INTRODUZ (termina em \":\"). */\n const description = isWarning\n ? translate(\n showResources\n ? 'common.subscription.frozen.modal.warningDescriptionWithResources'\n : 'common.subscription.frozen.modal.warningDescription',\n )\n : translate(\n showResources\n ? 'common.subscription.frozen.modal.descriptionWithResources'\n : 'common.subscription.frozen.modal.description',\n );\n\n const handleRegularize = () => {\n if (redirectToExternal('plans')) return;\n window.location.href = `${accountsUrl}/subscriptions`;\n };\n\n return (\n <Dialog open={isOpen} onOpenChange={() => closeModal()}>\n <DialogContent\n showCloseButton\n /* Sem isto o Radix move o foco para o primeiro focável ao abrir — que aqui é o\n * gatilho do tooltip — e o tooltip abre em FOCO, não só em hover: a modal\n * aparecia com um balão já aberto. O foco segue preso no dialog. */\n onOpenAutoFocus={(event) => event.preventDefault()}\n className=\"flex flex-col p-0! gap-0! max-w-[calc(100%-2rem)]! w-full sm:max-w-[400px]! lg:max-w-[420px]! rounded-lg border\"\n >\n <div className=\"flex flex-col gap-5 p-4 lg:p-5\">\n <div className=\"flex items-center justify-center w-10 h-10 bg-zinc-50 rounded-lg\">\n <IconLock size={20} className=\"text-zinc-950\" />\n </div>\n\n <div className=\"flex flex-col gap-2\">\n <DialogTitle className=\"paragraph-medium-semibold text-zinc-950\">\n {title}\n </DialogTitle>\n <DialogDescription className=\"paragraph-small-regular text-zinc-500\">\n {description}\n </DialogDescription>\n </div>\n\n {showResources && (\n <>\n {/* Um bloco só, grupos separados por linha. A descrição de cada grupo\n * vive no tooltip do ícone de info à direita: na modal ela empilhava\n * três parágrafos e virava um paredão. */}\n <div className=\"bg-white border border-zinc-100 rounded-lg\">\n {RESOURCE_GROUPS.map(({ titleKey, descriptionKey, icon: Icon }, index) => (\n <div key={titleKey}>\n {index > 0 && <div className=\"h-px bg-zinc-100\" />}\n <div className=\"flex items-center justify-between gap-3 p-4\">\n <div className=\"flex items-center gap-3\">\n <Icon size={20} className=\"text-zinc-950 shrink-0\" />\n <span className=\"paragraph-small-semibold text-zinc-950\">\n {translate(titleKey)}\n </span>\n </div>\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n aria-label={translate(titleKey)}\n className=\"flex items-center justify-center shrink-0 cursor-pointer\"\n >\n <IconInfoCircle className=\"size-4 text-zinc-400\" />\n </button>\n </TooltipTrigger>\n <TooltipContent\n side=\"top\"\n /* Acima do dialog: o globals.css do gapps-app\n * sobe o [data-slot='dialog-content'] para\n * z-index 1011 !important (o componente\n * declara 1001), então o z-50 padrão do\n * tooltip ficava atrás. */\n className=\"z-[1100] max-w-[240px]\"\n >\n {translate(descriptionKey)}\n </TooltipContent>\n </Tooltip>\n </div>\n </div>\n ))}\n </div>\n\n {/* Bloco de informação padrão da plataforma. Ciano fixo: o congelamento\n * é exclusivo da wl 1, então não existe o caso whitelabel/zinc aqui. */}\n <div className=\"flex items-center gap-3 p-4 rounded-lg bg-cyan-50\">\n <IconInfoCircle className=\"size-4 text-zinc-950 shrink-0\" />\n <span className=\"paragraph-small-regular text-zinc-950\">\n {translate('common.subscription.frozen.modal.keepsWorking')}\n </span>\n </div>\n </>\n )}\n </div>\n\n <div className=\"h-px bg-zinc-200\" />\n\n <div className=\"flex items-center gap-2 p-4 lg:p-5\">\n <Button className=\"h-10 w-fit\" onClick={handleRegularize}>\n {translate('common.subscription.frozen.modal.cta')}\n </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A,qBAAC,SAAI,WAAU,qDACX;AAAA,kCAAC,kBAAe,WAAU,iCAAgC;AAAA,cAC1D,oBAAC,UAAK,WAAU,yCACX,oBAAU,+CAA+C,GAC9D;AAAA,eACJ;AAAA,aACJ;AAAA,WAER;AAAA,QAEA,oBAAC,SAAI,WAAU,oBAAmB;AAAA,QAElC,oBAAC,SAAI,WAAU,sCACX,8BAAC,UAAO,WAAU,cAAa,SAAS,kBACnC,oBAAU,sCAAsC,GACrD,GACJ;AAAA;AAAA;AAAA,EACJ,GACJ;AAER;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/modals/AccountFrozenModal.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n IconLock,\n IconFile,\n IconFolder,\n IconWorld,\n IconInfoCircle,\n type IconProps,\n} from '@tabler/icons-react';\nimport type { ComponentType } from 'react';\nimport { useTranslations } from 'next-intl';\nimport { Button } from '../ui/buttons/Button';\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogTitle,\n} from '../ui/overlay/Dialog';\nimport { Tooltip, TooltipContent, TooltipTrigger } from '../ui/overlay/Tooltip';\nimport { useWhitelabelUrls, useExternalContracting } from '../../providers/whitelabel.provider';\nimport { useModalManager } from '../../store/useModalManager';\nimport { formatShortDate } from '../../infra/utils/date';\n\nconst RESOURCE_GROUPS = [\n {\n icon: IconFile,\n titleKey: 'common.subscription.frozen.modal.resources.pages.title',\n descriptionKey: 'common.subscription.frozen.modal.resources.pages.description',\n },\n {\n icon: IconFolder,\n titleKey: 'common.subscription.frozen.modal.resources.projects.title',\n descriptionKey: 'common.subscription.frozen.modal.resources.projects.description',\n },\n {\n icon: IconWorld,\n titleKey: 'common.subscription.frozen.modal.resources.domains.title',\n descriptionKey: 'common.subscription.frozen.modal.resources.domains.description',\n },\n] as const satisfies readonly {\n icon: ComponentType<IconProps>;\n titleKey: string;\n descriptionKey: string;\n}[];\n\ninterface FrozenModalData {\n freezeDate?: Date | string | null;\n showResources?: boolean;\n}\n\nexport default function AccountFrozenModal() {\n const translate = useTranslations();\n const { activeModal, closeModal, modalData } = useModalManager();\n const isOpen = activeModal === 'accountFrozenModal';\n const { accountsUrl } = useWhitelabelUrls();\n const { redirectToExternal } = useExternalContracting();\n\n const data = modalData as FrozenModalData | undefined;\n const freezeDate = data?.freezeDate ?? null;\n const isWarning = Boolean(freezeDate);\n const showResources = Boolean(data?.showResources);\n\n const title = isWarning\n ? translate('common.subscription.frozen.modal.warningTitle', {\n freezeDate: formatShortDate(freezeDate ? new Date(freezeDate) : null),\n })\n : translate('common.subscription.frozen.modal.title');\n\n const description = isWarning\n ? translate(\n showResources\n ? 'common.subscription.frozen.modal.warningDescriptionWithResources'\n : 'common.subscription.frozen.modal.warningDescription',\n )\n : translate(\n showResources\n ? 'common.subscription.frozen.modal.descriptionWithResources'\n : 'common.subscription.frozen.modal.description',\n );\n\n const handleRegularize = () => {\n if (redirectToExternal('plans')) return;\n window.location.href = `${accountsUrl}/subscriptions`;\n };\n\n return (\n <Dialog open={isOpen} onOpenChange={() => closeModal()}>\n <DialogContent\n showCloseButton\n onOpenAutoFocus={(event) => event.preventDefault()}\n className=\"flex flex-col p-0! gap-0! max-w-[calc(100%-2rem)]! w-full sm:max-w-[400px]! lg:max-w-[420px]! rounded-lg border\"\n >\n <div className=\"flex flex-col gap-5 p-4 lg:p-5\">\n <div className=\"flex items-center justify-center w-10 h-10 bg-zinc-50 rounded-lg\">\n <IconLock size={20} className=\"text-zinc-950\" />\n </div>\n\n <div className=\"flex flex-col gap-2\">\n <DialogTitle className=\"paragraph-medium-semibold text-zinc-950\">\n {title}\n </DialogTitle>\n <DialogDescription className=\"paragraph-small-regular text-zinc-500\">\n {description}\n </DialogDescription>\n </div>\n\n {showResources && (\n <>\n <div className=\"bg-white border border-zinc-100 rounded-lg\">\n {RESOURCE_GROUPS.map(({ titleKey, descriptionKey, icon: Icon }, index) => (\n <div key={titleKey}>\n {index > 0 && <div className=\"h-px bg-zinc-100\" />}\n <div className=\"flex items-center justify-between gap-3 p-4\">\n <div className=\"flex items-center gap-3\">\n <Icon size={20} className=\"text-zinc-950 shrink-0\" />\n <span className=\"paragraph-small-semibold text-zinc-950\">\n {translate(titleKey)}\n </span>\n </div>\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n aria-label={translate(titleKey)}\n className=\"flex items-center justify-center shrink-0 cursor-pointer\"\n >\n <IconInfoCircle className=\"size-4 text-zinc-400\" />\n </button>\n </TooltipTrigger>\n <TooltipContent\n side=\"top\"\n className=\"z-[1100] max-w-[240px]\"\n >\n {translate(descriptionKey)}\n </TooltipContent>\n </Tooltip>\n </div>\n </div>\n ))}\n </div>\n\n <div className=\"flex items-center gap-3 p-4 rounded-lg bg-cyan-50\">\n <IconInfoCircle className=\"size-4 text-zinc-950 shrink-0\" />\n <span className=\"paragraph-small-regular text-zinc-950\">\n {translate('common.subscription.frozen.modal.keepsWorking')}\n </span>\n </div>\n </>\n )}\n </div>\n\n <div className=\"h-px bg-zinc-200\" />\n\n <div className=\"flex items-center gap-2 p-4 lg:p-5\">\n <Button className=\"h-10 w-fit\" onClick={handleRegularize}>\n {translate('common.subscription.frozen.modal.cta')}\n </Button>\n </div>\n </DialogContent>\n </Dialog>\n );\n}\n"],"mappings":";AA+FwB,SAaA,UAbA,KAGJ,YAHI;AA7FxB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEG;AAEP,SAAS,uBAAuB;AAChC,SAAS,cAAc;AACvB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,SAAS,gBAAgB,sBAAsB;AACxD,SAAS,mBAAmB,8BAA8B;AAC1D,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAEhC,MAAM,kBAAkB;AAAA,EACpB;AAAA,IACI,MAAM;AAAA,IACN,UAAU;AAAA,IACV,gBAAgB;AAAA,EACpB;AAAA,EACA;AAAA,IACI,MAAM;AAAA,IACN,UAAU;AA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AI,WAAU,8CACV,0BAAgB,IAAI,CAAC,EAAE,UAAU,gBAAgB,MAAM,KAAK,GAAG,UAC5D,qBAAC,SACI;AAAA,sBAAQ,KAAK,oBAAC,SAAI,WAAU,oBAAmB;AAAA,cAChD,qBAAC,SAAI,WAAU,+CACX;AAAA,qCAAC,SAAI,WAAU,2BACX;AAAA,sCAAC,QAAK,MAAM,IAAI,WAAU,0BAAyB;AAAA,kBACnD,oBAAC,UAAK,WAAU,0CACX,oBAAU,QAAQ,GACvB;AAAA,mBACJ;AAAA,gBACA,qBAAC,WACG;AAAA,sCAAC,kBAAe,SAAO,MACnB;AAAA,oBAAC;AAAA;AAAA,sBACG,MAAK;AAAA,sBACL,cAAY,UAAU,QAAQ;AAAA,sBAC9B,WAAU;AAAA,sBAEV,8BAAC,kBAAe,WAAU,wBAAuB;AAAA;AAAA,kBACrD,GACJ;AAAA,kBACA;AAAA,oBAAC;AAAA;AAAA,sBACG,MAAK;AAAA,sBACL,WAAU;AAAA,sBAET,oBAAU,cAAc;AAAA;AAAA,kBAC7B;AAAA,mBACJ;AAAA,iBACJ;AAAA,iBA1BM,QA2BV,CACH,GACL;AAAA,YAEA,qBAAC,SAAI,WAAU,qDACX;AAAA,kCAAC,kBAAe,WAAU,iCAAgC;AAAA,cAC1D,oBAAC,UAAK,WAAU,yCACX,oBAAU,+CAA+C,GAC9D;AAAA,eACJ;AAAA,aACJ;AAAA,WAER;AAAA,QAEA,oBAAC,SAAI,WAAU,oBAAmB;AAAA,QAElC,oBAAC,SAAI,WAAU,sCACX,8BAAC,UAAO,WAAU,cAAa,SAAS,kBACnC,oBAAU,sCAAsC,GACrD,GACJ;AAAA;AAAA;AAAA,EACJ,GACJ;AAER;","names":[]}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useCallback, useState } from "react";
|
|
4
|
+
import { useStripe } from "@stripe/react-stripe-js";
|
|
5
|
+
import { IconCheck, IconX } from "@tabler/icons-react";
|
|
6
|
+
import { useLocale, useTranslations } from "next-intl";
|
|
7
|
+
import { toast } from "sonner";
|
|
8
|
+
import { Button } from "../../../ui/buttons/Button";
|
|
9
|
+
import { Dialog, DialogContent, DialogTitle } from "../../../ui/overlay/Dialog";
|
|
10
|
+
import { Toast } from "../../../ui/feedback/Toast";
|
|
11
|
+
import { useAuth } from "../../../../providers/auth.provider";
|
|
12
|
+
import { useWhitelabel, useWhitelabelUrls } from "../../../../providers/whitelabel.provider";
|
|
13
|
+
import { useActiveSubscription } from "../../../../modules/subscriptions/hooks/find-active-subscription.hook";
|
|
14
|
+
import { useCards } from "../../../../modules/cards/hooks/cards.hook";
|
|
15
|
+
import { useCurrencyFormatter } from "../../../../modules/accounts/hooks/use-currency-formatter.hook";
|
|
16
|
+
import { confirmPaymentIfRequired } from "../../../../modules/subscriptions/utils/confirm-payment-if-required";
|
|
17
|
+
import {
|
|
18
|
+
AI_CREDITS_FIRST_PURCHASE_OFFER,
|
|
19
|
+
AiCreditsOfferStage,
|
|
20
|
+
PAYMENT_METHOD_CARD
|
|
21
|
+
} from "../../../../modules/ia-credits/constants/ai-credits-offer.constants";
|
|
22
|
+
import { useAiCreditsOfferEligibility } from "../../../../modules/ia-credits/hooks/use-offer-eligibility.hook";
|
|
23
|
+
import { usePurchaseIaCredits } from "../../../../modules/ia-credits/hooks/purchase-ia-credits.hook";
|
|
24
|
+
import { readOfferStageCookie, writeOfferStageCookie } from "../../../../modules/ia-credits/utils/offer-stage-cookie";
|
|
25
|
+
import { useAiCreditsOfferModal } from "../../../../store/useAiCreditsOfferModal";
|
|
26
|
+
import { useModalManager } from "../../../../store/useModalManager";
|
|
27
|
+
import { LoseOfferDialog } from "./components/LoseOfferDialog";
|
|
28
|
+
import { OfferIllustration } from "./components/OfferIllustration";
|
|
29
|
+
import { OfferPaymentField } from "./components/OfferPaymentField";
|
|
30
|
+
function AiCreditsOfferModal() {
|
|
31
|
+
const translate = useTranslations();
|
|
32
|
+
const locale = useLocale();
|
|
33
|
+
const stripe = useStripe();
|
|
34
|
+
const { open, closeModal } = useAiCreditsOfferModal();
|
|
35
|
+
const { openModal } = useModalManager();
|
|
36
|
+
const { user } = useAuth();
|
|
37
|
+
const { whitelabel } = useWhitelabel();
|
|
38
|
+
const { accountsUrl } = useWhitelabelUrls();
|
|
39
|
+
const { formatCurrencyNumber } = useCurrencyFormatter();
|
|
40
|
+
const [confirmingExit, setConfirmingExit] = useState(false);
|
|
41
|
+
const [pickedCardId, setPickedCardId] = useState("");
|
|
42
|
+
const { data: cardsData } = useCards();
|
|
43
|
+
const { data: subscriptionData } = useActiveSubscription();
|
|
44
|
+
const eligibility = useAiCreditsOfferEligibility();
|
|
45
|
+
const purchaseMutation = usePurchaseIaCredits();
|
|
46
|
+
const subscription = subscriptionData?.data?.[0] ?? null;
|
|
47
|
+
const subscriptionId = subscription?.id;
|
|
48
|
+
const accountId = user?.id_account;
|
|
49
|
+
const defaultCardId = cardsData?.data?.find((card) => card.is_default)?.id?.toString() ?? cardsData?.data?.[0]?.id?.toString() ?? "";
|
|
50
|
+
const pickedCardExists = cardsData?.data?.some((card) => card.id.toString() === pickedCardId);
|
|
51
|
+
const selectedCardId = pickedCardExists ? pickedCardId : defaultCardId;
|
|
52
|
+
const offerPrice = AI_CREDITS_FIRST_PURCHASE_OFFER.price;
|
|
53
|
+
const fullPrice = eligibility.data?.anchorCents != null ? eligibility.data.anchorCents / 100 : null;
|
|
54
|
+
const discountPercent = fullPrice != null ? Math.round((1 - offerPrice / fullPrice) * 100) : null;
|
|
55
|
+
const creditsLabel = AI_CREDITS_FIRST_PURCHASE_OFFER.credits.toLocaleString(locale);
|
|
56
|
+
const discountLabel = discountPercent != null ? translate("common.promo.aiCreditsOffer.discountBadge", { percent: String(discountPercent) }) : "";
|
|
57
|
+
const hasCard = Boolean(selectedCardId);
|
|
58
|
+
const isSubmitting = purchaseMutation.isPending;
|
|
59
|
+
const dismiss = useCallback(() => {
|
|
60
|
+
setConfirmingExit(false);
|
|
61
|
+
closeModal();
|
|
62
|
+
}, [closeModal]);
|
|
63
|
+
const requestClose = useCallback(() => setConfirmingExit(true), []);
|
|
64
|
+
const submitPurchase = useCallback(
|
|
65
|
+
async (cardId) => {
|
|
66
|
+
if (subscriptionId == null) {
|
|
67
|
+
closeModal();
|
|
68
|
+
window.location.assign(`${accountsUrl}/subscriptions?tab=plans`);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const input = {
|
|
72
|
+
subscriptionId,
|
|
73
|
+
offer: AI_CREDITS_FIRST_PURCHASE_OFFER.slug,
|
|
74
|
+
paymentMethod: PAYMENT_METHOD_CARD,
|
|
75
|
+
idCard: cardId
|
|
76
|
+
};
|
|
77
|
+
try {
|
|
78
|
+
let result = await purchaseMutation.mutateAsync(input);
|
|
79
|
+
if (result.status === 2) {
|
|
80
|
+
await confirmPaymentIfRequired(stripe, result, translate("common.payment.authFailed"));
|
|
81
|
+
result = await purchaseMutation.mutateAsync(input);
|
|
82
|
+
}
|
|
83
|
+
if (result.status !== 1) {
|
|
84
|
+
toast.custom((toastId) => /* @__PURE__ */ jsx(
|
|
85
|
+
Toast,
|
|
86
|
+
{
|
|
87
|
+
variant: "error",
|
|
88
|
+
message: translate("common.promo.aiCreditsOffer.errorToast"),
|
|
89
|
+
toastId
|
|
90
|
+
}
|
|
91
|
+
));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (accountId != null) {
|
|
95
|
+
const cookie = readOfferStageCookie(accountId);
|
|
96
|
+
writeOfferStageCookie(
|
|
97
|
+
accountId,
|
|
98
|
+
{
|
|
99
|
+
stage: AiCreditsOfferStage.CONVERTED,
|
|
100
|
+
lastSessionIat: eligibility.data?.sessionIssuedAt ?? cookie.lastSessionIat,
|
|
101
|
+
repeatCount: cookie.repeatCount
|
|
102
|
+
},
|
|
103
|
+
whitelabel?.domain
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
toast.custom((toastId) => /* @__PURE__ */ jsx(
|
|
107
|
+
Toast,
|
|
108
|
+
{
|
|
109
|
+
variant: "success",
|
|
110
|
+
message: translate("common.promo.aiCreditsOffer.successToast", { credits: creditsLabel }),
|
|
111
|
+
toastId
|
|
112
|
+
}
|
|
113
|
+
));
|
|
114
|
+
dismiss();
|
|
115
|
+
} catch {
|
|
116
|
+
toast.custom((toastId) => /* @__PURE__ */ jsx(
|
|
117
|
+
Toast,
|
|
118
|
+
{
|
|
119
|
+
variant: "error",
|
|
120
|
+
message: translate("common.promo.aiCreditsOffer.errorToast"),
|
|
121
|
+
toastId
|
|
122
|
+
}
|
|
123
|
+
));
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
[
|
|
127
|
+
accountId,
|
|
128
|
+
accountsUrl,
|
|
129
|
+
closeModal,
|
|
130
|
+
creditsLabel,
|
|
131
|
+
dismiss,
|
|
132
|
+
eligibility.data?.sessionIssuedAt,
|
|
133
|
+
purchaseMutation,
|
|
134
|
+
stripe,
|
|
135
|
+
subscriptionId,
|
|
136
|
+
translate,
|
|
137
|
+
whitelabel?.domain
|
|
138
|
+
]
|
|
139
|
+
);
|
|
140
|
+
const handleOpenAddCard = useCallback(() => {
|
|
141
|
+
openModal("addCardModal", {
|
|
142
|
+
onCardAdded: (cardId) => {
|
|
143
|
+
setPickedCardId(cardId);
|
|
144
|
+
void submitPurchase(cardId);
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
}, [openModal, submitPurchase]);
|
|
148
|
+
const handleConfirm = useCallback(async () => {
|
|
149
|
+
if (!hasCard) {
|
|
150
|
+
handleOpenAddCard();
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
await submitPurchase(selectedCardId);
|
|
154
|
+
}, [handleOpenAddCard, hasCard, selectedCardId, submitPurchase]);
|
|
155
|
+
const bullets = [
|
|
156
|
+
translate("common.promo.aiCreditsOffer.bullets.first"),
|
|
157
|
+
translate("common.promo.aiCreditsOffer.bullets.second"),
|
|
158
|
+
translate("common.promo.aiCreditsOffer.bullets.third")
|
|
159
|
+
];
|
|
160
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
161
|
+
/* @__PURE__ */ jsx(Dialog, { open, onOpenChange: () => {
|
|
162
|
+
}, children: /* @__PURE__ */ jsx(
|
|
163
|
+
DialogContent,
|
|
164
|
+
{
|
|
165
|
+
showCloseButton: false,
|
|
166
|
+
onOpenAutoFocus: (event) => event.preventDefault(),
|
|
167
|
+
onEscapeKeyDown: (event) => {
|
|
168
|
+
event.preventDefault();
|
|
169
|
+
requestClose();
|
|
170
|
+
},
|
|
171
|
+
onPointerDownOutside: (event) => {
|
|
172
|
+
event.preventDefault();
|
|
173
|
+
requestClose();
|
|
174
|
+
},
|
|
175
|
+
onInteractOutside: (event) => event.preventDefault(),
|
|
176
|
+
overlayClassName: "duration-300",
|
|
177
|
+
className: [
|
|
178
|
+
// mobile: folha de tela cheia (mesma geometria do BuyCreditsModal)
|
|
179
|
+
"flex flex-col gap-0 overflow-hidden rounded-t-2xl rounded-b-none border-0 p-0 shadow-elevated",
|
|
180
|
+
"top-0 right-0 bottom-0 left-0 h-dvh max-w-full translate-x-0 translate-y-0 sm:max-w-full",
|
|
181
|
+
// desktop (≥ md): cartão de duas colunas, centralizado
|
|
182
|
+
"md:top-[50%] md:right-auto md:bottom-auto md:left-[50%] md:h-auto md:max-h-[92vh] md:w-[900px]! md:max-w-[900px]! md:translate-x-[-50%] md:translate-y-[-50%] md:rounded-xl md:border",
|
|
183
|
+
// entrada de baixo pra cima: a classe (e não utilidade `animate-[...]`) porque o
|
|
184
|
+
// `DialogContent` já traz `animate-in` e o merge do Tailwind não funde as duas — ver
|
|
185
|
+
// `.gp-offer-modal` no globals.css.
|
|
186
|
+
"gp-offer-modal"
|
|
187
|
+
].join(" "),
|
|
188
|
+
children: /* @__PURE__ */ jsxs("div", { className: "gm-scroll flex h-full flex-col overflow-y-auto md:h-auto md:min-h-[600px] md:flex-row md:items-stretch md:overflow-visible", children: [
|
|
189
|
+
/* @__PURE__ */ jsxs("div", { className: "relative h-[180px] w-full shrink-0 md:order-2 md:h-auto md:w-1/2", children: [
|
|
190
|
+
/* @__PURE__ */ jsx(OfferIllustration, { credits: AI_CREDITS_FIRST_PURCHASE_OFFER.credits, locale }),
|
|
191
|
+
/* @__PURE__ */ jsx(
|
|
192
|
+
"button",
|
|
193
|
+
{
|
|
194
|
+
type: "button",
|
|
195
|
+
onClick: requestClose,
|
|
196
|
+
"aria-label": translate("common.promo.aiCreditsOffer.close"),
|
|
197
|
+
className: "absolute top-4 right-4 z-10 flex size-8 cursor-pointer items-center justify-center rounded-lg text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-950",
|
|
198
|
+
children: /* @__PURE__ */ jsx(IconX, { className: "size-[18px]" })
|
|
199
|
+
}
|
|
200
|
+
)
|
|
201
|
+
] }),
|
|
202
|
+
/* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col gap-6 p-6 md:order-1 md:w-1/2 md:shrink-0 md:gap-7 md:p-10", children: [
|
|
203
|
+
/* @__PURE__ */ jsx(
|
|
204
|
+
"span",
|
|
205
|
+
{
|
|
206
|
+
className: "gp-offer-rise paragraph-xsmall-semibold w-fit rounded-full bg-cyan-50 px-2.5 py-1 text-cyan-700",
|
|
207
|
+
style: { animationDelay: "160ms" },
|
|
208
|
+
children: translate("common.promo.aiCreditsOffer.eyebrow")
|
|
209
|
+
}
|
|
210
|
+
),
|
|
211
|
+
/* @__PURE__ */ jsx("div", { className: "gp-offer-rise", style: { animationDelay: "220ms" }, children: /* @__PURE__ */ jsx(DialogTitle, { className: "title-large-semibold text-[26px] leading-8 font-bold tracking-[-0.4px] text-zinc-950", children: translate.rich("common.promo.aiCreditsOffer.title", {
|
|
212
|
+
credits: creditsLabel,
|
|
213
|
+
discount: discountLabel,
|
|
214
|
+
break: () => /* @__PURE__ */ jsx("br", {})
|
|
215
|
+
}) }) }),
|
|
216
|
+
/* @__PURE__ */ jsx("ul", { className: "flex flex-col gap-3.5", children: bullets.map((bullet, index) => /* @__PURE__ */ jsxs(
|
|
217
|
+
"li",
|
|
218
|
+
{
|
|
219
|
+
className: "gp-offer-rise flex items-start gap-2.5",
|
|
220
|
+
style: { animationDelay: `${300 + index * 70}ms` },
|
|
221
|
+
children: [
|
|
222
|
+
/* @__PURE__ */ jsx("span", { className: "mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full bg-cyan-50", children: /* @__PURE__ */ jsx(IconCheck, { size: 13, stroke: 3, className: "text-cyan-700" }) }),
|
|
223
|
+
/* @__PURE__ */ jsx("span", { className: "paragraph-small-medium text-zinc-600", children: bullet })
|
|
224
|
+
]
|
|
225
|
+
},
|
|
226
|
+
bullet
|
|
227
|
+
)) }),
|
|
228
|
+
/* @__PURE__ */ jsxs("div", { className: "gp-offer-rise flex flex-col gap-0.5", style: { animationDelay: "520ms" }, children: [
|
|
229
|
+
fullPrice != null && /* @__PURE__ */ jsx("span", { className: "paragraph-small-medium text-zinc-400 line-through", children: formatCurrencyNumber(fullPrice) }),
|
|
230
|
+
/* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2.5", children: [
|
|
231
|
+
/* @__PURE__ */ jsx("span", { className: "title-large-semibold font-bold tracking-[-0.4px] text-zinc-950", children: formatCurrencyNumber(offerPrice) }),
|
|
232
|
+
discountLabel && /* @__PURE__ */ jsx("span", { className: "paragraph-xsmall-semibold rounded-md bg-green-50 px-2 py-1 text-green-600", children: discountLabel })
|
|
233
|
+
] })
|
|
234
|
+
] }),
|
|
235
|
+
/* @__PURE__ */ jsx("div", { className: "gp-offer-rise mt-2", style: { animationDelay: "580ms" }, children: /* @__PURE__ */ jsx(OfferPaymentField, { cardId: selectedCardId, onCardAdded: setPickedCardId }) }),
|
|
236
|
+
/* @__PURE__ */ jsxs(
|
|
237
|
+
"div",
|
|
238
|
+
{
|
|
239
|
+
className: "gp-offer-rise mt-auto flex flex-col gap-2",
|
|
240
|
+
style: { animationDelay: "640ms" },
|
|
241
|
+
children: [
|
|
242
|
+
/* @__PURE__ */ jsx(Button, { className: "w-full", loading: isSubmitting, onClick: handleConfirm, children: hasCard ? translate("common.promo.aiCreditsOffer.cta", { discount: discountLabel }) : translate("common.promo.aiCreditsOffer.ctaAddCard") }),
|
|
243
|
+
/* @__PURE__ */ jsx(
|
|
244
|
+
Button,
|
|
245
|
+
{
|
|
246
|
+
variant: "secondary",
|
|
247
|
+
className: "h-10! w-full",
|
|
248
|
+
disabled: isSubmitting,
|
|
249
|
+
onClick: requestClose,
|
|
250
|
+
children: translate("common.promo.aiCreditsOffer.later")
|
|
251
|
+
}
|
|
252
|
+
)
|
|
253
|
+
]
|
|
254
|
+
}
|
|
255
|
+
)
|
|
256
|
+
] })
|
|
257
|
+
] })
|
|
258
|
+
}
|
|
259
|
+
) }),
|
|
260
|
+
/* @__PURE__ */ jsx(
|
|
261
|
+
LoseOfferDialog,
|
|
262
|
+
{
|
|
263
|
+
open: confirmingExit,
|
|
264
|
+
discountLabel,
|
|
265
|
+
creditsLabel,
|
|
266
|
+
fullPriceLabel: fullPrice != null ? formatCurrencyNumber(fullPrice) : "",
|
|
267
|
+
onKeep: () => setConfirmingExit(false),
|
|
268
|
+
onLose: dismiss
|
|
269
|
+
}
|
|
270
|
+
)
|
|
271
|
+
] });
|
|
272
|
+
}
|
|
273
|
+
export {
|
|
274
|
+
AiCreditsOfferModal as default
|
|
275
|
+
};
|
|
276
|
+
//# sourceMappingURL=AiCreditsOfferModal.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../src/components/modals/promo/AiCreditsOfferModal/AiCreditsOfferModal.tsx"],"sourcesContent":["'use client';\n\nimport { useCallback, useState } from 'react';\nimport { useStripe } from '@stripe/react-stripe-js';\nimport { IconCheck, IconX } from '@tabler/icons-react';\nimport { useLocale, useTranslations } from 'next-intl';\nimport { toast } from 'sonner';\nimport { Button } from '../../../ui/buttons/Button';\nimport { Dialog, DialogContent, DialogTitle } from '../../../ui/overlay/Dialog';\nimport { Toast } from '../../../ui/feedback/Toast';\nimport { useAuth } from '../../../../providers/auth.provider';\nimport { useWhitelabel, useWhitelabelUrls } from '../../../../providers/whitelabel.provider';\nimport { useActiveSubscription } from '../../../../modules/subscriptions/hooks/find-active-subscription.hook';\nimport { useCards } from '../../../../modules/cards/hooks/cards.hook';\nimport { useCurrencyFormatter } from '../../../../modules/accounts/hooks/use-currency-formatter.hook';\nimport { confirmPaymentIfRequired } from '../../../../modules/subscriptions/utils/confirm-payment-if-required';\nimport {\n AI_CREDITS_FIRST_PURCHASE_OFFER,\n AiCreditsOfferStage,\n PAYMENT_METHOD_CARD,\n} from '../../../../modules/ia-credits/constants/ai-credits-offer.constants';\nimport { useAiCreditsOfferEligibility } from '../../../../modules/ia-credits/hooks/use-offer-eligibility.hook';\nimport { usePurchaseIaCredits } from '../../../../modules/ia-credits/hooks/purchase-ia-credits.hook';\nimport type { PurchaseIaCreditsResult } from '../../../../modules/ia-credits/types/ai-credits-offer.type';\nimport { readOfferStageCookie, writeOfferStageCookie } from '../../../../modules/ia-credits/utils/offer-stage-cookie';\nimport { useAiCreditsOfferModal } from '../../../../store/useAiCreditsOfferModal';\nimport { useModalManager } from '../../../../store/useModalManager';\nimport { LoseOfferDialog } from './components/LoseOfferDialog';\nimport { OfferIllustration } from './components/OfferIllustration';\nimport { OfferPaymentField } from './components/OfferPaymentField';\n\n/**\n * Oferta de primeira compra de créditos de IA — a tela que a base gratuita vê quando o\n * `AiCreditsOfferGate` decide que é a vez dela.\n *\n * Duas colunas, como a referência de produto: à esquerda a oferta e o cartão (via\n * `OfferPaymentField`, que cadastra pelo `addCardModal` padrão da plataforma); à direita o\n * gradiente da tela de login com a ilustração do editor.\n *\n * Fechar não fecha: `X`, `Esc`, clique fora e \"Agora não\" caem todos no `LoseOfferDialog`, que\n * pergunta se a pessoa quer mesmo perder o desconto.\n *\n * ⚠️ PREÇO: o card manda só o SLUG da oferta (`AI_CREDITS_FIRST_PURCHASE_OFFER.slug`) — quem\n * resolve pacote, preço e elegibilidade é o backend (Asana ID-1217333331953496). O \"de/por\" desta\n * tela usa `AI_CREDITS_FIRST_PURCHASE_OFFER.price` (fixo, parte do contrato da oferta) contra\n * `anchorCents` do `useAiCreditsOfferEligibility` (derivado do preço real do addon no plano — nunca\n * hardcoded).\n *\n * ANIMAÇÃO: CSS puro, sem `motion/react` (a lib não depende dela). As classes `gp-offer-rise`,\n * `gp-offer-window-in`, `gp-offer-card-in` e `gp-offer-icon-pulse` vêm do `globals.css` de cada app\n * consumidor — bloco documentado abaixo, precisa estar presente nos 3 apps (gpages/gapps/editor):\n *\n * ```css\n * @keyframes gp-offer-rise {\n * from { opacity: 0; translate: 0 10px; }\n * to { opacity: 1; translate: 0 0; }\n * }\n * .gp-offer-rise { animation: gp-offer-rise 420ms cubic-bezier(0.22, 1, 0.36, 1) both; }\n *\n * @keyframes gp-offer-window-in {\n * from { opacity: 0; translate: 0 18px; scale: 0.985; }\n * to { opacity: 1; translate: 0 0; scale: 1; }\n * }\n * .gp-offer-window-in { animation: gp-offer-window-in 550ms cubic-bezier(0.22, 1, 0.36, 1) 50ms both; }\n *\n * @keyframes gp-offer-card-in {\n * from { opacity: 0; translate: 0 26px; scale: 0.97; }\n * to { opacity: 1; translate: 0 0; scale: 1; }\n * }\n * .gp-offer-card-in { animation: gp-offer-card-in 520ms cubic-bezier(0.34, 1.56, 0.64, 1) 340ms both; }\n *\n * @keyframes gp-offer-icon-pulse {\n * 0%, 100% { scale: 1; }\n * 50% { scale: 1.06; }\n * }\n * .gp-offer-icon-pulse { animation: gp-offer-icon-pulse 2.6s ease-in-out 1.6s infinite; }\n *\n * @media (prefers-reduced-motion: reduce) {\n * .gp-offer-rise, .gp-offer-window-in, .gp-offer-card-in, .gp-offer-icon-pulse { animation: none; }\n * }\n * ```\n *\n * `translate`/`scale` (propriedades CSS independentes, não `transform`) pra conviver sem conflito\n * com utilitários de posicionamento do Tailwind (mesmo problema que já forçou o `.gp-offer-modal`\n * de entrada/saída a sair de `@layer` — ver `AiCreditsOfferGate`/`globals.css`).\n */\nexport default function AiCreditsOfferModal() {\n const translate = useTranslations();\n const locale = useLocale();\n const stripe = useStripe();\n const { open, closeModal } = useAiCreditsOfferModal();\n const { openModal } = useModalManager();\n const { user } = useAuth();\n const { whitelabel } = useWhitelabel();\n const { accountsUrl } = useWhitelabelUrls();\n const { formatCurrencyNumber } = useCurrencyFormatter();\n\n const [confirmingExit, setConfirmingExit] = useState(false);\n const [pickedCardId, setPickedCardId] = useState('');\n\n const { data: cardsData } = useCards();\n const { data: subscriptionData } = useActiveSubscription();\n const eligibility = useAiCreditsOfferEligibility();\n const purchaseMutation = usePurchaseIaCredits();\n\n const subscription = subscriptionData?.data?.[0] ?? null;\n const subscriptionId = subscription?.id;\n const accountId = user?.id_account;\n\n const defaultCardId =\n cardsData?.data?.find((card) => card.is_default)?.id?.toString() ??\n cardsData?.data?.[0]?.id?.toString() ??\n '';\n\n // Os cartões chegam depois da abertura (query no client). Derivar — em vez de sincronizar num\n // efeito — faz o padrão da conta já entrar selecionado no render em que a lista chega, e a\n // escolha explícita da pessoa continua mandando.\n const pickedCardExists = cardsData?.data?.some((card) => card.id.toString() === pickedCardId);\n const selectedCardId = pickedCardExists ? pickedCardId : defaultCardId;\n\n const offerPrice = AI_CREDITS_FIRST_PURCHASE_OFFER.price;\n const fullPrice = eligibility.data?.anchorCents != null ? eligibility.data.anchorCents / 100 : null;\n const discountPercent = fullPrice != null ? Math.round((1 - offerPrice / fullPrice) * 100) : null;\n\n const creditsLabel = AI_CREDITS_FIRST_PURCHASE_OFFER.credits.toLocaleString(locale);\n const discountLabel =\n discountPercent != null\n ? translate('common.promo.aiCreditsOffer.discountBadge', { percent: String(discountPercent) })\n : '';\n\n const hasCard = Boolean(selectedCardId);\n const isSubmitting = purchaseMutation.isPending;\n\n /** Fecha de verdade — só o `LoseOfferDialog` e a compra concluída chegam aqui. */\n const dismiss = useCallback(() => {\n setConfirmingExit(false);\n closeModal();\n }, [closeModal]);\n\n /** Toda tentativa de sair passa por aqui — X, Esc, clique fora e \"Agora não\". */\n const requestClose = useCallback(() => setConfirmingExit(true), []);\n\n /**\n * Cobra o cartão informado e credita — sem tocar na recorrência do plano. Chamado tanto pelo CTA\n * com cartão já selecionado quanto (encadeado, sem segundo clique) pelo `onCardAdded` do\n * `addCardModal` quando a pessoa ainda não tinha cartão.\n */\n const submitPurchase = useCallback(\n async (cardId: string) => {\n // Sem assinatura não dá pra cobrar aqui — o CTA vira a porta do checkout do accounts em vez\n // de virar um botão morto.\n if (subscriptionId == null) {\n closeModal();\n window.location.assign(`${accountsUrl}/subscriptions?tab=plans`);\n return;\n }\n\n const input = {\n subscriptionId,\n offer: AI_CREDITS_FIRST_PURCHASE_OFFER.slug,\n paymentMethod: PAYMENT_METHOD_CARD,\n idCard: cardId,\n };\n\n try {\n let result: PurchaseIaCreditsResult = await purchaseMutation.mutateAsync(input);\n\n // 3DS: confirma o desafio e RE-POSTA o MESMO input — a chave de idempotência do backend\n // devolve a mesma cobrança já paga, então o segundo POST fecha com status 1.\n if (result.status === 2) {\n await confirmPaymentIfRequired(stripe, result, translate('common.payment.authFailed'));\n result = await purchaseMutation.mutateAsync(input);\n }\n\n // O `message` do status 0 é código de máquina do backend (`offer_consumed`,\n // `offer_card_only`…), não copy — a tela mostra o erro genérico do catálogo.\n if (result.status !== 1) {\n toast.custom((toastId) => (\n <Toast\n variant=\"error\"\n message={translate('common.promo.aiCreditsOffer.errorToast')}\n toastId={toastId}\n />\n ));\n return;\n }\n\n if (accountId != null) {\n const cookie = readOfferStageCookie(accountId);\n writeOfferStageCookie(\n accountId,\n {\n stage: AiCreditsOfferStage.CONVERTED,\n lastSessionIat: eligibility.data?.sessionIssuedAt ?? cookie.lastSessionIat,\n repeatCount: cookie.repeatCount,\n },\n whitelabel?.domain\n );\n }\n\n toast.custom((toastId) => (\n <Toast\n variant=\"success\"\n message={translate('common.promo.aiCreditsOffer.successToast', { credits: creditsLabel })}\n toastId={toastId}\n />\n ));\n dismiss();\n } catch {\n // Erro técnico (rede, HTTP não-JSON, resposta fora do `PurchaseIaCreditsResultSchema`) —\n // `error.message` aqui é texto de máquina (inclusive o dump do ZodError), nunca copy. Mesma\n // decisão do `status !== 1` acima: a tela mostra a mensagem genérica do catálogo.\n toast.custom((toastId) => (\n <Toast\n variant=\"error\"\n message={translate('common.promo.aiCreditsOffer.errorToast')}\n toastId={toastId}\n />\n ));\n }\n },\n [\n accountId,\n accountsUrl,\n closeModal,\n creditsLabel,\n dismiss,\n eligibility.data?.sessionIssuedAt,\n purchaseMutation,\n stripe,\n subscriptionId,\n translate,\n whitelabel?.domain,\n ]\n );\n\n const handleOpenAddCard = useCallback(() => {\n openModal('addCardModal', {\n onCardAdded: (cardId: string) => {\n setPickedCardId(cardId);\n void submitPurchase(cardId);\n },\n });\n }, [openModal, submitPurchase]);\n\n const handleConfirm = useCallback(async () => {\n // 1º passo do fluxo: sem cartão, o CTA é o próprio cadastro — a compra encadeia sozinha\n // assim que o cartão é criado (ver `handleOpenAddCard`).\n if (!hasCard) {\n handleOpenAddCard();\n return;\n }\n await submitPurchase(selectedCardId);\n }, [handleOpenAddCard, hasCard, selectedCardId, submitPurchase]);\n\n const bullets = [\n translate('common.promo.aiCreditsOffer.bullets.first'),\n translate('common.promo.aiCreditsOffer.bullets.second'),\n translate('common.promo.aiCreditsOffer.bullets.third'),\n ];\n\n return (\n <>\n <Dialog open={open} onOpenChange={() => {}}>\n <DialogContent\n showCloseButton={false}\n onOpenAutoFocus={(event) => event.preventDefault()}\n onEscapeKeyDown={(event) => {\n event.preventDefault();\n requestClose();\n }}\n onPointerDownOutside={(event) => {\n event.preventDefault();\n requestClose();\n }}\n onInteractOutside={(event) => event.preventDefault()}\n overlayClassName=\"duration-300\"\n className={[\n // mobile: folha de tela cheia (mesma geometria do BuyCreditsModal)\n 'flex flex-col gap-0 overflow-hidden rounded-t-2xl rounded-b-none border-0 p-0 shadow-elevated',\n 'top-0 right-0 bottom-0 left-0 h-dvh max-w-full translate-x-0 translate-y-0 sm:max-w-full',\n // desktop (≥ md): cartão de duas colunas, centralizado\n 'md:top-[50%] md:right-auto md:bottom-auto md:left-[50%] md:h-auto md:max-h-[92vh] md:w-[900px]! md:max-w-[900px]! md:translate-x-[-50%] md:translate-y-[-50%] md:rounded-xl md:border',\n // entrada de baixo pra cima: a classe (e não utilidade `animate-[...]`) porque o\n // `DialogContent` já traz `animate-in` e o merge do Tailwind não funde as duas — ver\n // `.gp-offer-modal` no globals.css.\n 'gp-offer-modal',\n ].join(' ')}\n >\n <div className=\"gm-scroll flex h-full flex-col overflow-y-auto md:h-auto md:min-h-[600px] md:flex-row md:items-stretch md:overflow-visible\">\n {/* Ilustração: topo no mobile, coluna da direita no desktop (`md:order-2`). */}\n <div className=\"relative h-[180px] w-full shrink-0 md:order-2 md:h-auto md:w-1/2\">\n <OfferIllustration credits={AI_CREDITS_FIRST_PURCHASE_OFFER.credits} locale={locale} />\n\n <button\n type=\"button\"\n onClick={requestClose}\n aria-label={translate('common.promo.aiCreditsOffer.close')}\n className=\"absolute top-4 right-4 z-10 flex size-8 cursor-pointer items-center justify-center rounded-lg text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-950\"\n >\n <IconX className=\"size-[18px]\" />\n </button>\n </div>\n\n {/* Coluna da oferta */}\n <div className=\"flex flex-1 flex-col gap-6 p-6 md:order-1 md:w-1/2 md:shrink-0 md:gap-7 md:p-10\">\n <span\n className=\"gp-offer-rise paragraph-xsmall-semibold w-fit rounded-full bg-cyan-50 px-2.5 py-1 text-cyan-700\"\n style={{ animationDelay: '160ms' }}\n >\n {translate('common.promo.aiCreditsOffer.eyebrow')}\n </span>\n\n {/* 26px (2px acima do `title-large`) e Outfit 700: a oferta bate mais forte que um\n título de modal comum. A quebra vem do catálogo, pela tag `<break>`, então cada\n idioma escolhe onde partir a frase. */}\n <div className=\"gp-offer-rise\" style={{ animationDelay: '220ms' }}>\n <DialogTitle className=\"title-large-semibold text-[26px] leading-8 font-bold tracking-[-0.4px] text-zinc-950\">\n {translate.rich('common.promo.aiCreditsOffer.title', {\n credits: creditsLabel,\n discount: discountLabel,\n break: () => <br />,\n })}\n </DialogTitle>\n </div>\n\n <ul className=\"flex flex-col gap-3.5\">\n {bullets.map((bullet, index) => (\n <li\n key={bullet}\n className=\"gp-offer-rise flex items-start gap-2.5\"\n style={{ animationDelay: `${300 + index * 70}ms` }}\n >\n <span className=\"mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full bg-cyan-50\">\n <IconCheck size={13} stroke={3} className=\"text-cyan-700\" />\n </span>\n <span className=\"paragraph-small-medium text-zinc-600\">{bullet}</span>\n </li>\n ))}\n </ul>\n\n {/* Preço de tabela em cima, pequeno e riscado; o de campanha embaixo, na mesma\n tipografia do título (Outfit 700) pra os dois números não competirem entre si. Sem\n âncora resolvida (elegibilidade ainda carregando) some a linha do preço cheio em\n vez de mostrar um \"de\" vazio. */}\n <div className=\"gp-offer-rise flex flex-col gap-0.5\" style={{ animationDelay: '520ms' }}>\n {fullPrice != null && (\n <span className=\"paragraph-small-medium text-zinc-400 line-through\">\n {formatCurrencyNumber(fullPrice)}\n </span>\n )}\n <div className=\"flex items-center gap-2.5\">\n <span className=\"title-large-semibold font-bold tracking-[-0.4px] text-zinc-950\">\n {formatCurrencyNumber(offerPrice)}\n </span>\n {discountLabel && (\n <span className=\"paragraph-xsmall-semibold rounded-md bg-green-50 px-2 py-1 text-green-600\">\n {discountLabel}\n </span>\n )}\n </div>\n </div>\n\n <div className=\"gp-offer-rise mt-2\" style={{ animationDelay: '580ms' }}>\n <OfferPaymentField cardId={selectedCardId} onCardAdded={setPickedCardId} />\n </div>\n\n <div\n className=\"gp-offer-rise mt-auto flex flex-col gap-2\"\n style={{ animationDelay: '640ms' }}\n >\n <Button className=\"w-full\" loading={isSubmitting} onClick={handleConfirm}>\n {hasCard\n ? translate('common.promo.aiCreditsOffer.cta', { discount: discountLabel })\n : translate('common.promo.aiCreditsOffer.ctaAddCard')}\n </Button>\n <Button\n variant=\"secondary\"\n className=\"h-10! w-full\"\n disabled={isSubmitting}\n onClick={requestClose}\n >\n {translate('common.promo.aiCreditsOffer.later')}\n </Button>\n </div>\n </div>\n </div>\n </DialogContent>\n </Dialog>\n\n <LoseOfferDialog\n open={confirmingExit}\n discountLabel={discountLabel}\n creditsLabel={creditsLabel}\n fullPriceLabel={fullPrice != null ? formatCurrencyNumber(fullPrice) : ''}\n onKeep={() => setConfirmingExit(false)}\n onLose={dismiss}\n />\n </>\n );\n}\n"],"mappings":";AAkLY,SAoFR,UApFQ,KAiHA,YAjHA;AAhLZ,SAAS,aAAa,gBAAgB;AACtC,SAAS,iBAAiB;AAC1B,SAAS,WAAW,aAAa;AACjC,SAAS,WAAW,uBAAuB;AAC3C,SAAS,aAAa;AACtB,SAAS,cAAc;AACvB,SAAS,QAAQ,eAAe,mBAAmB;AACnD,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,eAAe,yBAAyB;AACjD,SAAS,6BAA6B;AACtC,SAAS,gBAAgB;AACzB,SAAS,4BAA4B;AACrC,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC;AAC7C,SAAS,4BAA4B;AAErC,SAAS,sBAAsB,6BAA6B;AAC5D,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,yBAAyB;AAyDnB,SAAR,sBAAuC;AAC5C,QAAM,YAAY,gBAAgB;AAClC,QAAM,SAAS,UAAU;AACzB,QAAM,SAAS,UAAU;AACzB,QAAM,EAAE,MAAM,WAAW,IAAI,uBAAuB;AACpD,QAAM,EAAE,UAAU,IAAI,gBAAgB;AACtC,QAAM,EAAE,KAAK,IAAI,QAAQ;AACzB,QAAM,EAAE,WAAW,IAAI,cAAc;AACrC,QAAM,EAAE,YAAY,IAAI,kBAAkB;AAC1C,QAAM,EAAE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GACnE,8BAAC,qBAAkB,QAAQ,gBAAgB,aAAa,iBAAiB,GAC3E;AAAA,YAEA;AAAA,cAAC;AAAA;AAAA,gBACC,WAAU;AAAA,gBACV,OAAO,EAAE,gBAAgB,QAAQ;AAAA,gBAEjC;AAAA,sCAAC,UAAO,WAAU,UAAS,SAAS,cAAc,SAAS,eACxD,oBACG,UAAU,mCAAmC,EAAE,UAAU,cAAc,CAAC,IACxE,UAAU,wCAAwC,GACxD;AAAA,kBACA;AAAA,oBAAC;AAAA;AAAA,sBACC,SAAQ;AAAA,sBACR,WAAU;AAAA,sBACV,UAAU;AAAA,sBACV,SAAS;AAAA,sBAER,oBAAU,mCAAmC;AAAA;AAAA,kBAChD;AAAA;AAAA;AAAA,YACF;AAAA,aACF;AAAA,WACF;AAAA;AAAA,IACF,GACF;AAAA,IAEA;AAAA,MAAC;AAAA;AAAA,QACC,MAAM;AAAA,QACN;AAAA,QACA;AAAA,QACA,gBAAgB,aAAa,OAAO,qBAAqB,SAAS,IAAI;AAAA,QACtE,QAAQ,MAAM,kBAAkB,KAAK;AAAA,QACrC,QAAQ;AAAA;AAAA,IACV;AAAA,KACF;AAEJ;","names":[]}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useTranslations } from "next-intl";
|
|
4
|
+
import { Button } from "../../../../ui/buttons/Button";
|
|
5
|
+
import {
|
|
6
|
+
Dialog,
|
|
7
|
+
DialogContent,
|
|
8
|
+
DialogDescription,
|
|
9
|
+
DialogHeader,
|
|
10
|
+
DialogTitle
|
|
11
|
+
} from "../../../../ui/overlay/Dialog";
|
|
12
|
+
import { Separator } from "../../../../ui/data-display/Separator";
|
|
13
|
+
import { IconAlertTriangle } from "@tabler/icons-react";
|
|
14
|
+
function LoseOfferDialog({
|
|
15
|
+
open,
|
|
16
|
+
discountLabel,
|
|
17
|
+
creditsLabel,
|
|
18
|
+
fullPriceLabel,
|
|
19
|
+
onKeep,
|
|
20
|
+
onLose
|
|
21
|
+
}) {
|
|
22
|
+
const translate = useTranslations();
|
|
23
|
+
return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: (next) => !next && onKeep(), children: /* @__PURE__ */ jsxs(
|
|
24
|
+
DialogContent,
|
|
25
|
+
{
|
|
26
|
+
showCloseButton: false,
|
|
27
|
+
onOpenAutoFocus: (event) => event.preventDefault(),
|
|
28
|
+
overlayClassName: "z-[1002] bg-black/40",
|
|
29
|
+
className: "z-[1003] flex flex-col gap-0 p-0 max-[440px]:w-[calc(100%-32px)] md:w-[420px]! lg:w-[420px]! max-w-[420px]! data-[state=open]:animate-[gp-offer-confirm-in_260ms_cubic-bezier(0.16,1,0.3,1)]",
|
|
30
|
+
children: [
|
|
31
|
+
/* @__PURE__ */ jsxs(DialogHeader, { className: "gap-3 p-5 text-left", children: [
|
|
32
|
+
/* @__PURE__ */ jsx("div", { className: "flex w-fit items-center justify-center rounded-lg bg-red-50 p-2.5", children: /* @__PURE__ */ jsx(IconAlertTriangle, { size: 20, className: "text-red-500" }) }),
|
|
33
|
+
/* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
|
|
34
|
+
/* @__PURE__ */ jsx(DialogTitle, { className: "paragraph-medium-semibold text-zinc-950", children: translate("common.promo.aiCreditsOffer.exit.title", { discount: discountLabel }) }),
|
|
35
|
+
/* @__PURE__ */ jsx(DialogDescription, { className: "paragraph-small-regular text-zinc-600", children: fullPriceLabel ? translate("common.promo.aiCreditsOffer.exit.description", {
|
|
36
|
+
credits: creditsLabel,
|
|
37
|
+
price: fullPriceLabel
|
|
38
|
+
}) : translate("common.promo.aiCreditsOffer.exit.descriptionNoPrice", {
|
|
39
|
+
credits: creditsLabel
|
|
40
|
+
}) })
|
|
41
|
+
] })
|
|
42
|
+
] }),
|
|
43
|
+
/* @__PURE__ */ jsx(Separator, {}),
|
|
44
|
+
/* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 p-5", children: [
|
|
45
|
+
/* @__PURE__ */ jsx(Button, { className: "h-10! transition-colors", onClick: onKeep, children: translate("common.promo.aiCreditsOffer.exit.keep") }),
|
|
46
|
+
/* @__PURE__ */ jsx(Button, { variant: "secondary", className: "h-10! transition-colors", onClick: onLose, children: translate("common.promo.aiCreditsOffer.exit.lose") })
|
|
47
|
+
] })
|
|
48
|
+
]
|
|
49
|
+
}
|
|
50
|
+
) });
|
|
51
|
+
}
|
|
52
|
+
export {
|
|
53
|
+
LoseOfferDialog
|
|
54
|
+
};
|
|
55
|
+
//# sourceMappingURL=LoseOfferDialog.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/components/modals/promo/AiCreditsOfferModal/components/LoseOfferDialog.tsx"],"sourcesContent":["'use client';\n\nimport { useTranslations } from 'next-intl';\nimport { Button } from '../../../../ui/buttons/Button';\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from '../../../../ui/overlay/Dialog';\nimport { Separator } from '../../../../ui/data-display/Separator';\nimport { IconAlertTriangle } from '@tabler/icons-react';\n\ninterface LoseOfferDialogProps {\n open: boolean;\n /** Selo do desconto (\"50% OFF\") — repetido aqui porque é ele que dói. */\n discountLabel: string;\n /** Pacote ofertado, já formatado (\"1.000\"). */\n creditsLabel: string;\n /** Preço cheio formatado: o número que volta a valer. Vazio enquanto a âncora carrega. */\n fullPriceLabel: string;\n /** Volta pra oferta (fecha só esta confirmação). */\n onKeep: () => void;\n /** Abre mão da oferta e fecha tudo. */\n onLose: () => void;\n}\n\n/**\n * Confirmação de saída (\"quer mesmo perder essa oferta?\").\n *\n * É um Dialog SEPARADO, empilhado por cima da oferta com os mesmos z-index do\n * `InsufficientIaCreditsModal` (overlay 1002 / conteúdo 1003) — assim a oferta continua **visível\n * atrás do véu**: a pessoa decide olhando exatamente para o que está prestes a perder, que é o\n * ponto inteiro desta tela.\n *\n * O principal é VOLTAR para a oferta; perder fica como secundário, a um clique de distância. A\n * saída não está escondida — o peso da decisão está na frase, não no botão.\n */\nexport function LoseOfferDialog({\n open,\n discountLabel,\n creditsLabel,\n fullPriceLabel,\n onKeep,\n onLose,\n}: LoseOfferDialogProps) {\n const translate = useTranslations();\n\n return (\n <Dialog open={open} onOpenChange={(next) => !next && onKeep()}>\n <DialogContent\n showCloseButton={false}\n onOpenAutoFocus={(event) => event.preventDefault()}\n overlayClassName=\"z-[1002] bg-black/40\"\n className=\"z-[1003] flex flex-col gap-0 p-0 max-[440px]:w-[calc(100%-32px)] md:w-[420px]! lg:w-[420px]! max-w-[420px]! data-[state=open]:animate-[gp-offer-confirm-in_260ms_cubic-bezier(0.16,1,0.3,1)]\"\n >\n <DialogHeader className=\"gap-3 p-5 text-left\">\n <div className=\"flex w-fit items-center justify-center rounded-lg bg-red-50 p-2.5\">\n <IconAlertTriangle size={20} className=\"text-red-500\" />\n </div>\n <div className=\"flex flex-col gap-2\">\n <DialogTitle className=\"paragraph-medium-semibold text-zinc-950\">\n {translate('common.promo.aiCreditsOffer.exit.title', { discount: discountLabel })}\n </DialogTitle>\n <DialogDescription className=\"paragraph-small-regular text-zinc-600\">\n {/* Sem preço resolvido (elegibilidade ainda carregando) a frase cai na versão sem\n número — prometer \"volta a custar\" sem dizer quanto é pior do que não dizer. */}\n {fullPriceLabel\n ? translate('common.promo.aiCreditsOffer.exit.description', {\n credits: creditsLabel,\n price: fullPriceLabel,\n })\n : translate('common.promo.aiCreditsOffer.exit.descriptionNoPrice', {\n credits: creditsLabel,\n })}\n </DialogDescription>\n </div>\n </DialogHeader>\n\n <Separator />\n\n {/* Rodapé com os dois botões juntos à esquerda (`gap-2`, sem `justify-between`), o\n principal primeiro. Ficar é o caminho principal; perder a oferta continua a um clique,\n mas como ação secundária. */}\n <div className=\"flex items-center gap-2 p-5\">\n <Button className=\"h-10! transition-colors\" onClick={onKeep}>\n {translate('common.promo.aiCreditsOffer.exit.keep')}\n </Button>\n <Button variant=\"secondary\" className=\"h-10! transition-colors\" onClick={onLose}>\n {translate('common.promo.aiCreditsOffer.exit.lose')}\n </Button>\n </div>\n </DialogContent>\n </Dialog>\n );\n}\n"],"mappings":";AA2DY,cAEF,YAFE;AAzDZ,SAAS,uBAAuB;AAChC,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB;AAC1B,SAAS,yBAAyB;AA2B3B,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAyB;AACvB,QAAM,YAAY,gBAAgB;AAElC,SACE,oBAAC,UAAO,MAAY,cAAc,CAAC,SAAS,CAAC,QAAQ,OAAO,GAC1D;AAAA,IAAC;AAAA;AAAA,MACC,iBAAiB;AAAA,MACjB,iBAAiB,CAAC,UAAU,MAAM,eAAe;AAAA,MACjD,kBAAiB;AAAA,MACjB,WAAU;AAAA,MAEV;AAAA,6BAAC,gBAAa,WAAU,uBACtB;AAAA,8BAAC,SAAI,WAAU,qEACb,8BAAC,qBAAkB,MAAM,IAAI,WAAU,gBAAe,GACxD;AAAA,UACA,qBAAC,SAAI,WAAU,uBACb;AAAA,gCAAC,eAAY,WAAU,2CACpB,oBAAU,0CAA0C,EAAE,UAAU,cAAc,CAAC,GAClF;AAAA,YACA,oBAAC,qBAAkB,WAAU,yCAG1B,2BACG,UAAU,gDAAgD;AAAA,cACxD,SAAS;AAAA,cACT,OAAO;AAAA,YACT,CAAC,IACD,UAAU,uDAAuD;AAAA,cAC/D,SAAS;AAAA,YACX,CAAC,GACP;AAAA,aACF;AAAA,WACF;AAAA,QAEA,oBAAC,aAAU;AAAA,QAKX,qBAAC,SAAI,WAAU,+BACb;AAAA,8BAAC,UAAO,WAAU,2BAA0B,SAAS,QAClD,oBAAU,uCAAuC,GACpD;AAAA,UACA,oBAAC,UAAO,SAAQ,aAAY,WAAU,2BAA0B,SAAS,QACtE,oBA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