Add the quick sales report

Quick sales of a period by cash day, product, seller and VAT rate, with
credits, open cash days flagged, a chart by day or month and CSV. VAT is
taken out of each day's total of a rate, as on the cash day balance.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-25 08:44:20 +02:00
co-authored by Claude Sonnet 5.5
parent a57b383e4d
commit 568871c9dc
19 changed files with 748 additions and 2 deletions
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\Contracts;
use App\Modules\Reports\Application\DTOs\SalesData;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
/**
* Quick sales summed by day, product, seller and VAT rate, from the Sales module.
*/
interface ReportSales
{
public function between(ReportPeriod $period): SalesData;
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* Quick sales of a period as the Sales module sums them, amounts with VAT
* in cents and credits negative.
*/
final readonly class SalesData
{
/**
* @param list<array{day: string, count: int, cashCents: int, cardCents: int, isClosed: bool}> $days
* @param list<array{name: string, quantity: int, grossCents: int}> $products
* @param list<array{sellerId: int, count: int, grossCents: int}> $sellers
* @param list<array{day: string, vatBasisPoints: int, grossCents: int}> $dayVatTotals
*/
public function __construct(
public array $days,
public array $products,
public array $sellers,
public array $dayVatTotals,
) {}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* Quick sales of a period (spec 13), amounts with VAT in cents and
* credits negative: by cash day, product, seller (by name) and VAT rate,
* the totals, and a chart series by day or, for longer periods, by month
* (label Y-m-d or Y-m → cents).
*/
final readonly class SalesReport
{
/**
* @param list<array{day: string, count: int, cashCents: int, cardCents: int, totalCents: int, isClosed: bool}> $days
* @param list<array{name: string, quantity: int, grossCents: int}> $products
* @param list<array{name: string, count: int, grossCents: int}> $sellers
* @param list<array{vatBasisPoints: int, grossCents: int, netCents: int, vatCents: int}> $vatTotals
* @param array<string, int> $series
*/
public function __construct(
public array $days,
public array $products,
public array $sellers,
public array $vatTotals,
public int $count,
public int $cashCents,
public int $cardCents,
public int $openDays,
public array $series,
public bool $seriesByMonth,
) {}
public function totalCents(): int
{
return $this->cashCents + $this->cardCents;
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\UseCases;
use App\Modules\Reports\Application\Contracts\ReportPeople;
use App\Modules\Reports\Application\Contracts\ReportSales;
use App\Modules\Reports\Application\DTOs\SalesReport;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
/**
* Quick sales in a period (spec 7, 13). The VAT of a rate is taken out of
* each day's total of the rate, as on the cash day balance, and summed
* over the days, so the report matches the closed days' balances.
*/
final readonly class QuickSalesReport
{
/** Periods longer than this are charted by month. */
private const int DAILY_CHART_DAYS = 62;
public function __construct(
private ReportSales $sales,
private ReportPeople $people,
) {}
public function execute(ReportPeriod $period): SalesReport
{
$data = $this->sales->between($period);
$days = array_map(fn (array $day): array => [...$day, 'totalCents' => $day['cashCents'] + $day['cardCents']], $data->days);
$names = $this->people->namesByIds(array_map(fn (array $seller): int => $seller['sellerId'], $data->sellers));
$sellers = array_map(fn (array $seller): array => [
'name' => $names[$seller['sellerId']] ?? '',
'count' => $seller['count'],
'grossCents' => $seller['grossCents'],
], $data->sellers);
usort($sellers, fn (array $a, array $b): int => strnatcasecmp($a['name'], $b['name']));
$byRate = [];
foreach ($data->dayVatTotals as $total) {
$gross = $total['grossCents'];
$net = Money::fromCents(abs($gross))->removeVat(new VatPercentage($total['vatBasisPoints']))->cents;
$net = $gross < 0 ? -$net : $net;
$rate = $total['vatBasisPoints'];
$byRate[$rate] ??= ['vatBasisPoints' => $rate, 'grossCents' => 0, 'netCents' => 0, 'vatCents' => 0];
$byRate[$rate]['grossCents'] += $gross;
$byRate[$rate]['netCents'] += $net;
$byRate[$rate]['vatCents'] += $gross - $net;
}
krsort($byRate);
$byMonth = $period->dayCount() > self::DAILY_CHART_DAYS;
$series = [];
foreach ($days as $day) {
$key = $byMonth ? substr($day['day'], 0, 7) : $day['day'];
$series[$key] = ($series[$key] ?? 0) + $day['totalCents'];
}
return new SalesReport(
$days,
$data->products,
$sellers,
array_values($byRate),
array_sum(array_column($days, 'count')),
array_sum(array_column($days, 'cashCents')),
array_sum(array_column($days, 'cardCents')),
count(array_filter($days, fn (array $day): bool => ! $day['isClosed'])),
$series,
$byMonth,
);
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Modules\Reports\Infrastructure\Adapters;
use App\Modules\Reports\Application\Contracts\ReportSales;
use App\Modules\Reports\Application\DTOs\SalesData;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
use App\Modules\Sales\Application\Contracts\QuickSaleReportQueries;
/**
* Quick sales for reports through the Sales module.
*/
class SalesForReports implements ReportSales
{
public function __construct(private QuickSaleReportQueries $queries) {}
public function between(ReportPeriod $period): SalesData
{
$sales = $this->queries->between($period->from, $period->to);
return new SalesData($sales->days, $sales->products, $sales->sellers, $sales->dayVatTotals);
}
}
@@ -7,10 +7,12 @@ use App\Modules\Reports\Application\Contracts\ReportCatalog;
use App\Modules\Reports\Application\Contracts\ReportHours; use App\Modules\Reports\Application\Contracts\ReportHours;
use App\Modules\Reports\Application\Contracts\ReportJobs; use App\Modules\Reports\Application\Contracts\ReportJobs;
use App\Modules\Reports\Application\Contracts\ReportPeople; use App\Modules\Reports\Application\Contracts\ReportPeople;
use App\Modules\Reports\Application\Contracts\ReportSales;
use App\Modules\Reports\Infrastructure\Adapters\CatalogForReports; use App\Modules\Reports\Infrastructure\Adapters\CatalogForReports;
use App\Modules\Reports\Infrastructure\Adapters\HoursForReports; use App\Modules\Reports\Infrastructure\Adapters\HoursForReports;
use App\Modules\Reports\Infrastructure\Adapters\JobsForReports; use App\Modules\Reports\Infrastructure\Adapters\JobsForReports;
use App\Modules\Reports\Infrastructure\Adapters\PeopleForReports; use App\Modules\Reports\Infrastructure\Adapters\PeopleForReports;
use App\Modules\Reports\Infrastructure\Adapters\SalesForReports;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Livewire\Livewire; use Livewire\Livewire;
@@ -30,6 +32,7 @@ class ReportsServiceProvider extends ServiceProvider
ReportJobs::class => JobsForReports::class, ReportJobs::class => JobsForReports::class,
ReportCatalog::class => CatalogForReports::class, ReportCatalog::class => CatalogForReports::class,
ReportPeople::class => PeopleForReports::class, ReportPeople::class => PeopleForReports::class,
ReportSales::class => SalesForReports::class,
]; ];
public function boot(): void public function boot(): void
@@ -0,0 +1,40 @@
<?php
namespace App\Modules\Reports\Presentation\Csv;
use App\Modules\Reports\Application\UseCases\QuickSalesReport;
use Illuminate\Http\Request;
/**
* Quick sales as CSV: a row per cash day, amounts with VAT in cents.
*/
class SalesCsv implements ReportCsv
{
public function __construct(private QuickSalesReport $report) {}
public function fileName(Request $request): string
{
$period = CsvFilters::period($request);
return __('reports.sales.file').'-'.$period->from.'-'.$period->to;
}
public function headers(): array
{
return array_values(__('reports.sales.csv'));
}
public function rows(Request $request): iterable
{
foreach ($this->report->execute(CsvFilters::period($request))->days as $day) {
yield [
$day['day'],
$day['count'],
$day['cashCents'],
$day['cardCents'],
$day['totalCents'],
__($day['isClosed'] ? 'reports.yes' : 'reports.no'),
];
}
}
}
@@ -5,6 +5,7 @@ namespace App\Modules\Reports\Presentation\Http\Controllers;
use App\Modules\Reports\Domain\Exceptions\InvalidReportPeriod; use App\Modules\Reports\Domain\Exceptions\InvalidReportPeriod;
use App\Modules\Reports\Presentation\Csv\HoursCsv; use App\Modules\Reports\Presentation\Csv\HoursCsv;
use App\Modules\Reports\Presentation\Csv\ReportCsv; use App\Modules\Reports\Presentation\Csv\ReportCsv;
use App\Modules\Reports\Presentation\Csv\SalesCsv;
use App\Modules\Reports\Presentation\Csv\UnbilledCsv; use App\Modules\Reports\Presentation\Csv\UnbilledCsv;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
@@ -19,7 +20,7 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
class DownloadReport class DownloadReport
{ {
/** The reports that have a CSV, by their URL key. */ /** The reports that have a CSV, by their URL key. */
public const array REPORTS = ['hours', 'unbilled']; public const array REPORTS = ['hours', 'unbilled', 'sales'];
public function __invoke(string $report, Request $request): StreamedResponse public function __invoke(string $report, Request $request): StreamedResponse
{ {
@@ -73,6 +74,7 @@ class DownloadReport
return match ($report) { return match ($report) {
'hours' => app(HoursCsv::class), 'hours' => app(HoursCsv::class),
'unbilled' => app(UnbilledCsv::class), 'unbilled' => app(UnbilledCsv::class),
'sales' => app(SalesCsv::class),
default => abort(404), default => abort(404),
}; };
} }
@@ -89,7 +89,7 @@ trait ReportPage
* *
* @param array<string, string> $filters * @param array<string, string> $filters
*/ */
protected function csvUrl(string $report, array $filters = []): string public function csvUrl(string $report, array $filters = []): string
{ {
return route('reports.csv', array_filter(['report' => $report, 'alku' => $this->from, 'loppu' => $this->to, ...$filters], fn (string $value): bool => $value !== '')); return route('reports.csv', array_filter(['report' => $report, 'alku' => $this->from, 'loppu' => $this->to, ...$filters], fn (string $value): bool => $value !== ''));
} }
@@ -0,0 +1,219 @@
<?php
use App\Modules\Reports\Application\DTOs\SalesReport;
use App\Modules\Reports\Application\UseCases\QuickSalesReport;
use App\Modules\Reports\Presentation\Livewire\Concerns\ReportPage;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
use App\Modules\Users\Application\Contracts\Clock;
use Livewire\Attributes\Computed;
use Livewire\Component;
/**
* Quick sales in a period (spec 7, 13): by cash day, product, seller and
* VAT rate. They are counter sales apart from the billing material.
*/
new class extends Component
{
use ReportPage;
public function mount(Clock $clock): void
{
$this->startPeriod($clock);
}
#[Computed]
public function report(): ?SalesReport
{
$period = $this->period();
return $period === null ? null : app(QuickSalesReport::class)->execute($period);
}
public function updated(): void
{
$this->authorize('reports.view');
unset($this->report);
}
public function vatRate(int $basisPoints): string
{
return (new VatPercentage($basisPoints))->format();
}
public function seriesLabel(string $key): string
{
return strlen($key) === 7
? ((int) substr($key, 5, 2)).'/'.substr($key, 0, 4)
: $this->dateLabel($key);
}
public function render(): mixed
{
return $this->view()->title(__('reports.sales.title'));
}
};
?>
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ __('reports.sales.title') }}</h1>
<x-reports.period-filter :presets="$this->periodPresets()" :valid="$this->period !== null" />
@php($report = $this->report)
@if ($report !== null)
<div class="flex flex-wrap items-center justify-between gap-3">
<h2 class="text-xl font-semibold" role="status" aria-live="polite">{{ $this->periodLabel() }}</h2>
<x-button :href="$this->csvUrl('sales')" subtle color="black" icon="arrow-down-tray" :text="__('reports.download_csv')" />
</div>
@if ($report->days === [])
<p>{{ __('reports.sales.none') }}</p>
@else
@if ($report->openDays > 0)
<p class="flex items-start gap-2 text-sm">
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
{{ trans_choice('reports.sales.open_days', $report->openDays, ['count' => $report->openDays]) }}
</p>
@endif
<div class="grid gap-6 md:grid-cols-2">
<table class="w-full text-sm">
<caption class="mb-2 text-left text-base font-semibold">{{ __('reports.sales.totals') }}</caption>
<thead class="sr-only">
<tr>
<th scope="col">{{ __('reports.sales.item') }}</th>
<th scope="col">{{ __('reports.sales.amount') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
<tr>
<th scope="row" class="py-1 text-left font-normal">{{ __('reports.sales.count') }}</th>
<td class="py-1 text-right">{{ $report->count }}</td>
</tr>
<tr>
<th scope="row" class="py-1 text-left font-normal">{{ __('reports.sales.cash') }}</th>
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($report->cashCents) }}</td>
</tr>
<tr>
<th scope="row" class="py-1 text-left font-normal">{{ __('reports.sales.card') }}</th>
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($report->cardCents) }}</td>
</tr>
<tr>
<th scope="row" class="py-1 text-left font-semibold">{{ __('reports.sales.total') }}</th>
<td class="py-1 text-right font-semibold whitespace-nowrap">{{ $this->money($report->totalCents()) }}</td>
</tr>
</tbody>
</table>
<table class="w-full text-sm">
<caption class="mb-2 text-left text-base font-semibold">{{ __('reports.sales.by_vat') }}</caption>
<thead>
<tr class="text-left">
<th scope="col" class="py-1">{{ __('reports.sales.vat_rate') }}</th>
<th scope="col" class="py-1 text-right">{{ __('reports.sales.gross') }}</th>
<th scope="col" class="py-1 text-right">{{ __('reports.sales.net') }}</th>
<th scope="col" class="py-1 text-right">{{ __('reports.sales.vat') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($report->vatTotals as $vat)
<tr wire:key="vat-{{ $vat['vatBasisPoints'] }}">
<th scope="row" class="py-1 text-left font-normal">{{ $this->vatRate($vat['vatBasisPoints']) }}</th>
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($vat['grossCents']) }}</td>
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($vat['netCents']) }}</td>
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($vat['vatCents']) }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<x-reports.chart
:title="__($report->seriesByMonth ? 'reports.sales.chart_months' : 'reports.sales.chart_days')"
:summary="implode(', ', array_map(fn ($key, $cents) => $this->seriesLabel($key).' '.$this->money($cents), array_keys($report->series), $report->series))"
:labels="array_map(fn ($key) => $this->seriesLabel((string) $key), array_keys($report->series))"
:values="array_map(fn ($cents) => $cents / 100, array_values($report->series))"
:formatter="fn (float $value) => number_format($value, 0, ',', ' ').' €'"
/>
<div class="grid gap-6 md:grid-cols-2">
<table class="w-full text-sm">
<caption class="mb-2 text-left text-base font-semibold">{{ __('reports.sales.by_product') }}</caption>
<thead>
<tr class="text-left">
<th scope="col" class="py-1">{{ __('reports.sales.product') }}</th>
<th scope="col" class="py-1 text-right">{{ __('reports.sales.quantity') }}</th>
<th scope="col" class="py-1 text-right">{{ __('reports.sales.gross') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($report->products as $product)
<tr>
<th scope="row" class="py-1 text-left font-normal">{{ $product['name'] }}</th>
<td class="py-1 text-right">{{ $product['quantity'] }}</td>
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($product['grossCents']) }}</td>
</tr>
@endforeach
</tbody>
</table>
<table class="w-full text-sm">
<caption class="mb-2 text-left text-base font-semibold">{{ __('reports.sales.by_seller') }}</caption>
<thead>
<tr class="text-left">
<th scope="col" class="py-1">{{ __('reports.sales.seller') }}</th>
<th scope="col" class="py-1 text-right">{{ __('reports.sales.count') }}</th>
<th scope="col" class="py-1 text-right">{{ __('reports.sales.gross') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($report->sellers as $seller)
<tr>
<th scope="row" class="py-1 text-left font-normal">{{ $seller['name'] }}</th>
<td class="py-1 text-right">{{ $seller['count'] }}</td>
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($seller['grossCents']) }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<caption class="mb-2 text-left text-base font-semibold">{{ __('reports.sales.by_day') }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
<th scope="col" class="py-2 pr-3">{{ __('reports.sales.day') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.sales.count') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.sales.cash') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.sales.card') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.sales.total') }}</th>
<th scope="col" class="py-2">{{ __('reports.sales.cash_day') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($report->days as $day)
<tr wire:key="day-{{ $day['day'] }}">
<th scope="row" class="py-2 pr-3 text-left font-normal">
<x-link :href="route('sales.index', ['paiva' => $day['day']])" navigate>{{ $this->dateLabel($day['day']) }}</x-link>
</th>
<td class="py-2 pr-3 text-right">{{ $day['count'] }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($day['cashCents']) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($day['cardCents']) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($day['totalCents']) }}</td>
<td class="py-2">
@if ($day['isClosed'])
<span class="inline-flex items-center gap-1"><x-icon name="lock-closed" class="size-4" aria-hidden="true" />{{ __('reports.sales.closed') }}</span>
@else
<span class="inline-flex items-center gap-1"><x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('reports.sales.open') }}</span>
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endif
@endif
</div>
@@ -9,5 +9,6 @@ Route::middleware(['web', 'auth', 'can:reports.view'])
->group(function () { ->group(function () {
Route::livewire('/hours', 'reports::hours')->name('hours'); Route::livewire('/hours', 'reports::hours')->name('hours');
Route::livewire('/unbilled', 'reports::unbilled')->name('unbilled'); Route::livewire('/unbilled', 'reports::unbilled')->name('unbilled');
Route::livewire('/sales', 'reports::sales')->name('sales');
Route::get('/{report}/csv', DownloadReport::class)->whereIn('report', DownloadReport::REPORTS)->name('csv'); Route::get('/{report}/csv', DownloadReport::class)->whereIn('report', DownloadReport::REPORTS)->name('csv');
}); });
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\Contracts;
use App\Modules\Sales\Application\DTOs\QuickSalesInPeriod;
/**
* Quick sales summed for management's reports. Credits are included with
* negative amounts.
*/
interface QuickSaleReportQueries
{
/**
* Sales of the cash days from the first to the last (Y-m-d, both included).
*/
public function between(string $from, string $to): QuickSalesInPeriod;
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\DTOs;
/**
* Quick sales of a period, amounts with VAT in cents:
*
* - days: every cash day with sales, oldest first;
* - products: by product name, most sold (in euros) first;
* - sellers: by seller id;
* - dayVatTotals: each day's sales by VAT rate, for VAT taken out of the
* day's total of a rate as on the cash day balance.
*/
final readonly class QuickSalesInPeriod
{
/**
* @param list<array{day: string, count: int, cashCents: int, cardCents: int, isClosed: bool}> $days
* @param list<array{name: string, quantity: int, grossCents: int}> $products
* @param list<array{sellerId: int, count: int, grossCents: int}> $sellers
* @param list<array{day: string, vatBasisPoints: int, grossCents: int}> $dayVatTotals
*/
public function __construct(
public array $days,
public array $products,
public array $sellers,
public array $dayVatTotals,
) {}
}
@@ -0,0 +1,96 @@
<?php
namespace App\Modules\Sales\Infrastructure\Persistence\Repositories;
use App\Modules\Sales\Application\Contracts\QuickSaleReportQueries;
use App\Modules\Sales\Application\DTOs\QuickSalesInPeriod;
use DateTimeImmutable;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
/**
* Sums quick sales and their lines in the database.
*/
class EloquentQuickSaleReportQueries implements QuickSaleReportQueries
{
public function between(string $from, string $to): QuickSalesInPeriod
{
$until = (new DateTimeImmutable($to))->modify('+1 day')->format('Y-m-d');
$closedDays = DB::table('cash_days')
->whereNotNull('closed_at')
->where('day', '>=', $from)
->where('day', '<', $until)
->pluck('day')
->map(fn ($day): string => substr((string) $day, 0, 10))
->flip();
$days = DB::table('quick_sales')
->where('sold_on', '>=', $from)
->where('sold_on', '<', $until)
->groupBy('sold_on')
->orderBy('sold_on')
->select('sold_on')
->selectRaw('COUNT(*) as sale_count')
->selectRaw("SUM(CASE WHEN payment_method = 'cash' THEN total_cents ELSE 0 END) as cash_cents")
->selectRaw("SUM(CASE WHEN payment_method = 'cash' THEN 0 ELSE total_cents END) as card_cents")
->get()
->map(function (object $row) use ($closedDays): array {
$day = substr((string) $row->sold_on, 0, 10);
return [
'day' => $day,
'count' => (int) $row->sale_count,
'cashCents' => (int) $row->cash_cents,
'cardCents' => (int) $row->card_cents,
'isClosed' => $closedDays->has($day),
];
})
->all();
$products = $this->lines($from, $until)
->groupBy('quick_sale_lines.product_name')
->select('quick_sale_lines.product_name')
->selectRaw('SUM(quick_sale_lines.quantity) as quantity')
->selectRaw('SUM(quick_sale_lines.quantity * quick_sale_lines.unit_price_cents) as gross_cents')
->orderByDesc('gross_cents')
->orderBy('quick_sale_lines.product_name')
->get()
->map(fn (object $row): array => ['name' => (string) $row->product_name, 'quantity' => (int) $row->quantity, 'grossCents' => (int) $row->gross_cents])
->all();
$sellers = DB::table('quick_sales')
->where('sold_on', '>=', $from)
->where('sold_on', '<', $until)
->groupBy('user_id')
->select('user_id')
->selectRaw('COUNT(*) as sale_count')
->selectRaw('SUM(total_cents) as gross_cents')
->get()
->map(fn (object $row): array => ['sellerId' => (int) $row->user_id, 'count' => (int) $row->sale_count, 'grossCents' => (int) $row->gross_cents])
->all();
$dayVatTotals = $this->lines($from, $until)
->groupBy('quick_sales.sold_on', 'quick_sale_lines.vat_basis_points')
->orderBy('quick_sales.sold_on')
->orderBy('quick_sale_lines.vat_basis_points')
->select('quick_sales.sold_on', 'quick_sale_lines.vat_basis_points')
->selectRaw('SUM(quick_sale_lines.quantity * quick_sale_lines.unit_price_cents) as gross_cents')
->get()
->map(fn (object $row): array => [
'day' => substr((string) $row->sold_on, 0, 10),
'vatBasisPoints' => (int) $row->vat_basis_points,
'grossCents' => (int) $row->gross_cents,
])
->all();
return new QuickSalesInPeriod(array_values($days), array_values($products), array_values($sellers), array_values($dayVatTotals));
}
private function lines(string $from, string $until): Builder
{
return DB::table('quick_sale_lines')
->join('quick_sales', 'quick_sales.id', '=', 'quick_sale_lines.quick_sale_id')
->where('quick_sales.sold_on', '>=', $from)
->where('quick_sales.sold_on', '<', $until);
}
}
@@ -7,12 +7,14 @@ use App\Modules\Customers\Application\Contracts\CustomerReferences;
use App\Modules\Sales\Application\Contracts\QuickSaleHours; use App\Modules\Sales\Application\Contracts\QuickSaleHours;
use App\Modules\Sales\Application\Contracts\QuickSaleProducts; use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
use App\Modules\Sales\Application\Contracts\QuickSaleQueries; use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
use App\Modules\Sales\Application\Contracts\QuickSaleReportQueries;
use App\Modules\Sales\Domain\Contracts\CashDayRepository; use App\Modules\Sales\Domain\Contracts\CashDayRepository;
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository; use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
use App\Modules\Sales\Infrastructure\CustomerReferencesFromSales; use App\Modules\Sales\Infrastructure\CustomerReferencesFromSales;
use App\Modules\Sales\Infrastructure\HoursForQuickSales; use App\Modules\Sales\Infrastructure\HoursForQuickSales;
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentCashDayRepository; use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentCashDayRepository;
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleQueries; use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleQueries;
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleReportQueries;
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleRepository; use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleRepository;
use App\Modules\Sales\Infrastructure\ProductsFromPriceList; use App\Modules\Sales\Infrastructure\ProductsFromPriceList;
use App\Modules\Users\Domain\Enums\Role; use App\Modules\Users\Domain\Enums\Role;
@@ -34,6 +36,7 @@ class SalesServiceProvider extends ServiceProvider
QuickSaleRepository::class => EloquentQuickSaleRepository::class, QuickSaleRepository::class => EloquentQuickSaleRepository::class,
CashDayRepository::class => EloquentCashDayRepository::class, CashDayRepository::class => EloquentCashDayRepository::class,
QuickSaleQueries::class => EloquentQuickSaleQueries::class, QuickSaleQueries::class => EloquentQuickSaleQueries::class,
QuickSaleReportQueries::class => EloquentQuickSaleReportQueries::class,
QuickSaleProducts::class => ProductsFromPriceList::class, QuickSaleProducts::class => ProductsFromPriceList::class,
QuickSaleHours::class => HoursForQuickSales::class, QuickSaleHours::class => HoursForQuickSales::class,
]; ];
+1
View File
@@ -99,6 +99,7 @@ final class MainMenu
'items' => [ 'items' => [
['route' => 'reports.hours', 'pattern' => ['reports.hours'], 'label' => 'layout.report_hours', 'ability' => 'reports.view'], ['route' => 'reports.hours', 'pattern' => ['reports.hours'], 'label' => 'layout.report_hours', 'ability' => 'reports.view'],
['route' => 'reports.unbilled', 'pattern' => ['reports.unbilled'], 'label' => 'layout.report_unbilled', 'ability' => 'reports.view'], ['route' => 'reports.unbilled', 'pattern' => ['reports.unbilled'], 'label' => 'layout.report_unbilled', 'ability' => 'reports.view'],
['route' => 'reports.sales', 'pattern' => ['reports.sales'], 'label' => 'layout.report_sales', 'ability' => 'reports.view'],
], ],
], ],
'maintenance' => [ 'maintenance' => [
+39
View File
@@ -96,4 +96,43 @@ return [
'oldest' => 'Oldest entry', 'oldest' => 'Oldest entry',
], ],
], ],
'sales' => [
'title' => 'Quick sales',
'file' => 'quick-sales',
'none' => 'There are no quick sales in the period.',
'open_days' => '{1} One cash day is not closed, so its figures may still change.|[2,*] :count cash days are not closed, so their figures may still change.',
'totals' => 'Totals (with VAT)',
'item' => 'Item',
'amount' => 'Amount',
'count' => 'Sales',
'cash' => 'Cash',
'card' => 'Debit card',
'total' => 'Total',
'by_vat' => 'By VAT rate',
'vat_rate' => 'VAT rate',
'gross' => 'With VAT',
'net' => 'Without VAT',
'vat' => 'VAT',
'chart_days' => 'Sales by day (with VAT)',
'chart_months' => 'Sales by month (with VAT)',
'by_product' => 'By product',
'product' => 'Product',
'quantity' => 'Quantity',
'by_seller' => 'By seller',
'seller' => 'Seller',
'by_day' => 'By cash day',
'day' => 'Day',
'cash_day' => 'Cash day',
'closed' => 'Closed',
'open' => 'Not closed',
'csv' => [
'day' => 'Day',
'count' => 'Sales',
'cash' => 'Cash (cents)',
'card' => 'Debit card (cents)',
'total' => 'Total (cents)',
'closed' => 'Closed',
],
],
]; ];
+39
View File
@@ -96,4 +96,43 @@ return [
'oldest' => 'Vanhin kirjaus', 'oldest' => 'Vanhin kirjaus',
], ],
], ],
'sales' => [
'title' => 'Pikamyynnit',
'file' => 'pikamyynnit',
'none' => 'Aikavälillä ei ole pikamyyntejä.',
'open_days' => '{1} Yksi kassapäivä on päättämättä, joten sen luvut voivat vielä muuttua.|[2,*] :count kassapäivää on päättämättä, joten niiden luvut voivat vielä muuttua.',
'totals' => 'Yhteensä (verollinen)',
'item' => 'Erä',
'amount' => 'Määrä',
'count' => 'Myyntejä',
'cash' => 'Käteinen',
'card' => 'Pankkikortti',
'total' => 'Yhteensä',
'by_vat' => 'ALV-kannoittain',
'vat_rate' => 'ALV-kanta',
'gross' => 'Verollinen',
'net' => 'Veroton',
'vat' => 'Vero',
'chart_days' => 'Myynti päivittäin (verollinen)',
'chart_months' => 'Myynti kuukausittain (verollinen)',
'by_product' => 'Tuotteittain',
'product' => 'Tuote',
'quantity' => 'Määrä',
'by_seller' => 'Myyjittäin',
'seller' => 'Myyjä',
'by_day' => 'Kassapäivittäin',
'day' => 'Päivä',
'cash_day' => 'Kassapäivä',
'closed' => 'Päätetty',
'open' => 'Päättämättä',
'csv' => [
'day' => 'Päivä',
'count' => 'Myyntejä',
'cash' => 'Käteinen (snt)',
'card' => 'Pankkikortti (snt)',
'total' => 'Yhteensä (snt)',
'closed' => 'Päätetty',
],
],
]; ];
@@ -0,0 +1,75 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Sales\Domain\Enums\PaymentMethod;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->actingAs(User::factory()->management()->create());
$this->seller = User::factory()->employee()->create(['name' => 'Myyjä Maija']);
$this->photos = ProductModel::factory()->create(['name' => 'Passikuvat', 'price_cents' => 1990]);
$this->prints = ProductModel::factory()->create(['name' => 'Tuloste', 'price_cents' => 100]);
});
function reportSale(string $day, ProductModel $product, int $quantity, PaymentMethod $method = PaymentMethod::Cash, int $vat = 2550): QuickSaleModel
{
return QuickSaleModel::factory()->withLine($product, $quantity, $vat)->create([
'user_id' => test()->seller->id,
'payment_method' => $method,
'sold_on' => $day,
'sold_at' => $day.' 10:00:00',
]);
}
it('sums quick sales by day, product, seller and VAT rate with credits', function () {
$first = reportSale('2026-11-02', $this->photos, 2);
reportSale('2026-11-02', $this->prints, 5, PaymentMethod::Card, 1350);
reportSale('2026-11-03', $this->photos, 1, PaymentMethod::Card);
QuickSaleModel::factory()->withLine($this->photos, -2)->create([
'user_id' => $this->seller->id, 'sold_on' => '2026-11-03', 'sold_at' => '2026-11-03 12:00:00', 'credits_quick_sale_id' => $first->id,
]);
reportSale('2026-12-01', $this->photos, 9);
DB::table('cash_days')->insert(['day' => '2026-11-02', 'closed_at' => now(), 'closed_by' => $this->seller->id, 'created_at' => now(), 'updated_at' => now()]);
$report = Livewire::withQueryParams(['alku' => '2026-11-01', 'loppu' => '2026-11-30'])
->test('reports::sales')
->assertOk()
->assertSee('Passikuvat')
->assertSee('Myyjä Maija')
->instance()
->report();
expect($report->count)->toBe(4)
->and($report->cashCents)->toBe(0)
->and($report->cardCents)->toBe(2490)
->and($report->openDays)->toBe(1)
->and($report->days[0])->toBe(['day' => '2026-11-02', 'count' => 2, 'cashCents' => 3980, 'cardCents' => 500, 'isClosed' => true, 'totalCents' => 4480])
->and($report->products[0])->toBe(['name' => 'Passikuvat', 'quantity' => 1, 'grossCents' => 1990])
->and($report->sellers)->toBe([['name' => 'Myyjä Maija', 'count' => 4, 'grossCents' => 2490]])
->and($report->vatTotals)->toBe([
['vatBasisPoints' => 2550, 'grossCents' => 1990, 'netCents' => 1585, 'vatCents' => 405],
['vatBasisPoints' => 1350, 'grossCents' => 500, 'netCents' => 441, 'vatCents' => 59],
])
->and($report->series)->toBe(['2026-11-02' => 4480, '2026-11-03' => -1990]);
});
it('charts a long period by month and downloads the days as CSV', function () {
reportSale('2026-03-02', $this->photos, 1);
reportSale('2026-03-20', $this->photos, 1);
$report = Livewire::withQueryParams(['alku' => '2026-01-01', 'loppu' => '2026-12-31'])->test('reports::sales')->instance()->report();
expect($report->seriesByMonth)->toBeTrue()
->and($report->series)->toBe(['2026-03' => 3980]);
$response = $this->get(route('reports.csv', ['report' => 'sales', 'alku' => '2026-01-01', 'loppu' => '2026-12-31']))
->assertOk()
->assertDownload('pikamyynnit-2026-01-01-2026-12-31.csv');
expect($response->streamedContent())->toContain('2026-03-02;1;1990;0;1990;ei');
});