rapida-partner 8.15.0 → 8.17.0
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/README.md +4 -0
- package/package.json +5 -1
- package/src/interfaces/card-terminal.interface.ts +60 -0
- package/src/interfaces/cash.interface.ts +31 -0
- package/src/interfaces/project.interface.ts +8 -0
- package/src/interfaces/store-order.interface.ts +5 -0
- package/src/interfaces/store-settings.interface.ts +4 -0
- package/src/schemas/module.ref.json +14 -0
- package/src/schemas/store-settings.ref.json +2 -0
- package/src/utils/cash.test.ts +98 -0
- package/src/utils/cash.ts +81 -0
- package/src/utils/store-receivable.test.ts +76 -0
- package/src/utils/store-receivable.ts +76 -0
package/README.md
CHANGED
|
@@ -84,6 +84,10 @@ A validação é feita através do módulo `src/utils/json.ts`, que utiliza as
|
|
|
84
84
|
4. Exibe os erros de validação caso o projeto não esteja em conformidade.
|
|
85
85
|
|
|
86
86
|
|
|
87
|
+
## Publicação no npm
|
|
88
|
+
|
|
89
|
+
A publicação é automática: quando um merge na `main` muda a `version` do `package.json` para uma versão que ainda não está no npm, o workflow `.github/workflows/publish.yml` roda `bun test` e publica com `npm publish` (Trusted Publishing, com provenance). Não é preciso rodar `npm publish` à mão nem guardar token. Para publicar uma versão nova, basta subir a `version` (e o `CHANGELOG.md`) no PR. Se for preciso, dá para disparar o workflow manualmente em *Actions → Publish to npm → Run workflow*; versão já publicada é ignorada.
|
|
90
|
+
|
|
87
91
|
## Problemas Conhecidos
|
|
88
92
|
|
|
89
93
|
- No atributo `contracts[n].request.fields[n]`, se o `dataType` for `"array"`, é necessário inserir um campo `elements` para descrever melhor a estrutura do array no contrato.
|
package/package.json
CHANGED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { TStorePaymentChoice } from "./store-order.interface";
|
|
2
|
+
|
|
3
|
+
/** Formas que passam na maquininha e geram conta a receber com taxa e prazo (Fase 3 do PDV). */
|
|
4
|
+
export type TCardTerminalModality = Extract<TStorePaymentChoice, "debitCard" | "creditCard" | "pixTerminal">;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Maquininha da loja (Fase 3 do PDV). Uma loja pode ter várias (ex.: Stone no balcão, Cielo na entrega).
|
|
8
|
+
* Cada modalidade tem a taxa em % e o prazo de recebimento em dias corridos (D+N). Sem taxa, vale 0;
|
|
9
|
+
* sem prazo, vale D+0. bankAccountId é a conta onde a adquirente deposita.
|
|
10
|
+
* Crédito é só à vista nesta fase: parcelado fica para depois, sem quebrar este formato.
|
|
11
|
+
*/
|
|
12
|
+
export interface ICardTerminal {
|
|
13
|
+
name: string;
|
|
14
|
+
acquirer?: string;
|
|
15
|
+
bankAccountId: string;
|
|
16
|
+
isActive?: boolean;
|
|
17
|
+
debitFeePercent?: number;
|
|
18
|
+
debitSettlementDays?: number;
|
|
19
|
+
creditFeePercent?: number;
|
|
20
|
+
creditSettlementDays?: number;
|
|
21
|
+
pixFeePercent?: number;
|
|
22
|
+
pixSettlementDays?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Taxa e prazo de uma modalidade da maquininha. */
|
|
26
|
+
export interface ICardTerminalRate {
|
|
27
|
+
feePercent: number;
|
|
28
|
+
settlementDays: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** De onde veio a conta a receber: lançada à mão ou gerada pelo pedido entregue (PDV). */
|
|
32
|
+
export type TReceivableOrigin = "manual" | "storeOrder";
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Campos novos e opcionais da conta a receber (payableReceivableAccount), preenchidos só pelo sistema
|
|
36
|
+
* quando a conta nasce de um pedido entregue. Conta com origin "storeOrder" não é editável à mão:
|
|
37
|
+
* o acerto é pelo pedido (cancelar estorna).
|
|
38
|
+
* - grossAmount: valor do pedido; feeAmount: taxa da maquininha; netAmount: o que cai na conta.
|
|
39
|
+
* - A taxa entra como desconto na baixa: a baixa quita grossAmount com financeAmount = netAmount.
|
|
40
|
+
*/
|
|
41
|
+
export interface IStoreOrderReceivableFields {
|
|
42
|
+
origin?: TReceivableOrigin;
|
|
43
|
+
storeOrderId?: string;
|
|
44
|
+
paymentChoice?: TStorePaymentChoice;
|
|
45
|
+
cardTerminalId?: string;
|
|
46
|
+
grossAmount?: number;
|
|
47
|
+
feeAmount?: number;
|
|
48
|
+
netAmount?: number;
|
|
49
|
+
nsu?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Lançamento automático na conta a receber (Fase 3 do PDV), declarado no módulo das maquininhas
|
|
54
|
+
* (IModule.storeReceivables). Exige o quadro de pedidos (storeOrdersBoard), o módulo financeiro e
|
|
55
|
+
* flows.authentication + flows.permission. revenueCategoryName: categoria financeira das contas geradas
|
|
56
|
+
* (criada se não existir; padrão "Vendas da loja").
|
|
57
|
+
*/
|
|
58
|
+
export interface IStoreReceivables {
|
|
59
|
+
revenueCategoryName?: string;
|
|
60
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Suprimento (entra dinheiro no caixa) ou sangria (sai dinheiro do caixa). */
|
|
2
|
+
export type TCashMovementKind = "supply" | "withdrawal";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Movimento do caixa durante o turno (Fase 2 do PDV). approvedBy só existe quando o
|
|
6
|
+
* valor passou do limite da loja (IStoreSettings.cashApprovalLimit) e o gerente aprovou.
|
|
7
|
+
*/
|
|
8
|
+
export interface ICashMovement {
|
|
9
|
+
kind: TCashMovementKind;
|
|
10
|
+
amount: number;
|
|
11
|
+
reason: string;
|
|
12
|
+
createdBy: string;
|
|
13
|
+
approvedBy?: string;
|
|
14
|
+
createdAt: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Turno de um caixa. Um caixa só pode ter um turno aberto. cashSales soma as vendas em
|
|
19
|
+
* dinheiro do turno; countedAmount e justification existem depois do fechamento.
|
|
20
|
+
*/
|
|
21
|
+
export interface ICashShift {
|
|
22
|
+
registerName: string;
|
|
23
|
+
openedBy: string;
|
|
24
|
+
openedAt: string;
|
|
25
|
+
openingFloat: number;
|
|
26
|
+
cashSales: number;
|
|
27
|
+
movements: ICashMovement[];
|
|
28
|
+
closedAt?: string;
|
|
29
|
+
countedAmount?: number;
|
|
30
|
+
justification?: string;
|
|
31
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { IStoreReceivables } from "./card-terminal.interface";
|
|
1
2
|
import type { IAiAgentConfig } from "./ai-agent.interface";
|
|
2
3
|
import type { IDataCard } from "./data-card.interface";
|
|
3
4
|
import type { IDataChart } from "./data-chart.interface";
|
|
@@ -253,6 +254,13 @@ export interface IModule {
|
|
|
253
254
|
// Quadro de pedidos do vendedor (Fase 8): no módulo de pedidos da loja
|
|
254
255
|
// (getStoreOrdersModule), o gerador cria as rotas e a tela do quadro.
|
|
255
256
|
storeOrdersBoard?: IStoreOrdersBoard;
|
|
257
|
+
// Caixa e turno do balcão (Fase 2 do PDV): o gerador cria as rotas (abrir caixa, venda, suprimento e sangria,
|
|
258
|
+
// fechamento) no backend do vendedor. Exige flows.authentication e flows.permission. approvalLimit: acima deste
|
|
259
|
+
// valor, suprimento e sangria pedem login e senha de quem tem papel 'owner' ou 'manager' (sem valor, sempre pedem).
|
|
260
|
+
cashShift?: { approvalLimit?: number };
|
|
261
|
+
// Maquininhas e lançamento automático na conta a receber (Fase 3 do PDV), declarado no módulo das maquininhas:
|
|
262
|
+
// pedido entregue vira conta a receber (maquininha em D+N com taxa; Pix direto e dinheiro liquidados).
|
|
263
|
+
storeReceivables?: IStoreReceivables;
|
|
256
264
|
components: IComponent[];
|
|
257
265
|
businessRules?: IBusinessRule[];
|
|
258
266
|
todo?: ITodo[];
|
|
@@ -149,6 +149,11 @@ export interface IStoreOrder {
|
|
|
149
149
|
paymentChoice?: TStorePaymentChoice;
|
|
150
150
|
// Destino na mesa (fase 1): vazio fora da mesa.
|
|
151
151
|
consumptionMode?: TStoreConsumptionMode;
|
|
152
|
+
// Maquininha em que o pagamento passou, escolhida ao confirmar a entrega (Fase 3 do PDV), e o NSU do comprovante.
|
|
153
|
+
cardTerminalId?: string;
|
|
154
|
+
nsu?: string;
|
|
155
|
+
// Conta a receber gerada quando o pedido foi entregue (Fase 3 do PDV); voltar da entrega ou cancelar a estorna.
|
|
156
|
+
receivableAccountId?: string;
|
|
152
157
|
changeFor?: number;
|
|
153
158
|
paymentReceived?: boolean;
|
|
154
159
|
// Meio do pagamento online (Fase 8.1); vazio no pagamento na entrega.
|
|
@@ -164,6 +164,10 @@ export interface IStoreSettings extends Partial<Record<TStoreFeatureToggle, bool
|
|
|
164
164
|
deliveryPaymentChoices?: TStorePaymentChoice[];
|
|
165
165
|
// Chave Pix da loja, usada pela forma "pixDirect" (sem taxa, com confirmação manual pelo vendedor).
|
|
166
166
|
pixKey?: string;
|
|
167
|
+
// Conta bancária da chave Pix (Fase 3 do PDV): a conta a receber do Pix direto nasce liquidada nela.
|
|
168
|
+
pixBankAccountId?: string;
|
|
169
|
+
// Conta do dinheiro (tipo "cash", Fase 3 do PDV): o pedido entregue pago em dinheiro entra como recebido nela.
|
|
170
|
+
cashBankAccountId?: string;
|
|
167
171
|
// Funcionalidade "stockReservation": por quantos minutos o pedido aguardando
|
|
168
172
|
// pagamento segura o estoque (de 5 a 60). Vencido o prazo, o pedido é
|
|
169
173
|
// cancelado, o link de pagamento expira e a quantidade volta. Sem o campo,
|
|
@@ -30,6 +30,20 @@
|
|
|
30
30
|
"required": ["segment"],
|
|
31
31
|
"additionalProperties": false
|
|
32
32
|
},
|
|
33
|
+
"cashShift": {
|
|
34
|
+
"type": "object",
|
|
35
|
+
"properties": {
|
|
36
|
+
"approvalLimit": { "type": "number", "minimum": 0 }
|
|
37
|
+
},
|
|
38
|
+
"additionalProperties": false
|
|
39
|
+
},
|
|
40
|
+
"storeReceivables": {
|
|
41
|
+
"type": "object",
|
|
42
|
+
"properties": {
|
|
43
|
+
"revenueCategoryName": { "type": "string" }
|
|
44
|
+
},
|
|
45
|
+
"additionalProperties": false
|
|
46
|
+
},
|
|
33
47
|
"components": {
|
|
34
48
|
"type": "array",
|
|
35
49
|
"items": {
|
|
@@ -91,6 +91,8 @@
|
|
|
91
91
|
"items": { "enum": ["debitCard", "creditCard", "pixTerminal", "cash"] }
|
|
92
92
|
},
|
|
93
93
|
"pixKey": { "type": "string" },
|
|
94
|
+
"pixBankAccountId": { "type": "string" },
|
|
95
|
+
"cashBankAccountId": { "type": "string" },
|
|
94
96
|
"reservationMinutes": { "type": "integer", "minimum": 5, "maximum": 60 },
|
|
95
97
|
"ordersPaused": { "type": "boolean" },
|
|
96
98
|
"aboutText": { "type": "string" },
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import type { ICashShift } from "../interfaces/cash.interface";
|
|
3
|
+
import { canOpenShift, closeCashShift, cashDifferenceOf, expectedCashOf, recordCashMovement, withCashSale } from "./cash";
|
|
4
|
+
|
|
5
|
+
const openShift = (openingFloat: number): ICashShift => ({
|
|
6
|
+
registerName: "Caixa 1",
|
|
7
|
+
openedBy: "ana",
|
|
8
|
+
openedAt: "2026-11-28T08:00:00.000Z",
|
|
9
|
+
openingFloat,
|
|
10
|
+
cashSales: 0,
|
|
11
|
+
movements: [],
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
const at = "2026-11-28T10:00:00.000Z";
|
|
15
|
+
|
|
16
|
+
describe("abrir caixa", () => {
|
|
17
|
+
test("um turno aberto por caixa: não abre se o caixa já tem turno", () => {
|
|
18
|
+
expect(canOpenShift(false)).toBe(true);
|
|
19
|
+
expect(canOpenShift(true)).toBe(false);
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
describe("venda em dinheiro entra no turno", () => {
|
|
24
|
+
test("soma no turno aberto e recusa com o turno fechado", () => {
|
|
25
|
+
const sold = withCashSale(openShift(100), 24);
|
|
26
|
+
expect(sold.ok && sold.value.cashSales).toBe(24);
|
|
27
|
+
const closed = closeCashShift(openShift(100), 100, at);
|
|
28
|
+
if (!closed.ok) throw new Error("fechamento deveria passar");
|
|
29
|
+
expect(withCashSale(closed.value, 10)).toEqual({ ok: false, reason: "shiftClosed" });
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe("suprimento e sangria: limite da loja", () => {
|
|
34
|
+
test("abaixo do limite, a equipe registra sem gerente e fica quem fez", () => {
|
|
35
|
+
const result = recordCashMovement(openShift(100), { kind: "withdrawal", amount: 100, reason: "troco", createdBy: "ana", createdAt: at, approvalLimit: 300 });
|
|
36
|
+
expect(result.ok).toBe(true);
|
|
37
|
+
if (!result.ok) return;
|
|
38
|
+
expect(result.value.movements[0]).toEqual({ kind: "withdrawal", amount: 100, reason: "troco", createdBy: "ana", createdAt: at });
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("acima do limite, sem gerente, bloqueia", () => {
|
|
42
|
+
const result = recordCashMovement(openShift(100), { kind: "withdrawal", amount: 500, reason: "pagamento", createdBy: "ana", createdAt: at, approvalLimit: 300 });
|
|
43
|
+
expect(result).toEqual({ ok: false, reason: "managerApprovalRequired" });
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("acima do limite, com gerente, registra quem aprovou", () => {
|
|
47
|
+
const result = recordCashMovement(openShift(100), { kind: "withdrawal", amount: 500, reason: "pagamento", createdBy: "ana", approvedBy: "carlos", createdAt: at, approvalLimit: 300 });
|
|
48
|
+
expect(result.ok && result.value.movements[0]?.approvedBy).toBe("carlos");
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("sem limite configurado, sempre pede gerente; motivo e valor são obrigatórios", () => {
|
|
52
|
+
expect(recordCashMovement(openShift(100), { kind: "supply", amount: 10, reason: "x", createdBy: "ana", createdAt: at })).toEqual({ ok: false, reason: "managerApprovalRequired" });
|
|
53
|
+
expect(recordCashMovement(openShift(100), { kind: "supply", amount: 10, reason: " ", createdBy: "ana", createdAt: at, approvedBy: "carlos" })).toEqual({ ok: false, reason: "reasonRequired" });
|
|
54
|
+
expect(recordCashMovement(openShift(100), { kind: "supply", amount: 0, reason: "x", createdBy: "ana", createdAt: at, approvedBy: "carlos" })).toEqual({ ok: false, reason: "invalidAmount" });
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe("dinheiro esperado e fechamento", () => {
|
|
59
|
+
test("esperado = fundo + vendas em dinheiro + suprimentos − sangrias", () => {
|
|
60
|
+
let shift = openShift(100);
|
|
61
|
+
const sold = withCashSale(shift, 80);
|
|
62
|
+
if (!sold.ok) throw new Error("venda deveria passar");
|
|
63
|
+
shift = sold.value;
|
|
64
|
+
const supply = recordCashMovement(shift, { kind: "supply", amount: 20, reason: "reforço", createdBy: "ana", createdAt: at, approvalLimit: 300 });
|
|
65
|
+
if (!supply.ok) throw new Error("suprimento deveria passar");
|
|
66
|
+
const withdrawal = recordCashMovement(supply.value, { kind: "withdrawal", amount: 30, reason: "troco", createdBy: "ana", createdAt: at, approvalLimit: 300 });
|
|
67
|
+
if (!withdrawal.ok) throw new Error("sangria deveria passar");
|
|
68
|
+
expect(expectedCashOf(withdrawal.value)).toBe(170);
|
|
69
|
+
expect(cashDifferenceOf(withdrawal.value, 165)).toBe(-5);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test("diferença de R$ 5,00 sem justificativa não fecha", () => {
|
|
73
|
+
const shift = withCashSale(openShift(100), 80);
|
|
74
|
+
if (!shift.ok) throw new Error("venda deveria passar");
|
|
75
|
+
expect(closeCashShift(shift.value, 175, at)).toEqual({ ok: false, reason: "justificationRequired" });
|
|
76
|
+
expect(closeCashShift(shift.value, 175, at, " ")).toEqual({ ok: false, reason: "justificationRequired" });
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test("diferença com justificativa fecha e guarda o contado e a justificativa", () => {
|
|
80
|
+
const shift = withCashSale(openShift(100), 80);
|
|
81
|
+
if (!shift.ok) throw new Error("venda deveria passar");
|
|
82
|
+
const closed = closeCashShift(shift.value, 175, at, "troco errado");
|
|
83
|
+
expect(closed.ok && closed.value.countedAmount).toBe(175);
|
|
84
|
+
expect(closed.ok && closed.value.justification).toBe("troco errado");
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("sem diferença, fecha sem justificativa", () => {
|
|
88
|
+
const closed = closeCashShift(openShift(100), 100, at);
|
|
89
|
+
expect(closed.ok).toBe(true);
|
|
90
|
+
expect(closed.ok && closed.value.justification).toBeUndefined();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("turno fechado não aceita mais movimento", () => {
|
|
94
|
+
const closed = closeCashShift(openShift(100), 100, at);
|
|
95
|
+
if (!closed.ok) throw new Error("fechamento deveria passar");
|
|
96
|
+
expect(recordCashMovement(closed.value, { kind: "supply", amount: 10, reason: "x", createdBy: "ana", createdAt: at, approvedBy: "carlos" })).toEqual({ ok: false, reason: "shiftClosed" });
|
|
97
|
+
});
|
|
98
|
+
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { ICashMovement, ICashShift, TCashMovementKind } from "../interfaces/cash.interface";
|
|
2
|
+
|
|
3
|
+
export type TCashResult<T> = { ok: true; value: T } | { ok: false; reason: TCashRefusal };
|
|
4
|
+
|
|
5
|
+
export type TCashRefusal = "shiftClosed" | "invalidAmount" | "reasonRequired" | "managerApprovalRequired" | "justificationRequired";
|
|
6
|
+
|
|
7
|
+
const cents = (value: number): number => Math.round(value * 100) / 100;
|
|
8
|
+
|
|
9
|
+
/** Sem limite configurado, qualquer movimento pede aprovação do gerente. */
|
|
10
|
+
export const cashMovementNeedsApproval = (amount: number, approvalLimit: number | undefined): boolean =>
|
|
11
|
+
approvalLimit === undefined || amount > approvalLimit;
|
|
12
|
+
|
|
13
|
+
/** Dinheiro esperado na gaveta: fundo + vendas em dinheiro + suprimentos − sangrias. */
|
|
14
|
+
export const expectedCashOf = (shift: ICashShift): number => {
|
|
15
|
+
const movementTotal = (kind: TCashMovementKind): number =>
|
|
16
|
+
shift.movements.filter((movement: ICashMovement) => movement.kind === kind).reduce((sum, movement) => sum + movement.amount, 0);
|
|
17
|
+
return cents(shift.openingFloat + shift.cashSales + movementTotal("supply") - movementTotal("withdrawal"));
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** Diferença do fechamento: contado − esperado (negativa = falta dinheiro). */
|
|
21
|
+
export const cashDifferenceOf = (shift: ICashShift, counted: number): number => cents(counted - expectedCashOf(shift));
|
|
22
|
+
|
|
23
|
+
/** Um turno aberto por caixa: abrir é permitido só se o caixa não tem turno aberto. */
|
|
24
|
+
export const canOpenShift = (registerHasOpenShift: boolean): boolean => !registerHasOpenShift;
|
|
25
|
+
|
|
26
|
+
/** Registra uma venda em dinheiro no turno aberto. */
|
|
27
|
+
export const withCashSale = (shift: ICashShift, amount: number): TCashResult<ICashShift> => {
|
|
28
|
+
if (shift.closedAt) return { ok: false, reason: "shiftClosed" };
|
|
29
|
+
if (!(amount > 0)) return { ok: false, reason: "invalidAmount" };
|
|
30
|
+
return { ok: true, value: { ...shift, cashSales: cents(shift.cashSales + amount) } };
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export interface ICashMovementInput {
|
|
34
|
+
kind: TCashMovementKind;
|
|
35
|
+
amount: number;
|
|
36
|
+
reason: string;
|
|
37
|
+
createdBy: string;
|
|
38
|
+
createdAt: string;
|
|
39
|
+
approvedBy?: string;
|
|
40
|
+
approvalLimit?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Suprimento ou sangria. Acima do limite da loja, exige o gerente (approvedBy); abaixo,
|
|
45
|
+
* a própria equipe registra. Quem fez e, se houver, quem aprovou ficam no movimento.
|
|
46
|
+
*/
|
|
47
|
+
export const recordCashMovement = (shift: ICashShift, input: ICashMovementInput): TCashResult<ICashShift> => {
|
|
48
|
+
if (shift.closedAt) return { ok: false, reason: "shiftClosed" };
|
|
49
|
+
if (!(input.amount > 0)) return { ok: false, reason: "invalidAmount" };
|
|
50
|
+
if (!input.reason.trim()) return { ok: false, reason: "reasonRequired" };
|
|
51
|
+
const needsApproval = cashMovementNeedsApproval(input.amount, input.approvalLimit);
|
|
52
|
+
if (needsApproval && !input.approvedBy) return { ok: false, reason: "managerApprovalRequired" };
|
|
53
|
+
const movement: ICashMovement = {
|
|
54
|
+
kind: input.kind,
|
|
55
|
+
amount: cents(input.amount),
|
|
56
|
+
reason: input.reason.trim(),
|
|
57
|
+
createdBy: input.createdBy,
|
|
58
|
+
createdAt: input.createdAt,
|
|
59
|
+
...(needsApproval && input.approvedBy ? { approvedBy: input.approvedBy } : {}),
|
|
60
|
+
};
|
|
61
|
+
return { ok: true, value: { ...shift, movements: [...shift.movements, movement] } };
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Fechamento: compara contado com esperado. Diferença diferente de zero exige justificativa;
|
|
66
|
+
* depois de fechado, o turno não aceita mais movimento.
|
|
67
|
+
*/
|
|
68
|
+
export const closeCashShift = (shift: ICashShift, counted: number, closedAt: string, justification?: string): TCashResult<ICashShift> => {
|
|
69
|
+
if (shift.closedAt) return { ok: false, reason: "shiftClosed" };
|
|
70
|
+
const difference = cashDifferenceOf(shift, counted);
|
|
71
|
+
if (difference !== 0 && !(justification ?? "").trim()) return { ok: false, reason: "justificationRequired" };
|
|
72
|
+
return {
|
|
73
|
+
ok: true,
|
|
74
|
+
value: {
|
|
75
|
+
...shift,
|
|
76
|
+
closedAt,
|
|
77
|
+
countedAmount: cents(counted),
|
|
78
|
+
...(difference !== 0 ? { justification: (justification ?? "").trim() } : {}),
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import type { ICardTerminal } from "../interfaces/card-terminal.interface";
|
|
3
|
+
import { cardTerminalRateOf, needsCardTerminal, storeReceivablePlanOf } from "./store-receivable";
|
|
4
|
+
|
|
5
|
+
const stone: ICardTerminal = {
|
|
6
|
+
name: "Stone balcão",
|
|
7
|
+
bankAccountId: "bank-1",
|
|
8
|
+
debitFeePercent: 1.5,
|
|
9
|
+
debitSettlementDays: 1,
|
|
10
|
+
creditFeePercent: 3.2,
|
|
11
|
+
creditSettlementDays: 30,
|
|
12
|
+
};
|
|
13
|
+
const deliveredAt = new Date("2026-11-28T20:00:00.000Z");
|
|
14
|
+
|
|
15
|
+
describe("maquininha", () => {
|
|
16
|
+
test("só débito, crédito e Pix na maquininha pedem maquininha", () => {
|
|
17
|
+
expect(needsCardTerminal("debitCard")).toBe(true);
|
|
18
|
+
expect(needsCardTerminal("creditCard")).toBe(true);
|
|
19
|
+
expect(needsCardTerminal("pixTerminal")).toBe(true);
|
|
20
|
+
expect(needsCardTerminal("pixDirect")).toBe(false);
|
|
21
|
+
expect(needsCardTerminal("cash")).toBe(false);
|
|
22
|
+
expect(needsCardTerminal(undefined)).toBe(false);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("taxa e prazo por modalidade; sem valor vale 0 e D+0", () => {
|
|
26
|
+
expect(cardTerminalRateOf(stone, "creditCard")).toEqual({ feePercent: 3.2, settlementDays: 30 });
|
|
27
|
+
expect(cardTerminalRateOf(stone, "pixTerminal")).toEqual({ feePercent: 0, settlementDays: 0 });
|
|
28
|
+
expect(cardTerminalRateOf({ ...stone, debitFeePercent: -2, debitSettlementDays: 1.7 }, "debitCard")).toEqual({ feePercent: 0, settlementDays: 1 });
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
describe("pedido entregue vira conta a receber", () => {
|
|
33
|
+
test("crédito: em aberto em D+30, com taxa e líquido", () => {
|
|
34
|
+
expect(storeReceivablePlanOf({ total: 100, paymentChoice: "creditCard", deliveredAt, terminal: stone })).toEqual({
|
|
35
|
+
paymentChoice: "creditCard",
|
|
36
|
+
grossAmount: 100,
|
|
37
|
+
feePercent: 3.2,
|
|
38
|
+
feeAmount: 3.2,
|
|
39
|
+
netAmount: 96.8,
|
|
40
|
+
dueDate: "2026-12-28T20:00:00.000Z",
|
|
41
|
+
settled: false,
|
|
42
|
+
goesToCashShift: false,
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("taxa arredonda em centavos", () => {
|
|
47
|
+
const plan = storeReceivablePlanOf({ total: 33.33, paymentChoice: "debitCard", deliveredAt, terminal: stone });
|
|
48
|
+
expect(plan).toMatchObject({ feeAmount: 0.5, netAmount: 32.83, dueDate: "2026-11-29T20:00:00.000Z" });
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("maquininha sem maquininha escolhida é recusada", () => {
|
|
52
|
+
expect(storeReceivablePlanOf({ total: 50, paymentChoice: "debitCard", deliveredAt })).toBe("CARD_TERMINAL_REQUIRED");
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("Pix direto: liquidada na hora, sem taxa e fora do caixa", () => {
|
|
56
|
+
expect(storeReceivablePlanOf({ total: 40, paymentChoice: "pixDirect", deliveredAt })).toMatchObject({
|
|
57
|
+
feeAmount: 0,
|
|
58
|
+
netAmount: 40,
|
|
59
|
+
settled: true,
|
|
60
|
+
goesToCashShift: false,
|
|
61
|
+
dueDate: deliveredAt.toISOString(),
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("dinheiro: liquidada na hora e soma no turno aberto", () => {
|
|
66
|
+
expect(storeReceivablePlanOf({ total: 25, paymentChoice: "cash", deliveredAt, terminal: stone })).toMatchObject({
|
|
67
|
+
feeAmount: 0,
|
|
68
|
+
settled: true,
|
|
69
|
+
goesToCashShift: true,
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("pedido sem valor não gera conta", () => {
|
|
74
|
+
expect(storeReceivablePlanOf({ total: 0, paymentChoice: "cash", deliveredAt })).toBe("INVALID_AMOUNT");
|
|
75
|
+
});
|
|
76
|
+
});
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { ICardTerminal, ICardTerminalRate, TCardTerminalModality } from "../interfaces/card-terminal.interface";
|
|
2
|
+
import type { TStorePaymentChoice } from "../interfaces/store-order.interface";
|
|
3
|
+
|
|
4
|
+
/** Categoria das contas a receber geradas pelos pedidos, quando o módulo não informa outra. */
|
|
5
|
+
export const STORE_RECEIVABLE_DEFAULT_CATEGORY = "Vendas da loja";
|
|
6
|
+
|
|
7
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
8
|
+
const cents = (value: number): number => Math.round(value * 100) / 100;
|
|
9
|
+
|
|
10
|
+
/** Forma que passa na maquininha: precisa escolher qual maquininha ao confirmar a entrega. */
|
|
11
|
+
export const needsCardTerminal = (choice: TStorePaymentChoice | undefined): choice is TCardTerminalModality =>
|
|
12
|
+
choice === "debitCard" || choice === "creditCard" || choice === "pixTerminal";
|
|
13
|
+
|
|
14
|
+
/** Taxa e prazo da modalidade na maquininha. Sem valor, taxa 0 e D+0; valores negativos viram 0. */
|
|
15
|
+
export const cardTerminalRateOf = (terminal: ICardTerminal, modality: TCardTerminalModality): ICardTerminalRate => {
|
|
16
|
+
const pick = (fee: number | undefined, days: number | undefined): ICardTerminalRate => ({
|
|
17
|
+
feePercent: Math.max(Number(fee) || 0, 0),
|
|
18
|
+
settlementDays: Math.max(Math.trunc(Number(days) || 0), 0),
|
|
19
|
+
});
|
|
20
|
+
if (modality === "debitCard") return pick(terminal.debitFeePercent, terminal.debitSettlementDays);
|
|
21
|
+
if (modality === "creditCard") return pick(terminal.creditFeePercent, terminal.creditSettlementDays);
|
|
22
|
+
return pick(terminal.pixFeePercent, terminal.pixSettlementDays);
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Como o pedido entregue vira conta a receber:
|
|
27
|
+
* - maquininha (débito, crédito, Pix na maquininha): em aberto, vence em D+N, com taxa e líquido;
|
|
28
|
+
* - Pix direto: liquidada na hora, sem taxa;
|
|
29
|
+
* - dinheiro: liquidada na hora, sem taxa, e soma nas vendas em dinheiro do turno aberto (goesToCashShift).
|
|
30
|
+
*/
|
|
31
|
+
export interface IStoreReceivablePlan {
|
|
32
|
+
paymentChoice: TStorePaymentChoice;
|
|
33
|
+
grossAmount: number;
|
|
34
|
+
feePercent: number;
|
|
35
|
+
feeAmount: number;
|
|
36
|
+
netAmount: number;
|
|
37
|
+
dueDate: string;
|
|
38
|
+
settled: boolean;
|
|
39
|
+
goesToCashShift: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type TStoreReceivablePlanError = "CARD_TERMINAL_REQUIRED" | "INVALID_AMOUNT";
|
|
43
|
+
|
|
44
|
+
export const storeReceivablePlanOf = (input: {
|
|
45
|
+
total: number;
|
|
46
|
+
paymentChoice: TStorePaymentChoice;
|
|
47
|
+
deliveredAt: Date;
|
|
48
|
+
terminal?: ICardTerminal;
|
|
49
|
+
}): IStoreReceivablePlan | TStoreReceivablePlanError => {
|
|
50
|
+
const grossAmount = cents(Number(input.total) || 0);
|
|
51
|
+
if (grossAmount <= 0) return "INVALID_AMOUNT";
|
|
52
|
+
const base = { paymentChoice: input.paymentChoice, grossAmount };
|
|
53
|
+
if (!needsCardTerminal(input.paymentChoice)) {
|
|
54
|
+
return {
|
|
55
|
+
...base,
|
|
56
|
+
feePercent: 0,
|
|
57
|
+
feeAmount: 0,
|
|
58
|
+
netAmount: grossAmount,
|
|
59
|
+
dueDate: input.deliveredAt.toISOString(),
|
|
60
|
+
settled: true,
|
|
61
|
+
goesToCashShift: input.paymentChoice === "cash",
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
if (!input.terminal) return "CARD_TERMINAL_REQUIRED";
|
|
65
|
+
const rate = cardTerminalRateOf(input.terminal, input.paymentChoice);
|
|
66
|
+
const feeAmount = cents((grossAmount * rate.feePercent) / 100);
|
|
67
|
+
return {
|
|
68
|
+
...base,
|
|
69
|
+
feePercent: rate.feePercent,
|
|
70
|
+
feeAmount,
|
|
71
|
+
netAmount: cents(grossAmount - feeAmount),
|
|
72
|
+
dueDate: new Date(input.deliveredAt.getTime() + rate.settlementDays * DAY_MS).toISOString(),
|
|
73
|
+
settled: false,
|
|
74
|
+
goesToCashShift: false,
|
|
75
|
+
};
|
|
76
|
+
};
|