### BuyXGetYDiscount: key, label, calculate, and configuration example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/acoes.md BuyXGetYDiscount implements 'buy X get Y free' logic. The calculate method reads meta keys buy (default 2), free (default 1), and free_item (default 'cheapest' or 'most_expensive'), groups units by buy+free, and marks units at position % groupSize >= buy as free. Discounts accumulate per component (scope_index) and maxDiscount is applied via clampTo if present. ```php public static function key(): string // 'buy_x_get_y' public static function label(): string // 'Leve X pague Y' ``` ```php public function calculate( ActionDefinition $definition, CartContext $cart, DiscountScope $scope, ): DiscountAllocation { $buy = max(1, (int) $definition->meta('buy', 2)); $free = max(1, (int) $definition->meta('free', 1)); $groupSize = $buy + $free; $units = $this->units($scope); if (count($units) < $groupSize) { return DiscountAllocation::empty(); } $freeIsMostExpensive = $definition->meta('free_item', 'cheapest') === 'most_expensive'; usort( $units, static fn (array $a, array $b): int => $freeIsMostExpensive ? $a['cents'] <=> $b['cents'] : $b['cents'] <=> $a['cents'], ); ... } ``` ```php // Leve 2, pague 1, sai de graça a mais barata, só componentes 'base' ['type' => 'buy_x_get_y', 'value' => 0, 'target' => 'components', 'meta' => ['component_types' => ['base'], 'buy' => 2, 'free' => 1, 'free_item' => 'cheapest']] ``` -------------------------------- ### Basic Money usage example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/money.md Basic usage example: creates a Money from cents, sums it with another from a float, and outputs the formatted value and cents. ```php use SolutionsTI\DiscountEngine\Core\Money\Money; $precio = Money::fromCents(25000); // R$ 250,00 $total = Money::sum([$precio, Money::fromFloat(9.99)]); echo $total->format(); // R$ 259,99 echo $total->cents; // 25999 ``` -------------------------------- ### Install laravel-discount-engine with Composer and Artisan Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/README.md Installs the package, publishes its configuration, and runs migrations. After updating the package, rerun the publish command with the --force flag to refresh the configuration file, as it does not update automatically. ```bash composer require solutionsti/laravel-discount-engine php artisan vendor:publish --tag=discount-engine-config php artisan migrate ``` -------------------------------- ### Simulator request and response example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/http.md Example request to POST /admin/descontos/simulador with a cart containing one item, shipping cost, and a coupon, followed by the corresponding 200 JSON response showing applied and rejected rules and discount breakdowns. ```bash POST /admin/descontos/simulador { "items": [ { "sku": "CAMISA-P", "quantity": 2, "unit_price_cents": 4000, "category_ids": [7] } ], "shipping_cents": 1200, "coupons": ["BEMVINDO10"] } ``` ```json { "subtotal_cents": 8000, "shipping_cents": 1200, "total_discount_cents": 250, "final_total_cents": 8950, "applied": [ { "rule_name": "...", "action_type": "percentage", "amount_cents": 250 } ], "rejected": [ { "reason": "usage_limit_reached", "message": "Limite de uso atingido" } ], "by_item": { "1": 250 }, "by_component_type": { "base": 250 } } ``` -------------------------------- ### ActionRegistry usage example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/registros.md Example usage of ActionRegistry: instantiate with three discount actions, then retrieve one by key and call its calculate method. ```php $registry = new ActionRegistry([ new PercentageDiscount(), new FixedAmountDiscount(), new FreeShippingDiscount(), ]); $allocation = $registry->get('percentage')->calculate($def, $cart, $scope); ``` -------------------------------- ### DiscountScope::forCart example with scope components Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/alocacao.md Example of creating a DiscountScope with forCart, specifying componentTypes, categoryIds, and alreadyDiscounted amounts. Iterates over the scope's components, each exposing itemId, componentIndex, type, unitPrice, itemQuantity, componentQuantity, and available. ```php $scope = DiscountScope::forCart( cart: $cart, componentTypes: ['print'], categoryIds: [7], alreadyDiscounted: ['9::1' => Money::fromCents(300)], ); foreach ($scope->components as $c) { // cada $c: itemId, componentIndex, type, unitPrice, itemQuantity, // componentQuantity, available } ``` -------------------------------- ### Money allocate example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/money.md Example of allocating R$ 10,00 between two items with weights 1 and 2. The result is a = R$ 3,33 (333 cents) and b = R$ 6,67 (667 cents), summing exactly to 1000 cents. ```php $share = Money::fromCents(1000)->allocate([ 'a' => 1, 'b' => 2 ]); // ponderação 1:2 => a = R$ 3,33 (333), b = R$ 6,67 (667) // 333 + 667 === 1000, sem centavo perdido ``` -------------------------------- ### Basic Rule instantiation example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/regra.md Creates a Rule with id 12, name '10% na primeira compra', coupon trigger, a condition group, a percentage action of 10, coupon code 'BIENVENIDO10', and priority 10. ```php $regla = new Rule( id: 12, name: '10% na primeira compra', trigger: TriggerType::Coupon, conditions: $group, actions: [new ActionDefinition('percentage', 10)], couponCode: 'BIENVENIDO10', priority: 10, ); ``` -------------------------------- ### ComponentUnitPriceDiscount: key, calculate, and configuration example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/acoes.md ComponentUnitPriceDiscount applies a promotional price to the first N units per item, line, or cart. The 'per' meta controls how many units are discounted: 'item_unit' gives one per item, 'line' and 'cart' give one per line or cart. The discount is the difference between full and promotional price; it never increases cost if the component already costs less. The example sets the first print of each shirt to R$ 1.99. ```php public static function key(): string // 'component_unit_price' public static function label(): string // 'Preco promocional nas primeiras unidades' ``` ```php public function calculate( ActionDefinition $definition, CartContext $cart, DiscountScope $scope, ): DiscountAllocation { $firstN = max(1, (int) $definition->meta('first_n', 1)); $promoPrice = Money::fromCents((int) $definition->meta('unit_price_cents', 0)); $per = (string) $definition->meta('per', 'item_unit'); if ($scope->isEmpty()) { return DiscountAllocation::empty(); } ... } ``` ```php // Primera estampa (de cada camisa) a R$ 1,99 ['type' => 'component_unit_price', 'value' => 0, 'target' => 'components', 'meta' => [ 'component_types' => ['print'], 'category_ids' => [7], 'first_n' => 1, 'unit_price_cents' => 199, 'per' => 'item_unit', ]] ``` -------------------------------- ### FirstPurchaseCondition example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/condicoes.md Example of creating a ConditionDefinition for first purchase with value true. Anonymous customers always evaluate to false. ```php // Exemplo: é a primeira compra do cliente new ConditionDefinition('first_purchase', Operator::Equals, true); // Cliente anónimo => falsempre ``` -------------------------------- ### CategoryQuantityCondition example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/condicoes.md Example of creating a ConditionDefinition for at least 3 units of category 7. ```php // Exemplo: pelo menos 3 unidades da categoria 7 $def = new ConditionDefinition( 'category_quantity', Operator::Gte, 3, meta: ['category_id' => 7], ); ``` -------------------------------- ### ConditionRegistry usage example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/registros.md Example usage of ConditionRegistry: instantiate with an initial evaluator, register a custom one fluently, check existence, get options, and handle a missing key exception. ```php $registry = new ConditionRegistry([new CartSubtotalCondition()]); $registry->register(new MiCondicionCustom()); // fluido $registry->has('cart_subtotal'); // true $registry->options(); // ['cart_subtotal' => 'Subtotal do carrinho', …] try { $registry->get('no_existe'); } catch (InvalidArgumentException $e) { // 'Condicao nao registrada: [no_existe].' } ``` -------------------------------- ### DiscountResult basic usage example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/resultado.md Basic usage example: calculates a discount for a cart, prints the total discount formatted as R$ 25,00, prints the final total in cents (97500), and retrieves item allocations. ```php $resultado = Discounts::calculate($cart); echo $resultado->totalDiscount()->format(); // R$ 25,00 echo $resultado->finalTotal()->cents; // 97500 $resultado->itemAllocations(); // ['CAMISA-1' => Money, …] ``` -------------------------------- ### Instalar dependências e executar testes (composer install, vendor/bin/phpunit --testdox) Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/README.md Instala as dependências do Composer e executa a suíte de testes com a opção --testdox para saída detalhada. Exemplo para rodar os 124 testes existentes. ```bash composer install vendor/bin/phpunit --testdox ``` -------------------------------- ### DiscountCoupon creation and capacity check Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/modelos-laravel.md Example of creating a DiscountCoupon with a code that is automatically uppercased, and checking global capacity. ```php DiscountCoupon::create([ 'rule_id' => $regla->id, 'code' => 'bemvindo10', // se guarda 'BEMVINDO10' 'usage_limit' => 1000, 'usage_limit_per_customer' => 1, ]); $coupon->hasGlobalCapacity(); // true enquanto used_count < usage_limit ``` -------------------------------- ### EloquentRuleRepository usage example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/repositorios-laravel.md Example usage of EloquentRuleRepository: instantiate with hydrator, fetch automatic rules, fetch coupon rules, and flush cache. ```php $repo = new EloquentRuleRepository($hydrator); $automaticas = $repo->automaticRules(); // com caché $deCupones = $repo->rulesForCoupons(['BEMVINDO10']); $repo->flushCache(); // ao salvar/borrar reglas ``` -------------------------------- ### Usage example with rejected rules and snapshot persistence Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/resultado.md Shows how to iterate over rejected rules to output JSON with rule name, raw reason value, and human-readable message, and how to persist the full result snapshot to an order. ```php $resultado = Discounts::calculate($carrinho); $rechazadas = $resultado->rejected; // En o simulador do panel se mostra: nombre, motivo legible y value crudo foreach ($rechazadas as $r) { response()->json([ 'rule_name' => $r->ruleName, 'reason' => $r->reason->value, // 'conditions_not_met' 'message' => $r->message(), // 'Carrinho nao atende as condicioes' ]); } // Persistencia do snapshot para o pedido $pedido->update(['desconto_snapshot' => $resultado->toArray()]); ``` -------------------------------- ### Custom DiscountAction implementation (PrimeiraCompraCortesia) Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/contratos.md Example implementation of a custom discount action. The scope is already filtered, so the action only decides how much to discount, not where. It uses DiscountAllocation::spread to distribute the discount across the scope. ```php use SolutionsTI\DiscountEngine\Core\Contracts\DiscountAction; use SolutionsTI\DiscountEngine\Core\Allocation\DiscountAllocation; final class PrimeiraCompraCortesia implements DiscountAction { public static function key(): string { return 'cortesia'; } public static function label(): string { return 'Cortesia'; } public function calculate( ActionDefinition $definition, CartContext $cart, DiscountScope $scope, ): DiscountAllocation { // $scope já vem recortado: basta decidir QUANTO, não ONDE return DiscountAllocation::spread( $scope, Money::fromCents((int) $definition->value), ); } } ``` -------------------------------- ### Buy X get Y free on components Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/README.md Offers a buy X get Y free promotion on base componentsörnas. The 'free_item' selection happens within each group, not the whole cart; groups are formed in order. ```php ['type' => 'buy_x_get_y', 'value' => 0, 'target' => 'components', 'meta' => ['component_types' => ['base'], 'buy' => 2, 'free' => 1, 'free_item' => 'cheapest']] ``` -------------------------------- ### GET /admin/descontos/nova Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/endpoints.md Endpoint GET que apresenta o formulário de criação de regra com valores padrão. ```APIDOC ## GET /admin/descontos/nova ### Description Exibe o formulário para criar uma nova regra de desconto, com valores por defeito preenchidos. ### Method GET ### Endpoint /admin/descontos/nova ### Parameters #### Query Parameters - **trigger** (string) - Opcional - Valor por defeito: `automatic` - **priority** (int) - Opcional - Valor por defeito: `100` - **combination_mode** (string) - Opcional - Valor por defeito: `stackable` - **resolution_strategy** (string) - Opcional - Valor por defeito: `first_by_priority` - **calculation_base** (string) - Opcional - Valor por defeito: `current` - **active** (bool) - Opcional - Valor por defeito: `true` ### Response #### Success Response (200) - **form** (view) - Formulário com valores por defeito ``` -------------------------------- ### Calculate discounts from a CartContext with Discounts facade Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/README.md Builds a CartContext from order data and calculates discounts with the Discounts facade. The example expects a Money object from cents, plucks categories and groups, counts completed orders, and reads coupon codes from the session; the result offers total discount, final total, and per-item allocations. ```php use SolutionsTI\DiscountEngine\Core\Context\{CartContext, CartItem, CustomerContext, PriceComponent}; use SolutionsTI\DiscountEngine\Core\Money\Money; use SolutionsTI\DiscountEngine\Laravel\Facades\Discounts; $cart = new CartContext( items: [ new CartItem( id: $linha->id, sku: $linha->sku, quantity: $linha->quantidade, unitPrice: Money::fromCents($linha->preco_centavos), categoryIds: $linha->produto->categorias->pluck('id')->all(), ), ], shippingCost: Money::fromCents($frete), customer: new CustomerContext( id: $user->id, groups: $user->grupos->pluck('slug')->all(), completedOrders: $user->pedidos()->concluidos()->count(), ), couponCodes: session('cupons', []), ); $resultado = Discounts::calculate($cart); $resultado->totalDiscount()->format(); // R$ 25,00 $resultado->finalTotal()->cents; $resultado->itemAllocations(); // desconto exato por item ``` -------------------------------- ### TieredDiscount: key, calculate, and configuration example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/acoes.md TieredDiscount applies the highest reached tier based on subtotal or quantity. The meta accepts 'basis' ('subtotal' or 'quantity') and 'tiers' with each tier using 'percent' or 'amount_cents'. The array need not be sorted; highestMatchingTier selects the largest min with measure >= min. The example configuration defines three tiers with 5%, 10%, and 15% discounts. ```php public static function key(): string // 'tiered' public static function label(): string // 'Desconto escalonado por faixa' ``` ```php public function calculate( ActionDefinition $definition, CartContext $cart, DiscountScope $scope, ): DiscountAllocation { $tiers = $definition->meta('tiers', []); if (! is_array($tiers) || $tiers === [] || $scope->isEmpty()) { return DiscountAllocation::empty(); } $measure = $definition->meta('basis', 'subtotal') === 'quantity' ? $scope->totalUnits() : $scope->total()->cents; $tier = $this->highestMatchingTier($tiers, $measure); ... } ``` ```php ['type' => 'tiered', 'value' => 0, 'target' => 'cart', 'meta' => ['basis' => 'subtotal', 'tiers' => [ ['min' => 10000, 'percent' => 5], ['min' => 30000, 'percent' => 10], ['min' => 50000, 'percent' => 15], ]]] ``` -------------------------------- ### Exemplo básico de uso da facade Discounts Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/gerente-laravel.md Exemplo de uso da facade Discounts para calcular descontos. O resultado pode ser formatado com totalDiscount()->format(). ```php use SolutionsTI\DiscountEngine\Laravel\Facades\Discounts; $resultado = Discounts::calculate($cart); // $resultado->totalDiscount()->format(); // 'R$ 25,00' ``` -------------------------------- ### GET /admin/descontos Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/endpoints.md Endpoint GET que lista reglas de desconto paginadas com contagem de cupones. ```APIDOC ## GET /admin/descontos ### Description Lista paginada (25) de reglas de desconto com contagem de cupones, ordenada por `priority` e `name`. Renderiza a vista `discount-engine::rules.index`. ### Method GET ### Endpoint /admin/descontos ### Response #### Success Response (200) - **rules** (collection) - Lista de reglas paginada - **insecure** (bool) - Indica se o ambiente é inseguro #### Response Example ```json { "rules": [], "insecure": false } ``` ``` -------------------------------- ### GET /admin/descontos/{rule}/editar Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/endpoints.md Endpoint GET que apresenta o formulário de edição de uma regra existente. ```APIDOC ## GET /admin/descontos/{rule}/editar ### Description Exibe o formulário de edição para uma regra existente, com dados preenchidos e opções disponíveis. ### Method GET ### Endpoint /admin/descontos/{rule}/editar ### Parameters #### Path Parameters - **rule** (int) - Requerido - ID da regra ### Response #### Success Response (200) - **rule** (object) - Regra existente - **conditionsJson** (string) - JSON das condições - **actionsJson** (string) - JSON das ações - **couponCodes** (string) - Códigos de cupão (um por linha) - **availableConditions** (array) - Condições disponíveis - **availableActions** (array) - Ações disponíveis - **fieldMap** (object) - Mapa de campos - **conditionsData** (object) - Dados das condições - **actionsData** (object) - Dados das ações - **insecure** (bool) - Indica se o ambiente é inseguro ``` -------------------------------- ### DiscountAllocation constructor e fábricas empty/of Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/alocacao.md Constructor privado e fábricas estáticas. `empty()` cria uma alocação vazia; `of()` filtra entradas cujo montante não seja positivo. ```php private function __construct(public readonly array $entries = []) { } public static function empty(): self // new self() public static function of(array $entries): self // filtra amount->isPositive() ``` -------------------------------- ### Money percentage error handling example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/money.md Example of handling the InvalidArgumentException thrown by percentage when a negative percent is passed. The comment explains that a negative percent is not a discount but a price increase. ```php try { $desconto = Money::fromCents(10000)->percentage(-5); } catch (InvalidArgumentException $e) { // 'Percentual nao pode ser negativo.' // Um percentual negativo não é um desconto: é um incremento de preço. } ``` -------------------------------- ### ActionRegistry methods Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/registros.md Method signatures for ActionRegistry: register, has, get, and options. get() throws InvalidArgumentException with message 'Acao de desconto nao registrada: [{$key}].' if the key does not exist. ```php public function register(DiscountAction $action): self public function has(string $key): bool public function get(string $key): DiscountAction /** @return array */ public function options(): array ``` -------------------------------- ### Publish discount-engine config Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/gerente-laravel.md Run this artisan command to publish the package configuration. When updating the package, republish with --force because condition and action lists live in the published config. ```bash php artisan vendor:publish --tag=discount-engine-config ``` -------------------------------- ### Método getTable() Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/modelos-laravel.md Método que retorna o nome da tabela configurado em 'discount-engine.tables.rules', com fallback para 'discount_rules'. ```php public function getTable(): string ``` -------------------------------- ### Money comparison and limit methods Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/money.md Comparison and limit methods: isZero, isPositive, isNegative, equals, greaterThan, lessThan, min, max, clampTo (min($ceiling)), atLeastZero (returns zero() if negative), toFloat (cents/100 for output/serialization), and format (R$ 25,00 using number_format(toFloat(), 2, ',', '.') with the symbol prepended). ```php public function isZero(): bool public function isPositive(): bool public function isNegative(): bool public function equals(self $other): bool public function greaterThan(self $other): bool public function lessThan(self $other): bool public function min(self $other): self public function max(self $other): self ``` ```php public function clampTo(self $ceiling): self ``` ```php public function atLeastZero(): self ``` ```php public function toFloat(): float ``` ```php public function format(string $currency = 'R$'): string ``` -------------------------------- ### Executar testes com MySQL (DB_CONNECTION=mysql DB_DATABASE=discount_engine_test vendor/bin/phpunit) Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/README.md Executa os testes usando MySQL como banco de dados, definindo as variáveis de ambiente DB_CONNECTION e DB_DATABASE. Útil para verificar diferenças de tipo (JSON, collation, foreign key) que o SQLite não detecta. ```bash DB_CONNECTION=mysql DB_DATABASE=discount_engine_test vendor/bin/phpunit ``` -------------------------------- ### CustomerGroupCondition usage examples Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/condicoes.md Shows how to instantiate ConditionDefinition for the customer_group condition. The first example checks if the customer belongs to 'vip' or 'atacado' groups using ContainsAny; the second checks that the customer does not belong to the 'bloqueado' group using ContainsNone. ```php // Exemplo: cliente do grupo 'vip' (o 'atacado') new ConditionDefinition('customer_group', Operator::ContainsAny, ['vip', 'atacado']); // Inverso: new ConditionDefinition('customer_group', Operator::ContainsNone, ['bloqueado']); ``` -------------------------------- ### GET /admin/descontos/simulador Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/endpoints.md Displays the simulator view for the discount engine. ```APIDOC ## GET /admin/descontos/simulador ### Description Displays the simulator view for the discount engine. It renders the `discount-engine::simulator.index` view with an `insecure` variable. ### Method GET ### Endpoint /admin/descontos/simulador ### Response #### Success Response (200) - **view** (string) - The rendered view `discount-engine::simulator.index`. - **insecure** (boolean) - Variable passed to the view. ``` -------------------------------- ### DiscountResult toArray output structure Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/resultado.md Example structure of the array returned by toArray(). ```php [ 'subtotal_cents' => int, 'shipping_cents' => int, 'items_discount_cents' => int, 'shipping_discount_cents' => int, 'total_discount_cents' => int, 'final_total_cents' => int, 'applied' => array>, // AppliedDiscount::toArray() 'rejected' => array>, // RejectedRule::toArray() 'allocation' => array>,// AllocationEntry::toArray() 'item_allocations' => array, // itemId => cents ] ``` -------------------------------- ### DiscountEngine constructor Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/engine.md Constructor for the DiscountEngine class. Accepts a RuleRepository, ActionRegistry, ConditionMatcher, an optional UsageTracker for coupon balance simulation, and an optional global cap percentage that limits the total discount per order (applied to items, not shipping). ```php public function __construct( private readonly RuleRepository $rules, private readonly ActionRegistry $actions, private readonly ConditionMatcher $matcher, private readonly ?UsageTracker $usage = null, /** Teto de seguranca: nenhum pedido recebe mais que N% de desconto somado. */ private readonly ?float $globalCapPercentage = null, ) { } ``` -------------------------------- ### Métodos de instância básicos de DiscountAllocation Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/alocacao.md Métodos de instância básicos: `with` concatena uma entrada, `merge` concatena duas alocações, `isEmpty` verifica se está vazia, e `total`, `itemsTotal` e `shippingTotal` retornam montantes. ```php public function with(AllocationEntry $entry): self // concatena public function merge(self $other): self // concatena dos alocaciones public function isEmpty(): bool public function total(): Money public function itemsTotal(): Money public function shippingTotal(): Money ``` -------------------------------- ### Coupon Validation and Reservation Example Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/gerente-laravel.md Shows how to validate a coupon, calculate the discount, and reserve it inside a DB transaction during order closure. The validateCoupon call returns a CouponValidation object that can be converted to an array; the example includes a sample JSON response. The calculate method is used server-side to avoid trusting the frontend, and reserve returns false if the coupon is exhausted, with an internal exception reverting the transaction. ```php $validacion = Discounts::validateCoupon($request->input('codigo'), $cart); response()->json($validacion->toArray()); // {"accepted": false, "reason": "conditions_not_met", // "message": "Carrinho nao atende as condicioes"} DB::transaction(function () use ($cart, $pedido) { $resultado = Discounts::calculate($cart); // nunca confiar no front if (! Discounts::reserve($resultado, $pedido->id, $user->id)) { // Cupom esgotado entre simulação y fechamento: a excepção interna // reverteu a transação; aquí decidimos o error ao cliente } $pedido->update([ 'desconto_centavos' => $resultado->totalDiscount()->cents, 'desconto_snapshot' => $resultado->toArray(), ]); }); ``` -------------------------------- ### Contrato DiscountAction::calculate Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/acoes.md Assinatura do método calculate que todas as ações implementam. Recebe ActionDefinition, CartContext e DiscountScope e retorna DiscountAllocation. ```php public function calculate(ActionDefinition $definition, CartContext $cart, DiscountScope $scope): DiscountAllocation ``` -------------------------------- ### DiscountEngine::buildScope private method Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/engine.md Private method that builds the scope for an action. For Shipping target, it creates a single ScopedComponent::forShipping with the available balance. For other targets, it uses DiscountScope::forCart with componentTypes, alreadyDiscounted (if calculationBase is Current), category_ids, and skus from the action meta. ```php private function buildScope(Rule $rule, ActionDefinition $action, CartContext $cart, DiscountAllocation $used): DiscountScope ``` -------------------------------- ### ConditionRegistry get method Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/registros.md Retrieves a ConditionEvaluator by key. Throws InvalidArgumentException with message 'Condicao nao registrada: [{$key}].' if the key does not exist. ```php public function get(string $key): ConditionEvaluator ``` -------------------------------- ### AllocationEntry methods Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/alocacao.md Lists the AllocationEntry methods: isShipping, key, withAmount, and toArray. Comments indicate the logic for isShipping and key. ```php public function isShipping(): bool // componentType === self::SHIPPING public function key(): string // itemId === null ? SHIPPING : "itemId::componentIndex" public function withAmount(Money $amount): self public function toArray(): array ``` -------------------------------- ### Exemplo de condição própria (DeliveryStateCondition) Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/contratos.md Implementación de una condición personalizada que compara el atributo 'delivery_state' del carrito con el valor de la definición usando el operador. Debe registrarse en config/discount-engine.php bajo la clave 'conditions'. ```php use SolutionsTI\DiscountEngine\Core\Contracts\ConditionEvaluator; use SolutionsTI\DiscountEngine\Core\Rule\ConditionDefinition; use SolutionsTI\DiscountEngine\Core\Context\CartContext; final class DeliveryStateCondition implements ConditionEvaluator { public static function key(): string { return 'delivery_state'; } public static function label(): string { return 'UF de entrega'; } public function evaluate(ConditionDefinition $definition, CartContext $cart): bool { return $definition->operator->compare( $cart->attribute('delivery_state'), $definition->value, ); } } ``` -------------------------------- ### Simulator invalid cart 422 response Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/http.md Example 422 error response from the simulator when the cart is invalid, such as when unit_price_cents does not match the sum of the components. The error message is returned in the 'error' field. ```json // HTTP 422 { "error": "Item [CAMISA-P]: unitPrice (5000) nao bate com a soma dos componentes (4000)." } ``` -------------------------------- ### Basic DiscountEngine usage without Laravel Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/engine.md Basic usage of the DiscountEngine without Laravel. Requires a RuleRepository implementation, an ActionRegistry with a PercentageDiscount action, and a ConditionMatcher with a CartSubtotalCondition. The globalCapPercentage and usage tracker are optional. The result's totalDiscount() is formatted as currency, e.g., R$ 25,00. ```php use SolutionsTI\DiscountEngine\Core\Engine\{DiscountEngine, ConditionMatcher}; use SolutionsTI\DiscountEngine\Core\Registry\{ActionRegistry, ConditionRegistry}; $engine = new DiscountEngine( rules: $miRepositorio, // implementa RuleRepository actions: new ActionRegistry([new PercentageDiscount()]), matcher: new ConditionMatcher(new ConditionRegistry([new CartSubtotalCondition()])), usage: $miUsageTracker, // opcional globalCapPercentage: 50.0, // opcional ); $resultado = $engine->evaluate($cart); if ($resultado->hasDiscount()) { echo $resultado->totalDiscount()->format(); // R$ 25,00 } ``` -------------------------------- ### ConditionMatcher usage with nested ConditionGroup Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/engine.md Example of building a ConditionMatcher with a registry of conditions and a nested ConditionGroup. The group uses All logic with a cart_subtotal condition and an inner Any group for customer_group. The matches method returns a boolean. ```php $matcher = new ConditionMatcher(new ConditionRegistry([ new CartSubtotalCondition(), new CustomerGroupCondition(), ])); $grupo = new ConditionGroup(LogicOperator::All, [ new ConditionDefinition('cart_subtotal', Operator::Gte, 20000), new ConditionGroup(LogicOperator::Any, [ new ConditionDefinition('customer_group', Operator::ContainsAny, ['vip']), ]), ]); $matcher->matches($grupo, $cart); // bool ``` -------------------------------- ### Exemplo de configuração PercentageDiscount Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/acoes.md Exemplo de definição de ação para 10% de desconto no carrinho com teto de R$ 50 (max_discount_cents). ```php // 10% sobre o carrinho com techo de R$ 50 ['type' => 'percentage', 'value' => 10, 'target' => 'cart', 'max_discount_cents' => 5000] ``` -------------------------------- ### Exemplo: 3 ou mais unidades Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/condicoes.md Exemplo de criação de uma condição para quantidade total maior ou igual a 3 unidades. ```php // Exemplo: 3 ou mais unidades new ConditionDefinition('total_quantity', Operator::Gte, 3) ->operator->compare($cart->totalQuantity(), 3); ``` -------------------------------- ### Exemplo de uso de DiscountAllocation Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/alocacao.md Exemplo de uso: cria uma alocação com entradas de item e envio, e mostra os resultados de `total()`, `byItem()` e `byComponentType()`. ```php $allocation = DiscountAllocation::of([ new AllocationEntry(1, 0, 'base', Money::fromCents(800)), new AllocationEntry(2, 1, 'print', Money::fromCents(400)), AllocationEntry::shipping(Money::fromCents(1200)), ]); $allocation->total()->cents; // 2400 $allocation->byItem(); // [1 => R$ 800, 2 => R$ 400] $allocation->byComponentType(); // ['base' => R$ 800, 'print' => R$ 400, '__shipping__' => R$ 1200] ``` -------------------------------- ### Operator::compare usage examples with ContainsAny and Gte Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/enums.md Shows usage of the compare method: ContainsAny checks array intersection, and Gte (GreaterThanOrEqual) compares numeric values. The comment notes that 'vip' arrives as an array from the client and the rule value also arrives as an array. ```php use SolutionsTI\DiscountEngine\Core\Enums\Operator; Operator::ContainsAny->compare(['vip', 'atacado'], ['vip']); // true Operator::Gte->compare(25000, 20000); // true // 'vip' chega como array do cliente; o valor da regla também ``` -------------------------------- ### Método usages() Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/modelos-laravel.md Relação HasMany com DiscountUsage usando a chave estrangeira 'rule_id'. ```php public function usages(): HasMany ``` -------------------------------- ### DiscountEngine private helper methods Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/engine.md Group of private helper method signatures. applyGlobalCap calculates the cap as subtotal->percentage(globalCapPercentage), separates shipping entries, limits item entries with clampTo, and rejoins with shipping intact. ```php private function metaList(ActionDefinition $action, string $key): array private function componentTypes(ActionDefinition $action): array private function reasonToSkip(Rule $rule, CartContext $cart, DateTimeImmutable $now): ?RejectionReason private function applyGlobalCap(DiscountAllocation $allocation, Money $subtotal): DiscountAllocation ``` -------------------------------- ### FreeShippingDiscount: key, label, calculate, and configuration examples Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/acoes.md FreeShippingDiscount provides free shipping or partial subsidy when maxDiscount is less than the shipping cost. The scope contains a single synthetic component mounted by the engine from ActionTarget::Shipping. The calculate method clamps the discount to maxDiscount if set and spreads the allocation across the scope. ```php public static function key(): string // 'free_shipping' public static function label(): string // 'Frete gratis' ``` ```php public function calculate( ActionDefinition $definition, CartContext $cart, DiscountScope $scope, ): DiscountAllocation { $discount = $scope->total(); if ($definition->maxDiscount !== null) { $discount = $discount->clampTo($definition->maxDiscount); } return DiscountAllocation::spread($scope, $discount); } ``` ```php // Flete gratis total ['type' => 'free_shipping', 'value' => 0, 'target' => 'shipping'] // Subsidio de até R$ 10 ['type' => 'free_shipping', 'value' => 0, 'target' => 'shipping', 'max_discount_cents' => 1000] ``` -------------------------------- ### TotalQuantityCondition: key() e label() Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/condicoes.md Métodos estáticos que retornam a chave 'total_quantity' e o rótulo 'Quantidade total de itens'. ```php public static function key(): string // 'total_quantity' public static function label(): string // 'Quantidade total de itens' ``` -------------------------------- ### POST /admin/descontos/simulador Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/endpoints.md Runs the real discount engine with a test cart and returns JSON. It does not require minimum fields; defaults are applied to all missing fields. ```APIDOC ## POST /admin/descontos/simulador ### Description Runs the real discount engine with a test cart and returns JSON. It does not require minimum fields; `CartContextFactory::fromArray` applies defaults to everything. ### Method POST ### Endpoint /admin/descontos/simulador ### Parameters #### Request Body - **items** (array) - Optional - List of cart items. Each item has: `sku` (string), `quantity` (integer), `unit_price_cents` (integer), `category_ids` (array of integers). - **shipping_cents** (integer) - Optional - Shipping cost in cents. - **customer** (object) - Optional - Customer data with `id` (integer), `groups` (array of strings), `completed_orders` (integer). - **coupons** (array of strings) - Optional - List of coupon codes. - **attributes** (object) - Optional - Additional attributes, e.g., `canal` (string). ### Request Example ```json { "items": [{ "sku": "CAMISA-P", "quantity": 2, "unit_price_cents": 4000, "category_ids": [7] }], "shipping_cents": 1200, "customer": { "id": 42, "groups": ["vip"], "completed_orders": 3 }, "coupons": ["BEMVINDO10"], "attributes": { "canal": "web" } } ``` ### Response #### Success Response (200) - **subtotal_cents** (integer) - Subtotal in cents. - **shipping_cents** (integer) - Shipping cost in cents. - **items_discount_cents** (integer) - Total discount on items in cents. - **shipping_discount_cents** (integer) - Total discount on shipping in cents. - **total_discount_cents** (integer) - Total discount in cents. - **final_total_cents** (integer) - Final total in cents. - **applied** (array) - List of applied rules. Each has: `rule_name` (string), `action_type` (string), `target` (string), `coupon_code` (string), `amount_cents` (integer). - **rejected** (array) - List of rejected rules. Each has: `rule_name` (string), `reason` (string), `message` (string). - **by_item** (object) - Discount per item, keyed by item index. - **by_component_type** (object) - Discount per component type. #### Response Example ```json { "subtotal_cents": 8000, "shipping_cents": 1200, "items_discount_cents": 2500, "shipping_discount_cents": 0, "total_discount_cents": 2500, "final_total_cents": 6700, "applied": [{ "rule_name": "10% na primeira compra", "action_type": "percentage", "target": "Total do carrinho", "coupon_code": "BEMVINDO10", "amount_cents": 2500 }], "rejected": [{ "rule_name": "Regra esgotada", "reason": "usage_limit_reached", "message": "Limite de uso atingido" }], "by_item": { "1": 2500 }, "by_component_type": { "base": 2500 } } ``` #### Error Response (422) - **error** (string) - Error message describing the invalid cart or any thrown exception. #### Error Example ```json { "error": "Item [CAMISA-P]: unitPrice (5000) nao bate com a soma dos componentes (4000)." } ``` ``` -------------------------------- ### RuleController index method Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/http.md Returns a paginated list of discount rules with coupon counts, ordered by priority and name. Uses the view 'discount-engine::rules.index'. ```php public function index(): View ``` -------------------------------- ### DiscountEngine::resolveBestOffer private method Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/engine.md Private method that resolves the best offer among candidates. Returns an array with 'rule', 'simulation', and 'rejected' keys. In case of a tie, the rule with the lowest numeric priority wins (already the order of the list). ```php private function resolveBestOffer( Rule $trigger, array $candidates, CartContext $cart, DateTimeImmutable $now, DiscountAllocation $accumulated, ): array ``` -------------------------------- ### Método calculate do DiscountManager Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/gerente-laravel.md Calcula os descontos do carrinho. Deve ser chamado a cada mutação. Delega em engine->evaluate($cart) e retorna DiscountResult. ```php /** Calcula os descontos do carrinho. Chamar a cada mutacao. */ public function calculate(CartContext $cart): DiscountResult ``` -------------------------------- ### TotalQuantityCondition: evaluate() Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/condicoes.md Método evaluate que compara a quantidade total de unidades no carrinho com o valor da condição. ```php public function evaluate(ConditionDefinition $definition, CartContext $cart): bool { return $definition->operator->compare( $cart->totalQuantity(), $definition->value, ); } ``` -------------------------------- ### DiscountAllocation::spread Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/_autodocs/api-reference/alocacao.md Fábrica estática que distribui `$amount` entre os componentes do escopo proporcionalmente ao disponível, usando `Money::allocate` (maior resto). Devolve `empty()` se o montante é zero, o escopo está vazio ou a soma de pesos é <= 0. O `$amount` é limitado com `clampTo($scope->total())`. ```php public static function spread(DiscountScope $scope, Money $amount): self ``` -------------------------------- ### Estrutura de diretórios do projeto Laravel Discount Engine Source: https://github.com/andersonrubensfonseca/laravel-discount-engine/blob/main/README.md Estrutura de diretórios do pacote, mostrando a separação entre o núcleo em PHP puro (src/Core) e a camada de integração Laravel (src/Laravel). Inclui os principais contratos, enums, contextos, ações, registries e o motor de desconto. ```text src/Core/ PHP puro, zero Laravel ├── Contracts/ ConditionEvaluator, DiscountAction, RuleRepository, UsageTracker ├── Enums/ TriggerType, CombinationMode, CalculationBase, ResolutionStrategy... ├── Context/ CartContext, CartItem, PriceComponent, CustomerContext ├── Money/ Money (centavos, rateio sem perda) ├── Allocation/ DiscountAllocation, DiscountScope, ScopedComponent ├── Rule/ Rule, ConditionGroup, ConditionDefinition, ActionDefinition ├── Conditions/ 5 condicoes ├── Actions/ 6 acoes ├── Registry/ ConditionRegistry, ActionRegistry ├── Engine/ DiscountEngine, ConditionMatcher └── Result/ DiscountResult, AppliedDiscount, RejectedRule src/Laravel/ camada de integracao ├── Models/ Eloquent ├── Repositories/ EloquentRuleRepository (com cache), RuleHydrator ├── Support/ UsageReserver, CartContextFactory, validador, PanelFieldMap ├── Http/ controllers do painel e do simulador └── Console/ discount:race-test ```