ldc-cocotte/tests/Integration/WithApp/App/Services/StatsServiceTest.php

285 lines
12 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Integration\WithApp\App\Services;
use App\Models\Customer;
use App\Models\Employee;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\OrderTunnelAttempt;
use App\Services\StatsService;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Domain\Enums\OrderStatus;
use Domain\Enums\ProductBrand;
use Domain\Enums\StatsCustomerType;
use Domain\Enums\StatsShopType;
use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Models\ValueObjects\Code;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Email;
use Domain\Models\ValueObjects\Entities\ProductId;
use Domain\Models\ValueObjects\IncoId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderEmployee;
use Domain\Models\ValueObjects\OrderLineProduct;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Models\ValueObjects\ProductWeight;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Illuminate\Support\Facades\Date;
use Money\Currency;
use Money\Money;
use Shared\Helpers\UuidHelper;
covers(StatsService::class);
beforeEach(function (): void {
$now = CarbonImmutable::parse('2026-06-15 10:00:00', 'Europe/Paris');
Date::setTestNow($now);
CarbonImmutable::setTestNow($now);
Carbon::setTestNow($now);
});
afterEach(function (): void {
Date::setTestNow();
CarbonImmutable::setTestNow();
Carbon::setTestNow();
});
describe('StatsService', function (): void {
$createEmployee = function (int $id, string $matricule, ?Customer $customer = null, ?CarbonImmutable $createdAt = null): Employee {
$timestamp = $createdAt ?? CarbonImmutable::now();
$codeSuffix = str_replace('0', '9', (string) $id);
return Employee::query()->forceCreate([
'id' => $id,
'customer_id' => $customer?->id,
'matricule' => new Matricule($matricule),
'code' => new Code('ABCDE' . $codeSuffix),
'nom' => 'Doe',
'prenom' => 'John',
'etablissement' => 'ETAB',
'site' => 'SITE',
'service' => '101',
'created_at' => $timestamp,
'updated_at' => $timestamp,
]);
};
$createOrder = function (
OrderStatus $status,
string $matricule,
CarbonImmutable $createdAt,
?CarbonImmutable $pickupDay = null,
int $totalCents = 1000,
): Order {
return Order::query()->forceCreate([
'id' => UuidHelper::v7($createdAt)->toString(),
'reference' => new OrderReference(UuidHelper::v7()),
'status' => $status->value,
'total' => new Money($totalCents, new Currency('EUR')),
'pickup_day' => $pickupDay,
'employee' => new OrderEmployee(
new Matricule($matricule),
'John',
'Doe',
new ShopperEstablishmentCode('FAC01'),
new ShopperSiteCode('SITE'),
new ShopperServiceCode('101'),
),
'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'),
]);
};
it('calculates membership percentage and returns 0 when no active employees exist', function () use ($createEmployee): void {
// GIVEN
$service = new StatsService(new Currency('EUR'));
expect($service->getMembershipPercentage())->toBe(0.0);
$customer = Customer::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'hashcode' => UuidHelper::v4()->toString(),
'email' => new Email('member@example.com'),
]);
$createEmployee(101, '1000101', $customer);
$createEmployee(102, '1000102', null);
$createEmployee(103, '1000103', null);
$createEmployee(104, '1000104', null);
// WHEN
$percentage = $service->getMembershipPercentage();
// THEN
expect($percentage)->toBe(25.0);
});
it('calculates membership rate within period and previous period', function () use ($createEmployee): void {
// GIVEN
$service = new StatsService(new Currency('EUR'));
$now = CarbonImmutable::now();
$inRange = $now->subDays(3);
$outRange = $now->subDays(20);
$customer1 = Customer::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'hashcode' => UuidHelper::v4()->toString(),
'email' => new Email('range1@example.com'),
]);
$createEmployee(201, '1000201', $customer1, $inRange);
$createEmployee(202, '1000202', null, $inRange);
$createEmployee(203, '1000203', null, $outRange);
$start = $now->subDays(10);
$end = $now;
// WHEN
$rate = $service->getMembershipRate($start, $end);
$previousPeriod = $service->getPreviousPeriod($start, $end);
// THEN
expect($rate)->toBe(50.0)
->and($previousPeriod->getStartDate()->toDateString())->toBe($start->copy()->subDays(11)->toDateString())
->and($previousPeriod->getIncludedEndDate()->toDateString())->toBe($start->copy()->subDays(1)->toDateString());
});
it('computes customer and shop stats over current and previous periods', function () use ($createEmployee, $createOrder): void {
// GIVEN
$service = new StatsService(new Currency('EUR'));
$now = CarbonImmutable::now();
$customer = Customer::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'hashcode' => UuidHelper::v4()->toString(),
'email' => new Email('stats@example.com'),
]);
$createEmployee(301, '1000301', $customer, $now->subDays(3));
$createEmployee(302, '1000302', null, $now->subDays(15));
$validatedOrder = $createOrder(
OrderStatus::VALIDATED,
'1000301',
$now->subDays(2),
$now->addDays(2),
totalCents: 1200,
);
$createOrder(
OrderStatus::CANCELED,
'1000301',
$now->subDays(2),
$now->addDays(10),
);
$productVo = new OrderLineProduct(
incoId: new IncoId(1),
originalId: new ProductId(UuidHelper::v7()),
name: 'Poulet',
weight: new ProductWeight(1000, false),
brand: ProductBrand::loue,
orderUnit: OrderUnit::PCE,
price: new Money(1055, new Currency('EUR')),
discountedPrice: new Money(1055, new Currency('EUR')),
priceKgTtc: new Money(1055, new Currency('EUR')),
taxRate: TaxRate::TVA_5_5,
);
OrderLine::query()->forceCreate([
'order_id' => $validatedOrder->id,
'product' => $productVo,
'quantity' => 2,
'unit_price' => new Money(1000, new Currency('EUR')),
'unit_tax' => new Money(55, new Currency('EUR')),
'unit_discount' => new Money(0, new Currency('EUR')),
'tax_rate' => TaxRate::TVA_5_5,
'total_ht' => new Money(2000, new Currency('EUR')),
'total_ttc' => new Money(2110, new Currency('EUR')),
'total_tax' => new Money(110, new Currency('EUR')),
'total_discount' => new Money(0, new Currency('EUR')),
]);
// WHEN
$customerStats = $service->getStats(StatsCustomerType::cases(), $now->subDays(5), $now);
$shopStats = $service->getStats(StatsShopType::cases(), $now->subDays(5), $now);
// THEN
expect($customerStats[StatsCustomerType::nbSalarie->value]['current'])->toBe(1)
->and($customerStats[StatsCustomerType::nbSalarieWithAccount->value]['current'])->toBe(1)
->and($customerStats[StatsCustomerType::membershipRate->value]['current'])->toBe(100.0)
->and($shopStats[StatsShopType::nbValidateCmd->value]['current'])->toBe(1)
->and($shopStats[StatsShopType::nbCanceledCmd->value]['current'])->toBe(1)
->and($shopStats[StatsShopType::nbWaitingCmd->value]['current'])->toBe(0)
->and($shopStats[StatsShopType::canceledRate->value]['current'])->toBe(50.0)
->and($shopStats[StatsShopType::nbActiveClients->value]['current'])->toBe(1)
->and($shopStats[StatsShopType::nbCmdWith7DayDelay->value]['current'])->toBe(1)
->and($shopStats[StatsShopType::nbCmdWith14DayDelay->value]['current'])->toBe(0)
->and($shopStats[StatsShopType::caHt->value]['current'])->toBe(20.0)
->and($shopStats[StatsShopType::caTtc->value]['current'])->toBe(21.1)
->and($shopStats[StatsShopType::averageBasketHt->value]['current'])->toBe(20.0)
->and($shopStats[StatsShopType::averageProductCountPerOrder->value]['current'])->toBe(2.0);
});
it('combines legacy WAITING orders and unconverted tunnel attempts in waiting stats', function () use ($createOrder): void {
// GIVEN
$service = new StatsService(new Currency('EUR'));
$now = CarbonImmutable::now();
$customer = Customer::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'hashcode' => UuidHelper::v4()->toString(),
'email' => new Email('attempts-stats@example.com'),
]);
// 1 legacy WAITING order
$createOrder(OrderStatus::WAITING, '1000401', $now->subDays(2));
// 1 VALIDATED + 1 CANCELED business orders
$validatedOrder = $createOrder(OrderStatus::VALIDATED, '1000401', $now->subDays(2));
$createOrder(OrderStatus::CANCELED, '1000401', $now->subDays(2));
// Technical PENDING and FAILED orders must never pollute nbWaitingCmd or canceledRate
$createOrder(OrderStatus::PENDING, '1000401', $now->subDays(2));
$createOrder(OrderStatus::FAILED, '1000401', $now->subDays(2));
// 2 unconverted attempts in period
OrderTunnelAttempt::query()->forceCreate([
'customer_id' => $customer->id,
'order_id' => null,
'converted_at' => null,
'created_at' => $now->subDay()->utc(),
'updated_at' => $now->subDay()->utc(),
]);
OrderTunnelAttempt::query()->forceCreate([
'customer_id' => $customer->id,
'order_id' => null,
'converted_at' => null,
'created_at' => $now->subHours(2)->utc(),
'updated_at' => $now->subHours(2)->utc(),
]);
// 1 converted attempt (must not be counted as waiting)
OrderTunnelAttempt::query()->forceCreate([
'customer_id' => $customer->id,
'order_id' => $validatedOrder->id,
'converted_at' => $now->subDays(2)->utc(),
'created_at' => $now->subDays(2)->utc(),
'updated_at' => $now->subDays(2)->utc(),
]);
// 1 unconverted attempt outside the queried period (must not be counted)
OrderTunnelAttempt::query()->forceCreate([
'customer_id' => $customer->id,
'order_id' => null,
'converted_at' => null,
'created_at' => $now->subDays(12)->utc(),
'updated_at' => $now->subDays(12)->utc(),
]);
// WHEN
$shopStats = $service->getStats(StatsShopType::cases(), $now->subDays(5), $now);
// THEN: waiting = 1 legacy + 2 unconverted = 3 ; canceled = 1 ; validated = 1 => canceledRate = (4 / 5) * 100 = 80.0
expect($shopStats[StatsShopType::nbWaitingCmd->value]['current'])->toBe(3)
->and($shopStats[StatsShopType::nbValidateCmd->value]['current'])->toBe(1)
->and($shopStats[StatsShopType::nbCanceledCmd->value]['current'])->toBe(1)
->and($shopStats[StatsShopType::canceledRate->value]['current'])->toBe(80.0);
});
});