Files
Toiminnanohjaus/tests/Feature/Modules/Sales/QuickSalesTest.php
T
petriandClaude Opus 5.5 6de5d9bef1 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]>
2026-11-24 12:33:46 +02:00

272 lines
12 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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);
});