rapida-partner 8.17.0 → 8.19.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/package.json +1 -1
- package/src/interfaces/cash.interface.ts +8 -0
- package/src/interfaces/counter.interface.ts +38 -0
- package/src/interfaces/recipe.interface.ts +38 -0
- package/src/interfaces/store-order.interface.ts +15 -0
- package/src/interfaces/store-settings.interface.ts +5 -0
- package/src/schemas/store-settings.ref.json +2 -0
- package/src/utils/counter.test.ts +35 -0
- package/src/utils/counter.ts +55 -0
- package/src/utils/recipe.test.ts +66 -0
- package/src/utils/recipe.ts +113 -0
package/package.json
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { TCounterPaymentChoice } from "./counter.interface";
|
|
2
|
+
|
|
1
3
|
/** Suprimento (entra dinheiro no caixa) ou sangria (sai dinheiro do caixa). */
|
|
2
4
|
export type TCashMovementKind = "supply" | "withdrawal";
|
|
3
5
|
|
|
@@ -28,4 +30,10 @@ export interface ICashShift {
|
|
|
28
30
|
closedAt?: string;
|
|
29
31
|
countedAmount?: number;
|
|
30
32
|
justification?: string;
|
|
33
|
+
// Balcão (Fase 6): vendas por forma de pagamento (já sem o troco), número de vendas e de cancelamentos,
|
|
34
|
+
// e o que o operador contou de cada forma no fechamento (conferência por forma).
|
|
35
|
+
salesByMethod?: Partial<Record<TCounterPaymentChoice, number>>;
|
|
36
|
+
salesCount?: number;
|
|
37
|
+
cancelledCount?: number;
|
|
38
|
+
countedByMethod?: Partial<Record<TCounterPaymentChoice, number>>;
|
|
31
39
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { TStorePaymentChoice } from "./store-order.interface";
|
|
2
|
+
|
|
3
|
+
/** Canal da venda: loja online (padrão) ou balcão (PDV, Fase 6). */
|
|
4
|
+
export type TStoreSalesChannel = "online" | "counter";
|
|
5
|
+
|
|
6
|
+
/** Formas aceitas no caixa do balcão: dinheiro, Pix pela chave da loja (QR), Pix na maquininha, crédito e débito. */
|
|
7
|
+
export type TCounterPaymentChoice = Extract<TStorePaymentChoice, "cash" | "pixDirect" | "pixTerminal" | "creditCard" | "debitCard">;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Um pagamento da venda do balcão. A venda pode ser dividida em várias formas; só o dinheiro gera troco.
|
|
11
|
+
* cardTerminalId é a maquininha (crédito, débito e Pix na maquininha).
|
|
12
|
+
*/
|
|
13
|
+
export interface IStoreOrderPayment {
|
|
14
|
+
paymentChoice: TCounterPaymentChoice;
|
|
15
|
+
amount: number;
|
|
16
|
+
cardTerminalId?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Desconto da venda do balcão: em percentual do subtotal ou em reais. */
|
|
20
|
+
export interface ICounterDiscount {
|
|
21
|
+
kind: "percent" | "amount";
|
|
22
|
+
value: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Configuração do caixa do balcão (Fase 6), por cliente (workspace). approvalLimit já existia (Fase 2).
|
|
27
|
+
* - alertLimit: com mais dinheiro que isso na gaveta, o topo do caixa pede sangria;
|
|
28
|
+
* - blindClose: conferência cega (o operador conta antes de ver o esperado);
|
|
29
|
+
* - paymentChoices: formas aceitas no caixa;
|
|
30
|
+
* - registers: nomes dos caixas (ex.: "Caixa 1", "Balcão delivery").
|
|
31
|
+
*/
|
|
32
|
+
export interface ICashSettings {
|
|
33
|
+
approvalLimit?: number;
|
|
34
|
+
alertLimit?: number;
|
|
35
|
+
blindClose?: boolean;
|
|
36
|
+
paymentChoices?: TCounterPaymentChoice[];
|
|
37
|
+
registers?: string[];
|
|
38
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unidade de medida do produto (saleMeasure) e da linha da ficha técnica. Massa (kg, g, mg) e volume (l, ml)
|
|
3
|
+
* convertem entre si dentro da família; "unit" e as medidas de comprimento, área e volume sólido não convertem.
|
|
4
|
+
*/
|
|
5
|
+
export type TMeasureUnit = "unit" | "kg" | "g" | "mg" | "m" | "cm" | "mm" | "l" | "ml" | "m2" | "m3";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Linha da ficha técnica (aba "Insumos" do produto, productsInputs). inputQuantity aceita decimal (Fase 5 do PDV);
|
|
9
|
+
* inputUnit é a unidade da receita (ex.: 150 g de um insumo comprado em kg). Sem inputUnit, vale a unidade do insumo.
|
|
10
|
+
*/
|
|
11
|
+
export interface IRecipeLine {
|
|
12
|
+
productInputId: string;
|
|
13
|
+
inputQuantity: number;
|
|
14
|
+
inputUnit?: TMeasureUnit;
|
|
15
|
+
inputComment?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Produto com ficha técnica. stockByRecipe ("baixa pela ficha técnica"): o produto preparado não tem estoque
|
|
20
|
+
* próprio; vender baixa os insumos, e ele fica disponível enquanto todos os insumos têm saldo para 1 unidade.
|
|
21
|
+
*/
|
|
22
|
+
export interface IRecipeProduct {
|
|
23
|
+
saleMeasure?: TMeasureUnit;
|
|
24
|
+
stockByRecipe?: boolean;
|
|
25
|
+
productsInputs?: IRecipeLine[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Entrada de estoque usada no custo médio ponderado: quantidade e custo unitário na unidade do produto. */
|
|
29
|
+
export interface IStockCostEntry {
|
|
30
|
+
inputQuantity: number;
|
|
31
|
+
unitCost: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Etapa do pedido em que a ficha técnica baixa os insumos (Fase 5 do PDV). Padrão "preparing": pedido cancelado
|
|
36
|
+
* antes de preparar não mexe no estoque. Uma vez só por pedido; cancelar estorna.
|
|
37
|
+
*/
|
|
38
|
+
export type TRecipeStockStage = "received" | "preparing" | "delivered";
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { IStoreOrderPayment, TStoreSalesChannel } from "./counter.interface";
|
|
1
2
|
import type { TStoreOptionGroupKind } from "./store-option.interface";
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -154,6 +155,20 @@ export interface IStoreOrder {
|
|
|
154
155
|
nsu?: string;
|
|
155
156
|
// Conta a receber gerada quando o pedido foi entregue (Fase 3 do PDV); voltar da entrega ou cancelar a estorna.
|
|
156
157
|
receivableAccountId?: string;
|
|
158
|
+
// Saídas de estoque dos insumos da ficha técnica (Fase 5.2 do PDV); cancelar ou voltar antes da etapa estorna.
|
|
159
|
+
recipeStockOutIds?: string[];
|
|
160
|
+
// Venda do balcão (Fase 6): entra no quadro em "Recebido" e segue o mesmo fluxo, mas já paga. payments lista
|
|
161
|
+
// as formas (venda dividida), changeGiven o troco, discount o desconto aplicado, cashShiftId o turno do caixa
|
|
162
|
+
// e receivableAccountIds as contas a receber (uma por pagamento); cancelar estorna.
|
|
163
|
+
salesChannel?: TStoreSalesChannel;
|
|
164
|
+
payments?: IStoreOrderPayment[];
|
|
165
|
+
changeGiven?: number;
|
|
166
|
+
cashShiftId?: string;
|
|
167
|
+
receivableAccountIds?: string[];
|
|
168
|
+
// Foto do custo na entrega (Fase 5.3 do PDV): custo unitário de cada produto (ficha técnica ou custo médio de
|
|
169
|
+
// compra) na hora da entrega, usado pelo relatório de CMV. null quando o custo não era conhecido.
|
|
170
|
+
itemCosts?: { productId: string; unitCost: number | null }[];
|
|
171
|
+
costSnapshotAt?: string;
|
|
157
172
|
changeFor?: number;
|
|
158
173
|
paymentReceived?: boolean;
|
|
159
174
|
// Meio do pagamento online (Fase 8.1); vazio no pagamento na entrega.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { TRecipeStockStage } from "./recipe.interface";
|
|
1
2
|
import type { TStorePaymentChoice } from "./store-order.interface";
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -164,10 +165,14 @@ export interface IStoreSettings extends Partial<Record<TStoreFeatureToggle, bool
|
|
|
164
165
|
deliveryPaymentChoices?: TStorePaymentChoice[];
|
|
165
166
|
// Chave Pix da loja, usada pela forma "pixDirect" (sem taxa, com confirmação manual pelo vendedor).
|
|
166
167
|
pixKey?: string;
|
|
168
|
+
// Cidade de quem recebe no QR do Pix do balcão (Fase 6 do PDV); vazia usa "BRASIL".
|
|
169
|
+
pixCity?: string;
|
|
167
170
|
// Conta bancária da chave Pix (Fase 3 do PDV): a conta a receber do Pix direto nasce liquidada nela.
|
|
168
171
|
pixBankAccountId?: string;
|
|
169
172
|
// Conta do dinheiro (tipo "cash", Fase 3 do PDV): o pedido entregue pago em dinheiro entra como recebido nela.
|
|
170
173
|
cashBankAccountId?: string;
|
|
174
|
+
// Etapa em que a ficha técnica baixa os insumos (Fase 5.2 do PDV). Padrão "preparing".
|
|
175
|
+
recipeStockStage?: TRecipeStockStage;
|
|
171
176
|
// Funcionalidade "stockReservation": por quantos minutos o pedido aguardando
|
|
172
177
|
// pagamento segura o estoque (de 5 a 60). Vencido o prazo, o pedido é
|
|
173
178
|
// cancelado, o link de pagamento expira e a quantidade volta. Sem o campo,
|
|
@@ -91,8 +91,10 @@
|
|
|
91
91
|
"items": { "enum": ["debitCard", "creditCard", "pixTerminal", "cash"] }
|
|
92
92
|
},
|
|
93
93
|
"pixKey": { "type": "string" },
|
|
94
|
+
"pixCity": { "type": "string" },
|
|
94
95
|
"pixBankAccountId": { "type": "string" },
|
|
95
96
|
"cashBankAccountId": { "type": "string" },
|
|
97
|
+
"recipeStockStage": { "enum": ["received", "preparing", "delivered"] },
|
|
96
98
|
"reservationMinutes": { "type": "integer", "minimum": 5, "maximum": 60 },
|
|
97
99
|
"ordersPaused": { "type": "boolean" },
|
|
98
100
|
"aboutText": { "type": "string" },
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { closingDifferencesOf, counterDiscountOf, counterNetByMethod, counterPaymentsOf } from "./counter";
|
|
3
|
+
|
|
4
|
+
describe("desconto do balcão", () => {
|
|
5
|
+
test("percentual ou valor, sem passar do subtotal", () => {
|
|
6
|
+
expect(counterDiscountOf(80, { kind: "percent", value: 10 })).toBe(8);
|
|
7
|
+
expect(counterDiscountOf(80, { kind: "amount", value: 5 })).toBe(5);
|
|
8
|
+
expect(counterDiscountOf(80, { kind: "amount", value: 100 })).toBe(80);
|
|
9
|
+
expect(counterDiscountOf(80)).toBe(0);
|
|
10
|
+
});
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
describe("cobrança dividida", () => {
|
|
14
|
+
test("só o dinheiro gera troco; cartão e Pix não passam do total", () => {
|
|
15
|
+
expect(counterPaymentsOf(53.4, [{ paymentChoice: "creditCard", amount: 20 }, { paymentChoice: "cash", amount: 50 }])).toEqual({ ok: true, change: 16.6 });
|
|
16
|
+
expect(counterPaymentsOf(53.4, [{ paymentChoice: "pixDirect", amount: 60 }])).toEqual({ ok: false, reason: "overpaidWithoutCash" });
|
|
17
|
+
expect(counterPaymentsOf(53.4, [{ paymentChoice: "debitCard", amount: 50 }])).toEqual({ ok: false, reason: "notEnough" });
|
|
18
|
+
expect(counterPaymentsOf(53.4, [])).toEqual({ ok: false, reason: "noPayment" });
|
|
19
|
+
expect(counterPaymentsOf(53.4, [{ paymentChoice: "cash", amount: 0 }])).toEqual({ ok: false, reason: "invalidAmount" });
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("o troco sai do dinheiro no que entra em cada forma", () => {
|
|
23
|
+
expect(counterNetByMethod([{ paymentChoice: "creditCard", amount: 20 }, { paymentChoice: "cash", amount: 50 }], 16.6)).toEqual({ creditCard: 20, cash: 33.4 });
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe("fechamento por forma", () => {
|
|
28
|
+
test("diferença = contado − esperado em cada forma ligada", () => {
|
|
29
|
+
expect(closingDifferencesOf({ cash: 312.5, pixDirect: 486 }, { cash: 310, pixDirect: 486 }, ["cash", "pixDirect", "creditCard"])).toEqual([
|
|
30
|
+
{ method: "cash", expected: 312.5, counted: 310, difference: -2.5 },
|
|
31
|
+
{ method: "pixDirect", expected: 486, counted: 486, difference: 0 },
|
|
32
|
+
{ method: "creditCard", expected: 0, counted: 0, difference: 0 },
|
|
33
|
+
]);
|
|
34
|
+
});
|
|
35
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { ICounterDiscount, IStoreOrderPayment, TCounterPaymentChoice } from "../interfaces/counter.interface";
|
|
2
|
+
|
|
3
|
+
/** Formas do caixa do balcão, na ordem do mock: dinheiro, Pix (QR da chave), Pix na maquininha, crédito e débito. */
|
|
4
|
+
export const COUNTER_PAYMENT_CHOICES: TCounterPaymentChoice[] = ["cash", "pixDirect", "pixTerminal", "creditCard", "debitCard"];
|
|
5
|
+
|
|
6
|
+
const cents = (value: number): number => Math.round(value * 100) / 100;
|
|
7
|
+
|
|
8
|
+
/** Desconto em reais: percentual do subtotal ou valor fixo, nunca maior que o subtotal nem negativo. */
|
|
9
|
+
export const counterDiscountOf = (subtotal: number, discount?: ICounterDiscount): number => {
|
|
10
|
+
if (!discount || !(discount.value > 0) || subtotal <= 0) return 0;
|
|
11
|
+
const value = discount.kind === "percent" ? (subtotal * Math.min(discount.value, 100)) / 100 : discount.value;
|
|
12
|
+
return cents(Math.min(value, subtotal));
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export type TCounterPaymentRefusal = "noPayment" | "invalidAmount" | "overpaidWithoutCash" | "notEnough";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Confere os pagamentos da venda do balcão contra o total: cada valor positivo; só o dinheiro pode passar do que
|
|
19
|
+
* falta (troco); no fim, o pago cobre o total. Devolve o troco (sempre tirado do dinheiro).
|
|
20
|
+
*/
|
|
21
|
+
export const counterPaymentsOf = (
|
|
22
|
+
total: number,
|
|
23
|
+
payments: IStoreOrderPayment[],
|
|
24
|
+
): { ok: true; change: number } | { ok: false; reason: TCounterPaymentRefusal } => {
|
|
25
|
+
if (payments.length === 0) return { ok: false, reason: "noPayment" };
|
|
26
|
+
if (payments.some((payment) => !(payment.amount > 0))) return { ok: false, reason: "invalidAmount" };
|
|
27
|
+
const nonCash = cents(payments.filter((payment) => payment.paymentChoice !== "cash").reduce((sum, payment) => sum + payment.amount, 0));
|
|
28
|
+
if (nonCash > cents(total) + 0.001) return { ok: false, reason: "overpaidWithoutCash" };
|
|
29
|
+
const paid = cents(payments.reduce((sum, payment) => sum + payment.amount, 0));
|
|
30
|
+
if (paid + 0.001 < cents(total)) return { ok: false, reason: "notEnough" };
|
|
31
|
+
return { ok: true, change: cents(paid - total) };
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** Quanto entra de fato em cada forma (o troco sai do dinheiro): é o que soma nas vendas do turno e vira conta a receber. */
|
|
35
|
+
export const counterNetByMethod = (payments: IStoreOrderPayment[], change: number): Partial<Record<TCounterPaymentChoice, number>> => {
|
|
36
|
+
const result: Partial<Record<TCounterPaymentChoice, number>> = {};
|
|
37
|
+
for (const payment of payments) result[payment.paymentChoice] = cents((result[payment.paymentChoice] ?? 0) + payment.amount);
|
|
38
|
+
if (change > 0) result.cash = cents((result.cash ?? 0) - change);
|
|
39
|
+
return result;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Esperado em cada forma no fechamento: dinheiro = fundo + vendas em dinheiro + suprimentos − sangrias;
|
|
44
|
+
* as outras formas = vendas do turno nelas. Diferença = contado − esperado.
|
|
45
|
+
*/
|
|
46
|
+
export const closingDifferencesOf = (
|
|
47
|
+
expected: Partial<Record<TCounterPaymentChoice, number>>,
|
|
48
|
+
counted: Partial<Record<TCounterPaymentChoice, number>>,
|
|
49
|
+
methods: TCounterPaymentChoice[],
|
|
50
|
+
): { method: TCounterPaymentChoice; expected: number; counted: number; difference: number }[] =>
|
|
51
|
+
methods.map((method) => {
|
|
52
|
+
const expectedValue = cents(expected[method] ?? 0);
|
|
53
|
+
const countedValue = cents(counted[method] ?? 0);
|
|
54
|
+
return { method, expected: expectedValue, counted: countedValue, difference: cents(countedValue - expectedValue) };
|
|
55
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { convertQuantity, marginOf, reachedRecipeStage, recipeAvailabilityOf, recipeConsumptionOf, recipeCostOf, weightedAverageCost } from "./recipe";
|
|
3
|
+
|
|
4
|
+
describe("unidades", () => {
|
|
5
|
+
test("converte dentro da família e recusa famílias diferentes", () => {
|
|
6
|
+
expect(convertQuantity(150, "g", "kg")).toBe(0.15);
|
|
7
|
+
expect(convertQuantity(0.2, "l", "ml")).toBe(200);
|
|
8
|
+
expect(convertQuantity(2, undefined, "kg")).toBe(2);
|
|
9
|
+
expect(convertQuantity(1, "unit", "unit")).toBe(1);
|
|
10
|
+
expect(convertQuantity(100, "ml", "g")).toBeNull();
|
|
11
|
+
expect(convertQuantity(1, "unit", "kg")).toBeNull();
|
|
12
|
+
});
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
describe("custo médio ponderado", () => {
|
|
16
|
+
test("pesa pela quantidade e ignora entradas sem custo", () => {
|
|
17
|
+
expect(weightedAverageCost([{ inputQuantity: 10, unitCost: 30 }, { inputQuantity: 5, unitCost: 36 }, { inputQuantity: 3, unitCost: 0 }])).toBe(32);
|
|
18
|
+
expect(weightedAverageCost([])).toBeNull();
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
describe("custo da ficha técnica e margem", () => {
|
|
23
|
+
test("X-Burger: 150 g de carne a R$ 40/kg, 1 pão a R$ 1,20 e 20 ml de molho sem custo", () => {
|
|
24
|
+
const inputs = new Map([
|
|
25
|
+
["carne", { unit: "kg" as const, averageCost: 40 }],
|
|
26
|
+
["pao", { unit: "unit" as const, averageCost: 1.2 }],
|
|
27
|
+
["molho", { unit: "l" as const, averageCost: null }],
|
|
28
|
+
]);
|
|
29
|
+
const result = recipeCostOf(
|
|
30
|
+
[
|
|
31
|
+
{ productInputId: "carne", inputQuantity: 150, inputUnit: "g" },
|
|
32
|
+
{ productInputId: "pao", inputQuantity: 1 },
|
|
33
|
+
{ productInputId: "molho", inputQuantity: 20, inputUnit: "ml" },
|
|
34
|
+
{ productInputId: "pao", inputQuantity: 1, inputUnit: "kg" },
|
|
35
|
+
],
|
|
36
|
+
inputs,
|
|
37
|
+
);
|
|
38
|
+
expect(result).toEqual({ cost: 7.2, missing: ["molho"], invalid: ["pao"] });
|
|
39
|
+
expect(marginOf(25, 7.2)).toEqual({ amount: 17.8, percent: 71.2 });
|
|
40
|
+
expect(marginOf(0, 7.2).percent).toBeNull();
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe("baixa dos insumos (5.2)", () => {
|
|
45
|
+
const inputs = new Map([["carne", { unit: "kg" as const }], ["pao", { unit: "unit" as const }]]);
|
|
46
|
+
const burger = [{ productInputId: "carne", inputQuantity: 150, inputUnit: "g" as const }, { productInputId: "pao", inputQuantity: 1 }];
|
|
47
|
+
|
|
48
|
+
test("etapa alcançada: em preparo vale também para enviado e entregue; cancelado nunca", () => {
|
|
49
|
+
expect(reachedRecipeStage("received", "preparing")).toBe(false);
|
|
50
|
+
expect(reachedRecipeStage("preparing", "preparing")).toBe(true);
|
|
51
|
+
expect(reachedRecipeStage("delivered", "preparing")).toBe(true);
|
|
52
|
+
expect(reachedRecipeStage("received", "received")).toBe(true);
|
|
53
|
+
expect(reachedRecipeStage("cancelled", "received")).toBe(false);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("consumo soma os itens na unidade do insumo", () => {
|
|
57
|
+
const consumption = recipeConsumptionOf([{ productId: "x", quantity: 2 }, { productId: "y", quantity: 1 }], new Map([["x", burger]]), inputs);
|
|
58
|
+
expect([...consumption.entries()]).toEqual([["carne", 0.3], ["pao", 2]]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("disponível é o menor 'quantos dá para fazer' entre os insumos", () => {
|
|
62
|
+
expect(recipeAvailabilityOf(burger, { carne: 1, pao: 10 }, inputs)).toBe(6);
|
|
63
|
+
expect(recipeAvailabilityOf(burger, { carne: 0.1, pao: 10 }, inputs)).toBe(0);
|
|
64
|
+
expect(recipeAvailabilityOf([], { carne: 1 }, inputs)).toBe(0);
|
|
65
|
+
});
|
|
66
|
+
});
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { IRecipeLine, IStockCostEntry, TMeasureUnit, TRecipeStockStage } from "../interfaces/recipe.interface";
|
|
2
|
+
import type { TStoreOrderFulfillmentStatus } from "../interfaces/store-order.interface";
|
|
3
|
+
|
|
4
|
+
export const RECIPE_STOCK_STAGES: TRecipeStockStage[] = ["received", "preparing", "delivered"];
|
|
5
|
+
export const DEFAULT_RECIPE_STOCK_STAGE: TRecipeStockStage = "preparing";
|
|
6
|
+
|
|
7
|
+
// Fator para a unidade base da família: massa em g, volume em ml.
|
|
8
|
+
const FAMILY: Partial<Record<TMeasureUnit, { family: "mass" | "volume"; factor: number }>> = {
|
|
9
|
+
kg: { family: "mass", factor: 1000 },
|
|
10
|
+
g: { family: "mass", factor: 1 },
|
|
11
|
+
mg: { family: "mass", factor: 0.001 },
|
|
12
|
+
l: { family: "volume", factor: 1000 },
|
|
13
|
+
ml: { family: "volume", factor: 1 },
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const round = (value: number, digits: number): number => Math.round(value * 10 ** digits) / 10 ** digits;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Converte a quantidade da unidade da receita para a unidade do insumo (ex.: 150 g → 0,15 kg). Mesma unidade (ou
|
|
20
|
+
* sem unidade na receita) não converte. Unidades de famílias diferentes devolvem null: a ficha técnica fica inválida.
|
|
21
|
+
*/
|
|
22
|
+
export const convertQuantity = (quantity: number, from: TMeasureUnit | undefined, to: TMeasureUnit | undefined): number | null => {
|
|
23
|
+
if (!from || !to || from === to) return quantity;
|
|
24
|
+
const source = FAMILY[from];
|
|
25
|
+
const target = FAMILY[to];
|
|
26
|
+
if (!source || !target || source.family !== target.family) return null;
|
|
27
|
+
return round((quantity * source.factor) / target.factor, 6);
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** Custo médio ponderado: Σ(custo unitário × quantidade) / Σ quantidade das entradas com custo e quantidade positivos. */
|
|
31
|
+
export const weightedAverageCost = (entries: IStockCostEntry[]): number | null => {
|
|
32
|
+
const valid = entries.filter((entry) => Number(entry.inputQuantity) > 0 && Number(entry.unitCost) > 0);
|
|
33
|
+
const quantity = valid.reduce((sum, entry) => sum + Number(entry.inputQuantity), 0);
|
|
34
|
+
if (quantity <= 0) return null;
|
|
35
|
+
return round(valid.reduce((sum, entry) => sum + Number(entry.unitCost) * Number(entry.inputQuantity), 0) / quantity, 4);
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export interface IRecipeInputInfo {
|
|
39
|
+
unit?: TMeasureUnit;
|
|
40
|
+
averageCost: number | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Custo da ficha técnica: Σ quantidade convertida × custo médio do insumo. missing lista os insumos sem custo
|
|
45
|
+
* (nenhuma entrada com custo) e invalid os de unidade incompatível; nos dois casos o custo fica parcial.
|
|
46
|
+
*/
|
|
47
|
+
export const recipeCostOf = (
|
|
48
|
+
lines: IRecipeLine[],
|
|
49
|
+
inputs: Map<string, IRecipeInputInfo>,
|
|
50
|
+
): { cost: number; missing: string[]; invalid: string[] } => {
|
|
51
|
+
let cost = 0;
|
|
52
|
+
const missing: string[] = [];
|
|
53
|
+
const invalid: string[] = [];
|
|
54
|
+
for (const line of lines) {
|
|
55
|
+
const input = inputs.get(line.productInputId);
|
|
56
|
+
const quantity = convertQuantity(Number(line.inputQuantity) || 0, line.inputUnit, input?.unit);
|
|
57
|
+
if (quantity === null) invalid.push(line.productInputId);
|
|
58
|
+
else if (!input || input.averageCost === null) missing.push(line.productInputId);
|
|
59
|
+
else cost += quantity * input.averageCost;
|
|
60
|
+
}
|
|
61
|
+
return { cost: round(cost, 2), missing, invalid };
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** Margem sobre o preço de venda: valor (preço − custo) e percentual sobre o preço. Sem preço, percentual null. */
|
|
65
|
+
export const marginOf = (price: number, cost: number): { amount: number; percent: number | null } => ({
|
|
66
|
+
amount: round(price - cost, 2),
|
|
67
|
+
percent: price > 0 ? round(((price - cost) / price) * 100, 2) : null,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// Ordem das etapas do pedido; "cancelled" fica fora: cancelar sempre estorna.
|
|
71
|
+
const STAGE_ORDER: TStoreOrderFulfillmentStatus[] = ["received", "preparing", "shipped", "delivered"];
|
|
72
|
+
|
|
73
|
+
/** O pedido já chegou (ou passou) da etapa em que a ficha técnica baixa os insumos. */
|
|
74
|
+
export const reachedRecipeStage = (status: TStoreOrderFulfillmentStatus, stage: TRecipeStockStage): boolean =>
|
|
75
|
+
status !== "cancelled" && STAGE_ORDER.indexOf(status) >= STAGE_ORDER.indexOf(stage);
|
|
76
|
+
|
|
77
|
+
export interface IRecipeInputUnit {
|
|
78
|
+
unit?: TMeasureUnit;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Quanto de cada insumo um pedido consome: Σ quantidade do item × quantidade da linha, convertida para a unidade
|
|
83
|
+
* do insumo. Linhas com unidade incompatível ficam de fora (a ficha precisa ser corrigida).
|
|
84
|
+
*/
|
|
85
|
+
export const recipeConsumptionOf = (
|
|
86
|
+
items: { productId: string; quantity: number }[],
|
|
87
|
+
recipes: Map<string, IRecipeLine[]>,
|
|
88
|
+
inputs: Map<string, IRecipeInputUnit>,
|
|
89
|
+
): Map<string, number> => {
|
|
90
|
+
const consumption = new Map<string, number>();
|
|
91
|
+
for (const item of items) {
|
|
92
|
+
for (const line of recipes.get(item.productId) ?? []) {
|
|
93
|
+
const quantity = convertQuantity(Number(line.inputQuantity) || 0, line.inputUnit, inputs.get(line.productInputId)?.unit);
|
|
94
|
+
if (quantity === null || quantity <= 0) continue;
|
|
95
|
+
consumption.set(line.productInputId, round((consumption.get(line.productInputId) ?? 0) + quantity * item.quantity, 6));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return consumption;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Quantas unidades do produto preparado dá para fazer com o saldo dos insumos: o menor saldo ÷ consumo por unidade.
|
|
103
|
+
* Sem ficha válida, 0 (esgotado).
|
|
104
|
+
*/
|
|
105
|
+
export const recipeAvailabilityOf = (
|
|
106
|
+
lines: IRecipeLine[],
|
|
107
|
+
balances: Record<string, number>,
|
|
108
|
+
inputs: Map<string, IRecipeInputUnit>,
|
|
109
|
+
): number => {
|
|
110
|
+
const perUnit = recipeConsumptionOf([{ productId: "_", quantity: 1 }], new Map([["_", lines]]), inputs);
|
|
111
|
+
if (perUnit.size === 0) return 0;
|
|
112
|
+
return Math.max(0, Math.min(...[...perUnit.entries()].map(([id, need]) => Math.floor(((balances[id] ?? 0) + 1e-9) / need))));
|
|
113
|
+
};
|