From 6de5d9bef1095c7712692ea095dc42d7cb972f53 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Tue, 24 Nov 2026 12:33:46 +0200 Subject: [PATCH] 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 --- CLAUDE.md | 6 +- .../Application/Contracts/CustomerQueries.php | 6 + .../Application/UseCases/RegisterCustomer.php | 2 +- .../Application/UseCases/UpdateCustomer.php | 2 +- .../Domain/Contracts/CustomerRepository.php | 2 +- .../Customers/Domain/Entities/Customer.php | 2 +- .../Exceptions/BusinessIdAlreadyInUse.php | 2 +- .../Repositories/EloquentCustomerQueries.php | 7 + .../EloquentCustomerRepository.php | 2 +- .../Livewire/Forms/CustomerForm.php | 2 +- .../UseCases/ProvideQuickSaleTask.php | 122 +++++ .../Contracts/CustomerJobRepository.php | 7 + .../Jobs/Domain/Contracts/TaskRepository.php | 5 + .../Jobs/Domain/ValueObjects/JobDetails.php | 12 + .../Persistence/Eloquent/CustomerJobModel.php | 2 + .../EloquentCustomerJobRepository.php | 12 + .../Repositories/EloquentTaskRepository.php | 7 + .../Application/Contracts/QuickSaleHours.php | 22 + .../Contracts/QuickSaleProducts.php | 19 + .../Contracts/QuickSaleQueries.php | 34 ++ .../Sales/Application/DTOs/CashDaySummary.php | 25 + .../Application/DTOs/QuickSaleLineSummary.php | 16 + .../Application/DTOs/QuickSaleSummary.php | 64 +++ .../Sales/Application/DTOs/SaleData.php | 21 + .../Sales/Application/DTOs/SaleResult.php | 19 + .../Application/DTOs/SellableProduct.php | 23 + .../Application/UseCases/CloseCashDay.php | 44 ++ .../Application/UseCases/CreditQuickSale.php | 57 +++ .../Application/UseCases/ReopenCashDay.php | 36 ++ .../Application/UseCases/SellQuickSale.php | 94 ++++ .../Domain/Contracts/CashDayRepository.php | 28 + .../Domain/Contracts/QuickSaleRepository.php | 27 + app/Modules/Sales/Domain/Entities/CashDay.php | 118 +++++ .../Sales/Domain/Entities/QuickSale.php | 131 +++++ .../Sales/Domain/Enums/PaymentMethod.php | 14 + .../Sales/Domain/Exceptions/CashDayClosed.php | 15 + .../Domain/Exceptions/CashDayInFuture.php | 15 + .../Domain/Exceptions/CashDayNotClosed.php | 15 + .../Exceptions/CreditCannotBeCredited.php | 15 + .../Domain/Exceptions/InvalidQuantity.php | 15 + .../Domain/Exceptions/ProductNotSellable.php | 15 + .../Exceptions/QuickSaleAlreadyCredited.php | 15 + .../Exceptions/QuickSaleCustomerNotFound.php | 15 + .../Domain/Exceptions/QuickSaleEmpty.php | 15 + .../Domain/Exceptions/QuickSaleNotFound.php | 15 + .../Domain/ValueObjects/CashDayBalance.php | 67 +++ .../Domain/ValueObjects/QuickSaleLine.php | 53 ++ .../Sales/Domain/ValueObjects/VatTotal.php | 31 ++ .../Infrastructure/HoursForQuickSales.php | 43 ++ .../Persistence/Eloquent/CashDayModel.php | 53 ++ .../Eloquent/CashDayVatTotalModel.php | 38 ++ .../Eloquent/QuickSaleLineModel.php | 41 ++ .../Persistence/Eloquent/QuickSaleModel.php | 66 +++ .../EloquentCashDayRepository.php | 86 ++++ .../Repositories/EloquentQuickSaleQueries.php | 116 +++++ .../EloquentQuickSaleRepository.php | 84 +++ .../Infrastructure/ProductsFromPriceList.php | 30 ++ .../Providers/SalesServiceProvider.php | 65 +++ .../Http/Controllers/ShowReceipt.php | 31 ++ .../Livewire/Concerns/FormatsSales.php | 39 ++ .../Presentation/Livewire/⚡index.blade.php | 479 ++++++++++++++++++ .../Presentation/Livewire/⚡sell.blade.php | 432 ++++++++++++++++ app/Modules/Sales/Presentation/Routes/web.php | 13 + .../Presentation/Views/receipt.blade.php | 120 +++++ .../Application/DTOs/CompanyDetails.php | 28 + .../UseCases/CompanyDetailsStore.php | 83 +++ .../Domain/Exceptions/CompanyNameRequired.php | 13 + .../Domain/Exceptions/InvalidBusinessId.php | 4 +- .../Domain/ValueObjects/BusinessId.php | 4 +- .../Providers/SharedServiceProvider.php | 15 + .../Presentation/Livewire/⚡company.blade.php | 110 ++++ .../Shared/Presentation/Routes/web.php | 10 + bootstrap/providers.php | 2 + composer.json | 1 + composer.lock | 386 +++++++++++++- database/factories/QuickSaleFactory.php | 55 ++ ...quick_sale_year_to_customer_jobs_table.php | 27 + ...11_24_095655_create_quick_sales_tables.php | 47 ++ ...6_11_24_095656_create_cash_days_tables.php | 47 ++ docs/maarittely.md | 20 +- lang/fi/company.php | 24 + lang/fi/layout.php | 2 + lang/fi/sales.php | 141 ++++++ resources/views/layouts/app.blade.php | 8 + tests/Browser/SalesAccessibilityTest.php | 79 +++ tests/Fakes/FakeCustomerQueries.php | 5 + tests/Fakes/FakeQuickSaleHours.php | 25 + tests/Fakes/FakeQuickSaleProducts.php | 22 + tests/Fakes/InMemoryCashDayRepository.php | 30 ++ tests/Fakes/InMemoryCustomerJobRepository.php | 13 + tests/Fakes/InMemoryCustomerRepository.php | 2 +- tests/Fakes/InMemoryQuickSaleRepository.php | 52 ++ tests/Fakes/InMemoryTaskRepository.php | 11 + .../EloquentCustomerRepositoryTest.php | 2 +- .../Feature/Modules/Sales/QuickSalesTest.php | 271 ++++++++++ .../Modules/Shared/CompanyDetailsTest.php | 53 ++ .../Application/RegisterCustomerTest.php | 4 +- .../Application/UpdateCustomerTest.php | 2 +- .../Modules/Customers/Domain/CustomerTest.php | 2 +- tests/Unit/Modules/Sales/QuickSaleTest.php | 164 ++++++ .../Domain => Shared}/BusinessIdTest.php | 4 +- 101 files changed, 4768 insertions(+), 29 deletions(-) create mode 100644 app/Modules/Jobs/Application/UseCases/ProvideQuickSaleTask.php create mode 100644 app/Modules/Sales/Application/Contracts/QuickSaleHours.php create mode 100644 app/Modules/Sales/Application/Contracts/QuickSaleProducts.php create mode 100644 app/Modules/Sales/Application/Contracts/QuickSaleQueries.php create mode 100644 app/Modules/Sales/Application/DTOs/CashDaySummary.php create mode 100644 app/Modules/Sales/Application/DTOs/QuickSaleLineSummary.php create mode 100644 app/Modules/Sales/Application/DTOs/QuickSaleSummary.php create mode 100644 app/Modules/Sales/Application/DTOs/SaleData.php create mode 100644 app/Modules/Sales/Application/DTOs/SaleResult.php create mode 100644 app/Modules/Sales/Application/DTOs/SellableProduct.php create mode 100644 app/Modules/Sales/Application/UseCases/CloseCashDay.php create mode 100644 app/Modules/Sales/Application/UseCases/CreditQuickSale.php create mode 100644 app/Modules/Sales/Application/UseCases/ReopenCashDay.php create mode 100644 app/Modules/Sales/Application/UseCases/SellQuickSale.php create mode 100644 app/Modules/Sales/Domain/Contracts/CashDayRepository.php create mode 100644 app/Modules/Sales/Domain/Contracts/QuickSaleRepository.php create mode 100644 app/Modules/Sales/Domain/Entities/CashDay.php create mode 100644 app/Modules/Sales/Domain/Entities/QuickSale.php create mode 100644 app/Modules/Sales/Domain/Enums/PaymentMethod.php create mode 100644 app/Modules/Sales/Domain/Exceptions/CashDayClosed.php create mode 100644 app/Modules/Sales/Domain/Exceptions/CashDayInFuture.php create mode 100644 app/Modules/Sales/Domain/Exceptions/CashDayNotClosed.php create mode 100644 app/Modules/Sales/Domain/Exceptions/CreditCannotBeCredited.php create mode 100644 app/Modules/Sales/Domain/Exceptions/InvalidQuantity.php create mode 100644 app/Modules/Sales/Domain/Exceptions/ProductNotSellable.php create mode 100644 app/Modules/Sales/Domain/Exceptions/QuickSaleAlreadyCredited.php create mode 100644 app/Modules/Sales/Domain/Exceptions/QuickSaleCustomerNotFound.php create mode 100644 app/Modules/Sales/Domain/Exceptions/QuickSaleEmpty.php create mode 100644 app/Modules/Sales/Domain/Exceptions/QuickSaleNotFound.php create mode 100644 app/Modules/Sales/Domain/ValueObjects/CashDayBalance.php create mode 100644 app/Modules/Sales/Domain/ValueObjects/QuickSaleLine.php create mode 100644 app/Modules/Sales/Domain/ValueObjects/VatTotal.php create mode 100644 app/Modules/Sales/Infrastructure/HoursForQuickSales.php create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Eloquent/CashDayModel.php create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Eloquent/CashDayVatTotalModel.php create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleLineModel.php create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentCashDayRepository.php create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleQueries.php create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php create mode 100644 app/Modules/Sales/Infrastructure/ProductsFromPriceList.php create mode 100644 app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php create mode 100644 app/Modules/Sales/Presentation/Http/Controllers/ShowReceipt.php create mode 100644 app/Modules/Sales/Presentation/Livewire/Concerns/FormatsSales.php create mode 100644 app/Modules/Sales/Presentation/Livewire/⚡index.blade.php create mode 100644 app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php create mode 100644 app/Modules/Sales/Presentation/Routes/web.php create mode 100644 app/Modules/Sales/Presentation/Views/receipt.blade.php create mode 100644 app/Modules/Shared/Application/DTOs/CompanyDetails.php create mode 100644 app/Modules/Shared/Application/UseCases/CompanyDetailsStore.php create mode 100644 app/Modules/Shared/Domain/Exceptions/CompanyNameRequired.php rename app/Modules/{Customers => Shared}/Domain/Exceptions/InvalidBusinessId.php (66%) rename app/Modules/{Customers => Shared}/Domain/ValueObjects/BusinessId.php (92%) create mode 100644 app/Modules/Shared/Presentation/Livewire/⚡company.blade.php create mode 100644 app/Modules/Shared/Presentation/Routes/web.php create mode 100644 database/factories/QuickSaleFactory.php create mode 100644 database/migrations/2026_11_24_095654_add_quick_sale_year_to_customer_jobs_table.php create mode 100644 database/migrations/2026_11_24_095655_create_quick_sales_tables.php create mode 100644 database/migrations/2026_11_24_095656_create_cash_days_tables.php create mode 100644 lang/fi/company.php create mode 100644 lang/fi/sales.php create mode 100644 tests/Browser/SalesAccessibilityTest.php create mode 100644 tests/Fakes/FakeQuickSaleHours.php create mode 100644 tests/Fakes/FakeQuickSaleProducts.php create mode 100644 tests/Fakes/InMemoryCashDayRepository.php create mode 100644 tests/Fakes/InMemoryQuickSaleRepository.php create mode 100644 tests/Feature/Modules/Sales/QuickSalesTest.php create mode 100644 tests/Feature/Modules/Shared/CompanyDetailsTest.php create mode 100644 tests/Unit/Modules/Sales/QuickSaleTest.php rename tests/Unit/Modules/{Customers/Domain => Shared}/BusinessIdTest.php (89%) diff --git a/CLAUDE.md b/CLAUDE.md index f02feff..dec8c26 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project -An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) `TimeTracking` (hours on tasks: weekly sheet and task booking page) and `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users). +An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users). - **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec. - **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start. @@ -22,8 +22,10 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages. - Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules. -- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. +- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, `sales.use`, `sales.view-all`, `sales.view-sale`, `sales.credit`, `sales.close-day`, `sales.reopen-day`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. - **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP. +- **Company details** (name, business ID, address, phone, email) are kept by `Shared\Application\UseCases\CompanyDetailsStore` in the settings (`shared.company_*`) and edited by the admin on `shared::company` (`/settings/company`, gate `settings.manage`). `BusinessId` (Y-tunnus with check digit) is a Shared value object. +- **PDFs** use `barryvdh/laravel-dompdf` with a plain Blade view (no Tailwind; DejaVu Sans), streamed inline: see the quick sale receipt `Sales\Presentation\Http\Controllers\ShowReceipt` and `Sales/Presentation/Views/receipt.blade.php` (view namespace `sales-views`). - **Security headers** (`X-Frame-Options`, `frame-ancestors`, `nosniff`, `Referrer-Policy`, HSTS over HTTPS) come from the global `Shared\Presentation\Http\Middleware\SetSecurityHeaders`, pushed in `SharedServiceProvider`. No full CSP: Alpine/Livewire need `unsafe-eval`. - Money is `Shared\Domain\ValueObjects\Money` (whole cents, `parse()` accepts "85,50", `format()` gives "85,50 €", `addVat()`/`removeVat()` with a `VatPercentage` round half up); store it in `*_cents` integer columns. Prices are without VAT except consumer product prices, which are stored with VAT. Show other than consumer prices only behind `money.prices` and keep amounts out of public Livewire properties. App-wide settings go through `Shared\Application\Contracts\Settings` (`settings` table) with keys prefixed by the owning module. - `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`. diff --git a/app/Modules/Customers/Application/Contracts/CustomerQueries.php b/app/Modules/Customers/Application/Contracts/CustomerQueries.php index 101b850..881021b 100644 --- a/app/Modules/Customers/Application/Contracts/CustomerQueries.php +++ b/app/Modules/Customers/Application/Contracts/CustomerQueries.php @@ -25,6 +25,12 @@ interface CustomerQueries */ public function namesByIds(array $ids): array; + /** + * The company's own internal customer, whose jobs hold internal work + * and the yearly quick sale job. + */ + public function internalCustomerId(): ?int; + /** * The full personal identity code. Sensitive: call only after checking * the customers.view-personal-identity-code ability, and never log it. diff --git a/app/Modules/Customers/Application/UseCases/RegisterCustomer.php b/app/Modules/Customers/Application/UseCases/RegisterCustomer.php index b2eaf51..b11f054 100644 --- a/app/Modules/Customers/Application/UseCases/RegisterCustomer.php +++ b/app/Modules/Customers/Application/UseCases/RegisterCustomer.php @@ -10,11 +10,11 @@ use App\Modules\Customers\Domain\Entities\Customer; use App\Modules\Customers\Domain\Events\CustomerRegistered; use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse; use App\Modules\Customers\Domain\Exceptions\PersonalIdentityCodeAlreadyInUse; -use App\Modules\Customers\Domain\ValueObjects\BusinessId; use App\Modules\Customers\Domain\ValueObjects\CustomerName; use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode; use App\Modules\Shared\Application\Contracts\EventDispatcher; use App\Modules\Shared\Application\Contracts\TransactionManager; +use App\Modules\Shared\Domain\ValueObjects\BusinessId; final class RegisterCustomer { diff --git a/app/Modules/Customers/Application/UseCases/UpdateCustomer.php b/app/Modules/Customers/Application/UseCases/UpdateCustomer.php index 96cd1eb..477f311 100644 --- a/app/Modules/Customers/Application/UseCases/UpdateCustomer.php +++ b/app/Modules/Customers/Application/UseCases/UpdateCustomer.php @@ -9,10 +9,10 @@ use App\Modules\Customers\Domain\Contracts\CustomerRepository; use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse; use App\Modules\Customers\Domain\Exceptions\CustomerNotFound; use App\Modules\Customers\Domain\Exceptions\PersonalIdentityCodeAlreadyInUse; -use App\Modules\Customers\Domain\ValueObjects\BusinessId; use App\Modules\Customers\Domain\ValueObjects\CustomerName; use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode; use App\Modules\Shared\Application\Contracts\TransactionManager; +use App\Modules\Shared\Domain\ValueObjects\BusinessId; /** * Changes a customer's details. Who may remove a personal identity code is diff --git a/app/Modules/Customers/Domain/Contracts/CustomerRepository.php b/app/Modules/Customers/Domain/Contracts/CustomerRepository.php index 22b8090..fa1ed24 100644 --- a/app/Modules/Customers/Domain/Contracts/CustomerRepository.php +++ b/app/Modules/Customers/Domain/Contracts/CustomerRepository.php @@ -5,8 +5,8 @@ declare(strict_types=1); namespace App\Modules\Customers\Domain\Contracts; 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; interface CustomerRepository { diff --git a/app/Modules/Customers/Domain/Entities/Customer.php b/app/Modules/Customers/Domain/Entities/Customer.php index fcef73f..6e74444 100644 --- a/app/Modules/Customers/Domain/Entities/Customer.php +++ b/app/Modules/Customers/Domain/Entities/Customer.php @@ -8,9 +8,9 @@ use App\Modules\Customers\Domain\Enums\CustomerType; use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode; use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId; use App\Modules\Customers\Domain\Exceptions\InternalCustomerMustBeCompany; -use App\Modules\Customers\Domain\ValueObjects\BusinessId; use App\Modules\Customers\Domain\ValueObjects\CustomerName; use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode; +use App\Modules\Shared\Domain\ValueObjects\BusinessId; /** * A customer of the company: a business or a private consumer. diff --git a/app/Modules/Customers/Domain/Exceptions/BusinessIdAlreadyInUse.php b/app/Modules/Customers/Domain/Exceptions/BusinessIdAlreadyInUse.php index cf8cee3..3f776d1 100644 --- a/app/Modules/Customers/Domain/Exceptions/BusinessIdAlreadyInUse.php +++ b/app/Modules/Customers/Domain/Exceptions/BusinessIdAlreadyInUse.php @@ -4,8 +4,8 @@ declare(strict_types=1); namespace App\Modules\Customers\Domain\Exceptions; -use App\Modules\Customers\Domain\ValueObjects\BusinessId; use App\Modules\Shared\Domain\Exceptions\DomainException; +use App\Modules\Shared\Domain\ValueObjects\BusinessId; final class BusinessIdAlreadyInUse extends DomainException { diff --git a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerQueries.php b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerQueries.php index 212ed09..8f72c3f 100644 --- a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerQueries.php +++ b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerQueries.php @@ -27,6 +27,13 @@ class EloquentCustomerQueries implements CustomerQueries return $ids === [] ? [] : CustomerModel::query()->whereIn('id', $ids)->pluck('name', 'id')->all(); } + public function internalCustomerId(): ?int + { + $id = CustomerModel::query()->where('is_internal', true)->orderBy('id')->value('id'); + + return $id === null ? null : (int) $id; + } + public function personalIdentityCodeOf(int $customerId): ?string { return CustomerModel::query()->find($customerId)?->personal_identity_code; diff --git a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php index 857c447..0522654 100644 --- a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php +++ b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php @@ -4,11 +4,11 @@ namespace App\Modules\Customers\Infrastructure\Persistence\Repositories; 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\CustomerName; use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode; use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel; use App\Modules\Customers\Infrastructure\Persistence\PersonalIdentityCodeHasher; +use App\Modules\Shared\Domain\ValueObjects\BusinessId; class EloquentCustomerRepository implements CustomerRepository { diff --git a/app/Modules/Customers/Presentation/Livewire/Forms/CustomerForm.php b/app/Modules/Customers/Presentation/Livewire/Forms/CustomerForm.php index 87cec84..67f0e1b 100644 --- a/app/Modules/Customers/Presentation/Livewire/Forms/CustomerForm.php +++ b/app/Modules/Customers/Presentation/Livewire/Forms/CustomerForm.php @@ -9,11 +9,11 @@ use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse; use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode; use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId; use App\Modules\Customers\Domain\Exceptions\InternalCustomerMustBeCompany; -use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId; use App\Modules\Customers\Domain\Exceptions\InvalidCustomerName; use App\Modules\Customers\Domain\Exceptions\InvalidPersonalIdentityCode; use App\Modules\Customers\Domain\Exceptions\PersonalIdentityCodeAlreadyInUse; use App\Modules\Shared\Domain\Exceptions\DomainException; +use App\Modules\Shared\Domain\Exceptions\InvalidBusinessId; use Illuminate\Validation\Rule; use Livewire\Form; diff --git a/app/Modules/Jobs/Application/UseCases/ProvideQuickSaleTask.php b/app/Modules/Jobs/Application/UseCases/ProvideQuickSaleTask.php new file mode 100644 index 0000000..1afda04 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/ProvideQuickSaleTask.php @@ -0,0 +1,122 @@ +catalog->findWorkType($workTypeId) ?? throw new InvalidTaskReference('work_type'); + $unit = $this->catalog->findServiceUnit($workType->serviceUnitId); + $unitId = $unit !== null && ! $unit->isShared ? $unit->id : null; + + return $this->transactions->run(function () use ($year, $workTypeId, $workType, $unitId, $actorUserId, $jobName): int { + $job = $this->jobs->findQuickSaleJob($year) ?? $this->openJob($year, $unitId, $actorUserId, $jobName); + $jobId = (int) $job->id(); + + if ($unitId !== null && ! in_array($unitId, $job->details()->serviceUnitIds, true)) { + $changes = $job->changeDetails($job->details()->withServiceUnit($unitId)); + $this->jobs->save($job); + $this->jobs->recordChanges($jobId, $actorUserId, $changes); + } + + $task = $this->tasks->findByWorkType($jobId, $workTypeId) ?? $this->tasks->save(Task::create( + $jobId, + $job->details()->status, + $workTypeId, + new TaskTitle($workType->name), + null, + TaskStatus::InProgress, + null, + null, + [], + $actorUserId, + )); + + return (int) $task->id(); + }); + } + + private function openJob(int $year, ?int $unitId, int $actorUserId, string $jobName): CustomerJob + { + $customerId = $this->customers->internalCustomerId() ?? throw new LogicException('The internal customer is missing.'); + $unitId ??= $this->catalog->activeServiceUnits()[0]->id ?? throw new LogicException('There are no service units.'); + + $details = new JobDetails( + name: new JobName($jobName), + description: null, + customerId: $customerId, + serviceUnitIds: [$unitId], + startsOn: null, + dueOn: null, + plannedFrom: null, + plannedTo: null, + kind: JobKind::Ongoing, + status: JobStatus::InProduction, + priority: Priority::Normal, + paymentBasis: PaymentBasis::NotBillable, + estimatedHours: null, + customerReference: null, + instructions: null, + responsibleUserId: $actorUserId, + contactUserId: null, + customerContactId: null, + billerUserId: null, + billingUnitId: null, + memberUserIds: [], + tags: [], + links: [], + ); + + $job = $this->jobs->save(CustomerJob::open($this->numbers->next($year), $details, $actorUserId)); + $jobId = (int) $job->id(); + + $this->jobs->markAsQuickSaleJob($jobId, $year); + $this->jobs->recordChanges($jobId, $actorUserId, [new FieldChange('created', null, $job->number()->format())]); + + return $job; + } +} diff --git a/app/Modules/Jobs/Domain/Contracts/CustomerJobRepository.php b/app/Modules/Jobs/Domain/Contracts/CustomerJobRepository.php index 803fff6..d9395e1 100644 --- a/app/Modules/Jobs/Domain/Contracts/CustomerJobRepository.php +++ b/app/Modules/Jobs/Domain/Contracts/CustomerJobRepository.php @@ -17,6 +17,13 @@ interface CustomerJobRepository */ public function save(CustomerJob $job): CustomerJob; + /** + * The year's system job that quick sale hours are booked on. + */ + public function findQuickSaleJob(int $year): ?CustomerJob; + + public function markAsQuickSaleJob(int $jobId, int $year): void; + /** * @param list $changes */ diff --git a/app/Modules/Jobs/Domain/Contracts/TaskRepository.php b/app/Modules/Jobs/Domain/Contracts/TaskRepository.php index fed134e..8909448 100644 --- a/app/Modules/Jobs/Domain/Contracts/TaskRepository.php +++ b/app/Modules/Jobs/Domain/Contracts/TaskRepository.php @@ -13,6 +13,11 @@ interface TaskRepository */ public function findForJob(int $jobId, int $taskId): ?Task; + /** + * The job's first task of the work type, if any. + */ + public function findByWorkType(int $jobId, int $workTypeId): ?Task; + public function save(Task $task): Task; public function delete(Task $task): void; diff --git a/app/Modules/Jobs/Domain/ValueObjects/JobDetails.php b/app/Modules/Jobs/Domain/ValueObjects/JobDetails.php index ca16d86..238365b 100644 --- a/app/Modules/Jobs/Domain/ValueObjects/JobDetails.php +++ b/app/Modules/Jobs/Domain/ValueObjects/JobDetails.php @@ -101,6 +101,18 @@ final readonly class JobDetails ); } + public function withServiceUnit(int $serviceUnitId): self + { + return new self( + $this->name, $this->description, $this->customerId, [...$this->serviceUnitIds, $serviceUnitId], + $this->startsOn, $this->dueOn, $this->plannedFrom, $this->plannedTo, + $this->kind, $this->status, $this->priority, $this->paymentBasis, $this->estimatedHours, + $this->customerReference, $this->instructions, $this->responsibleUserId, $this->contactUserId, + $this->customerContactId, $this->billerUserId, $this->billingUnitId, $this->memberUserIds, + $this->tags, $this->links, $this->quotedAmount, + ); + } + /** * Whether the user is a named member of the job in any role. */ diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php index c8d8569..6e8dc8a 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php @@ -43,6 +43,7 @@ use Illuminate\Database\Eloquent\Model; * @property int $created_by * @property int|null $quoted_amount_cents * @property CarbonImmutable|null $completed_at + * @property int|null $quick_sale_year * @property CarbonImmutable $created_at */ #[Table('customer_jobs')] @@ -65,6 +66,7 @@ class CustomerJobModel extends Model return [ 'customer_id' => 'integer', 'quoted_amount_cents' => 'integer', + 'quick_sale_year' => 'integer', 'completed_at' => 'immutable_datetime', 'starts_on' => 'immutable_date', 'due_on' => 'immutable_date', diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php index 9ee9bd1..28b5a0d 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php @@ -70,6 +70,18 @@ class EloquentCustomerJobRepository implements CustomerJobRepository return $this->toEntity($model->refresh()); } + public function findQuickSaleJob(int $year): ?CustomerJob + { + $model = CustomerJobModel::query()->where('quick_sale_year', $year)->first(); + + return $model === null ? null : $this->toEntity($model); + } + + public function markAsQuickSaleJob(int $jobId, int $year): void + { + CustomerJobModel::query()->whereKey($jobId)->update(['quick_sale_year' => $year]); + } + public function recordChanges(int $jobId, int $userId, array $changes): void { $now = now(); diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php index c9ef0e5..0e3106d 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskRepository.php @@ -19,6 +19,13 @@ class EloquentTaskRepository implements TaskRepository return $model === null ? null : $this->toEntity($model); } + public function findByWorkType(int $jobId, int $workTypeId): ?Task + { + $model = TaskModel::query()->where('customer_job_id', $jobId)->where('work_type_id', $workTypeId)->orderBy('id')->first(); + + return $model === null ? null : $this->toEntity($model); + } + public function save(Task $task): Task { $model = $task->id() === null ? new TaskModel : TaskModel::query()->findOrFail($task->id()); diff --git a/app/Modules/Sales/Application/Contracts/QuickSaleHours.php b/app/Modules/Sales/Application/Contracts/QuickSaleHours.php new file mode 100644 index 0000000..b83752e --- /dev/null +++ b/app/Modules/Sales/Application/Contracts/QuickSaleHours.php @@ -0,0 +1,22 @@ + In price list order. + */ + public function sellable(): array; +} diff --git a/app/Modules/Sales/Application/Contracts/QuickSaleQueries.php b/app/Modules/Sales/Application/Contracts/QuickSaleQueries.php new file mode 100644 index 0000000..74f86b0 --- /dev/null +++ b/app/Modules/Sales/Application/Contracts/QuickSaleQueries.php @@ -0,0 +1,34 @@ + + */ + public function salesOn(string $day, ?int $sellerId = null): array; + + public function findSale(int $id): ?QuickSaleSummary; + + /** + * @param string $day Y-m-d + */ + public function cashDay(string $day): CashDaySummary; + + /** + * Earlier days with sales that have not been closed, oldest first. + * + * @param string $day Y-m-d + * @return list Y-m-d + */ + public function unclosedDaysBefore(string $day): array; +} diff --git a/app/Modules/Sales/Application/DTOs/CashDaySummary.php b/app/Modules/Sales/Application/DTOs/CashDaySummary.php new file mode 100644 index 0000000..6c7785c --- /dev/null +++ b/app/Modules/Sales/Application/DTOs/CashDaySummary.php @@ -0,0 +1,25 @@ + $lines + */ + public function __construct( + public int $id, + public string $soldAt, + public int $sellerId, + public string $sellerName, + public ?string $customerName, + public PaymentMethod $paymentMethod, + public int $totalCents, + public array $lines, + public ?int $creditsSaleId, + public ?int $creditedBySaleId, + ) {} + + public function isCredit(): bool + { + return $this->creditsSaleId !== null; + } + + public function canBeCredited(): bool + { + return $this->creditsSaleId === null && $this->creditedBySaleId === null; + } + + /** + * The sale's VAT by rate, highest rate first, as on its receipt. + * + * @return list + */ + public function vatTotals(): array + { + $grossByRate = []; + + foreach ($this->lines as $line) { + $grossByRate[$line->vatBasisPoints] = ($grossByRate[$line->vatBasisPoints] ?? 0) + $line->totalCents; + } + + krsort($grossByRate); + + return array_map( + fn (int $basisPoints, int $gross): VatTotal => VatTotal::ofGross($basisPoints, $gross), + array_keys($grossByRate), + array_values($grossByRate), + ); + } +} diff --git a/app/Modules/Sales/Application/DTOs/SaleData.php b/app/Modules/Sales/Application/DTOs/SaleData.php new file mode 100644 index 0000000..671d0e0 --- /dev/null +++ b/app/Modules/Sales/Application/DTOs/SaleData.php @@ -0,0 +1,21 @@ + $quantities + */ + public function __construct( + public array $quantities, + public string $paymentMethod, + public ?int $customerId = null, + ) {} +} diff --git a/app/Modules/Sales/Application/DTOs/SaleResult.php b/app/Modules/Sales/Application/DTOs/SaleResult.php new file mode 100644 index 0000000..d0113f4 --- /dev/null +++ b/app/Modules/Sales/Application/DTOs/SaleResult.php @@ -0,0 +1,19 @@ +format('Y-m-d') > $this->clock->today()->format('Y-m-d')) { + throw new CashDayInFuture; + } + + $this->transactions->run(function () use ($day, $actorUserId): void { + $cashDay = $this->cashDays->lockForDay($day); + $cashDay->close($this->sales->forDay($day), $actorUserId, $this->clock->now()); + $this->cashDays->save($cashDay); + }); + } +} diff --git a/app/Modules/Sales/Application/UseCases/CreditQuickSale.php b/app/Modules/Sales/Application/UseCases/CreditQuickSale.php new file mode 100644 index 0000000..5fa3f17 --- /dev/null +++ b/app/Modules/Sales/Application/UseCases/CreditQuickSale.php @@ -0,0 +1,57 @@ +clock->today(); + + return $this->transactions->run(function () use ($saleId, $actorUserId, $today): int { + $original = $this->sales->findById($saleId) ?? throw new QuickSaleNotFound($saleId); + $this->cashDays->lockForDay($today)->ensureOpen(); + + if ($this->sales->isCredited($saleId)) { + throw new QuickSaleAlreadyCredited; + } + + $credit = QuickSale::creditFor($original, $actorUserId, $this->clock->now(), $today); + + return (int) $this->sales->add($credit)->id(); + }); + } +} diff --git a/app/Modules/Sales/Application/UseCases/ReopenCashDay.php b/app/Modules/Sales/Application/UseCases/ReopenCashDay.php new file mode 100644 index 0000000..04b27b9 --- /dev/null +++ b/app/Modules/Sales/Application/UseCases/ReopenCashDay.php @@ -0,0 +1,36 @@ +transactions->run(function () use ($day, $actorUserId): void { + $cashDay = $this->cashDays->lockForDay($day); + $cashDay->reopen($actorUserId, $this->clock->now()); + $this->cashDays->save($cashDay); + }); + } +} diff --git a/app/Modules/Sales/Application/UseCases/SellQuickSale.php b/app/Modules/Sales/Application/UseCases/SellQuickSale.php new file mode 100644 index 0000000..2744d6d --- /dev/null +++ b/app/Modules/Sales/Application/UseCases/SellQuickSale.php @@ -0,0 +1,94 @@ +products->sellable() as $product) { + $sellable[$product->id] = $product; + } + + $lines = []; + $quartersByWorkType = []; + + foreach ($data->quantities as $productId => $quantity) { + $product = $sellable[$productId] ?? throw new ProductNotSellable($productId); + $lines[] = QuickSaleLine::sold($product->id, $product->name, $quantity, $product->grossCents, $product->vatBasisPoints); + + if ($product->durationQuarters > 0 && $product->workTypeId !== null) { + $quartersByWorkType[$product->workTypeId] = ($quartersByWorkType[$product->workTypeId] ?? 0) + $product->durationQuarters * $quantity; + } + } + + if ($data->customerId !== null && $this->customers->findSummary($data->customerId) === null) { + throw new QuickSaleCustomerNotFound($data->customerId); + } + + $today = $this->clock->today(); + $sale = QuickSale::sell($sellerId, $data->customerId, PaymentMethod::from($data->paymentMethod), $lines, $this->clock->now(), $today); + + return $this->transactions->run(function () use ($sale, $sellerId, $today, $quartersByWorkType): SaleResult { + $this->cashDays->lockForDay($today)->ensureOpen(); + $saleId = (int) $this->sales->add($sale)->id(); + + $booked = 0; + $unbooked = 0; + + foreach ($quartersByWorkType as $workTypeId => $quarters) { + if ($this->hours->book($sellerId, $today, $workTypeId, $quarters, $saleId)) { + $booked += $quarters; + } else { + $unbooked += $quarters; + } + } + + return new SaleResult($saleId, $sale->totalCents(), $booked, $unbooked); + }); + } +} diff --git a/app/Modules/Sales/Domain/Contracts/CashDayRepository.php b/app/Modules/Sales/Domain/Contracts/CashDayRepository.php new file mode 100644 index 0000000..62aca0b --- /dev/null +++ b/app/Modules/Sales/Domain/Contracts/CashDayRepository.php @@ -0,0 +1,28 @@ + + */ + public function forDay(DateTimeImmutable $day): array; +} diff --git a/app/Modules/Sales/Domain/Entities/CashDay.php b/app/Modules/Sales/Domain/Entities/CashDay.php new file mode 100644 index 0000000..cb3a483 --- /dev/null +++ b/app/Modules/Sales/Domain/Entities/CashDay.php @@ -0,0 +1,118 @@ + $sales The day's sales, credits included. + * + * @throws CashDayClosed + */ + public function close(array $sales, int $closedBy, DateTimeImmutable $now): void + { + $this->ensureOpen(); + + $this->balance = CashDayBalance::of($sales); + $this->closedBy = $closedBy; + $this->closedAt = $now; + } + + /** + * @throws CashDayNotClosed + */ + public function reopen(int $reopenedBy, DateTimeImmutable $now): void + { + if (! $this->isClosed()) { + throw new CashDayNotClosed; + } + + $this->balance = null; + $this->closedBy = null; + $this->closedAt = null; + $this->reopenedBy = $reopenedBy; + $this->reopenedAt = $now; + } + + /** + * @throws CashDayClosed + */ + public function ensureOpen(): void + { + if ($this->isClosed()) { + throw new CashDayClosed; + } + } + + public function isClosed(): bool + { + return $this->closedAt !== null; + } + + public function id(): ?int + { + return $this->id; + } + + public function day(): DateTimeImmutable + { + return $this->day; + } + + public function balance(): ?CashDayBalance + { + return $this->balance; + } + + public function closedBy(): ?int + { + return $this->closedBy; + } + + public function closedAt(): ?DateTimeImmutable + { + return $this->closedAt; + } + + public function reopenedBy(): ?int + { + return $this->reopenedBy; + } + + public function reopenedAt(): ?DateTimeImmutable + { + return $this->reopenedAt; + } +} diff --git a/app/Modules/Sales/Domain/Entities/QuickSale.php b/app/Modules/Sales/Domain/Entities/QuickSale.php new file mode 100644 index 0000000..5539bb3 --- /dev/null +++ b/app/Modules/Sales/Domain/Entities/QuickSale.php @@ -0,0 +1,131 @@ + $lines + */ + private function __construct( + private ?int $id, + private int $sellerId, + private ?int $customerId, + private PaymentMethod $paymentMethod, + private DateTimeImmutable $soldAt, + private DateTimeImmutable $soldOn, + private array $lines, + private ?int $creditsSaleId, + ) { + if ($lines === []) { + throw new QuickSaleEmpty; + } + } + + /** + * @param list $lines + * @param DateTimeImmutable $soldOn The cash day, in the company's time zone. + * + * @throws QuickSaleEmpty + */ + public static function sell(int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, array $lines, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn): self + { + return new self(null, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, null); + } + + /** + * @throws CreditCannotBeCredited + */ + public static function creditFor(self $original, int $actorUserId, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn): self + { + if ($original->isCredit()) { + throw new CreditCannotBeCredited; + } + + return new self( + null, + $actorUserId, + $original->customerId, + $original->paymentMethod, + $soldAt, + $soldOn, + array_map(fn (QuickSaleLine $line): QuickSaleLine => $line->negated(), $original->lines), + $original->id, + ); + } + + /** + * @param list $lines + */ + public static function reconstitute(int $id, int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn, array $lines, ?int $creditsSaleId): self + { + return new self($id, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, $creditsSaleId); + } + + public function totalCents(): int + { + return array_sum(array_map(fn (QuickSaleLine $line): int => $line->totalCents(), $this->lines)); + } + + public function isCredit(): bool + { + return $this->creditsSaleId !== null; + } + + public function id(): ?int + { + return $this->id; + } + + public function sellerId(): int + { + return $this->sellerId; + } + + public function customerId(): ?int + { + return $this->customerId; + } + + public function paymentMethod(): PaymentMethod + { + return $this->paymentMethod; + } + + public function soldAt(): DateTimeImmutable + { + return $this->soldAt; + } + + public function soldOn(): DateTimeImmutable + { + return $this->soldOn; + } + + /** + * @return list + */ + public function lines(): array + { + return $this->lines; + } + + public function creditsSaleId(): ?int + { + return $this->creditsSaleId; + } +} diff --git a/app/Modules/Sales/Domain/Enums/PaymentMethod.php b/app/Modules/Sales/Domain/Enums/PaymentMethod.php new file mode 100644 index 0000000..409f5ac --- /dev/null +++ b/app/Modules/Sales/Domain/Enums/PaymentMethod.php @@ -0,0 +1,14 @@ + $vatTotals + */ + public function __construct( + public int $saleCount, + public int $cashCents, + public int $cardCents, + public array $vatTotals, + ) {} + + public static function empty(): self + { + return new self(0, 0, 0, []); + } + + /** + * @param list $sales + */ + public static function of(array $sales): self + { + $cash = 0; + $card = 0; + $grossByRate = []; + + foreach ($sales as $sale) { + if ($sale->paymentMethod() === PaymentMethod::Cash) { + $cash += $sale->totalCents(); + } else { + $card += $sale->totalCents(); + } + + foreach ($sale->lines() as $line) { + $grossByRate[$line->vatBasisPoints] = ($grossByRate[$line->vatBasisPoints] ?? 0) + $line->totalCents(); + } + } + + krsort($grossByRate); + + $vatTotals = []; + foreach ($grossByRate as $basisPoints => $gross) { + $vatTotals[] = VatTotal::ofGross($basisPoints, $gross); + } + + return new self(count($sales), $cash, $card, $vatTotals); + } + + public function totalCents(): int + { + return $this->cashCents + $this->cardCents; + } +} diff --git a/app/Modules/Sales/Domain/ValueObjects/QuickSaleLine.php b/app/Modules/Sales/Domain/ValueObjects/QuickSaleLine.php new file mode 100644 index 0000000..a3a1bc3 --- /dev/null +++ b/app/Modules/Sales/Domain/ValueObjects/QuickSaleLine.php @@ -0,0 +1,53 @@ + self::MAX_QUANTITY) { + throw new InvalidQuantity; + } + } + + /** + * A sold line: the quantity must be positive. + * + * @throws InvalidQuantity + */ + public static function sold(int $productId, string $productName, int $quantity, int $unitPriceCents, int $vatBasisPoints): self + { + if ($quantity < 1) { + throw new InvalidQuantity; + } + + return new self($productId, $productName, $quantity, $unitPriceCents, $vatBasisPoints); + } + + public function negated(): self + { + return new self($this->productId, $this->productName, -$this->quantity, $this->unitPriceCents, $this->vatBasisPoints); + } + + public function totalCents(): int + { + return $this->quantity * $this->unitPriceCents; + } +} diff --git a/app/Modules/Sales/Domain/ValueObjects/VatTotal.php b/app/Modules/Sales/Domain/ValueObjects/VatTotal.php new file mode 100644 index 0000000..0db5b56 --- /dev/null +++ b/app/Modules/Sales/Domain/ValueObjects/VatTotal.php @@ -0,0 +1,31 @@ +removeVat(new VatPercentage($vatBasisPoints))->cents; + $net = $grossCents < 0 ? -$net : $net; + + return new self($vatBasisPoints, $grossCents, $net, $grossCents - $net); + } +} diff --git a/app/Modules/Sales/Infrastructure/HoursForQuickSales.php b/app/Modules/Sales/Infrastructure/HoursForQuickSales.php new file mode 100644 index 0000000..c52f258 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/HoursForQuickSales.php @@ -0,0 +1,43 @@ +format('Y'); + + try { + $taskId = $this->tasks->execute($year, $workTypeId, $sellerId, __('sales.job_name', ['year' => $year])); + $this->addHours->execute( + $sellerId, + $taskId, + $day->format('Y-m-d'), + number_format($quarters / 4, 2, ',', ''), + __('sales.hours_note', ['number' => $saleId]), + ); + } catch (DomainException) { + // Approved or locked hours, or a day over 24 hours: the sale stands without them. + return false; + } + + return true; + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Eloquent/CashDayModel.php b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/CashDayModel.php new file mode 100644 index 0000000..3f73c46 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/CashDayModel.php @@ -0,0 +1,53 @@ + + */ + public function vatTotals(): HasMany + { + return $this->hasMany(CashDayVatTotalModel::class, 'cash_day_id')->orderByDesc('vat_basis_points'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'closed_by' => 'integer', + 'closed_at' => 'datetime', + 'sale_count' => 'integer', + 'cash_cents' => 'integer', + 'card_cents' => 'integer', + 'total_cents' => 'integer', + 'reopened_by' => 'integer', + 'reopened_at' => 'datetime', + ]; + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Eloquent/CashDayVatTotalModel.php b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/CashDayVatTotalModel.php new file mode 100644 index 0000000..9274b3b --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/CashDayVatTotalModel.php @@ -0,0 +1,38 @@ + + */ + protected function casts(): array + { + return [ + 'cash_day_id' => 'integer', + 'vat_basis_points' => 'integer', + 'gross_cents' => 'integer', + 'net_cents' => 'integer', + 'vat_cents' => 'integer', + ]; + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleLineModel.php b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleLineModel.php new file mode 100644 index 0000000..d9e5257 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleLineModel.php @@ -0,0 +1,41 @@ + + */ + protected function casts(): array + { + return [ + 'quick_sale_id' => 'integer', + 'product_id' => 'integer', + 'quantity' => 'integer', + 'unit_price_cents' => 'integer', + 'vat_basis_points' => 'integer', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php new file mode 100644 index 0000000..db57e85 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php @@ -0,0 +1,66 @@ + */ + use HasFactory; + + /** + * @return HasMany + */ + public function lines(): HasMany + { + return $this->hasMany(QuickSaleLineModel::class, 'quick_sale_id')->orderBy('sort_order'); + } + + /** + * @return HasOne + */ + public function credit(): HasOne + { + return $this->hasOne(QuickSaleModel::class, 'credits_quick_sale_id'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'user_id' => 'integer', + 'customer_id' => 'integer', + 'payment_method' => PaymentMethod::class, + 'sold_at' => 'datetime', + 'total_cents' => 'integer', + 'credits_quick_sale_id' => 'integer', + ]; + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentCashDayRepository.php b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentCashDayRepository.php new file mode 100644 index 0000000..9284818 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentCashDayRepository.php @@ -0,0 +1,86 @@ +with('vatTotals')->where('day', $day->format('Y-m-d'))->first(); + + return $model === null ? CashDay::open($day) : $this->toEntity($model); + } + + public function lockForDay(DateTimeImmutable $day): CashDay + { + CashDayModel::query()->insertOrIgnore(['day' => $day->format('Y-m-d'), 'created_at' => now(), 'updated_at' => now()]); + + $model = CashDayModel::query()->with('vatTotals')->where('day', $day->format('Y-m-d'))->lockForUpdate()->firstOrFail(); + + return $this->toEntity($model); + } + + public function save(CashDay $cashDay): CashDay + { + $model = CashDayModel::query()->firstOrNew(['day' => $cashDay->day()->format('Y-m-d')]); + $balance = $cashDay->balance() ?? CashDayBalance::empty(); + + $model->fill([ + 'closed_by' => $cashDay->closedBy(), + 'closed_at' => $cashDay->closedAt()?->format('Y-m-d H:i:s'), + 'sale_count' => $balance->saleCount, + 'cash_cents' => $balance->cashCents, + 'card_cents' => $balance->cardCents, + 'total_cents' => $balance->totalCents(), + 'reopened_by' => $cashDay->reopenedBy(), + 'reopened_at' => $cashDay->reopenedAt()?->format('Y-m-d H:i:s'), + ])->save(); + + CashDayVatTotalModel::query()->where('cash_day_id', $model->id)->delete(); + + foreach ($balance->vatTotals as $total) { + CashDayVatTotalModel::query()->create([ + 'cash_day_id' => $model->id, + 'vat_basis_points' => $total->vatBasisPoints, + 'gross_cents' => $total->grossCents, + 'net_cents' => $total->netCents, + 'vat_cents' => $total->vatCents, + ]); + } + + return $this->toEntity($model->load('vatTotals')); + } + + private function toEntity(CashDayModel $model): CashDay + { + $balance = $model->closed_at === null ? null : new CashDayBalance( + $model->sale_count, + $model->cash_cents, + $model->card_cents, + $model->vatTotals->map(fn (CashDayVatTotalModel $total): VatTotal => new VatTotal( + $total->vat_basis_points, + $total->gross_cents, + $total->net_cents, + $total->vat_cents, + ))->values()->all(), + ); + + return CashDay::reconstitute( + $model->id, + new DateTimeImmutable($model->day), + $balance, + $model->closed_by, + $model->closed_at === null ? null : DateTimeImmutable::createFromInterface($model->closed_at), + $model->reopened_by, + $model->reopened_at === null ? null : DateTimeImmutable::createFromInterface($model->reopened_at), + ); + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleQueries.php b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleQueries.php new file mode 100644 index 0000000..81804d4 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleQueries.php @@ -0,0 +1,116 @@ +with(['lines', 'credit']) + ->where('sold_on', $day) + ->when($sellerId !== null, fn ($query) => $query->where('user_id', $sellerId)) + ->orderByDesc('sold_at') + ->orderByDesc('id') + ->get(); + + return $this->summaries($models); + } + + public function findSale(int $id): ?QuickSaleSummary + { + $model = QuickSaleModel::query()->with(['lines', 'credit'])->find($id); + + return $model === null ? null : $this->summaries(collect([$model]))[0]; + } + + public function cashDay(string $day): CashDaySummary + { + $date = new DateTimeImmutable($day); + $cashDay = $this->cashDays->forDay($date); + $names = $this->users->namesByIds(array_values(array_filter([$cashDay->closedBy(), $cashDay->reopenedBy()]))); + + return new CashDaySummary( + day: $day, + isClosed: $cashDay->isClosed(), + balance: $cashDay->balance() ?? CashDayBalance::of($this->sales->forDay($date)), + closedByName: $cashDay->closedBy() === null ? null : ($names[$cashDay->closedBy()] ?? ''), + closedAt: $this->localTime($cashDay->closedAt()), + reopenedByName: $cashDay->reopenedBy() === null ? null : ($names[$cashDay->reopenedBy()] ?? ''), + reopenedAt: $this->localTime($cashDay->reopenedAt()), + ); + } + + public function unclosedDaysBefore(string $day): array + { + $closed = CashDayModel::query()->whereNotNull('closed_at')->select('day'); + + return QuickSaleModel::query() + ->where('sold_on', '<', $day) + ->whereNotIn('sold_on', $closed) + ->distinct() + ->orderBy('sold_on') + ->pluck('sold_on') + ->map(fn ($value): string => substr((string) $value, 0, 10)) + ->values() + ->all(); + } + + /** + * @param Collection $models + * @return list + */ + private function summaries(Collection $models): array + { + $sellerNames = $this->users->namesByIds($models->pluck('user_id')->unique()->values()->all()); + $customerNames = $this->customers->namesByIds($models->pluck('customer_id')->filter()->unique()->values()->all()); + + return $models->map(fn (QuickSaleModel $model): QuickSaleSummary => new QuickSaleSummary( + id: $model->id, + soldAt: (string) $this->localTime($model->sold_at), + sellerId: $model->user_id, + sellerName: $sellerNames[$model->user_id] ?? '', + customerName: $model->customer_id === null ? null : ($customerNames[$model->customer_id] ?? ''), + paymentMethod: $model->payment_method, + totalCents: $model->total_cents, + lines: $model->lines->map(fn (QuickSaleLineModel $line): QuickSaleLineSummary => new QuickSaleLineSummary( + $line->product_name, + $line->quantity, + $line->unit_price_cents, + $line->quantity * $line->unit_price_cents, + $line->vat_basis_points, + ))->values()->all(), + creditsSaleId: $model->credits_quick_sale_id, + creditedBySaleId: $model->credit?->id, + ))->values()->all(); + } + + private function localTime(?DateTimeInterface $moment): ?string + { + return $moment === null ? null : Carbon::instance($moment)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'); + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php new file mode 100644 index 0000000..75d66fa --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php @@ -0,0 +1,84 @@ +with('lines')->find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function add(QuickSale $sale): QuickSale + { + $model = QuickSaleModel::query()->create([ + 'user_id' => $sale->sellerId(), + 'customer_id' => $sale->customerId(), + 'payment_method' => $sale->paymentMethod(), + 'sold_at' => $sale->soldAt()->format('Y-m-d H:i:s'), + 'sold_on' => $sale->soldOn()->format('Y-m-d'), + 'total_cents' => $sale->totalCents(), + 'credits_quick_sale_id' => $sale->creditsSaleId(), + ]); + + foreach ($sale->lines() as $index => $line) { + QuickSaleLineModel::query()->create([ + 'quick_sale_id' => $model->id, + 'product_id' => $line->productId, + 'product_name' => $line->productName, + 'quantity' => $line->quantity, + 'unit_price_cents' => $line->unitPriceCents, + 'vat_basis_points' => $line->vatBasisPoints, + 'sort_order' => $index + 1, + ]); + } + + return $this->toEntity($model->load('lines')); + } + + public function isCredited(int $saleId): bool + { + return QuickSaleModel::query()->where('credits_quick_sale_id', $saleId)->exists(); + } + + public function forDay(DateTimeImmutable $day): array + { + return QuickSaleModel::query() + ->with('lines') + ->where('sold_on', $day->format('Y-m-d')) + ->orderBy('id') + ->get() + ->map(fn (QuickSaleModel $model): QuickSale => $this->toEntity($model)) + ->values() + ->all(); + } + + private function toEntity(QuickSaleModel $model): QuickSale + { + return QuickSale::reconstitute( + $model->id, + $model->user_id, + $model->customer_id, + $model->payment_method, + DateTimeImmutable::createFromInterface($model->sold_at), + new DateTimeImmutable($model->sold_on), + $model->lines->map(fn (QuickSaleLineModel $line): QuickSaleLine => new QuickSaleLine( + $line->product_id, + $line->product_name, + $line->quantity, + $line->unit_price_cents, + $line->vat_basis_points, + ))->values()->all(), + $model->credits_quick_sale_id, + ); + } +} diff --git a/app/Modules/Sales/Infrastructure/ProductsFromPriceList.php b/app/Modules/Sales/Infrastructure/ProductsFromPriceList.php new file mode 100644 index 0000000..8d0ab61 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/ProductsFromPriceList.php @@ -0,0 +1,30 @@ + new SellableProduct( + $product->id, + $product->name, + $product->unit->value, + $product->grossCents, + $product->vatBasisPoints, + $product->durationQuarters, + $product->workTypeId, + ), $this->priceList->consumerProducts()); + } +} diff --git a/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php b/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php new file mode 100644 index 0000000..1302780 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php @@ -0,0 +1,65 @@ + + */ + public array $bindings = [ + QuickSaleRepository::class => EloquentQuickSaleRepository::class, + CashDayRepository::class => EloquentCashDayRepository::class, + QuickSaleQueries::class => EloquentQuickSaleQueries::class, + QuickSaleProducts::class => ProductsFromPriceList::class, + QuickSaleHours::class => HoursForQuickSales::class, + ]; + + public function boot(): void + { + $presentationPath = dirname(__DIR__, 2).'/Presentation'; + + Livewire::addNamespace('sales', viewPath: $presentationPath.'/Livewire'); + $this->loadViewsFrom($presentationPath.'/Views', 'sales-views'); + + if (! $this->app->routesAreCached()) { + $this->loadRoutesFrom($presentationPath.'/Routes/web.php'); + } + + // Everyone but subcontractors sells at the counter and closes the cash day (spec 2, 7). + Gate::define('sales.use', fn (User $user): bool => $user->role !== Role::Subcontractor); + + Gate::define('sales.view-all', fn (User $user): bool => $user->role->seesAllMoney()); + + Gate::define('sales.view-sale', fn (User $user, int $sellerId): bool => $user->role->seesAllMoney() + || ($user->role !== Role::Subcontractor && $user->id === $sellerId)); + + Gate::define('sales.credit', fn (User $user, int $sellerId): bool => $user->role->seesAllMoney() + || ($user->role !== Role::Subcontractor && $user->id === $sellerId)); + + Gate::define('sales.close-day', fn (User $user): bool => $user->role !== Role::Subcontractor); + + Gate::define('sales.reopen-day', fn (User $user): bool => $user->role->seesAllMoney()); + } +} diff --git a/app/Modules/Sales/Presentation/Http/Controllers/ShowReceipt.php b/app/Modules/Sales/Presentation/Http/Controllers/ShowReceipt.php new file mode 100644 index 0000000..fb4cfa0 --- /dev/null +++ b/app/Modules/Sales/Presentation/Http/Controllers/ShowReceipt.php @@ -0,0 +1,31 @@ +findSale($sale) ?? abort(404); + Gate::authorize('sales.view-sale', $summary->sellerId); + + return Pdf::loadView('sales-views::receipt', [ + 'sale' => $summary, + 'company' => $company->get(), + ]) + ->setPaper('a5') + ->setOption('isFontSubsettingEnabled', true) + ->stream(__('sales.receipt.file', ['number' => $summary->id])); + } +} diff --git a/app/Modules/Sales/Presentation/Livewire/Concerns/FormatsSales.php b/app/Modules/Sales/Presentation/Livewire/Concerns/FormatsSales.php new file mode 100644 index 0000000..e8af400 --- /dev/null +++ b/app/Modules/Sales/Presentation/Livewire/Concerns/FormatsSales.php @@ -0,0 +1,39 @@ +format(); + } + + public function vatRate(int $basisPoints): string + { + return (new VatPercentage($basisPoints))->format(); + } + + public function hours(int $quarters): string + { + return rtrim(rtrim(number_format($quarters / 4, 2, ',', ''), '0'), ','); + } + + /** + * "24.11.2026" for "2026-11-24"; "24.11.2026 klo 14.05" for "2026-11-24 14:05". + */ + public function dateLabel(string $value): string + { + return strlen($value) > 10 + ? CarbonImmutable::createFromFormat('Y-m-d H:i', $value)->format('j.n.Y \k\l\o H.i') + : CarbonImmutable::createFromFormat('!Y-m-d', $value)->format('j.n.Y'); + } +} diff --git a/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php b/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php new file mode 100644 index 0000000..285a474 --- /dev/null +++ b/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php @@ -0,0 +1,479 @@ +authorize('sales.use'); + + $this->day = $this->parseDay($this->day)?->format('Y-m-d') ?? $clock->today()->format('Y-m-d'); + } + + /** + * @return list + */ + #[Computed] + public function sales(): array + { + $sellerId = Gate::allows('sales.view-all') + ? ($this->seller === '' ? null : (int) $this->seller) + : (int) auth()->id(); + + return app(QuickSaleQueries::class)->salesOn($this->day, $sellerId); + } + + #[Computed] + public function cashDay(): CashDaySummary + { + return app(QuickSaleQueries::class)->cashDay($this->day); + } + + /** + * @return list + */ + #[Computed] + public function unclosedDays(): array + { + return app(QuickSaleQueries::class)->unclosedDaysBefore(app(Clock::class)->today()->format('Y-m-d')); + } + + /** + * @return list + */ + #[Computed] + public function sellers(): array + { + return Gate::allows('sales.view-all') ? app(UserAccountQueries::class)->activeUserOptions() : []; + } + + #[Computed] + public function isFuture(): bool + { + return $this->day > app(Clock::class)->today()->format('Y-m-d'); + } + + public function updatedSeller(): void + { + $this->authorize('sales.view-all'); + unset($this->sales); + } + + public function showDay(string $which, Clock $clock): void + { + $current = $this->parseDay($this->day) ?? CarbonImmutable::instance($clock->today()); + + $this->day = match ($which) { + 'previous' => $current->subDay()->format('Y-m-d'), + 'next' => $current->addDay()->format('Y-m-d'), + default => $clock->today()->format('Y-m-d'), + }; + + $this->statusMessage = ''; + unset($this->sales, $this->cashDay); + } + + public function confirmCredit(int $saleId): void + { + $sale = app(QuickSaleQueries::class)->findSale($saleId) ?? abort(404); + $this->authorize('sales.credit', $sale->sellerId); + + $this->creditSaleId = $saleId; + $this->js("document.getElementById('credit-dialog').showModal()"); + } + + public function credit(CreditQuickSale $creditQuickSale, Clock $clock): void + { + $sale = app(QuickSaleQueries::class)->findSale((int) $this->creditSaleId) ?? abort(404); + $this->authorize('sales.credit', $sale->sellerId); + + try { + $creditId = $creditQuickSale->execute($sale->id, (int) auth()->id()); + $this->statusMessage = __('sales.credited', ['number' => $sale->id, 'credit' => $creditId]); + $this->day = $clock->today()->format('Y-m-d'); + } catch (QuickSaleNotFound) { + $this->statusMessage = __('sales.errors.not_found'); + } catch (QuickSaleAlreadyCredited) { + $this->statusMessage = __('sales.errors.already_credited'); + } catch (CreditCannotBeCredited) { + $this->statusMessage = __('sales.errors.credit_of_credit'); + } catch (CashDayClosed) { + $this->statusMessage = __('sales.errors.day_closed'); + } + + $this->creditSaleId = null; + unset($this->sales, $this->cashDay); + $this->js("document.getElementById('credit-dialog').close(); document.getElementById('sales-status').focus()"); + } + + public function confirmClose(): void + { + $this->authorize('sales.close-day'); + $this->js("document.getElementById('close-dialog').showModal()"); + } + + public function closeDay(CloseCashDay $closeCashDay): void + { + $this->authorize('sales.close-day'); + + try { + $closeCashDay->execute(new DateTimeImmutable($this->day), (int) auth()->id()); + $this->statusMessage = __('sales.cash_day.closed_message', ['day' => $this->dateLabel($this->day)]); + } catch (CashDayClosed) { + $this->statusMessage = __('sales.errors.day_closed'); + } catch (CashDayInFuture) { + $this->statusMessage = __('sales.errors.future'); + } + + unset($this->cashDay, $this->unclosedDays); + $this->js("document.getElementById('close-dialog').close(); document.getElementById('sales-status').focus()"); + } + + public function confirmReopen(): void + { + $this->authorize('sales.reopen-day'); + $this->js("document.getElementById('reopen-dialog').showModal()"); + } + + public function reopenDay(ReopenCashDay $reopenCashDay): void + { + $this->authorize('sales.reopen-day'); + + try { + $reopenCashDay->execute(new DateTimeImmutable($this->day), (int) auth()->id()); + $this->statusMessage = __('sales.cash_day.reopened_message', ['day' => $this->dateLabel($this->day)]); + } catch (CashDayNotClosed) { + $this->statusMessage = __('sales.errors.not_closed'); + } + + unset($this->cashDay, $this->unclosedDays); + $this->js("document.getElementById('reopen-dialog').close(); document.getElementById('sales-status').focus()"); + } + + public function linesText(QuickSaleSummary $sale): string + { + return implode(', ', array_map(fn ($line): string => __('sales.line', [ + 'quantity' => $line->quantity, + 'product' => $line->productName, + 'price' => $this->money($line->unitPriceCents), + ]), $sale->lines)); + } + + /** + * @return list + */ + public function headers(): array + { + return [ + ['index' => 'time', 'label' => __('sales.columns.time'), 'sortable' => false], + ['index' => 'number', 'label' => __('sales.columns.number'), 'sortable' => false], + ['index' => 'seller', 'label' => __('sales.columns.seller'), 'sortable' => false], + ['index' => 'customer', 'label' => __('sales.columns.customer'), 'sortable' => false], + ['index' => 'products', 'label' => __('sales.columns.products'), 'sortable' => false], + ['index' => 'method', 'label' => __('sales.columns.payment_method'), 'sortable' => false], + ['index' => 'total', 'label' => __('sales.columns.total'), 'sortable' => false, 'align' => 'right'], + ['index' => 'actions', 'label' => __('sales.columns.actions'), 'sortable' => false], + ]; + } + + public function render(): mixed + { + return $this->view()->title(__('sales.index.title')); + } + + private function parseDay(string $day): ?CarbonImmutable + { + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $day) !== 1) { + return null; + } + + $date = CarbonImmutable::createFromFormat('!Y-m-d', $day); + + return $date !== null && $date->format('Y-m-d') === $day ? $date : null; + } +}; +?> + +
+
+

{{ __('sales.index.title') }}

+

+ +

+
+ + + +

{{ $statusMessage }}

+ + @if ($this->unclosedDays !== []) +
+

+

+
    + @foreach ($this->unclosedDays as $unclosed) +
  • {{ $this->dateLabel($unclosed) }}
  • + @endforeach +
+
+ @endif + +

{{ $this->dateLabel($day) }}

+ +
+

{{ __('sales.cash_day.title') }}

+ + @php($cashDay = $this->cashDay) + + @if ($cashDay->isClosed) +

+

+ @else +

{{ __('sales.cash_day.open') }}

+ @endif + + @if ($cashDay->reopenedAt !== null) +

{{ __('sales.cash_day.reopened', ['at' => $this->dateLabel($cashDay->reopenedAt), 'name' => $cashDay->reopenedByName]) }}

+ @endif + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
{{ $cashDay->isClosed ? __('sales.cash_day.balance') : __('sales.cash_day.preview') }}
{{ __('sales.cash_day.item') }}{{ __('sales.cash_day.amount') }}
{{ __('sales.cash_day.sale_count') }}{{ $cashDay->balance->saleCount }}
{{ __('sales.cash_day.cash') }}{{ $this->money($cashDay->balance->cashCents) }}
{{ __('sales.cash_day.card') }}{{ $this->money($cashDay->balance->cardCents) }}
{{ __('sales.cash_day.total') }}{{ $this->money($cashDay->balance->totalCents()) }}
+ + @if ($cashDay->balance->vatTotals !== []) + + + + + + + + + + + + @foreach ($cashDay->balance->vatTotals as $vatTotal) + + + + + + + @endforeach + +
{{ __('sales.cash_day.vat_breakdown') }}
{{ __('sales.cash_day.vat_rate') }}{{ __('sales.cash_day.gross') }}{{ __('sales.cash_day.net') }}{{ __('sales.cash_day.vat') }}
{{ $this->vatRate($vatTotal->vatBasisPoints) }}{{ $this->money($vatTotal->grossCents) }}{{ $this->money($vatTotal->netCents) }}{{ $this->money($vatTotal->vatCents) }}
+ @endif +
+ +
+ @if (! $cashDay->isClosed && ! $this->isFuture) + @can('sales.close-day') + + @endcan + @elseif ($cashDay->isClosed) + @can('sales.reopen-day') + + @endcan + @endif +
+
+ +
+

{{ __('sales.index.sales') }}

+ + @can('sales.view-all') +
+ {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($this->sellers as $option) + + @endforeach + +
+ @else +

{{ __('sales.index.own_only') }}

+ @endcan + + @if ($this->sales === []) +

{{ __('sales.index.none') }}

+ @else + + @interact('column_time', $sale) + {{ substr($sale->soldAt, 11) }} + @endinteract + + @interact('column_number', $sale) + #{{ $sale->id }} + @if ($sale->isCredit()) + {{ __('sales.credit_of', ['number' => $sale->creditsSaleId]) }} + @elseif ($sale->creditedBySaleId !== null) + {{ __('sales.credited_by', ['number' => $sale->creditedBySaleId]) }} + @endif + @endinteract + + @interact('column_seller', $sale) + {{ $sale->sellerName }} + @endinteract + + @interact('column_customer', $sale) + {{ $sale->customerName ?? __('sales.anonymous') }} + @endinteract + + @interact('column_products', $sale) + {{ $this->linesText($sale) }} + @endinteract + + @interact('column_method', $sale) + {{ __('sales.payment_methods.'.$sale->paymentMethod->value) }} + @endinteract + + @interact('column_total', $sale) + {{ $this->money($sale->totalCents) }} + @endinteract + + @interact('column_actions', $sale) + + + @if ($sale->canBeCredited()) + @can('sales.credit', $sale->sellerId) + + @endcan + @endif + @endinteract + + @endif +
+ + + @php($creditSale = $creditSaleId === null ? null : collect($this->sales)->firstWhere('id', $creditSaleId)) + @if ($creditSale !== null) +

{{ __('sales.credit_text', ['number' => $creditSale->id, 'total' => $this->money($creditSale->totalCents), 'method' => __('sales.payment_methods.'.$creditSale->paymentMethod->value)]) }}

+ @endif + + + + +
+ + +

{{ __('sales.cash_day.close_text') }}

+

+ {{ __('sales.cash_day.total') }}: {{ $this->money($cashDay->balance->totalCents()) }} + ({{ __('sales.cash_day.cash') }} {{ $this->money($cashDay->balance->cashCents) }}, + {{ __('sales.cash_day.card') }} {{ $this->money($cashDay->balance->cardCents) }}) +

+ + + + +
+ + @can('sales.reopen-day') + +

{{ __('sales.cash_day.reopen_text') }}

+ + + + +
+ @endcan +
diff --git a/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php b/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php new file mode 100644 index 0000000..07b82d3 --- /dev/null +++ b/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php @@ -0,0 +1,432 @@ + + */ + #[Locked] + public array $quantities = []; + + public string $paymentMethod = 'cash'; + + public string $customerSearch = ''; + + #[Locked] + public ?int $customerId = null; + + #[Locked] + public string $customerName = ''; + + #[Locked] + public string $cartMessage = ''; + + #[Locked] + public ?int $savedSaleId = null; + + #[Locked] + public string $savedMessage = ''; + + #[Locked] + public string $hoursMessage = ''; + + public function mount(): void + { + $this->authorize('sales.use'); + } + + /** + * @return array By product id, in price list order. + */ + #[Computed] + public function products(): array + { + $products = []; + + foreach (app(QuickSaleProducts::class)->sellable() as $product) { + $products[$product->id] = $product; + } + + return $products; + } + + /** + * The sale's lines with their products, in the order added. + * + * @return list + */ + #[Computed] + public function lines(): array + { + $lines = []; + + foreach ($this->quantities as $productId => $quantity) { + if (isset($this->products[$productId])) { + $lines[] = ['product' => $this->products[$productId], 'quantity' => $quantity]; + } + } + + return $lines; + } + + #[Computed] + public function totalCents(): int + { + return array_sum(array_map(fn (array $line): int => $line['quantity'] * $line['product']->grossCents, $this->lines)); + } + + /** + * @return list + */ + #[Computed] + public function customerResults(): array + { + $term = trim($this->customerSearch); + + return mb_strlen($term) < 2 ? [] : app(CustomerQueries::class)->search($term, 8); + } + + public function addProduct(int $productId): void + { + $this->authorize('sales.use'); + + if (! isset($this->products[$productId])) { + return; + } + + $this->quantities[$productId] = min(QuickSaleLine::MAX_QUANTITY, ($this->quantities[$productId] ?? 0) + 1); + $this->changed($productId); + } + + public function decreaseProduct(int $productId): void + { + $this->authorize('sales.use'); + + if (! isset($this->quantities[$productId])) { + return; + } + + if ($this->quantities[$productId] <= 1) { + $this->removeProduct($productId); + + return; + } + + $this->quantities[$productId]--; + $this->changed($productId); + } + + public function removeProduct(int $productId): void + { + $this->authorize('sales.use'); + + $name = $this->products[$productId]->name ?? ''; + unset($this->quantities[$productId]); + $this->forgetLines(); + + $this->cartMessage = __('sales.sell.removed', ['product' => $name, 'total' => $this->money($this->totalCents)]); + $this->js("document.getElementById('cart-heading')?.focus()"); + } + + public function selectCustomer(int $customerId): void + { + $this->authorize('sales.use'); + + $customer = app(CustomerQueries::class)->findSummary($customerId); + + if ($customer !== null) { + $this->customerId = $customer->id; + $this->customerName = $customer->name; + $this->customerSearch = ''; + $this->js("document.getElementById('change-customer')?.focus()"); + } + } + + public function clearCustomer(): void + { + $this->customerId = null; + $this->customerName = ''; + $this->js("document.getElementById('customer-search')?.focus()"); + } + + public function save(SellQuickSale $sellQuickSale): void + { + $this->authorize('sales.use'); + $this->savedMessage = ''; + $this->hoursMessage = ''; + $this->savedSaleId = null; + + $this->validate(['paymentMethod' => ['required', Rule::enum(PaymentMethod::class)]]); + + try { + $result = $sellQuickSale->execute((int) auth()->id(), new SaleData($this->quantities, $this->paymentMethod, $this->customerId)); + } catch (QuickSaleEmpty) { + $this->addError('quantities', __('sales.errors.empty')); + + return; + } catch (InvalidQuantity) { + $this->addError('quantities', __('sales.errors.quantity')); + + return; + } catch (ProductNotSellable $exception) { + unset($this->quantities[$exception->id], $this->products); + $this->forgetLines(); + $this->addError('quantities', __('sales.errors.product')); + + return; + } catch (QuickSaleCustomerNotFound) { + $this->addError('customerSearch', __('sales.errors.customer')); + $this->clearCustomer(); + + return; + } catch (CashDayClosed) { + $this->addError('sale', __('sales.errors.day_closed')); + + return; + } + + $this->savedSaleId = $result->saleId; + $this->savedMessage = __('sales.sell.saved', [ + 'number' => $result->saleId, + 'total' => $this->money($result->totalCents), + 'method' => __('sales.payment_methods.'.$this->paymentMethod), + ]); + + $this->hoursMessage = trim( + ($result->bookedQuarters > 0 ? __('sales.sell.hours_booked', ['hours' => $this->hours($result->bookedQuarters)]) : '') + .' '.($result->unbookedQuarters > 0 ? __('sales.sell.hours_not_booked', ['hours' => $this->hours($result->unbookedQuarters)]) : ''), + ); + + $this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage'); + $this->forgetLines(); + + $this->js("document.getElementById('sale-saved')?.focus()"); + } + + public function render(): mixed + { + return $this->view()->title(__('sales.sell.title')); + } + + private function changed(int $productId): void + { + $this->forgetLines(); + $this->resetErrorBag('quantities'); + + $this->cartMessage = __('sales.sell.changed', [ + 'product' => $this->products[$productId]->name, + 'quantity' => $this->quantities[$productId], + 'total' => $this->money($this->totalCents), + ]); + } + + private function forgetLines(): void + { + unset($this->lines, $this->totalCents); + } +}; +?> + +
+
+

{{ __('sales.sell.title') }}

+

{{ __('sales.sell.intro') }}

+

+ {{ __('sales.sell.to_list') }} +

+
+ +
+ @if ($savedMessage !== '') +
+

+

+ @if ($hoursMessage !== '') +

{{ $hoursMessage }}

+ @endif + @if ($savedSaleId !== null) +

+ + +

+ @endif +
+ @endif +
+ + @error('sale') + + @enderror + + @if ($this->products === []) +

{{ __('sales.sell.no_products') }}

+ @else +
+

{{ __('sales.sell.products') }}

+

{{ __('sales.sell.products_help') }}

+ +
    + @foreach ($this->products as $product) +
  • + +
  • + @endforeach +
+
+ +
+

{{ __('sales.sell.cart') }}

+ +

{{ $cartMessage }}

+ + @error('quantities') + + @enderror + + @if ($this->lines === []) +

{{ __('sales.sell.cart_empty') }}

+ @else +
    + @foreach ($this->lines as $line) + @php($product = $line['product']) +
  • +
    +

    {{ $product->name }}

    +

    + {{ __('sales.sell.line', ['quantity' => $line['quantity'], 'price' => $this->money($product->grossCents), 'total' => $this->money($line['quantity'] * $product->grossCents)]) }} +

    + @if ($product->durationQuarters > 0 && $product->workTypeId !== null) +

    {{ __('sales.sell.line_hours', ['hours' => $this->hours($product->durationQuarters * $line['quantity'])]) }}

    + @endif +
    +
    + + + + +
    +
  • + @endforeach +
+ @endif + +

+ {{ __('sales.sell.total', ['total' => $this->money($this->totalCents)]) }} +

+
+ +
+ + +
+ @if ($customerId !== null) +

{{ __('sales.sell.customer') }}

+
+ {{ $customerName }} + +
+ @else + + + @if (mb_strlen(trim($customerSearch)) >= 2) +

+ {{ trans_choice('sales.sell.customer_results', count($this->customerResults), ['count' => count($this->customerResults)]) }} +

+ +
    + @foreach ($this->customerResults as $customer) +
  • + +
  • + @endforeach +
+ @endif + @endif +
+ + + + @endif +
diff --git a/app/Modules/Sales/Presentation/Routes/web.php b/app/Modules/Sales/Presentation/Routes/web.php new file mode 100644 index 0000000..3240b8f --- /dev/null +++ b/app/Modules/Sales/Presentation/Routes/web.php @@ -0,0 +1,13 @@ +prefix('sales') + ->name('sales.') + ->group(function () { + Route::livewire('/', 'sales::index')->name('index'); + Route::livewire('/new', 'sales::sell')->name('sell'); + Route::get('/{sale}/receipt', ShowReceipt::class)->whereNumber('sale')->name('receipt'); + }); diff --git a/app/Modules/Sales/Presentation/Views/receipt.blade.php b/app/Modules/Sales/Presentation/Views/receipt.blade.php new file mode 100644 index 0000000..0e5ee14 --- /dev/null +++ b/app/Modules/Sales/Presentation/Views/receipt.blade.php @@ -0,0 +1,120 @@ +{{-- + PDF receipt of a quick sale, rendered by dompdf (no Tailwind or + JavaScript; DejaVu Sans has the € sign and Finnish letters). Amounts of + a credit are negative. +--}} +@use('App\Modules\Shared\Domain\ValueObjects\Money') +@use('App\Modules\Shared\Domain\ValueObjects\VatPercentage') +@use('Carbon\CarbonImmutable') +@php + $money = fn (int $cents): string => ($cents < 0 ? '-' : '').Money::fromCents(abs($cents))->format(); + $title = $sale->isCredit() ? __('sales.receipt.credit_title') : __('sales.receipt.title'); +@endphp + + + + + {{ $title }} {{ $sale->id }} + + + +
+ @if ($company !== null) +

{{ $company->name }}

+ @if ($company->address !== null) +

{!! nl2br(e($company->address)) !!}

+ @endif + @if ($company->phone !== null) +

{{ $company->phone }}

+ @endif + @if ($company->email !== null) +

{{ $company->email }}

+ @endif +

{{ __('sales.receipt.business_id') }}: {{ $company->businessId }}   {{ __('sales.receipt.vat_number') }}: {{ $company->vatNumber() }}

+ @else +

{{ __('sales.receipt.company_missing') }}

+ @endif +
+ +

{{ $title }}

+ + + + + + @if ($sale->customerName !== null) + + @endif + + @if ($sale->isCredit()) + + @endif +
{{ __('sales.receipt.number') }}{{ $sale->id }}
{{ __('sales.receipt.date') }}{{ CarbonImmutable::createFromFormat('Y-m-d H:i', $sale->soldAt)->format('j.n.Y H.i') }}
{{ __('sales.receipt.seller') }}{{ $sale->sellerName }}
{{ __('sales.receipt.customer') }}{{ $sale->customerName }}
{{ __('sales.receipt.payment_method') }}{{ __('sales.payment_methods.'.$sale->paymentMethod->value) }}
{{ __('sales.receipt.credits', ['number' => $sale->creditsSaleId]) }}
+ + + + + + + + + + + + + @foreach ($sale->lines as $line) + + + + + + + + @endforeach + + + + + +
{{ __('sales.receipt.product') }}{{ __('sales.receipt.quantity') }}{{ __('sales.receipt.unit_price') }}{{ __('sales.receipt.vat_rate') }}{{ __('sales.receipt.line_total') }}
{{ $line->productName }}{{ $line->quantity }}{{ $money($line->unitPriceCents) }}{{ (new VatPercentage($line->vatBasisPoints))->format() }}{{ $money($line->totalCents) }}
{{ __('sales.receipt.total') }}{{ $money($sale->totalCents) }}
+ +

{{ __('sales.receipt.vat_heading') }}

+ + + + + + + + + + + @foreach ($sale->vatTotals() as $vatTotal) + + + + + + + @endforeach + +
{{ __('sales.receipt.vat_rate') }}{{ __('sales.receipt.net') }}{{ __('sales.receipt.vat') }}{{ __('sales.receipt.gross') }}
{{ (new VatPercentage($vatTotal->vatBasisPoints))->format() }}{{ $money($vatTotal->netCents) }}{{ $money($vatTotal->vatCents) }}{{ $money($vatTotal->grossCents) }}
+ + + + diff --git a/app/Modules/Shared/Application/DTOs/CompanyDetails.php b/app/Modules/Shared/Application/DTOs/CompanyDetails.php new file mode 100644 index 0000000..71d69c4 --- /dev/null +++ b/app/Modules/Shared/Application/DTOs/CompanyDetails.php @@ -0,0 +1,28 @@ +businessId); + } +} diff --git a/app/Modules/Shared/Application/UseCases/CompanyDetailsStore.php b/app/Modules/Shared/Application/UseCases/CompanyDetailsStore.php new file mode 100644 index 0000000..2ae2943 --- /dev/null +++ b/app/Modules/Shared/Application/UseCases/CompanyDetailsStore.php @@ -0,0 +1,83 @@ + 'shared.company_name', + 'business_id' => 'shared.company_business_id', + 'address' => 'shared.company_address', + 'phone' => 'shared.company_phone', + 'email' => 'shared.company_email', + ]; + + public function __construct(private Settings $settings) {} + + /** + * Null until the details have been saved. + */ + public function get(): ?CompanyDetails + { + $name = $this->settings->get(self::KEYS['name']); + $businessId = $this->settings->get(self::KEYS['business_id']); + + if ($name === null || $businessId === null) { + return null; + } + + return new CompanyDetails( + $name, + $businessId, + $this->settings->get(self::KEYS['address']), + $this->settings->get(self::KEYS['phone']), + $this->settings->get(self::KEYS['email']), + ); + } + + /** + * @throws CompanyNameRequired + * @throws InvalidBusinessId + * @throws InvalidEmailAddress + */ + public function save(CompanyDetails $details): void + { + $name = trim($details->name); + + if ($name === '' || mb_strlen($name) > 255) { + throw new CompanyNameRequired; + } + + $businessId = new BusinessId($details->businessId); + $email = self::text($details->email); + $email = $email === null ? null : (new EmailAddress($email))->value; + + $this->settings->put(self::KEYS['name'], $name); + $this->settings->put(self::KEYS['business_id'], $businessId->value); + $this->settings->put(self::KEYS['address'], self::text($details->address)); + $this->settings->put(self::KEYS['phone'], self::text($details->phone)); + $this->settings->put(self::KEYS['email'], $email); + } + + private static function text(?string $value): ?string + { + $value = $value === null ? '' : trim($value); + + return $value === '' ? null : $value; + } +} diff --git a/app/Modules/Shared/Domain/Exceptions/CompanyNameRequired.php b/app/Modules/Shared/Domain/Exceptions/CompanyNameRequired.php new file mode 100644 index 0000000..81dbbf6 --- /dev/null +++ b/app/Modules/Shared/Domain/Exceptions/CompanyNameRequired.php @@ -0,0 +1,13 @@ +app->make(Kernel::class)->pushMiddleware(SetSecurityHeaders::class); + + $presentationPath = dirname(__DIR__, 2).'/Presentation'; + + Livewire::addNamespace('shared', viewPath: $presentationPath.'/Livewire'); + + if (! $this->app->routesAreCached()) { + $this->loadRoutesFrom($presentationPath.'/Routes/web.php'); + } + + // Settings, such as the company's details, are the admin's (spec 2). + Gate::define('settings.manage', fn (User $user): bool => $user->role === Role::Admin); } } diff --git a/app/Modules/Shared/Presentation/Livewire/⚡company.blade.php b/app/Modules/Shared/Presentation/Livewire/⚡company.blade.php new file mode 100644 index 0000000..e2b40b1 --- /dev/null +++ b/app/Modules/Shared/Presentation/Livewire/⚡company.blade.php @@ -0,0 +1,110 @@ +authorize('settings.manage'); + + $details = $store->get(); + + if ($details !== null) { + $this->name = $details->name; + $this->business_id = $details->businessId; + $this->address = $details->address ?? ''; + $this->phone = $details->phone ?? ''; + $this->email = $details->email ?? ''; + } + } + + public function save(CompanyDetailsStore $store): void + { + $this->authorize('settings.manage'); + $this->statusMessage = ''; + + $this->validate([ + 'name' => ['required', 'string', 'max:255'], + 'business_id' => ['required', 'string', 'max:20'], + 'address' => ['nullable', 'string', 'max:500'], + 'phone' => ['nullable', 'string', 'max:50'], + 'email' => ['nullable', 'string', 'max:255'], + ], [ + 'name.required' => __('company.errors.name'), + 'name.max' => __('company.errors.name'), + 'business_id.required' => __('company.errors.business_id'), + 'business_id.max' => __('company.errors.business_id'), + 'address.max' => __('company.errors.address'), + 'phone.max' => __('company.errors.phone'), + 'email.max' => __('company.errors.email'), + ]); + + try { + $store->save(new CompanyDetails($this->name, $this->business_id, $this->address, $this->phone, $this->email)); + } catch (CompanyNameRequired) { + $this->addError('name', __('company.errors.name')); + + return; + } catch (InvalidBusinessId) { + $this->addError('business_id', __('company.errors.business_id')); + + return; + } catch (InvalidEmailAddress) { + $this->addError('email', __('company.errors.email')); + + return; + } + + $this->business_id = (string) $store->get()?->businessId; + $this->statusMessage = __('company.saved'); + } + + public function render(): mixed + { + return $this->view()->title(__('company.title')); + } +}; +?> + +
+
+

{{ __('company.title') }}

+

{{ __('company.intro') }}

+
+ +

{{ $statusMessage }}

+ +
+ + + + + + + + +
diff --git a/app/Modules/Shared/Presentation/Routes/web.php b/app/Modules/Shared/Presentation/Routes/web.php new file mode 100644 index 0000000..91142c1 --- /dev/null +++ b/app/Modules/Shared/Presentation/Routes/web.php @@ -0,0 +1,10 @@ +prefix('settings') + ->name('settings.') + ->group(function () { + Route::livewire('/company', 'shared::company')->name('company'); + }); diff --git a/bootstrap/providers.php b/bootstrap/providers.php index d4505a5..5d3d6eb 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -4,6 +4,7 @@ use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider; use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider; use App\Modules\Expenses\Infrastructure\Providers\ExpensesServiceProvider; use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider; +use App\Modules\Sales\Infrastructure\Providers\SalesServiceProvider; use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider; use App\Modules\TimeTracking\Infrastructure\Providers\TimeTrackingServiceProvider; use App\Modules\Users\Infrastructure\Providers\UsersServiceProvider; @@ -20,4 +21,5 @@ return [ // After Jobs: replaces its TaskUsage binding. TimeTrackingServiceProvider::class, ExpensesServiceProvider::class, + SalesServiceProvider::class, ]; diff --git a/composer.json b/composer.json index f63510e..5913b5d 100644 --- a/composer.json +++ b/composer.json @@ -10,6 +10,7 @@ "license": "MIT", "require": { "php": "^8.3", + "barryvdh/laravel-dompdf": "^3.1", "laravel/framework": "^13.17", "laravel/tinker": "^3.0", "livewire/livewire": "^4.4", diff --git a/composer.lock b/composer.lock index a00760a..5a18ff6 100644 --- a/composer.lock +++ b/composer.lock @@ -4,8 +4,86 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "580c7495336bac049cf6ea6b355810d2", + "content-hash": "171928c5ac92bf93b1162a5b8413dd2a", "packages": [ + { + "name": "barryvdh/laravel-dompdf", + "version": "v3.1.2", + "source": { + "type": "git", + "url": "https://github.com/barryvdh/laravel-dompdf.git", + "reference": "ee3b72b19ccdf57d0243116ecb2b90261344dedc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/barryvdh/laravel-dompdf/zipball/ee3b72b19ccdf57d0243116ecb2b90261344dedc", + "reference": "ee3b72b19ccdf57d0243116ecb2b90261344dedc", + "shasum": "" + }, + "require": { + "dompdf/dompdf": "^3.0", + "illuminate/support": "^9|^10|^11|^12|^13.0", + "php": "^8.1" + }, + "require-dev": { + "larastan/larastan": "^2.7|^3.0", + "orchestra/testbench": "^7|^8|^9.16|^10|^11.0", + "phpro/grumphp": "^2.5", + "squizlabs/php_codesniffer": "^3.5" + }, + "type": "library", + "extra": { + "laravel": { + "aliases": { + "PDF": "Barryvdh\\DomPDF\\Facade\\Pdf", + "Pdf": "Barryvdh\\DomPDF\\Facade\\Pdf" + }, + "providers": [ + "Barryvdh\\DomPDF\\ServiceProvider" + ] + }, + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "psr-4": { + "Barryvdh\\DomPDF\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Barry vd. Heuvel", + "email": "barryvdh@gmail.com" + } + ], + "description": "A DOMPDF Wrapper for Laravel", + "keywords": [ + "dompdf", + "laravel", + "pdf" + ], + "support": { + "issues": "https://github.com/barryvdh/laravel-dompdf/issues", + "source": "https://github.com/barryvdh/laravel-dompdf/tree/v3.1.2" + }, + "funding": [ + { + "url": "https://fruitcake.nl", + "type": "custom" + }, + { + "url": "https://github.com/barryvdh", + "type": "github" + } + ], + "time": "2026-02-21T08:51:10+00:00", + "published-time": "2026-03-17T15:52:42+00:00" + }, { "name": "brick/math", "version": "1.0.0", @@ -385,6 +463,164 @@ "time": "2026-10-01T06:59:29+00:00", "published-time": "2026-10-01T07:01:28+00:00" }, + { + "name": "dompdf/dompdf", + "version": "v3.1.6", + "source": { + "type": "git", + "url": "https://github.com/dompdf/dompdf.git", + "reference": "6d4b4eb8500f7a786da8868ba463a71b725a4005" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dompdf/dompdf/zipball/6d4b4eb8500f7a786da8868ba463a71b725a4005", + "reference": "6d4b4eb8500f7a786da8868ba463a71b725a4005", + "shasum": "" + }, + "require": { + "dompdf/php-font-lib": "^1.0.0", + "dompdf/php-svg-lib": "^1.0.0", + "ext-dom": "*", + "ext-mbstring": "*", + "masterminds/html5": "^2.0", + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "ext-gd": "*", + "ext-json": "*", + "ext-zip": "*", + "mockery/mockery": "^1.3", + "phpunit/phpunit": "^7.5 || ^8 || ^9 || ^10 || ^11", + "squizlabs/php_codesniffer": "^3.5", + "symfony/process": "^4.4 || ^5.4 || ^6.2 || ^7.0" + }, + "suggest": { + "ext-gd": "Needed to process images", + "ext-gmagick": "Improves image processing performance", + "ext-imagick": "Improves image processing performance", + "ext-zlib": "Needed for pdf stream compression" + }, + "type": "library", + "autoload": { + "psr-4": { + "Dompdf\\": "src/" + }, + "classmap": [ + "lib/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1" + ], + "authors": [ + { + "name": "The Dompdf Community", + "homepage": "https://github.com/dompdf/dompdf/blob/master/AUTHORS.md" + } + ], + "description": "DOMPDF is a CSS 2.1 compliant HTML to PDF converter", + "homepage": "https://github.com/dompdf/dompdf", + "support": { + "issues": "https://github.com/dompdf/dompdf/issues", + "source": "https://github.com/dompdf/dompdf/tree/v3.1.6" + }, + "time": "2026-07-20T12:29:38+00:00", + "published-time": "2026-07-20T12:35:08+00:00" + }, + { + "name": "dompdf/php-font-lib", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/dompdf/php-font-lib.git", + "reference": "a6e9a688a2a80016ac080b97be73d3e10c444c9a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dompdf/php-font-lib/zipball/a6e9a688a2a80016ac080b97be73d3e10c444c9a", + "reference": "a6e9a688a2a80016ac080b97be73d3e10c444c9a", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "phpunit/phpunit": "^7.5 || ^8 || ^9 || ^10 || ^11 || ^12" + }, + "type": "library", + "autoload": { + "psr-4": { + "FontLib\\": "src/FontLib" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1-or-later" + ], + "authors": [ + { + "name": "The FontLib Community", + "homepage": "https://github.com/dompdf/php-font-lib/blob/master/AUTHORS.md" + } + ], + "description": "A library to read, parse, export and make subsets of different types of font files.", + "homepage": "https://github.com/dompdf/php-font-lib", + "support": { + "issues": "https://github.com/dompdf/php-font-lib/issues", + "source": "https://github.com/dompdf/php-font-lib/tree/1.0.2" + }, + "time": "2026-01-20T14:10:26+00:00", + "published-time": "2026-01-20T14:14:50+00:00" + }, + { + "name": "dompdf/php-svg-lib", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/dompdf/php-svg-lib.git", + "reference": "8259ffb930817e72b1ff1caef5d226501f3dfeb1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dompdf/php-svg-lib/zipball/8259ffb930817e72b1ff1caef5d226501f3dfeb1", + "reference": "8259ffb930817e72b1ff1caef5d226501f3dfeb1", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": "^7.1 || ^8.0", + "sabberworm/php-css-parser": "^8.4 || ^9.0" + }, + "require-dev": { + "phpunit/phpunit": "^7.5 || ^8 || ^9 || ^10 || ^11" + }, + "type": "library", + "autoload": { + "psr-4": { + "Svg\\": "src/Svg" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0-or-later" + ], + "authors": [ + { + "name": "The SvgLib Community", + "homepage": "https://github.com/dompdf/php-svg-lib/blob/master/AUTHORS.md" + } + ], + "description": "A library to read, parse and export to PDF SVG files.", + "homepage": "https://github.com/dompdf/php-svg-lib", + "support": { + "issues": "https://github.com/dompdf/php-svg-lib/issues", + "source": "https://github.com/dompdf/php-svg-lib/tree/1.0.2" + }, + "time": "2026-01-02T16:01:13+00:00", + "published-time": "2026-01-02T16:02:22+00:00" + }, { "name": "dragonmantank/cron-expression", "version": "v3.6.1", @@ -2143,6 +2379,75 @@ "time": "2026-11-21T01:02:00+00:00", "published-time": "2026-11-21T01:10:35+00:00" }, + { + "name": "masterminds/html5", + "version": "2.12.0", + "source": { + "type": "git", + "url": "https://github.com/Masterminds/html5-php.git", + "reference": "15e16663bd6f512352209d0e3a789c0a691c0d9b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Masterminds/html5-php/zipball/15e16663bd6f512352209d0e3a789c0a691c0d9b", + "reference": "15e16663bd6f512352209d0e3a789c0a691c0d9b", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-mbstring": "*", + "php": ">=7.4" + }, + "require-dev": { + "phpunit/phpunit": "^6 || ^7 || ^8 || ^9 || ^10" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.7-dev" + } + }, + "autoload": { + "psr-4": { + "Masterminds\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Matt Butcher", + "email": "technosophos@gmail.com" + }, + { + "name": "Matt Farina", + "email": "matt@mattfarina.com" + }, + { + "name": "Asmir Mustafic", + "email": "goetas@gmail.com" + } + ], + "description": "An HTML5 parser and serializer.", + "homepage": "http://masterminds.github.io/html5-php", + "keywords": [ + "HTML5", + "dom", + "html", + "parser", + "querypath", + "serializer", + "xml" + ], + "support": { + "issues": "https://github.com/Masterminds/html5-php/issues", + "source": "https://github.com/Masterminds/html5-php/tree/2.12.0" + }, + "time": "2026-10-25T08:57:58+00:00", + "published-time": "2026-10-25T08:58:48+00:00" + }, { "name": "monolog/monolog", "version": "3.13.0", @@ -3393,6 +3698,85 @@ "time": "2026-11-14T23:23:20+00:00", "published-time": "2026-11-14T23:35:39+00:00" }, + { + "name": "sabberworm/php-css-parser", + "version": "v9.5.0", + "source": { + "type": "git", + "url": "https://github.com/MyIntervals/PHP-CSS-Parser.git", + "reference": "f284e63b6e891e0c28631e54ba06c3ed102a9ef3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/MyIntervals/PHP-CSS-Parser/zipball/f284e63b6e891e0c28631e54ba06c3ed102a9ef3", + "reference": "f284e63b6e891e0c28631e54ba06c3ed102a9ef3", + "shasum": "" + }, + "require": { + "ext-iconv": "*", + "php": "^7.2.0 || ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" + }, + "require-dev": { + "php-parallel-lint/php-parallel-lint": "1.4.0", + "phpstan/extension-installer": "1.4.3", + "phpstan/phpstan": "1.12.33 || 2.2.9", + "phpstan/phpstan-phpunit": "1.4.2 || 2.0.18", + "phpstan/phpstan-strict-rules": "1.6.2 || 2.0.12", + "phpunit/phpunit": "8.5.54", + "rawr/phpunit-data-provider": "3.3.1", + "rector/rector": "1.2.10 || 2.6.2", + "rector/type-perfect": "1.0.0 || 2.1.4", + "squizlabs/php_codesniffer": "4.0.4" + }, + "suggest": { + "ext-mbstring": "for parsing UTF-8 CSS" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "9.6.x-dev" + } + }, + "autoload": { + "files": [ + "src/Rule/Rule.php", + "src/RuleSet/RuleContainer.php" + ], + "psr-4": { + "Sabberworm\\CSS\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Raphael Schweikert" + }, + { + "name": "Oliver Klee", + "email": "github@oliverklee.de" + }, + { + "name": "Jake Hotson", + "email": "jake.github@qzdesign.co.uk" + } + ], + "description": "Parser for CSS Files written in PHP", + "homepage": "https://www.sabberworm.com/blog/2010/6/10/php-css-parser", + "keywords": [ + "css", + "parser", + "stylesheet" + ], + "support": { + "issues": "https://github.com/MyIntervals/PHP-CSS-Parser/issues", + "source": "https://github.com/MyIntervals/PHP-CSS-Parser/tree/v9.5.0" + }, + "time": "2026-09-20T15:02:00+00:00", + "published-time": "2026-09-20T15:20:25+00:00" + }, { "name": "symfony/clock", "version": "v8.1.9", diff --git a/database/factories/QuickSaleFactory.php b/database/factories/QuickSaleFactory.php new file mode 100644 index 0000000..91b3007 --- /dev/null +++ b/database/factories/QuickSaleFactory.php @@ -0,0 +1,55 @@ + + */ +class QuickSaleFactory extends Factory +{ + protected $model = QuickSaleModel::class; + + /** + * @return array + */ + public function definition(): array + { + return [ + 'user_id' => User::factory(), + 'customer_id' => null, + 'payment_method' => PaymentMethod::Cash, + 'sold_at' => now(), + 'sold_on' => now(config('app.business_timezone'))->toDateString(), + 'total_cents' => 0, + 'credits_quick_sale_id' => null, + ]; + } + + /** + * Adds a line of the product and sets the sale's total. + */ + public function withLine(ProductModel $product, int $quantity = 1, int $vatBasisPoints = 2550): static + { + return $this->state(fn (): array => ['total_cents' => $quantity * $product->price_cents]) + ->afterCreating(function (QuickSaleModel $sale) use ($product, $quantity, $vatBasisPoints): void { + QuickSaleLineModel::query()->create([ + 'quick_sale_id' => $sale->id, + 'product_id' => $product->id, + 'product_name' => $product->name, + 'quantity' => $quantity, + 'unit_price_cents' => $product->price_cents, + 'vat_basis_points' => $vatBasisPoints, + 'sort_order' => 1, + ]); + }); + } +} diff --git a/database/migrations/2026_11_24_095654_add_quick_sale_year_to_customer_jobs_table.php b/database/migrations/2026_11_24_095654_add_quick_sale_year_to_customer_jobs_table.php new file mode 100644 index 0000000..19ada79 --- /dev/null +++ b/database/migrations/2026_11_24_095654_add_quick_sale_year_to_customer_jobs_table.php @@ -0,0 +1,27 @@ +unsignedSmallInteger('quick_sale_year')->nullable()->unique()->after('completed_at'); + }); + } + + public function down(): void + { + Schema::table('customer_jobs', function (Blueprint $table) { + $table->dropUnique(['quick_sale_year']); + $table->dropColumn('quick_sale_year'); + }); + } +}; diff --git a/database/migrations/2026_11_24_095655_create_quick_sales_tables.php b/database/migrations/2026_11_24_095655_create_quick_sales_tables.php new file mode 100644 index 0000000..edf72d4 --- /dev/null +++ b/database/migrations/2026_11_24_095655_create_quick_sales_tables.php @@ -0,0 +1,47 @@ +id(); + $table->foreignId('user_id')->constrained()->restrictOnDelete(); + $table->foreignId('customer_id')->nullable()->constrained()->restrictOnDelete(); + $table->string('payment_method', 10); + $table->timestamp('sold_at'); + $table->date('sold_on'); + $table->integer('total_cents'); + $table->foreignId('credits_quick_sale_id')->nullable()->unique()->constrained('quick_sales')->restrictOnDelete(); + $table->timestamps(); + + $table->index(['sold_on', 'user_id']); + }); + + Schema::create('quick_sale_lines', function (Blueprint $table) { + $table->id(); + $table->foreignId('quick_sale_id')->constrained()->cascadeOnDelete(); + $table->foreignId('product_id')->constrained()->restrictOnDelete(); + $table->string('product_name', 255); + $table->integer('quantity'); + $table->unsignedInteger('unit_price_cents'); + $table->unsignedSmallInteger('vat_basis_points'); + $table->unsignedSmallInteger('sort_order'); + }); + } + + public function down(): void + { + Schema::dropIfExists('quick_sale_lines'); + Schema::dropIfExists('quick_sales'); + } +}; diff --git a/database/migrations/2026_11_24_095656_create_cash_days_tables.php b/database/migrations/2026_11_24_095656_create_cash_days_tables.php new file mode 100644 index 0000000..c3b623f --- /dev/null +++ b/database/migrations/2026_11_24_095656_create_cash_days_tables.php @@ -0,0 +1,47 @@ +id(); + $table->date('day')->unique(); + $table->foreignId('closed_by')->nullable()->constrained('users')->restrictOnDelete(); + $table->timestamp('closed_at')->nullable(); + $table->unsignedInteger('sale_count')->default(0); + $table->integer('cash_cents')->default(0); + $table->integer('card_cents')->default(0); + $table->integer('total_cents')->default(0); + $table->foreignId('reopened_by')->nullable()->constrained('users')->restrictOnDelete(); + $table->timestamp('reopened_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('cash_day_vat_totals', function (Blueprint $table) { + $table->id(); + $table->foreignId('cash_day_id')->constrained()->cascadeOnDelete(); + $table->unsignedSmallInteger('vat_basis_points'); + $table->integer('gross_cents'); + $table->integer('net_cents'); + $table->integer('vat_cents'); + + $table->unique(['cash_day_id', 'vat_basis_points']); + }); + } + + public function down(): void + { + Schema::dropIfExists('cash_day_vat_totals'); + Schema::dropIfExists('cash_days'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index 9aa5d3b..d3cf9eb 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -214,8 +214,11 @@ Asiakastyön kenttien muutokset tallennetaan: kuka, milloin, mikä kenttä, vanh Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä (passikuvat, tulosteet, digitointi). -- Valitaan kiinteähintaiset tuotteet ja määrät; asiakas voi olla nimetön kuluttaja. -- Tuotteelle määritelty kesto kirjataan automaattisesti myyjän tunneiksi. +- Tuotteet ovat painikkeita (käytössä olevat kuluttajatuotteet, hinnat verollisina): jokainen painallus lisää myynnin listalle yhden, ja listalla määrää voi vähentää, lisätä tai rivin poistaa. Lisäksi valitaan maksutapa (käteinen / pankkikortti); asiakas voi olla nimetön kuluttaja tai valittu asiakas *(valmis)*. +- Jokaisesta myynnistä ja hyvityksestä saa **PDF-kuitin** (A5, avautuu selaimeen tulostettavaksi): yrityksen nimi, osoite ja yhteystiedot, Y-tunnus ja ALV-tunnus (FI + Y-tunnuksen numerot), kuitin numero, aika, myyjä, asiakas, maksutapa, rivit (määrä, à-hinta, ALV %, yhteensä), verollinen kokonaissumma ja ALV-laskelma kannoittain (veroton, vero, verollinen). Kuitin avaa myyjä omista myynneistään ja johto kaikista. Yritystiedot ylläpitää pääkäyttäjä valikon Yritystiedot-sivulla (`/settings/company`, asetukset `shared.company_*`). +- Tuotteelle määritelty kesto × määrä kirjataan automaattisesti myyjän tunneiksi järjestelmän vuosittaiselle asiakastyölle "Pikamyynnit VVVV" (sisäinen asiakas, ei laskutettava), työtehtäväkohtaiselle tehtävälle. Tunnit näkyvät viikkonäkymässä ja hyväksytään tavalliseen tapaan. Jos tunteja ei voi kirjata (päivän tunnit jo hyväksytty tai yli 24 h), myynti tallentuu silti ja myyjälle kerrotaan asiasta. +- Myyntiä ei poisteta. Virhe korjataan **hyvityksellä** (hyvityslaskumenettely): uusi myynti, joka viittaa alkuperäiseen, samat rivit miinusmerkkisinä ja sama maksutapa. Hyvitys kirjataan kuluvalle kassapäivälle, myynnin voi hyvittää vain kerran, ja hyvittää voi myyjä itse tai johto. Hyvitys ei muuta tunteja. +- **Kassapäivä**: päivän myynnit kirjataan yksitellen, ja kassapäivä päätetään. Päättämisestä muodostuu päivän saldo: myyntien määrä, summat maksutavoittain ja ALV-kannoittain (verollinen, veroton, vero; vero lasketaan kannan päiväsummasta). Päätettyyn päivään ei voi kirjata myyntejä. Päivän voi päättää kuka tahansa pikamyyntiä käyttävä (myös unohtuneen aiemman päivän), ja avata uudelleen vain johto, jolloin saldo muodostetaan uudelleen seuraavassa päättämisessä. Laskettua käteistä tai kassaeroa ei kirjata. - Myynnit tallentuvat laskuaineistosta erillisinä käteismyynteinä (raportit). ## 8. Tehtävät ja Kanban @@ -341,7 +344,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up - `settings` *(V2, olemassa)*: `key` (uniikki, omistajamoduulin etuliite, esim. `catalog.mileage_rate_cents`), `value` (esim. km-hinta, työajanseuranta päällä) **Jobs** (asiakastyöt) -- `customer_jobs`: `number`, `name`, `description`, `customer_id`, `starts_on`, `due_on`, `planned_from`, `planned_to`, `kind`, `status`, `priority`, `payment_basis`, `estimated_hours`, `customer_reference`, `instructions`, `responsible_user_id`, `contact_user_id`, `customer_contact_id`, `biller_user_id`, `billing_unit_id`, `created_by` *(olemassa)*; `quoted_amount_cents`, `completed_at` (asetetaan, kun työ saavuttaa lukitsevan tilan; tyhjennetään, kun lukitus avataan) *(V2, olemassa)* +- `customer_jobs`: `number`, `name`, `description`, `customer_id`, `starts_on`, `due_on`, `planned_from`, `planned_to`, `kind`, `status`, `priority`, `payment_basis`, `estimated_hours`, `customer_reference`, `instructions`, `responsible_user_id`, `contact_user_id`, `customer_contact_id`, `biller_user_id`, `billing_unit_id`, `created_by` *(olemassa)*; `quoted_amount_cents`, `completed_at` (asetetaan, kun työ saavuttaa lukitsevan tilan; tyhjennetään, kun lukitus avataan), `quick_sale_year` (uniikki; merkitsee vuoden pikamyyntityön) *(V2, olemassa)* - `job_number_sequences`: `year`, `last_number` - `customer_job_service_unit`: `customer_job_id`, `service_unit_id` - `customer_job_members`: `customer_job_id`, `user_id` @@ -364,9 +367,10 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up **Expenses** *(V2)* - `expenses` *(olemassa)*: `customer_job_id`, `user_id` (kenen kulu), `recorded_by`, `category` (`materials`/`mileage`/`other`), `paid_by` (`company`/`employee`), `spent_on`, `description`, `cost_cents` (hankintahinta), `kilometers` (decimal 7,1), `destination`, `purpose`, `is_billable`, `markup_basis_points`, `billed_amount_cents` (laskutettava summa, null jos ei laskuteta); `billing_export_id` lisätään laskutuksen osassa -**Sales** *(V2)* -- `quick_sales`: `user_id`, `customer_id` (nullable), `payment_method` (`cash`/`card`), `sold_at`, `total_cents` -- `quick_sale_lines`: `quick_sale_id`, `product_id`, `quantity`, `unit_price_cents` +**Sales** *(V2, olemassa)* +- `quick_sales`: `user_id` (myyjä), `customer_id` (nullable), `payment_method` (`cash`/`card`), `sold_at`, `sold_on` (kassapäivä yrityksen aikavyöhykkeellä), `total_cents` (verollinen, hyvityksellä negatiivinen), `credits_quick_sale_id` (nullable, uniikki: hyvitetty myynti) +- `quick_sale_lines`: `quick_sale_id`, `product_id`, `product_name`, `quantity` (hyvityksellä negatiivinen), `unit_price_cents` (verollinen), `vat_basis_points`, `sort_order` +- `cash_days`: `day` (uniikki), `closed_by`, `closed_at`, `sale_count`, `cash_cents`, `card_cents`, `total_cents`, `reopened_by`, `reopened_at`; `cash_day_vat_totals`: `cash_day_id`, `vat_basis_points`, `gross_cents`, `net_cents`, `vat_cents` **Billing** *(V2)* - `billing_exports`: `period` (kuukausi), `created_by`, `file_path` @@ -469,6 +473,10 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t - Työn lomakkeella "Budjetti / tarjoussumma (€, ALV 0)" ja työn sivulla sen arvo vain Tarjoukset-oikeudella; muutoshistorian tarjoussummarivit näytetään vain heille. - Työn sivulla "Valmistunut", kun työ on siirretty Valmis-tilaan (tai myöhempään); aika säilyy laskutustiloissa ja tyhjenee, kun johto avaa lukituksen. +### 17.6 Pikamyynti ja kassapäivä *(valmis)* +- Valikon "Pikamyynti" (`/sales/new`) puhelimelle sopiva lomake: tuotepainikkeet, myynnin lista määrineen (muutokset ja yhteissumma ilmoitetaan ruudunlukijalle), maksutapa ja vapaaehtoinen asiakas. Tallennuksen jälkeen lomake tyhjenee ja ilmoitus kertoo myynnin numeron, summan ja kirjatut tunnit sekä linkin PDF-kuittiin. Myynnit-sivulla on kuittilinkki jokaisella rivillä. +- Myynnit-sivu (`/sales?paiva=VVVV-KK-PP`): päivän myynnit (työntekijä näkee omansa, johto kaikkien ja voi suodattaa myyjän mukaan), hyvitys vahvistusdialogissa, kassapäivän tila, saldo ja ALV-erittely, päättäminen ja johdolle uudelleen avaaminen vahvistusdialogissa, muistutus päättämättömistä aiemmista päivistä. + ## 18. Avoimet kysymykset 1. ~~**Lukitus**~~: ratkaistu – vain johto avaa valmiin työn lukituksen siirtämällä työn aiempaan tilaan, ja avaus näkyy muutoshistoriassa (5.3). diff --git a/lang/fi/company.php b/lang/fi/company.php new file mode 100644 index 0000000..5193e6b --- /dev/null +++ b/lang/fi/company.php @@ -0,0 +1,24 @@ + 'Yritystiedot', + 'intro' => 'Yrityksen tiedot tulostuvat kuitteihin. Arvonlisäverotunnus muodostetaan Y-tunnuksesta.', + 'fields' => [ + 'name' => 'Yrityksen nimi', + 'business_id' => 'Y-tunnus', + 'business_id_hint' => 'Esimerkiksi 1234567-8.', + 'address' => 'Osoite', + 'address_hint' => 'Katuosoite, postinumero ja -toimipaikka omille riveilleen.', + 'phone' => 'Puhelin', + 'email' => 'Sähköposti', + ], + 'save' => 'Tallenna', + 'saved' => 'Yritystiedot tallennettu.', + 'errors' => [ + 'name' => 'Anna yrityksen nimi (enintään 255 merkkiä).', + 'business_id' => 'Anna kelvollinen Y-tunnus, esim. 1234567-8.', + 'address' => 'Osoite saa olla enintään 500 merkkiä.', + 'phone' => 'Puhelinnumero saa olla enintään 50 merkkiä.', + 'email' => 'Anna kelvollinen sähköpostiosoite.', + ], +]; diff --git a/lang/fi/layout.php b/lang/fi/layout.php index 7b6caa3..183bdd8 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -10,8 +10,10 @@ return [ 'time' => 'Tuntikirjaus', 'approvals' => 'Hyväksyntä', 'expenses' => 'Kulut', + 'quick_sale' => 'Pikamyynti', 'customers' => 'Asiakkaat', 'users' => 'Käyttäjät', + 'company' => 'Yritystiedot', 'catalog' => 'Pohjatiedot', 'prices' => 'Hinnasto', 'signed_in_as' => 'Kirjautuneena: :name', diff --git a/lang/fi/sales.php b/lang/fi/sales.php new file mode 100644 index 0000000..8a8da67 --- /dev/null +++ b/lang/fi/sales.php @@ -0,0 +1,141 @@ + 'Pikamyynnit :year', + 'hours_note' => 'Pikamyynti #:number', + 'payment_methods' => [ + 'cash' => 'Käteinen', + 'card' => 'Pankkikortti', + ], + 'sell' => [ + 'title' => 'Pikamyynti', + 'intro' => 'Käteis- ja korttimyynti kuluttajatuotteista. Hinnat sisältävät ALV:n. Tuotteiden kesto kirjataan tunneiksesi.', + 'products' => 'Tuotteet', + 'products_help' => 'Jokainen painallus lisää myyntiin yhden.', + 'add_named' => 'Lisää :product, :price / :unit', + 'cart' => 'Myynti', + 'cart_empty' => 'Myynnissä ei ole vielä tuotteita.', + 'line' => ':quantity × :price = :total', + 'line_hours' => 'Kirjaa tunneiksesi :hours h.', + 'decrease_named' => 'Vähennä yksi: :product', + 'increase_named' => 'Lisää yksi: :product', + 'remove_named' => 'Poista myynnistä: :product', + 'changed' => ':product: :quantity. Yhteensä :total.', + 'removed' => ':product poistettu. Yhteensä :total.', + 'no_products' => 'Hinnastossa ei ole käytössä olevia kuluttajatuotteita.', + 'total' => 'Yhteensä :total (sis. ALV)', + 'payment_method' => 'Maksutapa', + 'customer' => 'Asiakas (vapaaehtoinen)', + 'customer_search' => 'Hae asiakasta', + 'customer_search_description' => 'Jätä tyhjäksi, jos asiakas on nimetön kuluttaja.', + 'customer_results' => '{0} Ei asiakkaita haulla.|{1} 1 asiakas löytyi.|[2,*] :count asiakasta löytyi.', + 'choose_customer' => 'Valitse asiakas :name', + 'change_customer' => 'Poista asiakas', + 'save' => 'Kirjaa myynti', + 'saved' => 'Myynti #:number kirjattu: :total, :method.', + 'hours_booked' => 'Tunneillesi kirjattiin :hours h.', + 'hours_not_booked' => 'Tunteja (:hours h) ei voitu kirjata, koska päivän tunnit on jo hyväksytty tai päivään tulisi yli 24 h. Kirjaa ne viikkonäkymässä tai pyydä johtoa perumaan hyväksyntä.', + 'to_list' => 'Päivän myynnit ja kassapäivä', + ], + 'index' => [ + 'title' => 'Pikamyynnit', + 'day_navigation' => 'Päivän valinta', + 'previous' => 'Edellinen päivä', + 'today' => 'Tänään', + 'next' => 'Seuraava päivä', + 'new_sale' => 'Uusi myynti', + 'sales' => 'Myynnit', + 'own_only' => 'Näet omat myyntisi. Kassapäivän saldo sisältää kaikkien myynnit.', + 'seller' => 'Myyjä', + 'all_sellers' => 'Kaikki myyjät', + 'none' => 'Ei myyntejä tänä päivänä.', + 'unclosed' => 'Päättämättömiä kassapäiviä:', + ], + 'columns' => [ + 'time' => 'Aika', + 'number' => 'Numero', + 'seller' => 'Myyjä', + 'customer' => 'Asiakas', + 'products' => 'Tuotteet', + 'payment_method' => 'Maksutapa', + 'total' => 'Summa', + 'actions' => 'Toiminnot', + ], + 'anonymous' => 'Nimetön', + 'line' => ':quantity × :product à :price', + 'credit_of' => 'Hyvitys myynnille #:number', + 'credited_by' => 'Hyvitetty (#:number)', + 'credit' => 'Hyvitä', + 'credit_named' => 'Hyvitä myynti #:number', + 'credit_title' => 'Hyvitetäänkö myynti?', + 'credit_text' => 'Myynnille #:number (:total) kirjataan tälle päivälle hyvitys, jossa samat tuotteet ovat miinusmerkkisinä. Palauta raha asiakkaalle samalla maksutavalla (:method). Myynnin tunnit eivät muutu: korjaa ne tarvittaessa viikkonäkymässä.', + 'credit_confirm' => 'Kirjaa hyvitys', + 'receipt_link' => 'Kuitti', + 'receipt' => [ + 'open' => 'Avaa kuitti #:number (PDF, avautuu uuteen välilehteen)', + 'open_named' => 'Kuitti #:number (PDF, avautuu uuteen välilehteen)', + 'title' => 'Kuitti', + 'credit_title' => 'Hyvityskuitti', + 'file' => 'kuitti-:number.pdf', + 'number' => 'Kuitti nro', + 'date' => 'Päivämäärä', + 'seller' => 'Myyjä', + 'customer' => 'Asiakas', + 'payment_method' => 'Maksutapa', + 'credits' => 'Hyvittää kuitin nro :number', + 'business_id' => 'Y-tunnus', + 'vat_number' => 'ALV-tunnus', + 'product' => 'Tuote', + 'quantity' => 'Määrä', + 'unit_price' => 'À-hinta', + 'line_total' => 'Yhteensä', + 'total' => 'Yhteensä (sis. ALV)', + 'vat_heading' => 'Arvonlisävero', + 'vat_rate' => 'ALV %', + 'net' => 'Veroton', + 'vat' => 'Vero', + 'gross' => 'Verollinen', + 'thanks' => 'Kiitos käynnistä!', + 'company_missing' => 'Yrityksen tiedot puuttuvat: pääkäyttäjä täyttää ne kohdassa Yritystiedot.', + ], + 'credited' => 'Myynnille #:number kirjattiin hyvitys #:credit.', + 'cash_day' => [ + 'title' => 'Kassapäivä', + 'open' => 'Kassapäivä on avoinna.', + 'closed' => 'Kassapäivä päätetty :at (:name).', + 'reopened' => 'Avattu uudelleen :at (:name).', + 'balance' => 'Saldo', + 'preview' => 'Saldo, joka muodostuu päätettäessä', + 'sale_count' => 'Myyntejä (hyvitykset mukaan lukien)', + 'cash' => 'Käteinen', + 'card' => 'Pankkikortti', + 'total' => 'Yhteensä', + 'vat_breakdown' => 'ALV-erittely', + 'vat_rate' => 'ALV', + 'gross' => 'Verollinen', + 'net' => 'Veroton', + 'vat' => 'Vero', + 'item' => 'Erä', + 'amount' => 'Summa', + 'close' => 'Päätä kassapäivä', + 'close_title' => 'Päätetäänkö kassapäivä?', + 'close_text' => 'Päivän myynneistä muodostuu saldo, eikä päivälle voi enää kirjata myyntejä.', + 'closed_message' => 'Kassapäivä :day päätetty.', + 'reopen' => 'Avaa kassapäivä', + 'reopen_title' => 'Avataanko kassapäivä uudelleen?', + 'reopen_text' => 'Saldo poistetaan, ja se muodostetaan uudelleen, kun päivä päätetään.', + 'reopened_message' => 'Kassapäivä :day avattu uudelleen.', + ], + 'errors' => [ + 'empty' => 'Anna vähintään yhdelle tuotteelle määrä.', + 'quantity' => 'Anna määrä kokonaislukuna 0–999.', + 'product' => 'Tuote ei ole enää myynnissä. Päivitä sivu.', + 'customer' => 'Asiakasta ei löytynyt. Valitse asiakas uudelleen.', + 'day_closed' => 'Kassapäivä on päätetty; pyydä johtoa avaamaan se.', + 'already_credited' => 'Myynti on jo hyvitetty.', + 'credit_of_credit' => 'Hyvitystä ei voi hyvittää.', + 'not_found' => 'Myyntiä ei löytynyt.', + 'future' => 'Tulevaa kassapäivää ei voi päättää.', + 'not_closed' => 'Kassapäivä ei ole päätetty.', + ], +]; diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 3e3939b..2edf3c9 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -63,6 +63,10 @@ @include('partials.nav-item', ['route' => 'expenses.mine', 'pattern' => 'expenses.*', 'label' => __('layout.expenses')]) + @can('sales.use') + @include('partials.nav-item', ['route' => 'sales.sell', 'pattern' => 'sales.*', 'label' => __('layout.quick_sale')]) + @endcan + @can('jobs.manage') @include('partials.nav-item', ['route' => 'jobs.quick', 'pattern' => 'jobs.quick', 'label' => __('layout.quick_intake')]) @endcan @@ -86,6 +90,10 @@ @can('users.manage') @include('partials.nav-item', ['route' => 'users.index', 'pattern' => 'users.*', 'label' => __('layout.users')]) @endcan + + @can('settings.manage') + @include('partials.nav-item', ['route' => 'settings.company', 'pattern' => 'settings.*', 'label' => __('layout.company')]) + @endcan
diff --git a/tests/Browser/SalesAccessibilityTest.php b/tests/Browser/SalesAccessibilityTest.php new file mode 100644 index 0000000..76eda8c --- /dev/null +++ b/tests/Browser/SalesAccessibilityTest.php @@ -0,0 +1,79 @@ +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ä'); +}); diff --git a/tests/Fakes/FakeCustomerQueries.php b/tests/Fakes/FakeCustomerQueries.php index 2a606ab..7c5991d 100644 --- a/tests/Fakes/FakeCustomerQueries.php +++ b/tests/Fakes/FakeCustomerQueries.php @@ -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; diff --git a/tests/Fakes/FakeQuickSaleHours.php b/tests/Fakes/FakeQuickSaleHours.php new file mode 100644 index 0000000..57e3a3b --- /dev/null +++ b/tests/Fakes/FakeQuickSaleHours.php @@ -0,0 +1,25 @@ + 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; + } +} diff --git a/tests/Fakes/FakeQuickSaleProducts.php b/tests/Fakes/FakeQuickSaleProducts.php new file mode 100644 index 0000000..5226030 --- /dev/null +++ b/tests/Fakes/FakeQuickSaleProducts.php @@ -0,0 +1,22 @@ + */ + 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; + } +} diff --git a/tests/Fakes/InMemoryCashDayRepository.php b/tests/Fakes/InMemoryCashDayRepository.php new file mode 100644 index 0000000..4658108 --- /dev/null +++ b/tests/Fakes/InMemoryCashDayRepository.php @@ -0,0 +1,30 @@ + */ + 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); + } +} diff --git a/tests/Fakes/InMemoryCustomerJobRepository.php b/tests/Fakes/InMemoryCustomerJobRepository.php index 15d5848..90868a3 100644 --- a/tests/Fakes/InMemoryCustomerJobRepository.php +++ b/tests/Fakes/InMemoryCustomerJobRepository.php @@ -37,6 +37,19 @@ class InMemoryCustomerJobRepository implements CustomerJobRepository, JobNumberS return clone $this->jobs[$id]; } + /** @var array 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) { diff --git a/tests/Fakes/InMemoryCustomerRepository.php b/tests/Fakes/InMemoryCustomerRepository.php index d9546dd..888a299 100644 --- a/tests/Fakes/InMemoryCustomerRepository.php +++ b/tests/Fakes/InMemoryCustomerRepository.php @@ -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 { diff --git a/tests/Fakes/InMemoryQuickSaleRepository.php b/tests/Fakes/InMemoryQuickSaleRepository.php new file mode 100644 index 0000000..d1d2687 --- /dev/null +++ b/tests/Fakes/InMemoryQuickSaleRepository.php @@ -0,0 +1,52 @@ + */ + 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'))); + } +} diff --git a/tests/Fakes/InMemoryTaskRepository.php b/tests/Fakes/InMemoryTaskRepository.php index 007ae0c..4fbacf8 100644 --- a/tests/Fakes/InMemoryTaskRepository.php +++ b/tests/Fakes/InMemoryTaskRepository.php @@ -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++; diff --git a/tests/Feature/Modules/Customers/EloquentCustomerRepositoryTest.php b/tests/Feature/Modules/Customers/EloquentCustomerRepositoryTest.php index d329150..28e4403 100644 --- a/tests/Feature/Modules/Customers/EloquentCustomerRepositoryTest.php +++ b/tests/Feature/Modules/Customers/EloquentCustomerRepositoryTest.php @@ -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); diff --git a/tests/Feature/Modules/Sales/QuickSalesTest.php b/tests/Feature/Modules/Sales/QuickSalesTest.php new file mode 100644 index 0000000..84d4b84 --- /dev/null +++ b/tests/Feature/Modules/Sales/QuickSalesTest.php @@ -0,0 +1,271 @@ +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', 'info@example.fi')); + 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
', '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); +}); diff --git a/tests/Feature/Modules/Shared/CompanyDetailsTest.php b/tests/Feature/Modules/Shared/CompanyDetailsTest.php new file mode 100644 index 0000000..99dd69d --- /dev/null +++ b/tests/Feature/Modules/Shared/CompanyDetailsTest.php @@ -0,0 +1,53 @@ +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', 'INFO@example.fi') + ->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('info@example.fi') + ->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(); +}); diff --git a/tests/Unit/Modules/Customers/Application/RegisterCustomerTest.php b/tests/Unit/Modules/Customers/Application/RegisterCustomerTest.php index 143cc6d..5234ebc 100644 --- a/tests/Unit/Modules/Customers/Application/RegisterCustomerTest.php +++ b/tests/Unit/Modules/Customers/Application/RegisterCustomerTest.php @@ -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; diff --git a/tests/Unit/Modules/Customers/Application/UpdateCustomerTest.php b/tests/Unit/Modules/Customers/Application/UpdateCustomerTest.php index 84160e6..d754d2b 100644 --- a/tests/Unit/Modules/Customers/Application/UpdateCustomerTest.php +++ b/tests/Unit/Modules/Customers/Application/UpdateCustomerTest.php @@ -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; diff --git a/tests/Unit/Modules/Customers/Domain/CustomerTest.php b/tests/Unit/Modules/Customers/Domain/CustomerTest.php index a2cc62f..3ece4fe 100644 --- a/tests/Unit/Modules/Customers/Domain/CustomerTest.php +++ b/tests/Unit/Modules/Customers/Domain/CustomerTest.php @@ -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')); diff --git a/tests/Unit/Modules/Sales/QuickSaleTest.php b/tests/Unit/Modules/Sales/QuickSaleTest.php new file mode 100644 index 0000000..0cc6df6 --- /dev/null +++ b/tests/Unit/Modules/Sales/QuickSaleTest.php @@ -0,0 +1,164 @@ +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()); +}); diff --git a/tests/Unit/Modules/Customers/Domain/BusinessIdTest.php b/tests/Unit/Modules/Shared/BusinessIdTest.php similarity index 89% rename from tests/Unit/Modules/Customers/Domain/BusinessIdTest.php rename to tests/Unit/Modules/Shared/BusinessIdTest.php index ba3c328..94827fc 100644 --- a/tests/Unit/Modules/Customers/Domain/BusinessIdTest.php +++ b/tests/Unit/Modules/Shared/BusinessIdTest.php @@ -1,7 +1,7 @@ value)->toBe($expected);