Add quick sales with cash days, credits and PDF receipts
Quick sales (pikamyynti) of active consumer products at the counter, in a new Sales module: - Product buttons add one to the sale's list per press; quantities can be lowered, raised or removed. Payment by cash or card, optional customer. - Product durations are booked as the seller's hours on the yearly "Pikamyynnit" job (internal customer, not billed) through Jobs' ProvideQuickSaleTask and TimeTracking's AddTaskHours. The sale stands even when the hours cannot be booked, and the seller is told. - Sales are never deleted: a credit records the lines negated on today's cash day, once per sale, by the seller or management. - Closing a cash day stores its balance by payment method and VAT rate and stops sales on it; only management reopens a day. - A printable A5 PDF receipt (barryvdh/laravel-dompdf) with the company's details, business ID, VAT number, lines and VAT breakdown. Company details are kept in the settings and edited by the admin only on the new Yritystiedot page. BusinessId moves from Customers to Shared so both use the same check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -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: `<x-input>`, `<x-button>`), 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: `<x-input>`, `<x-button>`), 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` (`<module>::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`.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
+7
@@ -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;
|
||||
|
||||
+1
-1
@@ -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
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Application\UseCases;
|
||||
|
||||
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
|
||||
use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
|
||||
use App\Modules\Jobs\Domain\Contracts\JobNumberSequence;
|
||||
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
|
||||
use App\Modules\Jobs\Domain\Entities\CustomerJob;
|
||||
use App\Modules\Jobs\Domain\Entities\Task;
|
||||
use App\Modules\Jobs\Domain\Enums\JobKind;
|
||||
use App\Modules\Jobs\Domain\Enums\JobStatus;
|
||||
use App\Modules\Jobs\Domain\Enums\PaymentBasis;
|
||||
use App\Modules\Jobs\Domain\Enums\Priority;
|
||||
use App\Modules\Jobs\Domain\Enums\TaskStatus;
|
||||
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\FieldChange;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\JobDetails;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\JobName;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use LogicException;
|
||||
|
||||
/**
|
||||
* The task that quick sale hours of a work type are booked on. Hours of
|
||||
* quick sales go on one system job per year (on the internal customer, not
|
||||
* billed), which is opened on the year's first sale; each work type gets
|
||||
* its own task, and the job gets the work type's service unit.
|
||||
*/
|
||||
final class ProvideQuickSaleTask
|
||||
{
|
||||
public function __construct(
|
||||
private CustomerJobRepository $jobs,
|
||||
private JobNumberSequence $numbers,
|
||||
private TaskRepository $tasks,
|
||||
private CatalogQueries $catalog,
|
||||
private CustomerQueries $customers,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param string $jobName The name for a new job, e.g. "Pikamyynnit 2026".
|
||||
* @return int The task's id.
|
||||
*
|
||||
* @throws InvalidTaskReference When the work type does not exist.
|
||||
*/
|
||||
public function execute(int $year, int $workTypeId, int $actorUserId, string $jobName): int
|
||||
{
|
||||
$workType = $this->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;
|
||||
}
|
||||
}
|
||||
@@ -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<FieldChange> $changes
|
||||
*/
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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',
|
||||
|
||||
+12
@@ -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();
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\Contracts;
|
||||
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Books the hours of a quick sale on the seller, on the year's quick sale
|
||||
* job. Implemented with the Jobs and TimeTracking modules.
|
||||
*/
|
||||
interface QuickSaleHours
|
||||
{
|
||||
/**
|
||||
* Adds the hours to the seller's day on the work type's task.
|
||||
*
|
||||
* @return bool False when the hours could not be booked, e.g. the
|
||||
* day's hours are already approved or would pass 24 hours.
|
||||
*/
|
||||
public function book(int $sellerId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $saleId): bool;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\Contracts;
|
||||
|
||||
use App\Modules\Sales\Application\DTOs\SellableProduct;
|
||||
|
||||
/**
|
||||
* The products that can be sold at the counter: active consumer products
|
||||
* of the price list. Implemented with the Catalog module's queries.
|
||||
*/
|
||||
interface QuickSaleProducts
|
||||
{
|
||||
/**
|
||||
* @return list<SellableProduct> In price list order.
|
||||
*/
|
||||
public function sellable(): array;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\Contracts;
|
||||
|
||||
use App\Modules\Sales\Application\DTOs\CashDaySummary;
|
||||
use App\Modules\Sales\Application\DTOs\QuickSaleSummary;
|
||||
|
||||
interface QuickSaleQueries
|
||||
{
|
||||
/**
|
||||
* The day's sales and credits, latest first; only the seller's when given.
|
||||
*
|
||||
* @param string $day Y-m-d
|
||||
* @return list<QuickSaleSummary>
|
||||
*/
|
||||
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<string> Y-m-d
|
||||
*/
|
||||
public function unclosedDaysBefore(string $day): array;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
use App\Modules\Sales\Domain\ValueObjects\CashDayBalance;
|
||||
|
||||
/**
|
||||
* A cash day's state. The balance is the stored one of a closed day and
|
||||
* the balance that closing would form on an open day. Times are
|
||||
* "Y-m-d H:i" in the company's time zone.
|
||||
*/
|
||||
final readonly class CashDaySummary
|
||||
{
|
||||
public function __construct(
|
||||
public string $day,
|
||||
public bool $isClosed,
|
||||
public CashDayBalance $balance,
|
||||
public ?string $closedByName = null,
|
||||
public ?string $closedAt = null,
|
||||
public ?string $reopenedByName = null,
|
||||
public ?string $reopenedAt = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
final readonly class QuickSaleLineSummary
|
||||
{
|
||||
public function __construct(
|
||||
public string $productName,
|
||||
public int $quantity,
|
||||
public int $unitPriceCents,
|
||||
public int $totalCents,
|
||||
public int $vatBasisPoints = 0,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use App\Modules\Sales\Domain\ValueObjects\VatTotal;
|
||||
|
||||
/**
|
||||
* A quick sale as listed: amounts with VAT, negative on a credit.
|
||||
* $soldAt is "Y-m-d H:i" in the company's time zone. $creditsSaleId is set
|
||||
* on a credit, $creditedBySaleId on a sale that has been credited.
|
||||
*/
|
||||
final readonly class QuickSaleSummary
|
||||
{
|
||||
/**
|
||||
* @param list<QuickSaleLineSummary> $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<VatTotal>
|
||||
*/
|
||||
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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
/**
|
||||
* Input for a quick sale: quantities by product id (zero or empty ones are
|
||||
* left out by the caller), the payment method key and an optional customer.
|
||||
*/
|
||||
final readonly class SaleData
|
||||
{
|
||||
/**
|
||||
* @param array<int, int> $quantities
|
||||
*/
|
||||
public function __construct(
|
||||
public array $quantities,
|
||||
public string $paymentMethod,
|
||||
public ?int $customerId = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A recorded quick sale: its id and total with VAT, and the hours booked
|
||||
* on the seller or left unbooked (in quarters of an hour).
|
||||
*/
|
||||
final readonly class SaleResult
|
||||
{
|
||||
public function __construct(
|
||||
public int $saleId,
|
||||
public int $totalCents,
|
||||
public int $bookedQuarters,
|
||||
public int $unbookedQuarters,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A consumer product as it is sold: its price with VAT and the hours its
|
||||
* sale books on the seller ($durationQuarters on $workTypeId). $unit is
|
||||
* the price list unit key, e.g. "piece".
|
||||
*/
|
||||
final readonly class SellableProduct
|
||||
{
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public string $name,
|
||||
public string $unit,
|
||||
public int $grossCents,
|
||||
public int $vatBasisPoints,
|
||||
public int $durationQuarters,
|
||||
public ?int $workTypeId,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\UseCases;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayInFuture;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Closes a cash day (today or a forgotten earlier one) and stores the
|
||||
* balance of its quick sales.
|
||||
*/
|
||||
final class CloseCashDay
|
||||
{
|
||||
public function __construct(
|
||||
private CashDayRepository $cashDays,
|
||||
private QuickSaleRepository $sales,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws CashDayInFuture
|
||||
* @throws CashDayClosed
|
||||
*/
|
||||
public function execute(DateTimeImmutable $day, int $actorUserId): void
|
||||
{
|
||||
if ($day->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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\UseCases;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Domain\Entities\QuickSale;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CreditCannotBeCredited;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleAlreadyCredited;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleNotFound;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
|
||||
/**
|
||||
* Credits a quick sale (hyvitys): records the sale's lines negated on
|
||||
* today's cash day, so a sale of a closed day can be credited too. Hours
|
||||
* stay as they are: the work was done, and a wrong amount is corrected in
|
||||
* the weekly view. Who may credit is checked by the caller.
|
||||
*/
|
||||
final class CreditQuickSale
|
||||
{
|
||||
public function __construct(
|
||||
private QuickSaleRepository $sales,
|
||||
private CashDayRepository $cashDays,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return int The credit's id.
|
||||
*
|
||||
* @throws QuickSaleNotFound
|
||||
* @throws QuickSaleAlreadyCredited
|
||||
* @throws CreditCannotBeCredited
|
||||
* @throws CashDayClosed
|
||||
*/
|
||||
public function execute(int $saleId, int $actorUserId): int
|
||||
{
|
||||
$today = $this->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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\UseCases;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayNotClosed;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Reopens a closed cash day (management only, checked by the caller). The
|
||||
* balance is formed again when the day is closed again.
|
||||
*/
|
||||
final class ReopenCashDay
|
||||
{
|
||||
public function __construct(
|
||||
private CashDayRepository $cashDays,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws CashDayNotClosed
|
||||
*/
|
||||
public function execute(DateTimeImmutable $day, int $actorUserId): void
|
||||
{
|
||||
$this->transactions->run(function () use ($day, $actorUserId): void {
|
||||
$cashDay = $this->cashDays->lockForDay($day);
|
||||
$cashDay->reopen($actorUserId, $this->clock->now());
|
||||
$this->cashDays->save($cashDay);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\UseCases;
|
||||
|
||||
use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleHours;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
|
||||
use App\Modules\Sales\Application\DTOs\SaleData;
|
||||
use App\Modules\Sales\Application\DTOs\SaleResult;
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Domain\Entities\QuickSale;
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\InvalidQuantity;
|
||||
use App\Modules\Sales\Domain\Exceptions\ProductNotSellable;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
|
||||
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
|
||||
/**
|
||||
* Records a quick sale on today's cash day with the products' current
|
||||
* prices, and books the products' durations as the seller's hours. The
|
||||
* customer has paid, so the sale is kept even when the hours cannot be
|
||||
* booked; the result tells how many were left out.
|
||||
*/
|
||||
final class SellQuickSale
|
||||
{
|
||||
public function __construct(
|
||||
private QuickSaleRepository $sales,
|
||||
private CashDayRepository $cashDays,
|
||||
private QuickSaleProducts $products,
|
||||
private QuickSaleHours $hours,
|
||||
private CustomerQueries $customers,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws ProductNotSellable
|
||||
* @throws InvalidQuantity
|
||||
* @throws QuickSaleEmpty
|
||||
* @throws QuickSaleCustomerNotFound
|
||||
* @throws CashDayClosed
|
||||
*/
|
||||
public function execute(int $sellerId, SaleData $data): SaleResult
|
||||
{
|
||||
$sellable = [];
|
||||
foreach ($this->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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Contracts;
|
||||
|
||||
use App\Modules\Sales\Domain\Entities\CashDay;
|
||||
use DateTimeImmutable;
|
||||
|
||||
interface CashDayRepository
|
||||
{
|
||||
/**
|
||||
* The stored cash day, or an open one when the day has not been closed yet.
|
||||
*/
|
||||
public function forDay(DateTimeImmutable $day): CashDay;
|
||||
|
||||
/**
|
||||
* Stores the day's state and balance.
|
||||
*/
|
||||
public function save(CashDay $cashDay): CashDay;
|
||||
|
||||
/**
|
||||
* The day, stored if it was not, with its row locked until the
|
||||
* transaction ends, so a sale and the closing of the same day cannot
|
||||
* interleave.
|
||||
*/
|
||||
public function lockForDay(DateTimeImmutable $day): CashDay;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Contracts;
|
||||
|
||||
use App\Modules\Sales\Domain\Entities\QuickSale;
|
||||
use DateTimeImmutable;
|
||||
|
||||
interface QuickSaleRepository
|
||||
{
|
||||
public function findById(int $id): ?QuickSale;
|
||||
|
||||
/**
|
||||
* Inserts a new sale with its lines and returns the stored sale.
|
||||
*/
|
||||
public function add(QuickSale $sale): QuickSale;
|
||||
|
||||
public function isCredited(int $saleId): bool;
|
||||
|
||||
/**
|
||||
* The cash day's sales, credits included.
|
||||
*
|
||||
* @return list<QuickSale>
|
||||
*/
|
||||
public function forDay(DateTimeImmutable $day): array;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Entities;
|
||||
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayNotClosed;
|
||||
use App\Modules\Sales\Domain\ValueObjects\CashDayBalance;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* A day of quick sales at the counter (kassapäivä). Closing it forms the
|
||||
* day's balance and stops further sales on it; management may reopen it,
|
||||
* which empties the balance until it is closed again.
|
||||
*/
|
||||
final class CashDay
|
||||
{
|
||||
private function __construct(
|
||||
private ?int $id,
|
||||
private DateTimeImmutable $day,
|
||||
private ?CashDayBalance $balance,
|
||||
private ?int $closedBy,
|
||||
private ?DateTimeImmutable $closedAt,
|
||||
private ?int $reopenedBy,
|
||||
private ?DateTimeImmutable $reopenedAt,
|
||||
) {}
|
||||
|
||||
public static function open(DateTimeImmutable $day): self
|
||||
{
|
||||
return new self(null, $day, null, null, null, null, null);
|
||||
}
|
||||
|
||||
public static function reconstitute(int $id, DateTimeImmutable $day, ?CashDayBalance $balance, ?int $closedBy, ?DateTimeImmutable $closedAt, ?int $reopenedBy, ?DateTimeImmutable $reopenedAt): self
|
||||
{
|
||||
return new self($id, $day, $balance, $closedBy, $closedAt, $reopenedBy, $reopenedAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<QuickSale> $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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Entities;
|
||||
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use App\Modules\Sales\Domain\Exceptions\CreditCannotBeCredited;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
|
||||
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* A cash or card sale of consumer products at the counter (pikamyynti),
|
||||
* possibly to a named customer. A sale is never deleted: a mistake is
|
||||
* corrected with a credit, a sale of its own with the original's lines
|
||||
* negated, paid back the same way and booked on the day it is made.
|
||||
*/
|
||||
final class QuickSale
|
||||
{
|
||||
/**
|
||||
* @param list<QuickSaleLine> $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<QuickSaleLine> $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<QuickSaleLine> $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<QuickSaleLine>
|
||||
*/
|
||||
public function lines(): array
|
||||
{
|
||||
return $this->lines;
|
||||
}
|
||||
|
||||
public function creditsSaleId(): ?int
|
||||
{
|
||||
return $this->creditsSaleId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Enums;
|
||||
|
||||
/**
|
||||
* How a quick sale was paid at the counter.
|
||||
*/
|
||||
enum PaymentMethod: string
|
||||
{
|
||||
case Cash = 'cash';
|
||||
case Card = 'card';
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class CashDayClosed extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The cash day is closed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class CashDayInFuture extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A cash day in the future cannot be closed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class CashDayNotClosed extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The cash day is not closed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class CreditCannotBeCredited extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A credit cannot be credited.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidQuantity extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A quantity must be a whole number from 1 to 999.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class ProductNotSellable extends DomainException
|
||||
{
|
||||
public function __construct(public readonly int $id)
|
||||
{
|
||||
parent::__construct("Product {$id} is not an active consumer product.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class QuickSaleAlreadyCredited extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The quick sale has already been credited.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class QuickSaleCustomerNotFound extends DomainException
|
||||
{
|
||||
public function __construct(public readonly int $id)
|
||||
{
|
||||
parent::__construct("Customer {$id} was not found.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class QuickSaleEmpty extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A quick sale needs at least one product.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class QuickSaleNotFound extends DomainException
|
||||
{
|
||||
public function __construct(public readonly int $id)
|
||||
{
|
||||
parent::__construct("Quick sale {$id} was not found.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Sales\Domain\Entities\QuickSale;
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
|
||||
/**
|
||||
* The balance of a cash day's quick sales: how many, how much by payment
|
||||
* method and by VAT rate (highest rate first). Credits are included as
|
||||
* negative amounts.
|
||||
*/
|
||||
final readonly class CashDayBalance
|
||||
{
|
||||
/**
|
||||
* @param list<VatTotal> $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<QuickSale> $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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Sales\Domain\Exceptions\InvalidQuantity;
|
||||
|
||||
/**
|
||||
* One product on a quick sale. The name, price (with VAT) and VAT rate are
|
||||
* copied from the price list when sold, so later price changes do not
|
||||
* change the sale. A credit line has a negative quantity.
|
||||
*/
|
||||
final readonly class QuickSaleLine
|
||||
{
|
||||
public const int MAX_QUANTITY = 999;
|
||||
|
||||
public function __construct(
|
||||
public int $productId,
|
||||
public string $productName,
|
||||
public int $quantity,
|
||||
public int $unitPriceCents,
|
||||
public int $vatBasisPoints,
|
||||
) {
|
||||
if ($quantity === 0 || abs($quantity) > 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Shared\Domain\ValueObjects\Money;
|
||||
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
|
||||
|
||||
/**
|
||||
* A cash day's sales of one VAT rate: with VAT, without VAT and the VAT.
|
||||
* The VAT is taken out of the day's total of the rate, not line by line,
|
||||
* as on a till report. Credits make amounts negative.
|
||||
*/
|
||||
final readonly class VatTotal
|
||||
{
|
||||
public function __construct(
|
||||
public int $vatBasisPoints,
|
||||
public int $grossCents,
|
||||
public int $netCents,
|
||||
public int $vatCents,
|
||||
) {}
|
||||
|
||||
public static function ofGross(int $vatBasisPoints, int $grossCents): self
|
||||
{
|
||||
$net = Money::fromCents(abs($grossCents))->removeVat(new VatPercentage($vatBasisPoints))->cents;
|
||||
$net = $grossCents < 0 ? -$net : $net;
|
||||
|
||||
return new self($vatBasisPoints, $grossCents, $net, $grossCents - $net);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure;
|
||||
|
||||
use App\Modules\Jobs\Application\UseCases\ProvideQuickSaleTask;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleHours;
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
use App\Modules\TimeTracking\Application\UseCases\AddTaskHours;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Books quick sale hours with the Jobs module's yearly quick sale job and
|
||||
* the TimeTracking module's task booking, so they are the seller's usual
|
||||
* hours: in the weekly view, within 24 hours a day, approved as usual.
|
||||
*/
|
||||
class HoursForQuickSales implements QuickSaleHours
|
||||
{
|
||||
public function __construct(
|
||||
private ProvideQuickSaleTask $tasks,
|
||||
private AddTaskHours $addHours,
|
||||
) {}
|
||||
|
||||
public function book(int $sellerId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $saleId): bool
|
||||
{
|
||||
$year = (int) $day->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Sales Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property string $day Y-m-d
|
||||
* @property int|null $closed_by
|
||||
* @property Carbon|null $closed_at
|
||||
* @property int $sale_count
|
||||
* @property int $cash_cents
|
||||
* @property int $card_cents
|
||||
* @property int $total_cents
|
||||
* @property int|null $reopened_by
|
||||
* @property Carbon|null $reopened_at
|
||||
*/
|
||||
#[Table('cash_days')]
|
||||
#[Fillable(['day', 'closed_by', 'closed_at', 'sale_count', 'cash_cents', 'card_cents', 'total_cents', 'reopened_by', 'reopened_at'])]
|
||||
class CashDayModel extends Model
|
||||
{
|
||||
/**
|
||||
* @return HasMany<CashDayVatTotalModel, $this>
|
||||
*/
|
||||
public function vatTotals(): HasMany
|
||||
{
|
||||
return $this->hasMany(CashDayVatTotalModel::class, 'cash_day_id')->orderByDesc('vat_basis_points');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Sales Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $cash_day_id
|
||||
* @property int $vat_basis_points
|
||||
* @property int $gross_cents
|
||||
* @property int $net_cents
|
||||
* @property int $vat_cents
|
||||
*/
|
||||
#[Table('cash_day_vat_totals')]
|
||||
#[Fillable(['cash_day_id', 'vat_basis_points', 'gross_cents', 'net_cents', 'vat_cents'])]
|
||||
class CashDayVatTotalModel extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'cash_day_id' => 'integer',
|
||||
'vat_basis_points' => 'integer',
|
||||
'gross_cents' => 'integer',
|
||||
'net_cents' => 'integer',
|
||||
'vat_cents' => 'integer',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Sales Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $quick_sale_id
|
||||
* @property int $product_id
|
||||
* @property string $product_name
|
||||
* @property int $quantity
|
||||
* @property int $unit_price_cents
|
||||
* @property int $vat_basis_points
|
||||
* @property int $sort_order
|
||||
*/
|
||||
#[Table('quick_sale_lines')]
|
||||
#[Fillable(['quick_sale_id', 'product_id', 'product_name', 'quantity', 'unit_price_cents', 'vat_basis_points', 'sort_order'])]
|
||||
class QuickSaleLineModel extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use Database\Factories\QuickSaleFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Attributes\UseFactory;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Sales Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $user_id
|
||||
* @property int|null $customer_id
|
||||
* @property PaymentMethod $payment_method
|
||||
* @property Carbon $sold_at
|
||||
* @property string $sold_on Y-m-d
|
||||
* @property int $total_cents
|
||||
* @property int|null $credits_quick_sale_id
|
||||
*/
|
||||
#[Table('quick_sales')]
|
||||
#[Fillable(['user_id', 'customer_id', 'payment_method', 'sold_at', 'sold_on', 'total_cents', 'credits_quick_sale_id'])]
|
||||
#[UseFactory(QuickSaleFactory::class)]
|
||||
class QuickSaleModel extends Model
|
||||
{
|
||||
/** @use HasFactory<QuickSaleFactory> */
|
||||
use HasFactory;
|
||||
|
||||
/**
|
||||
* @return HasMany<QuickSaleLineModel, $this>
|
||||
*/
|
||||
public function lines(): HasMany
|
||||
{
|
||||
return $this->hasMany(QuickSaleLineModel::class, 'quick_sale_id')->orderBy('sort_order');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasOne<QuickSaleModel, $this>
|
||||
*/
|
||||
public function credit(): HasOne
|
||||
{
|
||||
return $this->hasOne(QuickSaleModel::class, 'credits_quick_sale_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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',
|
||||
];
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Entities\CashDay;
|
||||
use App\Modules\Sales\Domain\ValueObjects\CashDayBalance;
|
||||
use App\Modules\Sales\Domain\ValueObjects\VatTotal;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\CashDayModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\CashDayVatTotalModel;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class EloquentCashDayRepository implements CashDayRepository
|
||||
{
|
||||
public function forDay(DateTimeImmutable $day): CashDay
|
||||
{
|
||||
$model = CashDayModel::query()->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),
|
||||
);
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
|
||||
use App\Modules\Sales\Application\DTOs\CashDaySummary;
|
||||
use App\Modules\Sales\Application\DTOs\QuickSaleLineSummary;
|
||||
use App\Modules\Sales\Application\DTOs\QuickSaleSummary;
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Domain\ValueObjects\CashDayBalance;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\CashDayModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleLineModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class EloquentQuickSaleQueries implements QuickSaleQueries
|
||||
{
|
||||
public function __construct(
|
||||
private CashDayRepository $cashDays,
|
||||
private QuickSaleRepository $sales,
|
||||
private UserAccountQueries $users,
|
||||
private CustomerQueries $customers,
|
||||
) {}
|
||||
|
||||
public function salesOn(string $day, ?int $sellerId = null): array
|
||||
{
|
||||
$models = QuickSaleModel::query()
|
||||
->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<int, QuickSaleModel> $models
|
||||
* @return list<QuickSaleSummary>
|
||||
*/
|
||||
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');
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Domain\Entities\QuickSale;
|
||||
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleLineModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class EloquentQuickSaleRepository implements QuickSaleRepository
|
||||
{
|
||||
public function findById(int $id): ?QuickSale
|
||||
{
|
||||
$model = QuickSaleModel::query()->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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure;
|
||||
|
||||
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
|
||||
use App\Modules\Catalog\Application\DTOs\ProductSummary;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
|
||||
use App\Modules\Sales\Application\DTOs\SellableProduct;
|
||||
|
||||
/**
|
||||
* Sellable products from the Catalog module's price list: its active
|
||||
* consumer products, whose prices are stored with VAT.
|
||||
*/
|
||||
class ProductsFromPriceList implements QuickSaleProducts
|
||||
{
|
||||
public function __construct(private PriceListQueries $priceList) {}
|
||||
|
||||
public function sellable(): array
|
||||
{
|
||||
return array_map(fn (ProductSummary $product): SellableProduct => new SellableProduct(
|
||||
$product->id,
|
||||
$product->name,
|
||||
$product->unit->value,
|
||||
$product->grossCents,
|
||||
$product->vatBasisPoints,
|
||||
$product->durationQuarters,
|
||||
$product->workTypeId,
|
||||
), $this->priceList->consumerProducts());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Providers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleHours;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Infrastructure\HoursForQuickSales;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentCashDayRepository;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleQueries;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleRepository;
|
||||
use App\Modules\Sales\Infrastructure\ProductsFromPriceList;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Livewire\Livewire;
|
||||
|
||||
/**
|
||||
* Wires the Sales module (quick sales at the counter and cash days) into
|
||||
* Laravel: bindings, routes, the `sales::` Livewire namespace and the
|
||||
* `sales.*` abilities.
|
||||
*/
|
||||
class SalesServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Presentation\Http\Controllers;
|
||||
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
|
||||
use App\Modules\Shared\Application\UseCases\CompanyDetailsStore;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* The printable PDF receipt of a quick sale or credit, opened in the
|
||||
* browser: the company's details, the lines, the total and the VAT by
|
||||
* rate. Sellers open their own sales' receipts, management anyone's.
|
||||
*/
|
||||
class ShowReceipt
|
||||
{
|
||||
public function __invoke(int $sale, QuickSaleQueries $sales, CompanyDetailsStore $company): Response
|
||||
{
|
||||
$summary = $sales->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]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Presentation\Livewire\Concerns;
|
||||
|
||||
use App\Modules\Shared\Domain\ValueObjects\Money;
|
||||
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Formatting shared by the quick sale pages. Amounts of credits are
|
||||
* negative, which Money does not hold, so the sign is added here.
|
||||
*/
|
||||
trait FormatsSales
|
||||
{
|
||||
public function money(int $cents): string
|
||||
{
|
||||
return ($cents < 0 ? '-' : '').Money::fromCents(abs($cents))->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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
|
||||
use App\Modules\Sales\Application\DTOs\CashDaySummary;
|
||||
use App\Modules\Sales\Application\DTOs\QuickSaleSummary;
|
||||
use App\Modules\Sales\Application\UseCases\CloseCashDay;
|
||||
use App\Modules\Sales\Application\UseCases\CreditQuickSale;
|
||||
use App\Modules\Sales\Application\UseCases\ReopenCashDay;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayInFuture;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayNotClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CreditCannotBeCredited;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleAlreadyCredited;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleNotFound;
|
||||
use App\Modules\Sales\Presentation\Livewire\Concerns\FormatsSales;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use App\Modules\Users\Application\DTOs\UserOption;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Attributes\Url;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* A day's quick sales and its cash day (kassapäivä). Sellers see their own
|
||||
* sales, management everyone's. Anyone selling may close the day, which
|
||||
* forms its balance; management may reopen it. Sales are credited, never
|
||||
* deleted.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use FormatsSales;
|
||||
|
||||
/**
|
||||
* The day shown (Y-m-d). Read from the URL on mount and then changed
|
||||
* only by showDay(), so the browser cannot set it.
|
||||
*/
|
||||
#[Locked]
|
||||
#[Url(as: 'paiva', except: '')]
|
||||
public string $day = '';
|
||||
|
||||
/**
|
||||
* Management's seller filter: a user id, or empty for everyone.
|
||||
*/
|
||||
public string $seller = '';
|
||||
|
||||
#[Locked]
|
||||
public ?int $creditSaleId = null;
|
||||
|
||||
#[Locked]
|
||||
public string $statusMessage = '';
|
||||
|
||||
public function mount(Clock $clock): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
|
||||
$this->day = $this->parseDay($this->day)?->format('Y-m-d') ?? $clock->today()->format('Y-m-d');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<QuickSaleSummary>
|
||||
*/
|
||||
#[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<string>
|
||||
*/
|
||||
#[Computed]
|
||||
public function unclosedDays(): array
|
||||
{
|
||||
return app(QuickSaleQueries::class)->unclosedDaysBefore(app(Clock::class)->today()->format('Y-m-d'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<UserOption>
|
||||
*/
|
||||
#[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<array{index: string, label: string, sortable: bool, align?: string}>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
|
||||
<div class="space-y-2">
|
||||
<h1 class="text-2xl font-semibold">{{ __('sales.index.title') }}</h1>
|
||||
<p>
|
||||
<x-button :href="route('sales.sell')" wire:navigate icon="plus" :text="__('sales.index.new_sale')" />
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<nav aria-label="{{ __('sales.index.day_navigation') }}" class="flex flex-wrap items-center gap-2">
|
||||
<x-button wire:click="showDay('previous')" subtle color="black" sm icon="chevron-left" :text="__('sales.index.previous')" />
|
||||
<x-button wire:click="showDay('today')" subtle color="black" sm :text="__('sales.index.today')" />
|
||||
<x-button wire:click="showDay('next')" subtle color="black" sm icon="chevron-right" position="right" :text="__('sales.index.next')" />
|
||||
</nav>
|
||||
|
||||
<p id="sales-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $statusMessage }}</p>
|
||||
|
||||
@if ($this->unclosedDays !== [])
|
||||
<div class="rounded-lg border border-amber-700 p-4 text-sm dark:border-amber-400">
|
||||
<p class="flex items-start gap-2">
|
||||
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
|
||||
{{ __('sales.index.unclosed') }}
|
||||
</p>
|
||||
<ul class="mt-2 flex flex-wrap gap-x-4 gap-y-1">
|
||||
@foreach ($this->unclosedDays as $unclosed)
|
||||
<li><x-link :href="route('sales.index', ['paiva' => $unclosed])" navigate>{{ $this->dateLabel($unclosed) }}</x-link></li>
|
||||
@endforeach
|
||||
</ul>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<h2 class="text-xl font-semibold" aria-live="polite">{{ $this->dateLabel($day) }}</h2>
|
||||
|
||||
<section aria-labelledby="cash-day-heading" class="space-y-3">
|
||||
<h3 id="cash-day-heading" class="text-lg font-semibold">{{ __('sales.cash_day.title') }}</h3>
|
||||
|
||||
@php($cashDay = $this->cashDay)
|
||||
|
||||
@if ($cashDay->isClosed)
|
||||
<p class="flex items-center gap-2 text-sm">
|
||||
<x-icon name="lock-closed" class="size-5" aria-hidden="true" />
|
||||
{{ __('sales.cash_day.closed', ['at' => $this->dateLabel((string) $cashDay->closedAt), 'name' => $cashDay->closedByName]) }}
|
||||
</p>
|
||||
@else
|
||||
<p class="text-sm">{{ __('sales.cash_day.open') }}</p>
|
||||
@endif
|
||||
|
||||
@if ($cashDay->reopenedAt !== null)
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('sales.cash_day.reopened', ['at' => $this->dateLabel($cashDay->reopenedAt), 'name' => $cashDay->reopenedByName]) }}</p>
|
||||
@endif
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<table class="w-full text-sm">
|
||||
<caption class="mb-2 text-left font-semibold">{{ $cashDay->isClosed ? __('sales.cash_day.balance') : __('sales.cash_day.preview') }}</caption>
|
||||
<thead class="sr-only">
|
||||
<tr>
|
||||
<th scope="col">{{ __('sales.cash_day.item') }}</th>
|
||||
<th scope="col">{{ __('sales.cash_day.amount') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
|
||||
<tr>
|
||||
<th scope="row" class="py-1 text-left font-normal">{{ __('sales.cash_day.sale_count') }}</th>
|
||||
<td class="py-1 text-right">{{ $cashDay->balance->saleCount }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row" class="py-1 text-left font-normal">{{ __('sales.cash_day.cash') }}</th>
|
||||
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($cashDay->balance->cashCents) }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row" class="py-1 text-left font-normal">{{ __('sales.cash_day.card') }}</th>
|
||||
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($cashDay->balance->cardCents) }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row" class="py-1 text-left font-semibold">{{ __('sales.cash_day.total') }}</th>
|
||||
<td class="py-1 text-right font-semibold whitespace-nowrap">{{ $this->money($cashDay->balance->totalCents()) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@if ($cashDay->balance->vatTotals !== [])
|
||||
<table class="w-full text-sm">
|
||||
<caption class="mb-2 text-left font-semibold">{{ __('sales.cash_day.vat_breakdown') }}</caption>
|
||||
<thead>
|
||||
<tr class="text-left">
|
||||
<th scope="col" class="py-1">{{ __('sales.cash_day.vat_rate') }}</th>
|
||||
<th scope="col" class="py-1 text-right">{{ __('sales.cash_day.gross') }}</th>
|
||||
<th scope="col" class="py-1 text-right">{{ __('sales.cash_day.net') }}</th>
|
||||
<th scope="col" class="py-1 text-right">{{ __('sales.cash_day.vat') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
|
||||
@foreach ($cashDay->balance->vatTotals as $vatTotal)
|
||||
<tr wire:key="vat-{{ $vatTotal->vatBasisPoints }}">
|
||||
<th scope="row" class="py-1 text-left font-normal">{{ $this->vatRate($vatTotal->vatBasisPoints) }}</th>
|
||||
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($vatTotal->grossCents) }}</td>
|
||||
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($vatTotal->netCents) }}</td>
|
||||
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($vatTotal->vatCents) }}</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-3">
|
||||
@if (! $cashDay->isClosed && ! $this->isFuture)
|
||||
@can('sales.close-day')
|
||||
<x-button wire:click="confirmClose" icon="lock-closed" :text="__('sales.cash_day.close')" />
|
||||
@endcan
|
||||
@elseif ($cashDay->isClosed)
|
||||
@can('sales.reopen-day')
|
||||
<x-button wire:click="confirmReopen" subtle color="black" icon="lock-open" :text="__('sales.cash_day.reopen')" />
|
||||
@endcan
|
||||
@endif
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="sales-heading" class="space-y-3">
|
||||
<h3 id="sales-heading" class="text-lg font-semibold">{{ __('sales.index.sales') }}</h3>
|
||||
|
||||
@can('sales.view-all')
|
||||
<div class="max-w-xs">
|
||||
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
|
||||
<x-select.native wire:model.live="seller" :label="__('sales.index.seller')" :aria-label="__('sales.index.seller')">
|
||||
<option value="">{{ __('sales.index.all_sellers') }}</option>
|
||||
@foreach ($this->sellers as $option)
|
||||
<option value="{{ $option->id }}">{{ $option->name }}</option>
|
||||
@endforeach
|
||||
</x-select.native>
|
||||
</div>
|
||||
@else
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('sales.index.own_only') }}</p>
|
||||
@endcan
|
||||
|
||||
@if ($this->sales === [])
|
||||
<p class="text-sm">{{ __('sales.index.none') }}</p>
|
||||
@else
|
||||
<x-table :headers="$this->headers()" :rows="$this->sales">
|
||||
@interact('column_time', $sale)
|
||||
<span class="whitespace-nowrap">{{ substr($sale->soldAt, 11) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_number', $sale)
|
||||
<span class="whitespace-nowrap">#{{ $sale->id }}</span>
|
||||
@if ($sale->isCredit())
|
||||
<span class="block text-xs">{{ __('sales.credit_of', ['number' => $sale->creditsSaleId]) }}</span>
|
||||
@elseif ($sale->creditedBySaleId !== null)
|
||||
<span class="block text-xs">{{ __('sales.credited_by', ['number' => $sale->creditedBySaleId]) }}</span>
|
||||
@endif
|
||||
@endinteract
|
||||
|
||||
@interact('column_seller', $sale)
|
||||
{{ $sale->sellerName }}
|
||||
@endinteract
|
||||
|
||||
@interact('column_customer', $sale)
|
||||
<span class="whitespace-normal">{{ $sale->customerName ?? __('sales.anonymous') }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_products', $sale)
|
||||
<span class="block whitespace-normal">{{ $this->linesText($sale) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_method', $sale)
|
||||
{{ __('sales.payment_methods.'.$sale->paymentMethod->value) }}
|
||||
@endinteract
|
||||
|
||||
@interact('column_total', $sale)
|
||||
<span class="whitespace-nowrap">{{ $this->money($sale->totalCents) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_actions', $sale)
|
||||
<a
|
||||
href="{{ route('sales.receipt', $sale->id) }}"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
class="mr-2 inline-flex items-center gap-1 text-sm font-medium underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700"
|
||||
aria-label="{{ __('sales.receipt.open_named', ['number' => $sale->id]) }}"
|
||||
>
|
||||
<x-icon name="document-text" class="size-4" aria-hidden="true" />
|
||||
{{ __('sales.receipt_link') }}
|
||||
</a>
|
||||
@if ($sale->canBeCredited())
|
||||
@can('sales.credit', $sale->sellerId)
|
||||
<x-button
|
||||
wire:click="confirmCredit({{ $sale->id }})"
|
||||
subtle
|
||||
color="black"
|
||||
sm
|
||||
icon="arrow-uturn-left"
|
||||
:text="__('sales.credit')"
|
||||
:aria-label="__('sales.credit_named', ['number' => $sale->id])"
|
||||
/>
|
||||
@endcan
|
||||
@endif
|
||||
@endinteract
|
||||
</x-table>
|
||||
@endif
|
||||
</section>
|
||||
|
||||
<x-confirm-dialog id="credit-dialog" :title="__('sales.credit_title')">
|
||||
@php($creditSale = $creditSaleId === null ? null : collect($this->sales)->firstWhere('id', $creditSaleId))
|
||||
@if ($creditSale !== null)
|
||||
<p>{{ __('sales.credit_text', ['number' => $creditSale->id, 'total' => $this->money($creditSale->totalCents), 'method' => __('sales.payment_methods.'.$creditSale->paymentMethod->value)]) }}</p>
|
||||
@endif
|
||||
|
||||
<x-slot:actions>
|
||||
<x-button wire:click="credit" color="red" :text="__('sales.credit_confirm')" />
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
|
||||
<x-confirm-dialog id="close-dialog" :title="__('sales.cash_day.close_title')">
|
||||
<p>{{ __('sales.cash_day.close_text') }}</p>
|
||||
<p class="mt-2 font-medium">
|
||||
{{ __('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) }})
|
||||
</p>
|
||||
|
||||
<x-slot:actions>
|
||||
<x-button wire:click="closeDay" :text="__('sales.cash_day.close')" />
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
|
||||
@can('sales.reopen-day')
|
||||
<x-confirm-dialog id="reopen-dialog" :title="__('sales.cash_day.reopen_title')">
|
||||
<p>{{ __('sales.cash_day.reopen_text') }}</p>
|
||||
|
||||
<x-slot:actions>
|
||||
<x-button wire:click="reopenDay" :text="__('sales.cash_day.reopen')" />
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
@endcan
|
||||
</div>
|
||||
@@ -0,0 +1,432 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Customers\Application\DTOs\CustomerSummary;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
|
||||
use App\Modules\Sales\Application\DTOs\SaleData;
|
||||
use App\Modules\Sales\Application\DTOs\SellableProduct;
|
||||
use App\Modules\Sales\Application\UseCases\SellQuickSale;
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\InvalidQuantity;
|
||||
use App\Modules\Sales\Domain\Exceptions\ProductNotSellable;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
|
||||
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
|
||||
use App\Modules\Sales\Presentation\Livewire\Concerns\FormatsSales;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* A quick sale at the counter (pikamyynti), made for phones: each press of
|
||||
* a product button adds one to the sale's list, where quantities can be
|
||||
* lowered, raised or removed; then the payment method and an optional
|
||||
* customer. After saving, the form empties for the next customer and the
|
||||
* result is announced with a link to the PDF receipt. Prices are consumer
|
||||
* prices with VAT, which everyone may see.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use FormatsSales;
|
||||
|
||||
/**
|
||||
* Quantities on the sale by product id, in the order added. Changed only
|
||||
* by the add, decrease and remove actions.
|
||||
*
|
||||
* @var array<int, int>
|
||||
*/
|
||||
#[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<int, SellableProduct> 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<array{product: SellableProduct, quantity: int}>
|
||||
*/
|
||||
#[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<CustomerSummary>
|
||||
*/
|
||||
#[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);
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-lg space-y-6 p-4 sm:p-6">
|
||||
<div class="space-y-1">
|
||||
<h1 class="text-2xl font-semibold">{{ __('sales.sell.title') }}</h1>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('sales.sell.intro') }}</p>
|
||||
<p class="text-sm">
|
||||
<x-link :href="route('sales.index')" navigate>{{ __('sales.sell.to_list') }}</x-link>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div id="sale-saved" tabindex="-1" role="status" aria-live="polite" class="focus:outline-none">
|
||||
@if ($savedMessage !== '')
|
||||
<div class="space-y-2 rounded-lg border border-green-700 bg-green-50 p-4 text-sm text-green-900 dark:border-green-500 dark:bg-green-950 dark:text-green-100">
|
||||
<p class="flex items-start gap-2 font-medium">
|
||||
<x-icon name="check-circle" class="size-5 shrink-0" aria-hidden="true" />
|
||||
{{ $savedMessage }}
|
||||
</p>
|
||||
@if ($hoursMessage !== '')
|
||||
<p>{{ $hoursMessage }}</p>
|
||||
@endif
|
||||
@if ($savedSaleId !== null)
|
||||
<p>
|
||||
<a
|
||||
href="{{ route('sales.receipt', $savedSaleId) }}"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
class="inline-flex items-center gap-1 font-medium underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700"
|
||||
>
|
||||
<x-icon name="document-text" class="size-5" aria-hidden="true" />
|
||||
{{ __('sales.receipt.open', ['number' => $savedSaleId]) }}
|
||||
</a>
|
||||
</p>
|
||||
@endif
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
@error('sale')
|
||||
<p role="alert" class="flex items-start gap-2 rounded-lg border border-red-700 p-4 text-sm text-red-700 dark:border-red-400 dark:text-red-400">
|
||||
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
|
||||
{{ $message }}
|
||||
</p>
|
||||
@enderror
|
||||
|
||||
@if ($this->products === [])
|
||||
<p class="text-sm">{{ __('sales.sell.no_products') }}</p>
|
||||
@else
|
||||
<section aria-labelledby="products-heading" class="space-y-3">
|
||||
<h2 id="products-heading" class="text-lg font-semibold">{{ __('sales.sell.products') }}</h2>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('sales.sell.products_help') }}</p>
|
||||
|
||||
<ul class="grid grid-cols-2 gap-2">
|
||||
@foreach ($this->products as $product)
|
||||
<li wire:key="product-{{ $product->id }}">
|
||||
<button
|
||||
type="button"
|
||||
wire:click="addProduct({{ $product->id }})"
|
||||
class="flex h-full min-h-16 w-full flex-col items-start justify-center rounded-lg border border-zinc-400 bg-white px-3 py-2 text-left hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-500 dark:bg-zinc-800 dark:hover:bg-zinc-700"
|
||||
aria-label="{{ __('sales.sell.add_named', ['product' => $product->name, 'price' => $this->money($product->grossCents), 'unit' => __('catalog.units.'.$product->unit)]) }}"
|
||||
>
|
||||
<span class="font-medium break-words">{{ $product->name }}</span>
|
||||
<span class="text-sm text-zinc-700 dark:text-zinc-300">{{ $this->money($product->grossCents) }} / {{ __('catalog.units.'.$product->unit) }}</span>
|
||||
</button>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="cart-heading" class="space-y-3">
|
||||
<h2 id="cart-heading" tabindex="-1" class="text-lg font-semibold focus:outline-none">{{ __('sales.sell.cart') }}</h2>
|
||||
|
||||
<p role="status" aria-live="polite" class="sr-only">{{ $cartMessage }}</p>
|
||||
|
||||
@error('quantities')
|
||||
<p role="alert" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
|
||||
@enderror
|
||||
|
||||
@if ($this->lines === [])
|
||||
<p class="text-sm">{{ __('sales.sell.cart_empty') }}</p>
|
||||
@else
|
||||
<ul class="divide-y divide-zinc-200 dark:divide-zinc-700">
|
||||
@foreach ($this->lines as $line)
|
||||
@php($product = $line['product'])
|
||||
<li wire:key="line-{{ $product->id }}" class="flex flex-wrap items-center gap-x-3 gap-y-2 py-2">
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="font-medium break-words">{{ $product->name }}</p>
|
||||
<p class="text-sm text-zinc-700 dark:text-zinc-300">
|
||||
{{ __('sales.sell.line', ['quantity' => $line['quantity'], 'price' => $this->money($product->grossCents), 'total' => $this->money($line['quantity'] * $product->grossCents)]) }}
|
||||
</p>
|
||||
@if ($product->durationQuarters > 0 && $product->workTypeId !== null)
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('sales.sell.line_hours', ['hours' => $this->hours($product->durationQuarters * $line['quantity'])]) }}</p>
|
||||
@endif
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<x-button wire:click="decreaseProduct({{ $product->id }})" subtle color="black" sm icon="minus" :aria-label="__('sales.sell.decrease_named', ['product' => $product->name])" />
|
||||
<span class="min-w-8 text-center font-medium" aria-hidden="true">{{ $line['quantity'] }}</span>
|
||||
<x-button wire:click="addProduct({{ $product->id }})" subtle color="black" sm icon="plus" :aria-label="__('sales.sell.increase_named', ['product' => $product->name])" />
|
||||
<x-button wire:click="removeProduct({{ $product->id }})" subtle color="black" sm icon="trash" :aria-label="__('sales.sell.remove_named', ['product' => $product->name])" />
|
||||
</div>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
|
||||
<p class="text-lg font-semibold">
|
||||
{{ __('sales.sell.total', ['total' => $this->money($this->totalCents)]) }}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<form wire:submit="save" class="space-y-6" novalidate>
|
||||
<x-radio.group
|
||||
wire:model="paymentMethod"
|
||||
:label="__('sales.sell.payment_method')"
|
||||
:options="[
|
||||
['label' => __('sales.payment_methods.cash'), 'value' => PaymentMethod::Cash->value],
|
||||
['label' => __('sales.payment_methods.card'), 'value' => PaymentMethod::Card->value],
|
||||
]"
|
||||
/>
|
||||
|
||||
<div class="space-y-2">
|
||||
@if ($customerId !== null)
|
||||
<p class="text-sm font-semibold text-gray-700 dark:text-dark-300">{{ __('sales.sell.customer') }}</p>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<span class="font-medium break-words">{{ $customerName }}</span>
|
||||
<x-button
|
||||
id="change-customer"
|
||||
wire:click="clearCustomer"
|
||||
subtle
|
||||
color="black"
|
||||
sm
|
||||
:text="__('sales.sell.change_customer')"
|
||||
:aria-label="__('sales.sell.change_customer').': '.$customerName"
|
||||
/>
|
||||
</div>
|
||||
@else
|
||||
<x-input
|
||||
id="customer-search"
|
||||
wire:model.live.debounce.300ms="customerSearch"
|
||||
type="search"
|
||||
icon="magnifying-glass"
|
||||
:label="__('sales.sell.customer')"
|
||||
:hint="__('sales.sell.customer_search_description')"
|
||||
autocomplete="off"
|
||||
/>
|
||||
|
||||
@if (mb_strlen(trim($customerSearch)) >= 2)
|
||||
<p role="status" aria-live="polite" class="text-sm text-zinc-600 dark:text-zinc-300">
|
||||
{{ trans_choice('sales.sell.customer_results', count($this->customerResults), ['count' => count($this->customerResults)]) }}
|
||||
</p>
|
||||
|
||||
<ul class="space-y-1">
|
||||
@foreach ($this->customerResults as $customer)
|
||||
<li wire:key="customer-result-{{ $customer->id }}">
|
||||
<button
|
||||
type="button"
|
||||
wire:click="selectCustomer({{ $customer->id }})"
|
||||
class="w-full rounded-md px-3 py-2 text-left text-sm hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:hover:bg-zinc-700"
|
||||
aria-label="{{ __('sales.sell.choose_customer', ['name' => $customer->name]) }}"
|
||||
>
|
||||
<span class="font-medium">{{ $customer->name }}</span>
|
||||
</button>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<x-button submit lg class="w-full" :text="__('sales.sell.save')" />
|
||||
</form>
|
||||
@endif
|
||||
</div>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Sales\Presentation\Http\Controllers\ShowReceipt;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::middleware(['web', 'auth', 'can:sales.use'])
|
||||
->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');
|
||||
});
|
||||
@@ -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
|
||||
<!DOCTYPE html>
|
||||
<html lang="fi">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>{{ $title }} {{ $sale->id }}</title>
|
||||
<style>
|
||||
@page { margin: 14mm 12mm; }
|
||||
body { font-family: "DejaVu Sans", sans-serif; font-size: 9.5pt; color: #000; }
|
||||
h1 { font-size: 14pt; margin: 0 0 2mm; }
|
||||
h2 { font-size: 10.5pt; margin: 5mm 0 1.5mm; }
|
||||
p { margin: 0 0 1mm; }
|
||||
.company { margin-bottom: 5mm; }
|
||||
.company .name { font-size: 12pt; font-weight: bold; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { padding: 1.2mm 1mm; vertical-align: top; }
|
||||
thead th { border-bottom: 0.6pt solid #000; text-align: left; }
|
||||
.num { text-align: right; white-space: nowrap; }
|
||||
.meta th { text-align: left; font-weight: normal; width: 35%; }
|
||||
.total td, .total th { border-top: 0.6pt solid #000; font-weight: bold; font-size: 11pt; }
|
||||
.footer { margin-top: 8mm; text-align: center; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="company">
|
||||
@if ($company !== null)
|
||||
<p class="name">{{ $company->name }}</p>
|
||||
@if ($company->address !== null)
|
||||
<p>{!! nl2br(e($company->address)) !!}</p>
|
||||
@endif
|
||||
@if ($company->phone !== null)
|
||||
<p>{{ $company->phone }}</p>
|
||||
@endif
|
||||
@if ($company->email !== null)
|
||||
<p>{{ $company->email }}</p>
|
||||
@endif
|
||||
<p>{{ __('sales.receipt.business_id') }}: {{ $company->businessId }} {{ __('sales.receipt.vat_number') }}: {{ $company->vatNumber() }}</p>
|
||||
@else
|
||||
<p>{{ __('sales.receipt.company_missing') }}</p>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<h1>{{ $title }}</h1>
|
||||
|
||||
<table class="meta">
|
||||
<tr><th scope="row">{{ __('sales.receipt.number') }}</th><td>{{ $sale->id }}</td></tr>
|
||||
<tr><th scope="row">{{ __('sales.receipt.date') }}</th><td>{{ CarbonImmutable::createFromFormat('Y-m-d H:i', $sale->soldAt)->format('j.n.Y H.i') }}</td></tr>
|
||||
<tr><th scope="row">{{ __('sales.receipt.seller') }}</th><td>{{ $sale->sellerName }}</td></tr>
|
||||
@if ($sale->customerName !== null)
|
||||
<tr><th scope="row">{{ __('sales.receipt.customer') }}</th><td>{{ $sale->customerName }}</td></tr>
|
||||
@endif
|
||||
<tr><th scope="row">{{ __('sales.receipt.payment_method') }}</th><td>{{ __('sales.payment_methods.'.$sale->paymentMethod->value) }}</td></tr>
|
||||
@if ($sale->isCredit())
|
||||
<tr><th scope="row"></th><td>{{ __('sales.receipt.credits', ['number' => $sale->creditsSaleId]) }}</td></tr>
|
||||
@endif
|
||||
</table>
|
||||
|
||||
<table style="margin-top: 5mm;">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{{ __('sales.receipt.product') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.quantity') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.unit_price') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.vat_rate') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.line_total') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach ($sale->lines as $line)
|
||||
<tr>
|
||||
<td>{{ $line->productName }}</td>
|
||||
<td class="num">{{ $line->quantity }}</td>
|
||||
<td class="num">{{ $money($line->unitPriceCents) }}</td>
|
||||
<td class="num">{{ (new VatPercentage($line->vatBasisPoints))->format() }}</td>
|
||||
<td class="num">{{ $money($line->totalCents) }}</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
<tr class="total">
|
||||
<th scope="row" colspan="4" style="text-align: left;">{{ __('sales.receipt.total') }}</th>
|
||||
<td class="num">{{ $money($sale->totalCents) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<h2>{{ __('sales.receipt.vat_heading') }}</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{{ __('sales.receipt.vat_rate') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.net') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.vat') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.gross') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach ($sale->vatTotals() as $vatTotal)
|
||||
<tr>
|
||||
<td>{{ (new VatPercentage($vatTotal->vatBasisPoints))->format() }}</td>
|
||||
<td class="num">{{ $money($vatTotal->netCents) }}</td>
|
||||
<td class="num">{{ $money($vatTotal->vatCents) }}</td>
|
||||
<td class="num">{{ $money($vatTotal->grossCents) }}</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p class="footer">{{ __('sales.receipt.thanks') }}</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Shared\Application\DTOs;
|
||||
|
||||
/**
|
||||
* The company's own details, printed on receipts and other documents.
|
||||
* Empty optional values are null.
|
||||
*/
|
||||
final readonly class CompanyDetails
|
||||
{
|
||||
public function __construct(
|
||||
public string $name,
|
||||
public string $businessId,
|
||||
public ?string $address = null,
|
||||
public ?string $phone = null,
|
||||
public ?string $email = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* The EU VAT number of a Finnish business ID, e.g. FI07375462.
|
||||
*/
|
||||
public function vatNumber(): string
|
||||
{
|
||||
return 'FI'.str_replace('-', '', $this->businessId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Shared\Application\UseCases;
|
||||
|
||||
use App\Modules\Shared\Application\Contracts\Settings;
|
||||
use App\Modules\Shared\Application\DTOs\CompanyDetails;
|
||||
use App\Modules\Shared\Domain\Exceptions\CompanyNameRequired;
|
||||
use App\Modules\Shared\Domain\Exceptions\InvalidBusinessId;
|
||||
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
|
||||
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
|
||||
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
|
||||
|
||||
/**
|
||||
* Reads and saves the company's details (Asetukset → Yritystiedot), kept
|
||||
* in the settings under `shared.company_*`. Who may save is checked by
|
||||
* the caller (admin).
|
||||
*/
|
||||
final class CompanyDetailsStore
|
||||
{
|
||||
private const array KEYS = [
|
||||
'name' => '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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Shared\Domain\Exceptions;
|
||||
|
||||
final class CompanyNameRequired extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The company needs a name of at most 255 characters.');
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -2,9 +2,7 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Customers\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
namespace App\Modules\Shared\Domain\Exceptions;
|
||||
|
||||
final class InvalidBusinessId extends DomainException
|
||||
{
|
||||
+2
-2
@@ -2,9 +2,9 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Customers\Domain\ValueObjects;
|
||||
namespace App\Modules\Shared\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId;
|
||||
use App\Modules\Shared\Domain\Exceptions\InvalidBusinessId;
|
||||
|
||||
/**
|
||||
* Finnish business ID (Y-tunnus), e.g. 0737546-2.
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Modules\Shared\Infrastructure\Providers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Shared\Application\Contracts\EventDispatcher;
|
||||
use App\Modules\Shared\Application\Contracts\Settings;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
@@ -9,8 +10,11 @@ use App\Modules\Shared\Infrastructure\Events\LaravelEventDispatcher;
|
||||
use App\Modules\Shared\Infrastructure\Persistence\DatabaseSettings;
|
||||
use App\Modules\Shared\Infrastructure\Persistence\LaravelTransactionManager;
|
||||
use App\Modules\Shared\Presentation\Http\Middleware\SetSecurityHeaders;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Illuminate\Contracts\Http\Kernel;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Livewire\Livewire;
|
||||
|
||||
class SharedServiceProvider extends ServiceProvider
|
||||
{
|
||||
@@ -26,5 +30,16 @@ class SharedServiceProvider extends ServiceProvider
|
||||
public function boot(): void
|
||||
{
|
||||
$this->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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Shared\Application\DTOs\CompanyDetails;
|
||||
use App\Modules\Shared\Application\UseCases\CompanyDetailsStore;
|
||||
use App\Modules\Shared\Domain\Exceptions\CompanyNameRequired;
|
||||
use App\Modules\Shared\Domain\Exceptions\InvalidBusinessId;
|
||||
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* The company's own details (Yritystiedot) for receipts and other
|
||||
* documents. Only admins change settings (spec 2).
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
public string $name = '';
|
||||
|
||||
public string $business_id = '';
|
||||
|
||||
public string $address = '';
|
||||
|
||||
public string $phone = '';
|
||||
|
||||
public string $email = '';
|
||||
|
||||
#[Locked]
|
||||
public string $statusMessage = '';
|
||||
|
||||
public function mount(CompanyDetailsStore $store): void
|
||||
{
|
||||
$this->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'));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-lg space-y-6 p-4 sm:p-6">
|
||||
<div class="space-y-1">
|
||||
<h1 class="text-2xl font-semibold">{{ __('company.title') }}</h1>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('company.intro') }}</p>
|
||||
</div>
|
||||
|
||||
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $statusMessage }}</p>
|
||||
|
||||
<form wire:submit="save" class="space-y-6" novalidate>
|
||||
<x-input wire:model="name" :label="__('company.fields.name')" autocomplete="organization" required />
|
||||
<x-input wire:model="business_id" :label="__('company.fields.business_id')" :hint="__('company.fields.business_id_hint')" autocomplete="off" required />
|
||||
<x-textarea wire:model="address" :label="__('company.fields.address')" :hint="__('company.fields.address_hint')" rows="3" autocomplete="street-address" />
|
||||
<x-input wire:model="phone" type="tel" :label="__('company.fields.phone')" autocomplete="tel" />
|
||||
<x-input wire:model="email" type="email" :label="__('company.fields.email')" autocomplete="email" />
|
||||
|
||||
<x-button submit :text="__('company.save')" />
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::middleware(['web', 'auth', 'can:settings.manage'])
|
||||
->prefix('settings')
|
||||
->name('settings.')
|
||||
->group(function () {
|
||||
Route::livewire('/company', 'shared::company')->name('company');
|
||||
});
|
||||
@@ -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,
|
||||
];
|
||||
|
||||
@@ -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",
|
||||
|
||||
Generated
+385
-1
@@ -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": "[email protected]"
|
||||
}
|
||||
],
|
||||
"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": "[email protected]"
|
||||
},
|
||||
{
|
||||
"name": "Matt Farina",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
{
|
||||
"name": "Asmir Mustafic",
|
||||
"email": "[email protected]"
|
||||
}
|
||||
],
|
||||
"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": "[email protected]"
|
||||
},
|
||||
{
|
||||
"name": "Jake Hotson",
|
||||
"email": "[email protected]"
|
||||
}
|
||||
],
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleLineModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
/**
|
||||
* A quick sale of one product line, sold today.
|
||||
*
|
||||
* @extends Factory<QuickSaleModel>
|
||||
*/
|
||||
class QuickSaleFactory extends Factory
|
||||
{
|
||||
protected $model = QuickSaleModel::class;
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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,
|
||||
]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Marks the system job of a year that quick sale hours are booked on,
|
||||
* so that there is only one per year.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('customer_jobs', function (Blueprint $table) {
|
||||
$table->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');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Quick sales (cash and card sales of consumer products) and their
|
||||
* lines. Prices are with VAT; a credit is a sale of its own whose
|
||||
* quantities and total are negative.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('quick_sales', function (Blueprint $table) {
|
||||
$table->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');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Closed cash days: the balance of a day's quick sales by payment method
|
||||
* and VAT rate. Reopening empties the balance until the day is closed
|
||||
* again.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('cash_days', function (Blueprint $table) {
|
||||
$table->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');
|
||||
}
|
||||
};
|
||||
+14
-6
@@ -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).
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'title' => '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.',
|
||||
],
|
||||
];
|
||||
@@ -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',
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'job_name' => '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.',
|
||||
],
|
||||
];
|
||||
@@ -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
|
||||
</nav>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
$this->user = User::factory()->management()->create(['name' => 'Johtaja']);
|
||||
$this->actingAs($this->user);
|
||||
$this->photos = ProductModel::factory()->consumer()->withAutoHours(0.25)->create(['name' => 'Passikuvat', 'price_cents' => 1500]);
|
||||
QuickSaleModel::factory()->withLine($this->photos, 2)->create(['user_id' => $this->user->id]);
|
||||
});
|
||||
|
||||
it('has no accessibility issues on the quick sale pages and no sideways scrolling', function (string $page, string $device, string $colorScheme) {
|
||||
$url = match ($page) {
|
||||
'sell' => route('sales.sell'),
|
||||
'sales' => route('sales.index'),
|
||||
};
|
||||
|
||||
$visit = visit($url);
|
||||
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
|
||||
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
|
||||
|
||||
$visit->assertSee('Passikuvat')
|
||||
->assertNoJavaScriptErrors()
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
})->with(['sell', 'sales'])->with([
|
||||
'desktop, light' => ['desktop', 'light'],
|
||||
'desktop, dark' => ['desktop', 'dark'],
|
||||
'mobile, light' => ['mobile', 'light'],
|
||||
'mobile, dark' => ['mobile', 'dark'],
|
||||
]);
|
||||
|
||||
it('adds products with their buttons and announces the sale', function () {
|
||||
$button = '[wire\\:click="addProduct('.$this->photos->id.')"]';
|
||||
|
||||
$page = visit(route('sales.sell'));
|
||||
$page->click('#products-heading ~ ul '.$button)
|
||||
->click('#products-heading ~ ul '.$button)
|
||||
->click('#products-heading ~ ul '.$button)
|
||||
->assertSee('Yhteensä 45,00')
|
||||
->assertSee('3 × 15,00')
|
||||
->assertNoAccessibilityIssues(level: 2)
|
||||
->click('Kirjaa myynti')
|
||||
->assertSee('kirjattu: 45,00')
|
||||
->assertSee('Tunneillesi kirjattiin 0,75 h.')
|
||||
->assertSee('Avaa kuitti')
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
});
|
||||
|
||||
it('has no accessibility issues on the company details page', function (string $device, string $colorScheme) {
|
||||
$this->actingAs(User::factory()->admin()->create());
|
||||
|
||||
$visit = visit(route('settings.company'));
|
||||
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
|
||||
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
|
||||
|
||||
$visit->assertSee('Yritystiedot')
|
||||
->assertNoJavaScriptErrors()
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
})->with([
|
||||
'desktop, light' => ['desktop', 'light'],
|
||||
'desktop, dark' => ['desktop', 'dark'],
|
||||
'mobile, light' => ['mobile', 'light'],
|
||||
'mobile, dark' => ['mobile', 'dark'],
|
||||
]);
|
||||
|
||||
it('closes the cash day from its dialog', function () {
|
||||
visit(route('sales.index'))
|
||||
->click('Päätä kassapäivä')
|
||||
->assertSee('Päätetäänkö kassapäivä?')
|
||||
->assertNoAccessibilityIssues(level: 2)
|
||||
->click('#close-dialog button:last-child')
|
||||
->assertSee('Kassapäivä päätetty')
|
||||
->assertSee('Avaa kassapäivä');
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Fakes;
|
||||
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleHours;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class FakeQuickSaleHours implements QuickSaleHours
|
||||
{
|
||||
/** @var list<array{int, string, int, int, int}> seller, day, work type, quarters, sale */
|
||||
public array $booked = [];
|
||||
|
||||
public bool $fails = false;
|
||||
|
||||
public function book(int $sellerId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $saleId): bool
|
||||
{
|
||||
if ($this->fails) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->booked[] = [$sellerId, $day->format('Y-m-d'), $workTypeId, $quarters, $saleId];
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Fakes;
|
||||
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
|
||||
use App\Modules\Sales\Application\DTOs\SellableProduct;
|
||||
|
||||
class FakeQuickSaleProducts implements QuickSaleProducts
|
||||
{
|
||||
/** @var list<SellableProduct> */
|
||||
public array $products = [];
|
||||
|
||||
public function add(int $id, string $name, int $grossCents, int $vatBasisPoints = 2550, int $durationQuarters = 0, ?int $workTypeId = null): void
|
||||
{
|
||||
$this->products[] = new SellableProduct($id, $name, 'piece', $grossCents, $vatBasisPoints, $durationQuarters, $workTypeId);
|
||||
}
|
||||
|
||||
public function sellable(): array
|
||||
{
|
||||
return $this->products;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Fakes;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Entities\CashDay;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class InMemoryCashDayRepository implements CashDayRepository
|
||||
{
|
||||
/** @var array<string, CashDay> */
|
||||
public array $days = [];
|
||||
|
||||
public function forDay(DateTimeImmutable $day): CashDay
|
||||
{
|
||||
return isset($this->days[$day->format('Y-m-d')]) ? clone $this->days[$day->format('Y-m-d')] : CashDay::open($day);
|
||||
}
|
||||
|
||||
public function save(CashDay $cashDay): CashDay
|
||||
{
|
||||
$this->days[$cashDay->day()->format('Y-m-d')] = clone $cashDay;
|
||||
|
||||
return $cashDay;
|
||||
}
|
||||
|
||||
public function lockForDay(DateTimeImmutable $day): CashDay
|
||||
{
|
||||
return $this->forDay($day);
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,19 @@ class InMemoryCustomerJobRepository implements CustomerJobRepository, JobNumberS
|
||||
return clone $this->jobs[$id];
|
||||
}
|
||||
|
||||
/** @var array<int, int> year => job id */
|
||||
public array $quickSaleJobs = [];
|
||||
|
||||
public function findQuickSaleJob(int $year): ?CustomerJob
|
||||
{
|
||||
return isset($this->quickSaleJobs[$year]) ? $this->findById($this->quickSaleJobs[$year]) : null;
|
||||
}
|
||||
|
||||
public function markAsQuickSaleJob(int $jobId, int $year): void
|
||||
{
|
||||
$this->quickSaleJobs[$year] = $jobId;
|
||||
}
|
||||
|
||||
public function recordChanges(int $jobId, int $userId, array $changes): void
|
||||
{
|
||||
foreach ($changes as $change) {
|
||||
|
||||
@@ -4,8 +4,8 @@ namespace Tests\Fakes;
|
||||
|
||||
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
|
||||
use App\Modules\Customers\Domain\Entities\Customer;
|
||||
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
|
||||
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
|
||||
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
|
||||
|
||||
class InMemoryCustomerRepository implements CustomerRepository
|
||||
{
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Fakes;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Domain\Entities\QuickSale;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class InMemoryQuickSaleRepository implements QuickSaleRepository
|
||||
{
|
||||
/** @var array<int, QuickSale> */
|
||||
public array $sales = [];
|
||||
|
||||
private int $nextId = 1;
|
||||
|
||||
public function findById(int $id): ?QuickSale
|
||||
{
|
||||
return $this->sales[$id] ?? null;
|
||||
}
|
||||
|
||||
public function add(QuickSale $sale): QuickSale
|
||||
{
|
||||
$id = $this->nextId++;
|
||||
|
||||
return $this->sales[$id] = QuickSale::reconstitute(
|
||||
$id,
|
||||
$sale->sellerId(),
|
||||
$sale->customerId(),
|
||||
$sale->paymentMethod(),
|
||||
$sale->soldAt(),
|
||||
$sale->soldOn(),
|
||||
$sale->lines(),
|
||||
$sale->creditsSaleId(),
|
||||
);
|
||||
}
|
||||
|
||||
public function isCredited(int $saleId): bool
|
||||
{
|
||||
foreach ($this->sales as $sale) {
|
||||
if ($sale->creditsSaleId() === $saleId) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function forDay(DateTimeImmutable $day): array
|
||||
{
|
||||
return array_values(array_filter($this->sales, fn (QuickSale $sale): bool => $sale->soldOn()->format('Y-m-d') === $day->format('Y-m-d')));
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,17 @@ class InMemoryTaskRepository implements TaskRepository
|
||||
return $task !== null && $task->jobId() === $jobId ? clone $task : null;
|
||||
}
|
||||
|
||||
public function findByWorkType(int $jobId, int $workTypeId): ?Task
|
||||
{
|
||||
foreach ($this->tasks as $task) {
|
||||
if ($task->jobId() === $jobId && $task->workTypeId() === $workTypeId) {
|
||||
return clone $task;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function save(Task $task): Task
|
||||
{
|
||||
$id = $task->id() ?? $this->nextId++;
|
||||
|
||||
@@ -4,9 +4,9 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
|
||||
use App\Modules\Customers\Domain\Entities\Customer;
|
||||
use App\Modules\Customers\Domain\Enums\CustomerType;
|
||||
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
|
||||
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
|
||||
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
|
||||
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
|
||||
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
|
||||
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\CashDayModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
|
||||
use App\Modules\Shared\Application\DTOs\CompanyDetails;
|
||||
use App\Modules\Shared\Application\UseCases\CompanyDetailsStore;
|
||||
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
$this->travelTo(now()->setTimezone(config('app.business_timezone'))->setTime(12, 0));
|
||||
$this->today = now(config('app.business_timezone'))->toDateString();
|
||||
$this->employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']);
|
||||
$this->photos = ProductModel::factory()->consumer()->withAutoHours(0.25)->create(['name' => 'Passikuvat', 'price_cents' => 1500]);
|
||||
$this->prints = ProductModel::factory()->consumer()->create(['name' => 'Tuloste A4', 'price_cents' => 50]);
|
||||
$this->actingAs($this->employee);
|
||||
});
|
||||
|
||||
function sell(array $quantities, string $method = 'cash'): mixed
|
||||
{
|
||||
$component = Livewire::test('sales::sell');
|
||||
|
||||
foreach ($quantities as $productId => $quantity) {
|
||||
for ($i = 0; $i < $quantity; $i++) {
|
||||
$component->call('addProduct', $productId);
|
||||
}
|
||||
}
|
||||
|
||||
return $component->set('paymentMethod', $method)->call('save');
|
||||
}
|
||||
|
||||
it('sells consumer products, keeps a snapshot of the prices and books the hours on the yearly quick sale job', function () {
|
||||
sell([$this->photos->id => 2, $this->prints->id => 3])
|
||||
->assertHasNoErrors()
|
||||
->assertSet('savedMessage', fn (string $message) => str_contains($message, "31,50\u{00A0}€, Käteinen"))
|
||||
->assertSet('hoursMessage', 'Tunneillesi kirjattiin 0,5 h.')
|
||||
->assertSet('quantities', []);
|
||||
|
||||
$sale = QuickSaleModel::query()->with('lines')->sole();
|
||||
|
||||
expect($sale->total_cents)->toBe(3150)
|
||||
->and($sale->user_id)->toBe($this->employee->id)
|
||||
->and($sale->sold_on)->toBe($this->today)
|
||||
->and($sale->lines->map->only(['product_name', 'quantity', 'unit_price_cents', 'vat_basis_points'])->all())->toBe([
|
||||
['product_name' => 'Passikuvat', 'quantity' => 2, 'unit_price_cents' => 1500, 'vat_basis_points' => 2550],
|
||||
['product_name' => 'Tuloste A4', 'quantity' => 3, 'unit_price_cents' => 50, 'vat_basis_points' => 2550],
|
||||
]);
|
||||
|
||||
$job = CustomerJobModel::query()->where('quick_sale_year', now()->year)->sole();
|
||||
$entry = TimeEntryModel::query()->sole();
|
||||
|
||||
expect($job->name)->toBe('Pikamyynnit '.now()->year)
|
||||
->and($entry->customer_job_id)->toBe($job->id)
|
||||
->and($entry->work_type_id)->toBe($this->photos->work_type_id)
|
||||
->and((float) $entry->hours)->toBe(0.5)
|
||||
->and($entry->note)->toBe('Pikamyynti #'.$sale->id);
|
||||
|
||||
sell([$this->photos->id => 1], 'card')->assertHasNoErrors();
|
||||
|
||||
expect(CustomerJobModel::query()->where('quick_sale_year', now()->year)->count())->toBe(1)
|
||||
->and(TaskModel::query()->where('customer_job_id', $job->id)->count())->toBe(1)
|
||||
->and((float) $entry->refresh()->hours)->toBe(0.75);
|
||||
});
|
||||
|
||||
it('keeps the sale when the day\'s hours are already approved', function () {
|
||||
sell([$this->photos->id => 1]);
|
||||
TimeEntryModel::query()->update(['approved_at' => now(), 'approved_by' => $this->employee->id]);
|
||||
|
||||
sell([$this->photos->id => 1])
|
||||
->assertHasNoErrors()
|
||||
->assertSet('hoursMessage', fn (string $message) => str_starts_with($message, 'Tunteja (0,25 h) ei voitu kirjata'));
|
||||
|
||||
expect(QuickSaleModel::query()->count())->toBe(2)
|
||||
->and((float) TimeEntryModel::query()->sole()->hours)->toBe(0.25);
|
||||
});
|
||||
|
||||
it('adds a product with each press and lowers or removes it from the list', function () {
|
||||
Livewire::test('sales::sell')
|
||||
->call('addProduct', $this->photos->id)
|
||||
->call('addProduct', $this->photos->id)
|
||||
->call('addProduct', $this->prints->id)
|
||||
->assertSet('quantities', [$this->photos->id => 2, $this->prints->id => 1])
|
||||
->assertSet('cartMessage', "Tuloste A4: 1. Yhteensä 30,50\u{00A0}€.")
|
||||
->assertSee("2 × 15,00\u{00A0}€ = 30,00\u{00A0}€", false)
|
||||
->call('decreaseProduct', $this->photos->id)
|
||||
->call('decreaseProduct', $this->prints->id)
|
||||
->assertSet('quantities', [$this->photos->id => 1])
|
||||
->assertSet('cartMessage', "Tuloste A4 poistettu. Yhteensä 15,00\u{00A0}€.")
|
||||
->call('removeProduct', $this->photos->id)
|
||||
->assertSet('quantities', [])
|
||||
->assertSee(__('sales.sell.cart_empty'));
|
||||
});
|
||||
|
||||
it('rejects an empty sale and products that are not consumer products or no longer sold', function () {
|
||||
$other = ProductModel::factory()->create();
|
||||
|
||||
sell([])->assertHasErrors(['quantities' => [__('sales.errors.empty')]]);
|
||||
sell([$other->id => 1])->assertSet('quantities', [])->assertHasErrors(['quantities' => [__('sales.errors.empty')]]);
|
||||
|
||||
$component = Livewire::test('sales::sell')->call('addProduct', $this->prints->id);
|
||||
$this->prints->update(['is_active' => false]);
|
||||
$component->call('save')
|
||||
->assertHasErrors(['quantities' => [__('sales.errors.product')]])
|
||||
->assertSet('quantities', []);
|
||||
|
||||
expect(QuickSaleModel::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
it('opens the receipt as a PDF for the seller and management only', function () {
|
||||
sell([$this->photos->id => 2]);
|
||||
$sale = QuickSaleModel::query()->sole();
|
||||
|
||||
$this->get(route('sales.receipt', $sale->id))
|
||||
->assertOk()
|
||||
->assertHeader('content-type', 'application/pdf')
|
||||
->assertHeader('content-disposition', 'inline; filename=kuitti-'.$sale->id.'.pdf');
|
||||
|
||||
$this->actingAs(User::factory()->employee()->create());
|
||||
$this->get(route('sales.receipt', $sale->id))->assertForbidden();
|
||||
|
||||
$this->actingAs(User::factory()->management()->create());
|
||||
$this->get(route('sales.receipt', $sale->id))->assertOk();
|
||||
$this->get(route('sales.receipt', 999))->assertNotFound();
|
||||
});
|
||||
|
||||
it('prints the company details, lines and VAT breakdown on the receipt', function () {
|
||||
app(CompanyDetailsStore::class)->save(new CompanyDetails('Mediatalo Oy', '0737546-2', "Kauppakatu 1\n40100 Jyväskylä", '014 123 456', '[email protected]'));
|
||||
sell([$this->photos->id => 2, $this->prints->id => 1], 'card');
|
||||
$sale = app(QuickSaleQueries::class)->findSale(QuickSaleModel::query()->sole()->id);
|
||||
|
||||
$html = view('sales-views::receipt', ['sale' => $sale, 'company' => app(CompanyDetailsStore::class)->get()])->render();
|
||||
|
||||
expect($html)->toContain('Mediatalo Oy', 'Kauppakatu 1<br />', 'Y-tunnus: 0737546-2', 'ALV-tunnus: FI07375462', 'Pankkikortti', 'Eero Työntekijä')
|
||||
->toContain("30,50\u{00A0}€", "24,30\u{00A0}€", "6,20\u{00A0}€")
|
||||
->not->toContain(__('sales.receipt.company_missing'));
|
||||
});
|
||||
|
||||
it('keeps subcontractors out', function () {
|
||||
$this->actingAs(User::factory()->subcontractor()->create());
|
||||
|
||||
$this->get(route('sales.sell'))->assertForbidden();
|
||||
$this->get(route('sales.index'))->assertForbidden();
|
||||
});
|
||||
|
||||
it('shows employees their own sales and management everyone\'s', function () {
|
||||
$colleague = User::factory()->employee()->create(['name' => 'Kaisa Kollega']);
|
||||
QuickSaleModel::factory()->withLine($this->prints, 4)->create(['user_id' => $colleague->id]);
|
||||
sell([$this->photos->id => 1]);
|
||||
|
||||
Livewire::test('sales::index')
|
||||
->assertSee('Eero Työntekijä')
|
||||
->assertDontSee('Kaisa Kollega')
|
||||
->assertSee("17,00\u{00A0}€", false);
|
||||
|
||||
$this->actingAs(User::factory()->management()->create());
|
||||
|
||||
Livewire::test('sales::index')
|
||||
->assertSee('Eero Työntekijä')
|
||||
->assertSee('Kaisa Kollega')
|
||||
->set('seller', (string) $colleague->id)
|
||||
->assertDontSee('1 × Passikuvat');
|
||||
});
|
||||
|
||||
it('credits a sale once, by its seller or management only', function () {
|
||||
sell([$this->photos->id => 2]);
|
||||
$sale = QuickSaleModel::query()->sole();
|
||||
|
||||
$this->actingAs(User::factory()->employee()->create());
|
||||
Livewire::test('sales::index')->call('confirmCredit', $sale->id)->assertForbidden();
|
||||
|
||||
$this->actingAs($this->employee);
|
||||
Livewire::test('sales::index')
|
||||
->call('confirmCredit', $sale->id)
|
||||
->call('credit')
|
||||
->assertSet('statusMessage', fn (string $message) => str_starts_with($message, 'Myynnille #'.$sale->id.' kirjattiin hyvitys'))
|
||||
->assertSee('Hyvitys myynnille #'.$sale->id)
|
||||
->assertSee("-30,00\u{00A0}€", false)
|
||||
->assertDontSee(__('sales.credit_named', ['number' => $sale->id]));
|
||||
|
||||
$credit = QuickSaleModel::query()->with('lines')->where('credits_quick_sale_id', $sale->id)->sole();
|
||||
|
||||
expect($credit->total_cents)->toBe(-3000)
|
||||
->and($credit->lines->sole()->quantity)->toBe(-2)
|
||||
->and((float) TimeEntryModel::query()->sole()->hours)->toBe(0.5);
|
||||
|
||||
$this->actingAs(User::factory()->management()->create());
|
||||
Livewire::test('sales::index')
|
||||
->call('confirmCredit', $sale->id)
|
||||
->call('credit')
|
||||
->assertSet('statusMessage', __('sales.errors.already_credited'));
|
||||
|
||||
expect(QuickSaleModel::query()->count())->toBe(2);
|
||||
});
|
||||
|
||||
it('closes the cash day with its balance by payment method and VAT rate', function () {
|
||||
sell([$this->photos->id => 2], 'cash');
|
||||
sell([$this->prints->id => 3], 'card');
|
||||
$first = QuickSaleModel::query()->orderBy('id')->first();
|
||||
|
||||
Livewire::test('sales::index')
|
||||
->call('confirmCredit', $first->id)
|
||||
->call('credit')
|
||||
->assertSee(__('sales.cash_day.preview'))
|
||||
->call('closeDay')
|
||||
->assertSet('statusMessage', fn (string $message) => str_ends_with($message, 'päätetty.'))
|
||||
->assertSee('Kassapäivä päätetty')
|
||||
->assertDontSee(__('sales.cash_day.reopen'));
|
||||
|
||||
$day = CashDayModel::query()->with('vatTotals')->sole();
|
||||
|
||||
expect($day->only(['sale_count', 'cash_cents', 'card_cents', 'total_cents', 'closed_by']))->toBe([
|
||||
'sale_count' => 3,
|
||||
'cash_cents' => 0,
|
||||
'card_cents' => 150,
|
||||
'total_cents' => 150,
|
||||
'closed_by' => $this->employee->id,
|
||||
])->and($day->vatTotals->sole()->only(['vat_basis_points', 'gross_cents', 'net_cents', 'vat_cents']))->toBe([
|
||||
'vat_basis_points' => 2550, 'gross_cents' => 150, 'net_cents' => 120, 'vat_cents' => 30,
|
||||
]);
|
||||
|
||||
sell([$this->prints->id => 1])->assertHasErrors(['sale' => [__('sales.errors.day_closed')]]);
|
||||
expect(QuickSaleModel::query()->count())->toBe(3);
|
||||
});
|
||||
|
||||
it('lets only management reopen a closed day, and closing again forms the balance anew', function () {
|
||||
sell([$this->prints->id => 2]);
|
||||
Livewire::test('sales::index')->call('closeDay');
|
||||
Livewire::test('sales::index')->call('reopenDay')->assertForbidden();
|
||||
|
||||
$this->actingAs(User::factory()->management()->create(['name' => 'Johtaja']));
|
||||
Livewire::test('sales::index')
|
||||
->call('reopenDay')
|
||||
->assertSee('Avattu uudelleen');
|
||||
|
||||
expect(CashDayModel::query()->sole()->closed_at)->toBeNull();
|
||||
|
||||
sell([$this->prints->id => 1])->assertHasNoErrors();
|
||||
Livewire::test('sales::index')->call('closeDay');
|
||||
|
||||
expect(CashDayModel::query()->sole()->total_cents)->toBe(150);
|
||||
});
|
||||
|
||||
it('credits a sale of a closed day on today\'s cash day and reminds of unclosed days', function () {
|
||||
$yesterday = now()->subDay()->toDateString();
|
||||
$old = QuickSaleModel::factory()->withLine($this->prints, 2)->create([
|
||||
'user_id' => $this->employee->id,
|
||||
'sold_at' => now()->subDay(),
|
||||
'sold_on' => $yesterday,
|
||||
]);
|
||||
|
||||
Livewire::test('sales::index')->assertSee(__('sales.index.unclosed'));
|
||||
|
||||
Livewire::withQueryParams(['paiva' => $yesterday])->test('sales::index')->call('closeDay');
|
||||
|
||||
Livewire::test('sales::index')
|
||||
->assertDontSee(__('sales.index.unclosed'))
|
||||
->call('confirmCredit', $old->id)
|
||||
->call('credit')
|
||||
->assertSet('day', $this->today);
|
||||
|
||||
expect(QuickSaleModel::query()->where('credits_quick_sale_id', $old->id)->sole()->sold_on)->toBe($this->today)
|
||||
->and(CashDayModel::query()->where('day', $yesterday)->sole()->total_cents)->toBe(100);
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Shared\Application\UseCases\CompanyDetailsStore;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('lets the admin save the company details', function () {
|
||||
$this->actingAs(User::factory()->admin()->create());
|
||||
|
||||
Livewire::test('shared::company')
|
||||
->set('name', 'Mediatalo Oy')
|
||||
->set('business_id', '737546-2')
|
||||
->set('address', "Kauppakatu 1\n40100 Jyväskylä")
|
||||
->set('email', '[email protected]')
|
||||
->call('save')
|
||||
->assertHasNoErrors()
|
||||
->assertSet('business_id', '0737546-2')
|
||||
->assertSet('statusMessage', __('company.saved'));
|
||||
|
||||
$details = app(CompanyDetailsStore::class)->get();
|
||||
|
||||
expect($details->name)->toBe('Mediatalo Oy')
|
||||
->and($details->email)->toBe('[email protected]')
|
||||
->and($details->phone)->toBeNull()
|
||||
->and($details->vatNumber())->toBe('FI07375462');
|
||||
|
||||
Livewire::test('shared::company')->assertSet('name', 'Mediatalo Oy');
|
||||
});
|
||||
|
||||
it('rejects an invalid business ID and email address', function () {
|
||||
$this->actingAs(User::factory()->admin()->create());
|
||||
|
||||
Livewire::test('shared::company')
|
||||
->set('name', 'Mediatalo Oy')
|
||||
->set('business_id', '1234567-8')
|
||||
->call('save')
|
||||
->assertHasErrors(['business_id' => [__('company.errors.business_id')]])
|
||||
->set('business_id', '0737546-2')
|
||||
->set('email', 'ei-osoite')
|
||||
->call('save')
|
||||
->assertHasErrors(['email' => [__('company.errors.email')]]);
|
||||
|
||||
expect(app(CompanyDetailsStore::class)->get())->toBeNull();
|
||||
});
|
||||
|
||||
it('keeps everyone but the admin out', function () {
|
||||
$this->actingAs(User::factory()->management()->create());
|
||||
|
||||
$this->get(route('settings.company'))->assertForbidden();
|
||||
});
|
||||
@@ -6,9 +6,9 @@ use App\Modules\Customers\Domain\Entities\Customer;
|
||||
use App\Modules\Customers\Domain\Enums\CustomerType;
|
||||
use App\Modules\Customers\Domain\Events\CustomerRegistered;
|
||||
use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse;
|
||||
use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId;
|
||||
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
|
||||
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
|
||||
use App\Modules\Shared\Domain\Exceptions\InvalidBusinessId;
|
||||
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
|
||||
use Tests\Fakes\FakeEventDispatcher;
|
||||
use Tests\Fakes\FakeTransactionManager;
|
||||
use Tests\Fakes\InMemoryCustomerRepository;
|
||||
|
||||
@@ -6,8 +6,8 @@ use App\Modules\Customers\Domain\Entities\Customer;
|
||||
use App\Modules\Customers\Domain\Enums\CustomerType;
|
||||
use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse;
|
||||
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
|
||||
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
|
||||
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
|
||||
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
|
||||
use Tests\Fakes\FakeTransactionManager;
|
||||
use Tests\Fakes\InMemoryCustomerRepository;
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
use App\Modules\Customers\Domain\Entities\Customer;
|
||||
use App\Modules\Customers\Domain\Enums\CustomerType;
|
||||
use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId;
|
||||
use App\Modules\Customers\Domain\ValueObjects\BusinessId;
|
||||
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
|
||||
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
|
||||
|
||||
it('registers a company with a business id and no id yet', function () {
|
||||
$customer = Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company, new BusinessId('0737546-2'));
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Sales\Application\DTOs\SaleData;
|
||||
use App\Modules\Sales\Application\UseCases\CloseCashDay;
|
||||
use App\Modules\Sales\Application\UseCases\CreditQuickSale;
|
||||
use App\Modules\Sales\Application\UseCases\ReopenCashDay;
|
||||
use App\Modules\Sales\Application\UseCases\SellQuickSale;
|
||||
use App\Modules\Sales\Domain\Entities\CashDay;
|
||||
use App\Modules\Sales\Domain\Entities\QuickSale;
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayInFuture;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayNotClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CreditCannotBeCredited;
|
||||
use App\Modules\Sales\Domain\Exceptions\InvalidQuantity;
|
||||
use App\Modules\Sales\Domain\Exceptions\ProductNotSellable;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleAlreadyCredited;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
|
||||
use App\Modules\Sales\Domain\ValueObjects\CashDayBalance;
|
||||
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
|
||||
use App\Modules\Sales\Domain\ValueObjects\VatTotal;
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
use Tests\Fakes\FakeClock;
|
||||
use Tests\Fakes\FakeCustomerQueries;
|
||||
use Tests\Fakes\FakeQuickSaleHours;
|
||||
use Tests\Fakes\FakeQuickSaleProducts;
|
||||
use Tests\Fakes\FakeTransactionManager;
|
||||
use Tests\Fakes\InMemoryCashDayRepository;
|
||||
use Tests\Fakes\InMemoryQuickSaleRepository;
|
||||
|
||||
beforeEach(function () {
|
||||
$this->sales = new InMemoryQuickSaleRepository;
|
||||
$this->cashDays = new InMemoryCashDayRepository;
|
||||
$this->products = new FakeQuickSaleProducts;
|
||||
$this->hours = new FakeQuickSaleHours;
|
||||
$this->customers = new FakeCustomerQueries;
|
||||
$this->clock = new FakeClock(new DateTimeImmutable('2026-11-24'));
|
||||
$transactions = new FakeTransactionManager;
|
||||
|
||||
$this->sell = new SellQuickSale($this->sales, $this->cashDays, $this->products, $this->hours, $this->customers, $transactions, $this->clock);
|
||||
$this->credit = new CreditQuickSale($this->sales, $this->cashDays, $transactions, $this->clock);
|
||||
$this->close = new CloseCashDay($this->cashDays, $this->sales, $transactions, $this->clock);
|
||||
$this->reopen = new ReopenCashDay($this->cashDays, $transactions, $this->clock);
|
||||
|
||||
$this->products->add(1, 'Passikuvat', 1500, durationQuarters: 1, workTypeId: 7);
|
||||
$this->products->add(2, 'Digitointi', 2000, durationQuarters: 2, workTypeId: 7);
|
||||
$this->products->add(3, 'Kirja', 1000, vatBasisPoints: 1000);
|
||||
});
|
||||
|
||||
it('totals a sale and credits it with the lines negated and the same payment method', function () {
|
||||
$sale = QuickSale::reconstitute(5, 1, null, PaymentMethod::Card, new DateTimeImmutable, new DateTimeImmutable('2026-11-20'), [
|
||||
QuickSaleLine::sold(1, 'Passikuvat', 2, 1500, 2550),
|
||||
QuickSaleLine::sold(3, 'Kirja', 1, 1000, 1000),
|
||||
], null);
|
||||
$credit = QuickSale::creditFor($sale, 9, new DateTimeImmutable, new DateTimeImmutable('2026-11-24'));
|
||||
|
||||
expect($sale->totalCents())->toBe(4000)
|
||||
->and($credit->totalCents())->toBe(-4000)
|
||||
->and($credit->paymentMethod())->toBe(PaymentMethod::Card)
|
||||
->and($credit->creditsSaleId())->toBe(5)
|
||||
->and($credit->sellerId())->toBe(9)
|
||||
->and(array_map(fn (QuickSaleLine $line): int => $line->quantity, $credit->lines()))->toBe([-2, -1]);
|
||||
|
||||
QuickSale::creditFor(QuickSale::reconstitute(6, 1, null, PaymentMethod::Card, new DateTimeImmutable, new DateTimeImmutable, $credit->lines(), 5), 9, new DateTimeImmutable, new DateTimeImmutable);
|
||||
})->throws(CreditCannotBeCredited::class);
|
||||
|
||||
it('rejects empty sales and quantities outside 1–999', function (callable $make) {
|
||||
$make();
|
||||
})->with([
|
||||
'no lines' => [fn () => QuickSale::sell(1, null, PaymentMethod::Cash, [], new DateTimeImmutable, new DateTimeImmutable)],
|
||||
'zero' => [fn () => QuickSaleLine::sold(1, 'A', 0, 100, 0)],
|
||||
'too many' => [fn () => QuickSaleLine::sold(1, 'A', 1000, 100, 0)],
|
||||
])->throws(DomainException::class);
|
||||
|
||||
it('takes the VAT out of each rate\'s total, credits included', function () {
|
||||
$day = new DateTimeImmutable('2026-11-24');
|
||||
$balance = CashDayBalance::of([
|
||||
QuickSale::sell(1, null, PaymentMethod::Cash, [QuickSaleLine::sold(1, 'A', 3, 1500, 2550)], $day, $day),
|
||||
QuickSale::sell(1, null, PaymentMethod::Card, [QuickSaleLine::sold(3, 'B', 1, 1000, 1000), QuickSaleLine::sold(1, 'A', 1, 1500, 2550)], $day, $day),
|
||||
QuickSale::reconstitute(9, 1, null, PaymentMethod::Cash, $day, $day, [new QuickSaleLine(1, 'A', -1, 1500, 2550)], 1),
|
||||
]);
|
||||
|
||||
expect($balance->saleCount)->toBe(3)
|
||||
->and($balance->cashCents)->toBe(3000)
|
||||
->and($balance->cardCents)->toBe(2500)
|
||||
->and($balance->totalCents())->toBe(5500)
|
||||
->and($balance->vatTotals)->toEqual([
|
||||
new VatTotal(2550, 4500, 3586, 914),
|
||||
new VatTotal(1000, 1000, 909, 91),
|
||||
])
|
||||
->and(VatTotal::ofGross(2550, -1500))->toEqual(new VatTotal(2550, -1500, -1195, -305));
|
||||
});
|
||||
|
||||
it('sells at current prices on today and books the hours by work type', function () {
|
||||
$result = $this->sell->execute(4, new SaleData([1 => 2, 2 => 1, 3 => 1], 'card'));
|
||||
|
||||
$sale = $this->sales->findById($result->saleId);
|
||||
|
||||
expect($result->totalCents)->toBe(6000)
|
||||
->and($result->bookedQuarters)->toBe(4)
|
||||
->and($result->unbookedQuarters)->toBe(0)
|
||||
->and($sale->soldOn()->format('Y-m-d'))->toBe('2026-11-24')
|
||||
->and($sale->paymentMethod())->toBe(PaymentMethod::Card)
|
||||
->and($this->hours->booked)->toBe([[4, '2026-11-24', 7, 4, $result->saleId]]);
|
||||
});
|
||||
|
||||
it('keeps the sale when the hours cannot be booked', function () {
|
||||
$this->hours->fails = true;
|
||||
|
||||
$result = $this->sell->execute(4, new SaleData([1 => 1], 'cash'));
|
||||
|
||||
expect($result->bookedQuarters)->toBe(0)
|
||||
->and($result->unbookedQuarters)->toBe(1)
|
||||
->and($this->sales->sales)->toHaveCount(1);
|
||||
});
|
||||
|
||||
it('rejects what cannot be sold', function (array $quantities, ?int $customerId, string $exception) {
|
||||
expect(fn () => $this->sell->execute(4, new SaleData($quantities, 'cash', $customerId)))->toThrow($exception);
|
||||
})->with([
|
||||
'unknown product' => [[99 => 1], null, ProductNotSellable::class],
|
||||
'no products' => [[], null, QuickSaleEmpty::class],
|
||||
'negative quantity' => [[1 => -1], null, InvalidQuantity::class],
|
||||
'unknown customer' => [[1 => 1], 5, QuickSaleCustomerNotFound::class],
|
||||
]);
|
||||
|
||||
it('credits a sale once, on today\'s cash day', function () {
|
||||
$saleId = $this->sell->execute(4, new SaleData([1 => 1], 'cash'))->saleId;
|
||||
$this->clock->today = new DateTimeImmutable('2026-11-25');
|
||||
|
||||
$creditId = $this->credit->execute($saleId, 8);
|
||||
|
||||
expect($this->sales->findById($creditId)->soldOn()->format('Y-m-d'))->toBe('2026-11-25')
|
||||
->and(fn () => $this->credit->execute($saleId, 8))->toThrow(QuickSaleAlreadyCredited::class);
|
||||
});
|
||||
|
||||
it('closes a day with its balance, refuses sales on it and lets it be reopened', function () {
|
||||
$this->sell->execute(4, new SaleData([1 => 2], 'cash'));
|
||||
$this->close->execute(new DateTimeImmutable('2026-11-24'), 4);
|
||||
|
||||
$day = $this->cashDays->forDay(new DateTimeImmutable('2026-11-24'));
|
||||
|
||||
expect($day->isClosed())->toBeTrue()
|
||||
->and($day->closedBy())->toBe(4)
|
||||
->and($day->balance()->totalCents())->toBe(3000)
|
||||
->and(fn () => $this->sell->execute(4, new SaleData([1 => 1], 'cash')))->toThrow(CashDayClosed::class)
|
||||
->and(fn () => $this->close->execute(new DateTimeImmutable('2026-11-24'), 4))->toThrow(CashDayClosed::class)
|
||||
->and(fn () => $this->close->execute(new DateTimeImmutable('2026-11-25'), 4))->toThrow(CashDayInFuture::class);
|
||||
|
||||
$this->reopen->execute(new DateTimeImmutable('2026-11-24'), 1);
|
||||
$day = $this->cashDays->forDay(new DateTimeImmutable('2026-11-24'));
|
||||
|
||||
expect($day->isClosed())->toBeFalse()
|
||||
->and($day->balance())->toBeNull()
|
||||
->and($day->reopenedBy())->toBe(1)
|
||||
->and(fn () => $this->reopen->execute(new DateTimeImmutable('2026-11-24'), 1))->toThrow(CashDayNotClosed::class);
|
||||
});
|
||||
|
||||
it('closes a day without sales with a zero balance', function () {
|
||||
$day = CashDay::open(new DateTimeImmutable('2026-11-24'));
|
||||
$day->close([], 1, new DateTimeImmutable);
|
||||
|
||||
expect($day->balance())->toEqual(CashDayBalance::empty());
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user