Add quick sales with cash days, credits and PDF receipts

Quick sales (pikamyynti) of active consumer products at the counter, in a
new Sales module:

- Product buttons add one to the sale's list per press; quantities can be
  lowered, raised or removed. Payment by cash or card, optional customer.
- Product durations are booked as the seller's hours on the yearly
  "Pikamyynnit" job (internal customer, not billed) through Jobs'
  ProvideQuickSaleTask and TimeTracking's AddTaskHours. The sale stands
  even when the hours cannot be booked, and the seller is told.
- Sales are never deleted: a credit records the lines negated on today's
  cash day, once per sale, by the seller or management.
- Closing a cash day stores its balance by payment method and VAT rate and
  stops sales on it; only management reopens a day.
- A printable A5 PDF receipt (barryvdh/laravel-dompdf) with the company's
  details, business ID, VAT number, lines and VAT breakdown.

Company details are kept in the settings and edited by the admin only on
the new Yritystiedot page. BusinessId moves from Customers to Shared so
both use the same check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 12:33:46 +02:00
co-authored by Claude Opus 5.5
parent c149c56388
commit 6de5d9bef1
101 changed files with 4768 additions and 29 deletions
+79
View File
@@ -0,0 +1,79 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->user = User::factory()->management()->create(['name' => 'Johtaja']);
$this->actingAs($this->user);
$this->photos = ProductModel::factory()->consumer()->withAutoHours(0.25)->create(['name' => 'Passikuvat', 'price_cents' => 1500]);
QuickSaleModel::factory()->withLine($this->photos, 2)->create(['user_id' => $this->user->id]);
});
it('has no accessibility issues on the quick sale pages and no sideways scrolling', function (string $page, string $device, string $colorScheme) {
$url = match ($page) {
'sell' => route('sales.sell'),
'sales' => route('sales.index'),
};
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertSee('Passikuvat')
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['sell', 'sales'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('adds products with their buttons and announces the sale', function () {
$button = '[wire\\:click="addProduct('.$this->photos->id.')"]';
$page = visit(route('sales.sell'));
$page->click('#products-heading ~ ul '.$button)
->click('#products-heading ~ ul '.$button)
->click('#products-heading ~ ul '.$button)
->assertSee('Yhteensä 45,00')
->assertSee('3 × 15,00')
->assertNoAccessibilityIssues(level: 2)
->click('Kirjaa myynti')
->assertSee('kirjattu: 45,00')
->assertSee('Tunneillesi kirjattiin 0,75 h.')
->assertSee('Avaa kuitti')
->assertNoAccessibilityIssues(level: 2);
});
it('has no accessibility issues on the company details page', function (string $device, string $colorScheme) {
$this->actingAs(User::factory()->admin()->create());
$visit = visit(route('settings.company'));
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertSee('Yritystiedot')
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('closes the cash day from its dialog', function () {
visit(route('sales.index'))
->click('Päätä kassapäivä')
->assertSee('Päätetäänkö kassapäivä?')
->assertNoAccessibilityIssues(level: 2)
->click('#close-dialog button:last-child')
->assertSee('Kassapäivä päätetty')
->assertSee('Avaa kassapäivä');
});
+5
View File
@@ -35,6 +35,11 @@ class FakeCustomerQueries implements CustomerQueries
return array_intersect_key($this->customers, array_flip($ids));
}
public function internalCustomerId(): ?int
{
return null;
}
public function personalIdentityCodeOf(int $customerId): ?string
{
return null;
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace Tests\Fakes;
use App\Modules\Sales\Application\Contracts\QuickSaleHours;
use DateTimeImmutable;
class FakeQuickSaleHours implements QuickSaleHours
{
/** @var list<array{int, string, int, int, int}> seller, day, work type, quarters, sale */
public array $booked = [];
public bool $fails = false;
public function book(int $sellerId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $saleId): bool
{
if ($this->fails) {
return false;
}
$this->booked[] = [$sellerId, $day->format('Y-m-d'), $workTypeId, $quarters, $saleId];
return true;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace Tests\Fakes;
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
use App\Modules\Sales\Application\DTOs\SellableProduct;
class FakeQuickSaleProducts implements QuickSaleProducts
{
/** @var list<SellableProduct> */
public array $products = [];
public function add(int $id, string $name, int $grossCents, int $vatBasisPoints = 2550, int $durationQuarters = 0, ?int $workTypeId = null): void
{
$this->products[] = new SellableProduct($id, $name, 'piece', $grossCents, $vatBasisPoints, $durationQuarters, $workTypeId);
}
public function sellable(): array
{
return $this->products;
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace Tests\Fakes;
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
use App\Modules\Sales\Domain\Entities\CashDay;
use DateTimeImmutable;
class InMemoryCashDayRepository implements CashDayRepository
{
/** @var array<string, CashDay> */
public array $days = [];
public function forDay(DateTimeImmutable $day): CashDay
{
return isset($this->days[$day->format('Y-m-d')]) ? clone $this->days[$day->format('Y-m-d')] : CashDay::open($day);
}
public function save(CashDay $cashDay): CashDay
{
$this->days[$cashDay->day()->format('Y-m-d')] = clone $cashDay;
return $cashDay;
}
public function lockForDay(DateTimeImmutable $day): CashDay
{
return $this->forDay($day);
}
}
@@ -37,6 +37,19 @@ class InMemoryCustomerJobRepository implements CustomerJobRepository, JobNumberS
return clone $this->jobs[$id];
}
/** @var array<int, int> year => job id */
public array $quickSaleJobs = [];
public function findQuickSaleJob(int $year): ?CustomerJob
{
return isset($this->quickSaleJobs[$year]) ? $this->findById($this->quickSaleJobs[$year]) : null;
}
public function markAsQuickSaleJob(int $jobId, int $year): void
{
$this->quickSaleJobs[$year] = $jobId;
}
public function recordChanges(int $jobId, int $userId, array $changes): void
{
foreach ($changes as $change) {
+1 -1
View File
@@ -4,8 +4,8 @@ namespace Tests\Fakes;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
class InMemoryCustomerRepository implements CustomerRepository
{
@@ -0,0 +1,52 @@
<?php
namespace Tests\Fakes;
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
use App\Modules\Sales\Domain\Entities\QuickSale;
use DateTimeImmutable;
class InMemoryQuickSaleRepository implements QuickSaleRepository
{
/** @var array<int, QuickSale> */
public array $sales = [];
private int $nextId = 1;
public function findById(int $id): ?QuickSale
{
return $this->sales[$id] ?? null;
}
public function add(QuickSale $sale): QuickSale
{
$id = $this->nextId++;
return $this->sales[$id] = QuickSale::reconstitute(
$id,
$sale->sellerId(),
$sale->customerId(),
$sale->paymentMethod(),
$sale->soldAt(),
$sale->soldOn(),
$sale->lines(),
$sale->creditsSaleId(),
);
}
public function isCredited(int $saleId): bool
{
foreach ($this->sales as $sale) {
if ($sale->creditsSaleId() === $saleId) {
return true;
}
}
return false;
}
public function forDay(DateTimeImmutable $day): array
{
return array_values(array_filter($this->sales, fn (QuickSale $sale): bool => $sale->soldOn()->format('Y-m-d') === $day->format('Y-m-d')));
}
}
+11
View File
@@ -19,6 +19,17 @@ class InMemoryTaskRepository implements TaskRepository
return $task !== null && $task->jobId() === $jobId ? clone $task : null;
}
public function findByWorkType(int $jobId, int $workTypeId): ?Task
{
foreach ($this->tasks as $task) {
if ($task->jobId() === $jobId && $task->workTypeId() === $workTypeId) {
return clone $task;
}
}
return null;
}
public function save(Task $task): Task
{
$id = $task->id() ?? $this->nextId++;
@@ -4,9 +4,9 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
@@ -0,0 +1,271 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\CashDayModel;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
use App\Modules\Shared\Application\DTOs\CompanyDetails;
use App\Modules\Shared\Application\UseCases\CompanyDetailsStore;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->travelTo(now()->setTimezone(config('app.business_timezone'))->setTime(12, 0));
$this->today = now(config('app.business_timezone'))->toDateString();
$this->employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']);
$this->photos = ProductModel::factory()->consumer()->withAutoHours(0.25)->create(['name' => 'Passikuvat', 'price_cents' => 1500]);
$this->prints = ProductModel::factory()->consumer()->create(['name' => 'Tuloste A4', 'price_cents' => 50]);
$this->actingAs($this->employee);
});
function sell(array $quantities, string $method = 'cash'): mixed
{
$component = Livewire::test('sales::sell');
foreach ($quantities as $productId => $quantity) {
for ($i = 0; $i < $quantity; $i++) {
$component->call('addProduct', $productId);
}
}
return $component->set('paymentMethod', $method)->call('save');
}
it('sells consumer products, keeps a snapshot of the prices and books the hours on the yearly quick sale job', function () {
sell([$this->photos->id => 2, $this->prints->id => 3])
->assertHasNoErrors()
->assertSet('savedMessage', fn (string $message) => str_contains($message, "31,50\u{00A0}€, Käteinen"))
->assertSet('hoursMessage', 'Tunneillesi kirjattiin 0,5 h.')
->assertSet('quantities', []);
$sale = QuickSaleModel::query()->with('lines')->sole();
expect($sale->total_cents)->toBe(3150)
->and($sale->user_id)->toBe($this->employee->id)
->and($sale->sold_on)->toBe($this->today)
->and($sale->lines->map->only(['product_name', 'quantity', 'unit_price_cents', 'vat_basis_points'])->all())->toBe([
['product_name' => 'Passikuvat', 'quantity' => 2, 'unit_price_cents' => 1500, 'vat_basis_points' => 2550],
['product_name' => 'Tuloste A4', 'quantity' => 3, 'unit_price_cents' => 50, 'vat_basis_points' => 2550],
]);
$job = CustomerJobModel::query()->where('quick_sale_year', now()->year)->sole();
$entry = TimeEntryModel::query()->sole();
expect($job->name)->toBe('Pikamyynnit '.now()->year)
->and($entry->customer_job_id)->toBe($job->id)
->and($entry->work_type_id)->toBe($this->photos->work_type_id)
->and((float) $entry->hours)->toBe(0.5)
->and($entry->note)->toBe('Pikamyynti #'.$sale->id);
sell([$this->photos->id => 1], 'card')->assertHasNoErrors();
expect(CustomerJobModel::query()->where('quick_sale_year', now()->year)->count())->toBe(1)
->and(TaskModel::query()->where('customer_job_id', $job->id)->count())->toBe(1)
->and((float) $entry->refresh()->hours)->toBe(0.75);
});
it('keeps the sale when the day\'s hours are already approved', function () {
sell([$this->photos->id => 1]);
TimeEntryModel::query()->update(['approved_at' => now(), 'approved_by' => $this->employee->id]);
sell([$this->photos->id => 1])
->assertHasNoErrors()
->assertSet('hoursMessage', fn (string $message) => str_starts_with($message, 'Tunteja (0,25 h) ei voitu kirjata'));
expect(QuickSaleModel::query()->count())->toBe(2)
->and((float) TimeEntryModel::query()->sole()->hours)->toBe(0.25);
});
it('adds a product with each press and lowers or removes it from the list', function () {
Livewire::test('sales::sell')
->call('addProduct', $this->photos->id)
->call('addProduct', $this->photos->id)
->call('addProduct', $this->prints->id)
->assertSet('quantities', [$this->photos->id => 2, $this->prints->id => 1])
->assertSet('cartMessage', "Tuloste A4: 1. Yhteensä 30,50\u{00A0}€.")
->assertSee("2 × 15,00\u{00A0}€ = 30,00\u{00A0}€", false)
->call('decreaseProduct', $this->photos->id)
->call('decreaseProduct', $this->prints->id)
->assertSet('quantities', [$this->photos->id => 1])
->assertSet('cartMessage', "Tuloste A4 poistettu. Yhteensä 15,00\u{00A0}€.")
->call('removeProduct', $this->photos->id)
->assertSet('quantities', [])
->assertSee(__('sales.sell.cart_empty'));
});
it('rejects an empty sale and products that are not consumer products or no longer sold', function () {
$other = ProductModel::factory()->create();
sell([])->assertHasErrors(['quantities' => [__('sales.errors.empty')]]);
sell([$other->id => 1])->assertSet('quantities', [])->assertHasErrors(['quantities' => [__('sales.errors.empty')]]);
$component = Livewire::test('sales::sell')->call('addProduct', $this->prints->id);
$this->prints->update(['is_active' => false]);
$component->call('save')
->assertHasErrors(['quantities' => [__('sales.errors.product')]])
->assertSet('quantities', []);
expect(QuickSaleModel::query()->count())->toBe(0);
});
it('opens the receipt as a PDF for the seller and management only', function () {
sell([$this->photos->id => 2]);
$sale = QuickSaleModel::query()->sole();
$this->get(route('sales.receipt', $sale->id))
->assertOk()
->assertHeader('content-type', 'application/pdf')
->assertHeader('content-disposition', 'inline; filename=kuitti-'.$sale->id.'.pdf');
$this->actingAs(User::factory()->employee()->create());
$this->get(route('sales.receipt', $sale->id))->assertForbidden();
$this->actingAs(User::factory()->management()->create());
$this->get(route('sales.receipt', $sale->id))->assertOk();
$this->get(route('sales.receipt', 999))->assertNotFound();
});
it('prints the company details, lines and VAT breakdown on the receipt', function () {
app(CompanyDetailsStore::class)->save(new CompanyDetails('Mediatalo Oy', '0737546-2', "Kauppakatu 1\n40100 Jyväskylä", '014 123 456', '[email protected]'));
sell([$this->photos->id => 2, $this->prints->id => 1], 'card');
$sale = app(QuickSaleQueries::class)->findSale(QuickSaleModel::query()->sole()->id);
$html = view('sales-views::receipt', ['sale' => $sale, 'company' => app(CompanyDetailsStore::class)->get()])->render();
expect($html)->toContain('Mediatalo Oy', 'Kauppakatu 1<br />', 'Y-tunnus: 0737546-2', 'ALV-tunnus: FI07375462', 'Pankkikortti', 'Eero Työntekijä')
->toContain("30,50\u{00A0}€", "24,30\u{00A0}€", "6,20\u{00A0}€")
->not->toContain(__('sales.receipt.company_missing'));
});
it('keeps subcontractors out', function () {
$this->actingAs(User::factory()->subcontractor()->create());
$this->get(route('sales.sell'))->assertForbidden();
$this->get(route('sales.index'))->assertForbidden();
});
it('shows employees their own sales and management everyone\'s', function () {
$colleague = User::factory()->employee()->create(['name' => 'Kaisa Kollega']);
QuickSaleModel::factory()->withLine($this->prints, 4)->create(['user_id' => $colleague->id]);
sell([$this->photos->id => 1]);
Livewire::test('sales::index')
->assertSee('Eero Työntekijä')
->assertDontSee('Kaisa Kollega')
->assertSee("17,00\u{00A0}€", false);
$this->actingAs(User::factory()->management()->create());
Livewire::test('sales::index')
->assertSee('Eero Työntekijä')
->assertSee('Kaisa Kollega')
->set('seller', (string) $colleague->id)
->assertDontSee('1 × Passikuvat');
});
it('credits a sale once, by its seller or management only', function () {
sell([$this->photos->id => 2]);
$sale = QuickSaleModel::query()->sole();
$this->actingAs(User::factory()->employee()->create());
Livewire::test('sales::index')->call('confirmCredit', $sale->id)->assertForbidden();
$this->actingAs($this->employee);
Livewire::test('sales::index')
->call('confirmCredit', $sale->id)
->call('credit')
->assertSet('statusMessage', fn (string $message) => str_starts_with($message, 'Myynnille #'.$sale->id.' kirjattiin hyvitys'))
->assertSee('Hyvitys myynnille #'.$sale->id)
->assertSee("-30,00\u{00A0}€", false)
->assertDontSee(__('sales.credit_named', ['number' => $sale->id]));
$credit = QuickSaleModel::query()->with('lines')->where('credits_quick_sale_id', $sale->id)->sole();
expect($credit->total_cents)->toBe(-3000)
->and($credit->lines->sole()->quantity)->toBe(-2)
->and((float) TimeEntryModel::query()->sole()->hours)->toBe(0.5);
$this->actingAs(User::factory()->management()->create());
Livewire::test('sales::index')
->call('confirmCredit', $sale->id)
->call('credit')
->assertSet('statusMessage', __('sales.errors.already_credited'));
expect(QuickSaleModel::query()->count())->toBe(2);
});
it('closes the cash day with its balance by payment method and VAT rate', function () {
sell([$this->photos->id => 2], 'cash');
sell([$this->prints->id => 3], 'card');
$first = QuickSaleModel::query()->orderBy('id')->first();
Livewire::test('sales::index')
->call('confirmCredit', $first->id)
->call('credit')
->assertSee(__('sales.cash_day.preview'))
->call('closeDay')
->assertSet('statusMessage', fn (string $message) => str_ends_with($message, 'päätetty.'))
->assertSee('Kassapäivä päätetty')
->assertDontSee(__('sales.cash_day.reopen'));
$day = CashDayModel::query()->with('vatTotals')->sole();
expect($day->only(['sale_count', 'cash_cents', 'card_cents', 'total_cents', 'closed_by']))->toBe([
'sale_count' => 3,
'cash_cents' => 0,
'card_cents' => 150,
'total_cents' => 150,
'closed_by' => $this->employee->id,
])->and($day->vatTotals->sole()->only(['vat_basis_points', 'gross_cents', 'net_cents', 'vat_cents']))->toBe([
'vat_basis_points' => 2550, 'gross_cents' => 150, 'net_cents' => 120, 'vat_cents' => 30,
]);
sell([$this->prints->id => 1])->assertHasErrors(['sale' => [__('sales.errors.day_closed')]]);
expect(QuickSaleModel::query()->count())->toBe(3);
});
it('lets only management reopen a closed day, and closing again forms the balance anew', function () {
sell([$this->prints->id => 2]);
Livewire::test('sales::index')->call('closeDay');
Livewire::test('sales::index')->call('reopenDay')->assertForbidden();
$this->actingAs(User::factory()->management()->create(['name' => 'Johtaja']));
Livewire::test('sales::index')
->call('reopenDay')
->assertSee('Avattu uudelleen');
expect(CashDayModel::query()->sole()->closed_at)->toBeNull();
sell([$this->prints->id => 1])->assertHasNoErrors();
Livewire::test('sales::index')->call('closeDay');
expect(CashDayModel::query()->sole()->total_cents)->toBe(150);
});
it('credits a sale of a closed day on today\'s cash day and reminds of unclosed days', function () {
$yesterday = now()->subDay()->toDateString();
$old = QuickSaleModel::factory()->withLine($this->prints, 2)->create([
'user_id' => $this->employee->id,
'sold_at' => now()->subDay(),
'sold_on' => $yesterday,
]);
Livewire::test('sales::index')->assertSee(__('sales.index.unclosed'));
Livewire::withQueryParams(['paiva' => $yesterday])->test('sales::index')->call('closeDay');
Livewire::test('sales::index')
->assertDontSee(__('sales.index.unclosed'))
->call('confirmCredit', $old->id)
->call('credit')
->assertSet('day', $this->today);
expect(QuickSaleModel::query()->where('credits_quick_sale_id', $old->id)->sole()->sold_on)->toBe($this->today)
->and(CashDayModel::query()->where('day', $yesterday)->sole()->total_cents)->toBe(100);
});
@@ -0,0 +1,53 @@
<?php
use App\Models\User;
use App\Modules\Shared\Application\UseCases\CompanyDetailsStore;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
it('lets the admin save the company details', function () {
$this->actingAs(User::factory()->admin()->create());
Livewire::test('shared::company')
->set('name', 'Mediatalo Oy')
->set('business_id', '737546-2')
->set('address', "Kauppakatu 1\n40100 Jyväskylä")
->set('email', '[email protected]')
->call('save')
->assertHasNoErrors()
->assertSet('business_id', '0737546-2')
->assertSet('statusMessage', __('company.saved'));
$details = app(CompanyDetailsStore::class)->get();
expect($details->name)->toBe('Mediatalo Oy')
->and($details->email)->toBe('[email protected]')
->and($details->phone)->toBeNull()
->and($details->vatNumber())->toBe('FI07375462');
Livewire::test('shared::company')->assertSet('name', 'Mediatalo Oy');
});
it('rejects an invalid business ID and email address', function () {
$this->actingAs(User::factory()->admin()->create());
Livewire::test('shared::company')
->set('name', 'Mediatalo Oy')
->set('business_id', '1234567-8')
->call('save')
->assertHasErrors(['business_id' => [__('company.errors.business_id')]])
->set('business_id', '0737546-2')
->set('email', 'ei-osoite')
->call('save')
->assertHasErrors(['email' => [__('company.errors.email')]]);
expect(app(CompanyDetailsStore::class)->get())->toBeNull();
});
it('keeps everyone but the admin out', function () {
$this->actingAs(User::factory()->management()->create());
$this->get(route('settings.company'))->assertForbidden();
});
@@ -6,9 +6,9 @@ use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Events\CustomerRegistered;
use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse;
use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Shared\Domain\Exceptions\InvalidBusinessId;
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
use Tests\Fakes\FakeEventDispatcher;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryCustomerRepository;
@@ -6,8 +6,8 @@ use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryCustomerRepository;
@@ -3,8 +3,8 @@
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
it('registers a company with a business id and no id yet', function () {
$customer = Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company, new BusinessId('0737546-2'));
+164
View File
@@ -0,0 +1,164 @@
<?php
use App\Modules\Sales\Application\DTOs\SaleData;
use App\Modules\Sales\Application\UseCases\CloseCashDay;
use App\Modules\Sales\Application\UseCases\CreditQuickSale;
use App\Modules\Sales\Application\UseCases\ReopenCashDay;
use App\Modules\Sales\Application\UseCases\SellQuickSale;
use App\Modules\Sales\Domain\Entities\CashDay;
use App\Modules\Sales\Domain\Entities\QuickSale;
use App\Modules\Sales\Domain\Enums\PaymentMethod;
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
use App\Modules\Sales\Domain\Exceptions\CashDayInFuture;
use App\Modules\Sales\Domain\Exceptions\CashDayNotClosed;
use App\Modules\Sales\Domain\Exceptions\CreditCannotBeCredited;
use App\Modules\Sales\Domain\Exceptions\InvalidQuantity;
use App\Modules\Sales\Domain\Exceptions\ProductNotSellable;
use App\Modules\Sales\Domain\Exceptions\QuickSaleAlreadyCredited;
use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound;
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
use App\Modules\Sales\Domain\ValueObjects\CashDayBalance;
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
use App\Modules\Sales\Domain\ValueObjects\VatTotal;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeCustomerQueries;
use Tests\Fakes\FakeQuickSaleHours;
use Tests\Fakes\FakeQuickSaleProducts;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryCashDayRepository;
use Tests\Fakes\InMemoryQuickSaleRepository;
beforeEach(function () {
$this->sales = new InMemoryQuickSaleRepository;
$this->cashDays = new InMemoryCashDayRepository;
$this->products = new FakeQuickSaleProducts;
$this->hours = new FakeQuickSaleHours;
$this->customers = new FakeCustomerQueries;
$this->clock = new FakeClock(new DateTimeImmutable('2026-11-24'));
$transactions = new FakeTransactionManager;
$this->sell = new SellQuickSale($this->sales, $this->cashDays, $this->products, $this->hours, $this->customers, $transactions, $this->clock);
$this->credit = new CreditQuickSale($this->sales, $this->cashDays, $transactions, $this->clock);
$this->close = new CloseCashDay($this->cashDays, $this->sales, $transactions, $this->clock);
$this->reopen = new ReopenCashDay($this->cashDays, $transactions, $this->clock);
$this->products->add(1, 'Passikuvat', 1500, durationQuarters: 1, workTypeId: 7);
$this->products->add(2, 'Digitointi', 2000, durationQuarters: 2, workTypeId: 7);
$this->products->add(3, 'Kirja', 1000, vatBasisPoints: 1000);
});
it('totals a sale and credits it with the lines negated and the same payment method', function () {
$sale = QuickSale::reconstitute(5, 1, null, PaymentMethod::Card, new DateTimeImmutable, new DateTimeImmutable('2026-11-20'), [
QuickSaleLine::sold(1, 'Passikuvat', 2, 1500, 2550),
QuickSaleLine::sold(3, 'Kirja', 1, 1000, 1000),
], null);
$credit = QuickSale::creditFor($sale, 9, new DateTimeImmutable, new DateTimeImmutable('2026-11-24'));
expect($sale->totalCents())->toBe(4000)
->and($credit->totalCents())->toBe(-4000)
->and($credit->paymentMethod())->toBe(PaymentMethod::Card)
->and($credit->creditsSaleId())->toBe(5)
->and($credit->sellerId())->toBe(9)
->and(array_map(fn (QuickSaleLine $line): int => $line->quantity, $credit->lines()))->toBe([-2, -1]);
QuickSale::creditFor(QuickSale::reconstitute(6, 1, null, PaymentMethod::Card, new DateTimeImmutable, new DateTimeImmutable, $credit->lines(), 5), 9, new DateTimeImmutable, new DateTimeImmutable);
})->throws(CreditCannotBeCredited::class);
it('rejects empty sales and quantities outside 1–999', function (callable $make) {
$make();
})->with([
'no lines' => [fn () => QuickSale::sell(1, null, PaymentMethod::Cash, [], new DateTimeImmutable, new DateTimeImmutable)],
'zero' => [fn () => QuickSaleLine::sold(1, 'A', 0, 100, 0)],
'too many' => [fn () => QuickSaleLine::sold(1, 'A', 1000, 100, 0)],
])->throws(DomainException::class);
it('takes the VAT out of each rate\'s total, credits included', function () {
$day = new DateTimeImmutable('2026-11-24');
$balance = CashDayBalance::of([
QuickSale::sell(1, null, PaymentMethod::Cash, [QuickSaleLine::sold(1, 'A', 3, 1500, 2550)], $day, $day),
QuickSale::sell(1, null, PaymentMethod::Card, [QuickSaleLine::sold(3, 'B', 1, 1000, 1000), QuickSaleLine::sold(1, 'A', 1, 1500, 2550)], $day, $day),
QuickSale::reconstitute(9, 1, null, PaymentMethod::Cash, $day, $day, [new QuickSaleLine(1, 'A', -1, 1500, 2550)], 1),
]);
expect($balance->saleCount)->toBe(3)
->and($balance->cashCents)->toBe(3000)
->and($balance->cardCents)->toBe(2500)
->and($balance->totalCents())->toBe(5500)
->and($balance->vatTotals)->toEqual([
new VatTotal(2550, 4500, 3586, 914),
new VatTotal(1000, 1000, 909, 91),
])
->and(VatTotal::ofGross(2550, -1500))->toEqual(new VatTotal(2550, -1500, -1195, -305));
});
it('sells at current prices on today and books the hours by work type', function () {
$result = $this->sell->execute(4, new SaleData([1 => 2, 2 => 1, 3 => 1], 'card'));
$sale = $this->sales->findById($result->saleId);
expect($result->totalCents)->toBe(6000)
->and($result->bookedQuarters)->toBe(4)
->and($result->unbookedQuarters)->toBe(0)
->and($sale->soldOn()->format('Y-m-d'))->toBe('2026-11-24')
->and($sale->paymentMethod())->toBe(PaymentMethod::Card)
->and($this->hours->booked)->toBe([[4, '2026-11-24', 7, 4, $result->saleId]]);
});
it('keeps the sale when the hours cannot be booked', function () {
$this->hours->fails = true;
$result = $this->sell->execute(4, new SaleData([1 => 1], 'cash'));
expect($result->bookedQuarters)->toBe(0)
->and($result->unbookedQuarters)->toBe(1)
->and($this->sales->sales)->toHaveCount(1);
});
it('rejects what cannot be sold', function (array $quantities, ?int $customerId, string $exception) {
expect(fn () => $this->sell->execute(4, new SaleData($quantities, 'cash', $customerId)))->toThrow($exception);
})->with([
'unknown product' => [[99 => 1], null, ProductNotSellable::class],
'no products' => [[], null, QuickSaleEmpty::class],
'negative quantity' => [[1 => -1], null, InvalidQuantity::class],
'unknown customer' => [[1 => 1], 5, QuickSaleCustomerNotFound::class],
]);
it('credits a sale once, on today\'s cash day', function () {
$saleId = $this->sell->execute(4, new SaleData([1 => 1], 'cash'))->saleId;
$this->clock->today = new DateTimeImmutable('2026-11-25');
$creditId = $this->credit->execute($saleId, 8);
expect($this->sales->findById($creditId)->soldOn()->format('Y-m-d'))->toBe('2026-11-25')
->and(fn () => $this->credit->execute($saleId, 8))->toThrow(QuickSaleAlreadyCredited::class);
});
it('closes a day with its balance, refuses sales on it and lets it be reopened', function () {
$this->sell->execute(4, new SaleData([1 => 2], 'cash'));
$this->close->execute(new DateTimeImmutable('2026-11-24'), 4);
$day = $this->cashDays->forDay(new DateTimeImmutable('2026-11-24'));
expect($day->isClosed())->toBeTrue()
->and($day->closedBy())->toBe(4)
->and($day->balance()->totalCents())->toBe(3000)
->and(fn () => $this->sell->execute(4, new SaleData([1 => 1], 'cash')))->toThrow(CashDayClosed::class)
->and(fn () => $this->close->execute(new DateTimeImmutable('2026-11-24'), 4))->toThrow(CashDayClosed::class)
->and(fn () => $this->close->execute(new DateTimeImmutable('2026-11-25'), 4))->toThrow(CashDayInFuture::class);
$this->reopen->execute(new DateTimeImmutable('2026-11-24'), 1);
$day = $this->cashDays->forDay(new DateTimeImmutable('2026-11-24'));
expect($day->isClosed())->toBeFalse()
->and($day->balance())->toBeNull()
->and($day->reopenedBy())->toBe(1)
->and(fn () => $this->reopen->execute(new DateTimeImmutable('2026-11-24'), 1))->toThrow(CashDayNotClosed::class);
});
it('closes a day without sales with a zero balance', function () {
$day = CashDay::open(new DateTimeImmutable('2026-11-24'));
$day->close([], 1, new DateTimeImmutable);
expect($day->balance())->toEqual(CashDayBalance::empty());
});
@@ -1,7 +1,7 @@
<?php
use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId;
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Shared\Domain\Exceptions\InvalidBusinessId;
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
it('accepts a business id with a correct check digit', function (string $input, string $expected) {
expect((new BusinessId($input))->value)->toBe($expected);