29 Commits
Author SHA1 Message Date
petriandClaude Opus 5.5 f16ad3c15b Show the Kanban columns as a carousel on phones, enlarge time sheet text
Below lg the board's columns form a snapping carousel with a strip of the
neighbouring columns on both sides, previous/next stage buttons and a
"Vaihe 2/7" status. A card dragged to the carousel's edge turns it to the
next column in that direction, and on while held there; Sortable's own
auto-scroll stays on only on desktop.

In the weekly time sheet the hour fields use a 14 px normal-weight font
and customer names are text-sm instead of text-xs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 19:42:02 +02:00
petriandClaude Opus 5.5 8be732ada8 Pass the choice to the Kanban column menus (they called the action without it)
Collection::join() plucks from objects, so joining the Js arguments gave an
empty string and the sort and urgent threshold menus called
setColumnSort() / setUrgentThreshold() with no arguments (500).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:59:14 +02:00
petriandClaude Opus 5.5 9eac4c4d4e Remember for each user which Kanban cards have their task list open
The open cards are kept in the user's board preferences (expanded_cards,
at most 500), saved without redrawing the board and restored on return.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:25:58 +02:00
petriandClaude Opus 5.5 e274a8d2b1 Scroll only the body of work dialogs, so there is one scrollbar
The native dialog scrolled too once its content outgrew the browser's
default max-height. It now clips to the viewport and only the body scrolls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:13:38 +02:00
petriandClaude Opus 5.5 f3d2b3e39e Give the editor's task checklist its own toggle, comments and images their tabs
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:05:44 +02:00
petriandClaude Opus 5.5 1d9bcefb41 Fix editor colour refresh, task row layout, dark date icons and time cell width
- The job editor redraws its customer-coloured header when the board saves
  a customer colour (customer-color-changed).
- Service units and members in the editor's sidebar are in two columns.
- Native controls follow the dark theme (color-scheme), so the date
  picker's calendar icon is light.
- Task status, assignee and due date sit side by side in the editor.
- Each task in the editor has its checklist, comments and images.
- The time sheet's time field shows five characters (00:00).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:00:53 +02:00
petriandClaude Opus 5.5 38c5b43018 Include the last day of a date range in expense and time entry queries
SQLite stores date casts as "Y-m-d 00:00:00", so a between ending at
"Y-m-d" left out the month's last day and the week's Sunday (the own
expenses test failed on the 30th). Ranges now end before the next day.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:47:01 +02:00
petriandClaude Opus 5.5 f24bd3cc35 Document the board, time sheet and colour pieces in CLAUDE.md
Also drops a redundant array_values() that Larastan flagged in MoveBoardCard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:32:15 +02:00
petri a4dbe8ce09 Kanban / timesheet update 2026-11-30 06:56:14 +02:00
petriandClaude Opus 5.5 6332ff0fa9 Rebuild the Kanban board after the prototype, with the job editor and quick intake dialog
- Toolbar: whose board (own, a person, a service line, all), pipeline
  views (daily, sales, full), urgent and late filters with a live count,
  normal and compact density, and the quick intake button.
- Columns side by side with horizontal scrolling on desktop, stacked on
  phones; each user's own column colours and order, the urgent column's
  threshold menu, and the continuing jobs column.
- Cards in customer colours: job cards with their tasks checked off inside
  the card (the status select is gone), continuing job cards with the next
  period, PIN and quick add, and pinned task cards. Dragging moves and
  orders cards; the keyboard opens the job editor from the card title.
- Job editor dialog: every job detail, tasks with checklists and
  templates, quick hours (TimeTracking) and expenses (Expenses), history.
- The quick intake form also adds a contact person, initial status and
  priority, and opens as a dialog on the board.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 06:33:28 +02:00
petriandClaude Opus 5.5 f4b58f6b1d Darken the dark canvas, add customer colours, the ongoing status and the board model
- Dark theme page background is #5a5e60; text on it is lifted to zinc-200 /
  primary-100 and TallStackUI's dark labels, hints and checkbox labels are
  lightened so everything stays at 4.5:1.
- Shared HexColor picks white or black text by the higher WCAG contrast; a
  native-dialog colour picker and a large work dialog component.
- Customers get a header colour (customers.header_color), set on the
  customer page.
- New job status Jatkuvat / Kausi (ongoing): open, never late, billed
  monthly like running jobs.
- Kanban model: board columns and views, urgent threshold, per-user board
  preferences (density, column colours and sort), card positions, tasks of
  continuing jobs pinned to the board, MoveBoardCard and board queries with
  logged hours from TimeTracking.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 06:11:49 +02:00
petriandClaude Opus 5.5 de168619b3 Card the remaining form pages in the new look
The tasks-from-template, expense, stock item, workflow template and task
hour forms sat inside @if blocks, so the earlier pass left them as bare
fields on the page background. They are now cards; the template table has
the indigo header row and primary focus rings, the expense billing fieldset
and workflow steps get an inner surface instead of a nested card, locked-job
notices are amber, and the item image picker button uses the primary colour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 11:15:09 +02:00
petriandClaude Opus 5.5 51b40b24fe Give the UI an indigo look with cards, status badges and empty states
- Dark indigo header and tinted page background; the mobile main menu gets
  its own row, in the same order as the keyboard reaches it.
- Page titles with an icon chip (x-page-title, x-page, x-page-header) and
  card sections (x-panel, the card utility); x-table styled as a card with
  an indigo header row in AppServiceProvider::styleTables().
- Job and task statuses, late work, unapproved hours and stock states as
  badges with icon and text (x-status-badge, x-jobs.status,
  x-jobs.task-status), never colour alone.
- Empty lists as x-empty-state; dashboard quick link tiles, week hour bars
  and trend arrows; Kanban columns and task cards edged by status; calendar
  today column and bar accents; quick sale, reports and machine console
  restyled; signed-out pages show the app name.
- Focus rings use the primary colour in both themes (white in the header).
- Document the components in CLAUDE.md; test the status badges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 10:53:10 +02:00
petriandClaude Sonnet 5.5 ef400054b0 Return stock of cancelled maintenance, throttle the PIN page's password
Cancelling a maintenance record now reverses the stock it used, through
Inventory's new ReverseMaintenanceStockUse behind the MaintenanceMaterials
port, in the same transaction as the cancellation.

The PIN page allows 5 wrong current passwords a minute per user, as the
login form does, so a signed-in session cannot be used to guess the
password.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 10:10:18 +02:00
petriandClaude Sonnet 5.5 6692396a63 Fix console hours, sign-in landing and counter usage races
- Hours the counter reading cannot parse (",5") no longer fail after
  they are saved; they just get no hour counter suggestion.
- The console's sign-in falls back to a console machine list
  (machines::console-picker at /console/machines) instead of /machines,
  so it stays in the console's own session.
- Recording counter usage locks the counter first, so usage saved at
  the same time from two devices is not lost.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 10:05:02 +02:00
petriandClaude Sonnet 5.5 32c33e2a64 Give the machine console its own session with PIN sign-in, make counters cumulative
The console under console/ has its own session cookie and console guard
(UseConsoleSession), so signing out or changing user there leaves the
normal interface alone. Links open it in a new window through a one-time
handoff key; a signed-out console asks for a PIN code or password on its
own login page. Users set their 4-6 digit PIN on the profile's PIN page,
and the console's change user dialog takes it on a keypad; five wrong
PINs lock PIN sign-in for 15 minutes.

Machine counters are cumulative: users record how much a job used and it
is added to the latest reading. A maintenance record restarts the whole
counter interval from the reading at the record.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 09:58:11 +02:00
petriandClaude Sonnet 5.5 87e38260dc Show a task card's actions above tabs for notes, images and materials
The opened task card keeps its details and description at the top, then
the status, book hours, edit and remove actions, and below them tabs:
checklist and comments, images, and materials and machines. The tabs are
a project component (x-tabs) after the WAI-ARIA pattern, because
TallStackUI's tab ties its panels to missing ids and has no arrow keys.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 09:58:04 +02:00
petriandClaude Sonnet 5.5 701f05780f Change a quick sale order before making starts
An unpaid order whose lines have no completed step can be reopened in the
cart from the open orders list; saving replaces its lines with current
prices and processes, moves the machine work list rows and keeps the
pickup number. Keyboard browser tests cover changing and cancelling an
order and moving production steps.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 09:11:36 +02:00
petri acf87aa3cd Calender test 2026-11-27 09:46:09 +02:00
petriandClaude Sonnet 5.5 3207d0064a Report stock usage and value, add material cost to profitability, document phase 5
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 17:24:07 +02:00
petriandClaude Sonnet 5.5 38b8075a9c Make quick sale products on machines as orders paid when ready
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 17:11:54 +02:00
petriandClaude Sonnet 5.5 920fecdeb2 Add the touch-screen machine console
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:57:56 +02:00
petriandClaude Sonnet 5.5 3e1c671949 Track machine counters and maintenance with counter and time intervals
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:52:49 +02:00
petriandClaude Sonnet 5.5 aac579257a Add machines with day-by-day work lists for job tasks
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:43:55 +02:00
petriandClaude Sonnet 5.5 0de0e332b2 Count stock and correct the differences on confirmation
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:34:08 +02:00
petriandClaude Sonnet 5.5 bca1eed166 Record used material on tasks and suggest workflow steps' default materials
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:28:16 +02:00
petriandClaude Sonnet 5.5 30132deb0e Add stock items, groups and movements at a moving average cost
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:18:59 +02:00
petriandClaude Sonnet 5.5 361a2974cf Let a service unit use stock and machines
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:01:59 +02:00
petriandClaude Sonnet 5.5 d160854b79 Email quick sale receipts and send them again from the sales list
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:00:15 +02:00
588 changed files with 38816 additions and 1497 deletions
+4 -2
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -33,7 +33,7 @@ use Illuminate\Support\Carbon;
* @property-read UserMoneyPermissionsModel|null $moneyPermissions * @property-read UserMoneyPermissionsModel|null $moneyPermissions
*/ */
#[Fillable(['name', 'email', 'password', 'role', 'is_active', 'employment_ends_on', 'supervisor_id', 'locale'])] #[Fillable(['name', 'email', 'password', 'role', 'is_active', 'employment_ends_on', 'supervisor_id', 'locale'])]
#[Hidden(['password', 'remember_token'])] #[Hidden(['password', 'remember_token', 'pin_hash'])]
class User extends Authenticatable implements HasLocalePreference class User extends Authenticatable implements HasLocalePreference
{ {
/** @use HasFactory<UserFactory> */ /** @use HasFactory<UserFactory> */
@@ -21,8 +21,8 @@ use App\Modules\Jobs\Domain\Enums\PaymentBasis;
*/ */
class JobsForBilling implements BillingJobs class JobsForBilling implements BillingJobs
{ {
/** Statuses in which a monthly fee job is billed: running or done. */ /** Statuses in which a monthly fee job is billed: running, ongoing or done. */
private const array MONTHLY_STATUSES = [JobStatus::Order, JobStatus::InProduction, JobStatus::OnHold, JobStatus::Done]; private const array MONTHLY_STATUSES = [JobStatus::Order, JobStatus::InProduction, JobStatus::OnHold, JobStatus::Done, JobStatus::Ongoing];
public function __construct( public function __construct(
private CustomerJobQueries $jobs, private CustomerJobQueries $jobs,
@@ -318,7 +318,7 @@ new class extends Component
<div class="space-y-2"> <div class="space-y-2">
<p><x-link :href="route('billing.index')" navigate>{{ __('billing.export.back') }}</x-link></p> <p><x-link :href="route('billing.index')" navigate>{{ __('billing.export.back') }}</x-link></p>
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="document-arrow-down">{{ $this->heading() }}</x-page-title>
<p class="flex items-center gap-2 text-sm"> <p class="flex items-center gap-2 text-sm">
@if ($export->isDraft()) @if ($export->isDraft())
<x-icon name="pencil-square" class="size-5 shrink-0" aria-hidden="true" /> <x-icon name="pencil-square" class="size-5 shrink-0" aria-hidden="true" />
@@ -353,16 +353,16 @@ new class extends Component
wire:change="savePeriod($event.target.value)" wire:change="savePeriod($event.target.value)"
aria-describedby="billing-period-help @error('period') billing-period-error @enderror" aria-describedby="billing-period-help @error('period') billing-period-error @enderror"
@error('period') aria-invalid="true" @enderror @error('period') aria-invalid="true" @enderror
class="w-full rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400 dark:[color-scheme:dark]" class="w-full rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400 dark:[color-scheme:dark]"
/> />
<p id="billing-period-help" class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('billing.export.period_help') }}</p> <p id="billing-period-help" class="text-xs text-zinc-600 dark:text-zinc-200">{{ __('billing.export.period_help') }}</p>
@error('period') @error('period')
<p id="billing-period-error" class="text-xs text-red-700 dark:text-red-400">{{ $message }}</p> <p id="billing-period-error" class="text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror @enderror
</div> </div>
@if ($export->hasProblems()) @if ($export->hasProblems())
<p class="flex items-start gap-2 rounded-lg border border-amber-700 p-4 text-sm dark:border-amber-400"> <p class="flex items-start gap-2 rounded-lg border border-amber-700 bg-amber-50 p-4 text-sm text-amber-950 dark:border-amber-400 dark:bg-amber-400/10 dark:text-amber-100">
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" /> <x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
{{ __('billing.export.problems') }} {{ __('billing.export.problems') }}
</p> </p>
@@ -380,11 +380,11 @@ new class extends Component
<h2 id="invoices-heading" class="text-xl font-semibold">{{ __('billing.invoices.title') }}</h2> <h2 id="invoices-heading" class="text-xl font-semibold">{{ __('billing.invoices.title') }}</h2>
@if ($export->invoices === []) @if ($export->invoices === [])
<p class="text-sm">{{ __('billing.invoices.none') }}</p> <x-empty-state icon="banknotes">{{ __('billing.invoices.none') }}</x-empty-state>
@endif @endif
@foreach ($export->invoices as $invoiceNumber => $invoice) @foreach ($export->invoices as $invoiceNumber => $invoice)
<section wire:key="invoice-{{ $invoice->key }}" aria-labelledby="invoice-{{ $invoice->key }}-heading" class="space-y-4 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900"> <section wire:key="invoice-{{ $invoice->key }}" aria-labelledby="invoice-{{ $invoice->key }}-heading" class="card space-y-4">
<div class="space-y-1"> <div class="space-y-1">
<h3 id="invoice-{{ $invoice->key }}-heading" class="text-lg font-semibold">{{ __('billing.invoices.heading', ['number' => $invoiceNumber + 1, 'customer' => $invoice->customerName]) }}</h3> <h3 id="invoice-{{ $invoice->key }}-heading" class="text-lg font-semibold">{{ __('billing.invoices.heading', ['number' => $invoiceNumber + 1, 'customer' => $invoice->customerName]) }}</h3>
<dl class="grid gap-x-4 gap-y-1 text-sm sm:grid-cols-[auto_1fr]"> <dl class="grid gap-x-4 gap-y-1 text-sm sm:grid-cols-[auto_1fr]">
@@ -428,7 +428,7 @@ new class extends Component
<table class="w-full text-sm"> <table class="w-full text-sm">
<caption class="mb-1 text-left font-medium">{{ __('billing.jobs.months_caption', ['job' => $job->label()]) }}</caption> <caption class="mb-1 text-left font-medium">{{ __('billing.jobs.months_caption', ['job' => $job->label()]) }}</caption>
<thead> <thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600"> <tr class="border-b-2 border-primary-200 text-left text-primary-900 dark:border-primary-800 dark:text-primary-100">
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.month') }}</th> <th scope="col" class="py-2 pr-3">{{ __('billing.jobs.month') }}</th>
<th scope="col" class="py-2 text-right">{{ __('billing.jobs.amount') }}</th> <th scope="col" class="py-2 text-right">{{ __('billing.jobs.amount') }}</th>
</tr> </tr>
@@ -463,7 +463,7 @@ new class extends Component
<table class="w-full text-sm"> <table class="w-full text-sm">
<caption class="sr-only">{{ __('billing.jobs.hours_caption', ['job' => $job->label()]) }}</caption> <caption class="sr-only">{{ __('billing.jobs.hours_caption', ['job' => $job->label()]) }}</caption>
<thead> <thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600"> <tr class="border-b-2 border-primary-200 text-left text-primary-900 dark:border-primary-800 dark:text-primary-100">
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.work_type') }}</th> <th scope="col" class="py-2 pr-3">{{ __('billing.jobs.work_type') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.jobs.approved_hours') }}</th> <th scope="col" class="py-2 pr-3 text-right">{{ __('billing.jobs.approved_hours') }}</th>
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.billable_hours') }}</th> <th scope="col" class="py-2 pr-3">{{ __('billing.jobs.billable_hours') }}</th>
@@ -488,7 +488,7 @@ new class extends Component
aria-label="{{ __('billing.jobs.billable_label', ['work_type' => $row->name]) }}" aria-label="{{ __('billing.jobs.billable_label', ['work_type' => $row->name]) }}"
aria-describedby="hours-help-{{ $job->jobId }}" aria-describedby="hours-help-{{ $job->jobId }}"
@error('hours.'.$job->jobId.'.'.$row->workTypeId) aria-invalid="true" aria-errormessage="{{ $fieldId }}-error" @enderror @error('hours.'.$job->jobId.'.'.$row->workTypeId) aria-invalid="true" aria-errormessage="{{ $fieldId }}-error" @enderror
class="w-20 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400" class="w-20 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400"
/> />
@if ($row->isAdjusted) @if ($row->isAdjusted)
<span class="ml-1 text-xs">({{ __('billing.jobs.adjusted') }})</span> <span class="ml-1 text-xs">({{ __('billing.jobs.adjusted') }})</span>
@@ -504,7 +504,7 @@ new class extends Component
</tbody> </tbody>
</table> </table>
</div> </div>
<p id="hours-help-{{ $job->jobId }}" class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('billing.jobs.billable_help') }}</p> <p id="hours-help-{{ $job->jobId }}" class="text-xs text-zinc-600 dark:text-zinc-200">{{ __('billing.jobs.billable_help') }}</p>
@endif @endif
@php($expenseLines = $this->linesOfKind($job, LineKind::Expense)) @php($expenseLines = $this->linesOfKind($job, LineKind::Expense))
@@ -512,7 +512,7 @@ new class extends Component
<table class="w-full text-sm"> <table class="w-full text-sm">
<caption class="mb-1 text-left font-medium">{{ __('billing.jobs.expenses_caption', ['job' => $job->label()]) }}</caption> <caption class="mb-1 text-left font-medium">{{ __('billing.jobs.expenses_caption', ['job' => $job->label()]) }}</caption>
<thead> <thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600"> <tr class="border-b-2 border-primary-200 text-left text-primary-900 dark:border-primary-800 dark:text-primary-100">
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.expense') }}</th> <th scope="col" class="py-2 pr-3">{{ __('billing.jobs.expense') }}</th>
<th scope="col" class="py-2 text-right">{{ __('billing.jobs.amount') }}</th> <th scope="col" class="py-2 text-right">{{ __('billing.jobs.amount') }}</th>
</tr> </tr>
@@ -557,7 +557,7 @@ new class extends Component
<table class="w-full text-sm"> <table class="w-full text-sm">
<caption class="sr-only">{{ __('billing.lines.caption', ['job' => $job->label()]) }}</caption> <caption class="sr-only">{{ __('billing.lines.caption', ['job' => $job->label()]) }}</caption>
<thead> <thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600"> <tr class="border-b-2 border-primary-200 text-left text-primary-900 dark:border-primary-800 dark:text-primary-100">
<th scope="col" class="py-2 pr-3">{{ __('billing.lines.description') }}</th> <th scope="col" class="py-2 pr-3">{{ __('billing.lines.description') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.lines.recorded') }}</th> <th scope="col" class="py-2 pr-3 text-right">{{ __('billing.lines.recorded') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.lines.quantity') }}</th> <th scope="col" class="py-2 pr-3 text-right">{{ __('billing.lines.quantity') }}</th>
@@ -630,7 +630,7 @@ new class extends Component
<p class="text-sm">{{ __('billing.available.intro') }}</p> <p class="text-sm">{{ __('billing.available.intro') }}</p>
@if ($export->availableJobs === []) @if ($export->availableJobs === [])
<p class="text-sm">{{ __('billing.available.none') }}</p> <x-empty-state icon="banknotes">{{ __('billing.available.none') }}</x-empty-state>
@else @else
<x-table :headers="$this->availableHeaders()" :rows="$export->availableJobs"> <x-table :headers="$this->availableHeaders()" :rows="$export->availableJobs">
@interact('column_job', $available) @interact('column_job', $available)
@@ -87,7 +87,7 @@ new class extends Component
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
<div class="space-y-2"> <div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('billing.index.title') }}</h1> <x-page-title icon="banknotes">{{ __('billing.index.title') }}</x-page-title>
<p class="max-w-3xl text-sm">{{ __('billing.index.intro') }}</p> <p class="max-w-3xl text-sm">{{ __('billing.index.intro') }}</p>
</div> </div>
@@ -102,7 +102,7 @@ new class extends Component
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $statusMessage }}</p> <p role="status" aria-live="polite" class="text-sm font-medium">{{ $statusMessage }}</p>
@if ($this->exports === []) @if ($this->exports === [])
<p class="text-sm">{{ __('billing.index.none') }}</p> <x-empty-state icon="banknotes">{{ __('billing.index.none') }}</x-empty-state>
@else @else
<x-table :headers="$this->headers()" :rows="$this->exports"> <x-table :headers="$this->headers()" :rows="$this->exports">
@interact('column_number', $export) @interact('column_number', $export)
@@ -78,11 +78,11 @@ new class extends Component
<div class="mx-auto max-w-4xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-4xl space-y-6 p-4 sm:p-6">
<div class="space-y-2"> <div class="space-y-2">
<p><x-link :href="route('jobs.show', $job->id)" navigate>{{ __('billing.job_months.back') }}</x-link></p> <p><x-link :href="route('jobs.show', $job->id)" navigate>{{ __('billing.job_months.back') }}</x-link></p>
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="calendar">{{ $this->heading() }}</x-page-title>
<p class="max-w-3xl text-sm">{{ __('billing.job_months.intro') }}</p> <p class="max-w-3xl text-sm">{{ __('billing.job_months.intro') }}</p>
</div> </div>
<section aria-labelledby="summary-heading" class="space-y-2"> <section aria-labelledby="summary-heading" class="card space-y-2">
<h2 id="summary-heading" class="sr-only">{{ __('billing.job_months.summary') }}</h2> <h2 id="summary-heading" class="sr-only">{{ __('billing.job_months.summary') }}</h2>
<dl class="grid grid-cols-1 gap-x-6 gap-y-1 text-sm sm:grid-cols-[auto_1fr]"> <dl class="grid grid-cols-1 gap-x-6 gap-y-1 text-sm sm:grid-cols-[auto_1fr]">
<dt class="font-medium">{{ __('billing.job_months.customer') }}</dt> <dt class="font-medium">{{ __('billing.job_months.customer') }}</dt>
@@ -113,7 +113,7 @@ new class extends Component
<h2 id="billed-heading" class="text-xl font-semibold">{{ __('billing.job_months.billed_title', ['count' => count($billing->billed)]) }}</h2> <h2 id="billed-heading" class="text-xl font-semibold">{{ __('billing.job_months.billed_title', ['count' => count($billing->billed)]) }}</h2>
@if ($billing->billed === []) @if ($billing->billed === [])
<p class="text-sm">{{ __('billing.job_months.none_billed') }}</p> <x-empty-state icon="banknotes">{{ __('billing.job_months.none_billed') }}</x-empty-state>
@else @else
<x-table :headers="$this->headers()" :rows="$billing->billed"> <x-table :headers="$this->headers()" :rows="$billing->billed">
@interact('column_month', $month) @interact('column_month', $month)
@@ -137,7 +137,7 @@ new class extends Component
@endif @endif
</section> </section>
<section aria-labelledby="unbilled-heading" class="space-y-3"> <section aria-labelledby="unbilled-heading" class="card space-y-3">
<h2 id="unbilled-heading" class="text-xl font-semibold">{{ __('billing.job_months.unbilled_title', ['month' => $this->monthLabel($billing->currentMonth)]) }}</h2> <h2 id="unbilled-heading" class="text-xl font-semibold">{{ __('billing.job_months.unbilled_title', ['month' => $this->monthLabel($billing->currentMonth)]) }}</h2>
@if ($billing->unbilled === []) @if ($billing->unbilled === [])
@@ -38,6 +38,14 @@ interface CatalogQueries
*/ */
public function activeWorkTypesFor(array $serviceUnitIds): array; public function activeWorkTypesFor(array $serviceUnitIds): array;
/**
* Active service units where stock and machine features are in use
* (spec 19), in catalog order.
*
* @return list<int>
*/
public function stockServiceUnitIds(): array;
public function findServiceUnit(int $id): ?ServiceUnitSummary; public function findServiceUnit(int $id): ?ServiceUnitSummary;
/** /**
@@ -11,5 +11,6 @@ final readonly class ServiceUnitSummary
public string $name, public string $name,
public bool $isShared, public bool $isShared,
public bool $isActive, public bool $isActive,
public bool $usesStock = false,
) {} ) {}
} }
@@ -5,27 +5,45 @@ declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs; namespace App\Modules\Catalog\Application\DTOs;
/** /**
* A step of a workflow template as entered. A null work type means the template's own. * A step of a workflow template as entered. A null work type means the
* template's own. Materials are the step's default materials: a stock item
* id and the quantity as typed ("2,5").
*/ */
final readonly class WorkflowStepData final readonly class WorkflowStepData
{ {
/**
* @param list<array{stockItemId: int, quantity: string}> $materials
*/
public function __construct( public function __construct(
public string $title, public string $title,
public ?string $description = null, public ?string $description = null,
public ?int $workTypeId = null, public ?int $workTypeId = null,
public array $materials = [],
) {} ) {}
/** /**
* @param array{title?: string, description?: string|null, work_type_id?: int|string|null} $input * Rows without an item are left out.
*
* @param array{title?: string, description?: string|null, work_type_id?: int|string|null, materials?: list<array{stock_item_id?: int|string|null, quantity?: string|null}>} $input
*/ */
public static function fromArray(array $input): self public static function fromArray(array $input): self
{ {
$workTypeId = $input['work_type_id'] ?? null; $workTypeId = $input['work_type_id'] ?? null;
$materials = [];
foreach ($input['materials'] ?? [] as $material) {
$itemId = $material['stock_item_id'] ?? null;
if ($itemId !== null && $itemId !== '') {
$materials[] = ['stockItemId' => (int) $itemId, 'quantity' => (string) ($material['quantity'] ?? '')];
}
}
return new self( return new self(
(string) ($input['title'] ?? ''), (string) ($input['title'] ?? ''),
$input['description'] ?? null, $input['description'] ?? null,
$workTypeId === null || $workTypeId === '' ? null : (int) $workTypeId, $workTypeId === null || $workTypeId === '' ? null : (int) $workTypeId,
$materials,
); );
} }
} }
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A default material of a workflow step: a stock item and its quantity in
* thousandths of the item's unit.
*/
final readonly class WorkflowStepMaterialSummary
{
public function __construct(
public int $stockItemId,
public int $quantityMilli,
) {}
}
@@ -6,15 +6,20 @@ namespace App\Modules\Catalog\Application\DTOs;
/** /**
* A step of a workflow template. $workTypeId is the step's own work type * A step of a workflow template. $workTypeId is the step's own work type
* (null: the template's), $effectiveWorkTypeId the one its task gets. * (null: the template's), $effectiveWorkTypeId the one its task gets, and
* $materials the default materials suggested on the task.
*/ */
final readonly class WorkflowStepSummary final readonly class WorkflowStepSummary
{ {
/**
* @param list<WorkflowStepMaterialSummary> $materials
*/
public function __construct( public function __construct(
public string $title, public string $title,
public ?string $description, public ?string $description,
public ?int $workTypeId, public ?int $workTypeId,
public int $effectiveWorkTypeId, public int $effectiveWorkTypeId,
public string $workTypeName, public string $workTypeName,
public array $materials = [],
) {} ) {}
} }
@@ -8,9 +8,11 @@ use App\Modules\Catalog\Application\DTOs\WorkflowStepData;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository; use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository; use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Domain\Entities\WorkType; use App\Modules\Catalog\Domain\Entities\WorkType;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepMaterial;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle; use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle;
use App\Modules\Catalog\Domain\Exceptions\WorkflowStepWorkTypeNotAllowed; use App\Modules\Catalog\Domain\Exceptions\WorkflowStepWorkTypeNotAllowed;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStep; use App\Modules\Catalog\Domain\ValueObjects\WorkflowStep;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepMaterial;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepTitle; use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepTitle;
/** /**
@@ -28,6 +30,7 @@ final class WorkflowStepBuilder
* @return list<WorkflowStep> * @return list<WorkflowStep>
* *
* @throws InvalidWorkflowStepTitle with the index of the step * @throws InvalidWorkflowStepTitle with the index of the step
* @throws InvalidWorkflowStepMaterial with the indexes of the step and the material
*/ */
public function build(array $input): array public function build(array $input): array
{ {
@@ -40,7 +43,17 @@ final class WorkflowStepBuilder
throw new InvalidWorkflowStepTitle($index); throw new InvalidWorkflowStepTitle($index);
} }
$steps[] = new WorkflowStep($title, $step->description, $step->workTypeId); $materials = [];
foreach ($step->materials as $materialIndex => $material) {
try {
$materials[] = WorkflowStepMaterial::parse($material['stockItemId'], $material['quantity']);
} catch (InvalidWorkflowStepMaterial) {
throw new InvalidWorkflowStepMaterial($index, $materialIndex);
}
}
$steps[] = new WorkflowStep($title, $step->description, $step->workTypeId, $materials);
} }
return $steps; return $steps;
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\SharedUnitCannotUseStock;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Turns the stock and machine features on or off in a service unit. Turning
* them off hides the features; recorded movements and work lists stay.
*/
final class SetServiceUnitUsesStock
{
public function __construct(
private ServiceUnitRepository $serviceUnits,
private TransactionManager $transactions,
) {}
/**
* @throws CatalogItemNotFound
* @throws SharedUnitCannotUseStock
*/
public function execute(int $serviceUnitId, bool $usesStock): void
{
$this->transactions->run(function () use ($serviceUnitId, $usesStock): void {
$unit = $this->serviceUnits->findById($serviceUnitId) ?? throw new CatalogItemNotFound(CatalogLevel::ServiceUnit, $serviceUnitId);
$unit->useStock($usesStock);
$this->serviceUnits->save($unit);
});
}
}
@@ -4,32 +4,51 @@ declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Entities; namespace App\Modules\Catalog\Domain\Entities;
use App\Modules\Catalog\Domain\Exceptions\SharedUnitCannotUseStock;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName; use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
/** /**
* A service unit (palveluyksikkö), e.g. Mediatuotanto. The shared unit * A service unit (palveluyksikkö), e.g. Mediatuotanto. The shared unit
* ("Kaikille yhteiset") holds work types offered in every unit and has no * ("Kaikille yhteiset") holds work types offered in every unit and has no
* services. * services. A unit may use stock and machines (varaston ja koneiden
* käyttö); the shared unit follows the job's units instead.
*/ */
final class ServiceUnit extends CatalogItem final class ServiceUnit extends CatalogItem
{ {
private function __construct(?int $id, CatalogName $name, private bool $shared, bool $active, int $sortOrder) private function __construct(?int $id, CatalogName $name, private bool $shared, bool $active, int $sortOrder, private bool $usesStock)
{ {
parent::__construct($id, $name, $active, $sortOrder); parent::__construct($id, $name, $active, $sortOrder);
} }
public static function create(CatalogName $name, int $sortOrder, bool $shared = false): self public static function create(CatalogName $name, int $sortOrder, bool $shared = false): self
{ {
return new self(null, $name, $shared, true, $sortOrder); return new self(null, $name, $shared, true, $sortOrder, false);
} }
public static function reconstitute(int $id, CatalogName $name, bool $shared, bool $active, int $sortOrder): self public static function reconstitute(int $id, CatalogName $name, bool $shared, bool $active, int $sortOrder, bool $usesStock = false): self
{ {
return new self($id, $name, $shared, $active, $sortOrder); return new self($id, $name, $shared, $active, $sortOrder, $usesStock);
} }
public function isShared(): bool public function isShared(): bool
{ {
return $this->shared; return $this->shared;
} }
public function usesStock(): bool
{
return $this->usesStock;
}
/**
* @throws SharedUnitCannotUseStock
*/
public function useStock(bool $usesStock): void
{
if ($usesStock && $this->shared) {
throw new SharedUnitCannotUseStock;
}
$this->usesStock = $usesStock;
}
} }
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* A step's default material has no item or no valid quantity. $stepIndex
* and $materialIndex count from 0 when known.
*/
final class InvalidWorkflowStepMaterial extends DomainException
{
public function __construct(public readonly ?int $stepIndex = null, public readonly ?int $materialIndex = null)
{
parent::__construct('A default material needs an item and a quantity greater than zero.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class SharedUnitCannotUseStock extends DomainException
{
public function __construct()
{
parent::__construct('The shared service unit follows the job\'s units and cannot use stock by itself.');
}
}
@@ -7,16 +7,20 @@ namespace App\Modules\Catalog\Domain\ValueObjects;
/** /**
* One step of a workflow template. A task is made of it: the title, the * One step of a workflow template. A task is made of it: the title, the
* description and the work type, which is the template's own when * description and the work type, which is the template's own when
* $workTypeId is null. * $workTypeId is null, and the default materials suggested on the task.
*/ */
final readonly class WorkflowStep final readonly class WorkflowStep
{ {
public ?string $description; public ?string $description;
/**
* @param list<WorkflowStepMaterial> $materials
*/
public function __construct( public function __construct(
public WorkflowStepTitle $title, public WorkflowStepTitle $title,
?string $description = null, ?string $description = null,
public ?int $workTypeId = null, public ?int $workTypeId = null,
public array $materials = [],
) { ) {
$description = $description === null ? '' : trim($description); $description = $description === null ? '' : trim($description);
$this->description = $description === '' ? null : $description; $this->description = $description === '' ? null : $description;
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\ValueObjects;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepMaterial;
/**
* A default material of a workflow step (spec 19.4): a stock item and its
* quantity in thousandths of the item's unit, suggested on the step's task.
*/
final readonly class WorkflowStepMaterial
{
public const int MAX_MILLI = 9_999_999_999;
public function __construct(
public int $stockItemId,
public int $quantityMilli,
) {
if ($stockItemId < 1 || $quantityMilli < 1 || $quantityMilli > self::MAX_MILLI) {
throw new InvalidWorkflowStepMaterial;
}
}
/**
* A quantity typed as "2,5" or "2.5", with at most three decimals.
*
* @throws InvalidWorkflowStepMaterial
*/
public static function parse(int $stockItemId, string $quantity): self
{
$quantity = str_replace(',', '.', preg_replace('/[\s\x{00A0}]+/u', '', $quantity) ?? '');
if (preg_match('/^(\d{1,7})(?:\.(\d{1,3}))?$/', $quantity, $matches) !== 1) {
throw new InvalidWorkflowStepMaterial;
}
return new self($stockItemId, (int) $matches[1] * 1000 + (int) str_pad($matches[2] ?? '', 3, '0'));
}
}
@@ -15,11 +15,12 @@ use Illuminate\Database\Eloquent\Model;
* @property int $id * @property int $id
* @property string $name * @property string $name
* @property bool $is_shared * @property bool $is_shared
* @property bool $uses_stock
* @property bool $is_active * @property bool $is_active
* @property int $sort_order * @property int $sort_order
*/ */
#[Table('service_units')] #[Table('service_units')]
#[Fillable(['name', 'is_shared', 'is_active', 'sort_order'])] #[Fillable(['name', 'is_shared', 'uses_stock', 'is_active', 'sort_order'])]
#[UseFactory(ServiceUnitFactory::class)] #[UseFactory(ServiceUnitFactory::class)]
class ServiceUnitModel extends Model class ServiceUnitModel extends Model
{ {
@@ -33,6 +34,7 @@ class ServiceUnitModel extends Model
{ {
return [ return [
'is_shared' => 'boolean', 'is_shared' => 'boolean',
'uses_stock' => 'boolean',
'is_active' => 'boolean', 'is_active' => 'boolean',
'sort_order' => 'integer', 'sort_order' => 'integer',
]; ];
@@ -0,0 +1,34 @@
<?php
namespace App\Modules\Catalog\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 Catalog Infrastructure layer.
*
* @property int $id
* @property int $workflow_template_step_id
* @property int $stock_item_id
* @property int $quantity_milli
* @property int $sort_order
*/
#[Table('workflow_template_step_materials')]
#[Fillable(['workflow_template_step_id', 'stock_item_id', 'quantity_milli', 'sort_order'])]
class WorkflowTemplateStepMaterialModel extends Model
{
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'workflow_template_step_id' => 'integer',
'stock_item_id' => 'integer',
'quantity_milli' => 'integer',
'sort_order' => 'integer',
];
}
}
@@ -5,6 +5,7 @@ namespace App\Modules\Catalog\Infrastructure\Persistence\Eloquent;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/** /**
* Persistence model, used only inside the Catalog Infrastructure layer. * Persistence model, used only inside the Catalog Infrastructure layer.
@@ -20,6 +21,14 @@ use Illuminate\Database\Eloquent\Model;
#[Fillable(['workflow_template_id', 'work_type_id', 'title', 'description', 'sort_order'])] #[Fillable(['workflow_template_id', 'work_type_id', 'title', 'description', 'sort_order'])]
class WorkflowTemplateStepModel extends Model class WorkflowTemplateStepModel extends Model
{ {
/**
* @return HasMany<WorkflowTemplateStepMaterialModel, $this>
*/
public function materials(): HasMany
{
return $this->hasMany(WorkflowTemplateStepMaterialModel::class, 'workflow_template_step_id')->orderBy('sort_order');
}
/** /**
* @return array<string, string> * @return array<string, string>
*/ */
@@ -42,6 +42,18 @@ class EloquentCatalogQueries implements CatalogQueries
return $this->buildTree($units, includeInactive: false); return $this->buildTree($units, includeInactive: false);
} }
public function stockServiceUnitIds(): array
{
return ServiceUnitModel::query()
->where('uses_stock', true)
->where('is_active', true)
->orderBy('sort_order')
->pluck('id')
->map(fn ($id): int => (int) $id)
->values()
->all();
}
public function findServiceUnit(int $id): ?ServiceUnitSummary public function findServiceUnit(int $id): ?ServiceUnitSummary
{ {
$model = ServiceUnitModel::query()->find($id); $model = ServiceUnitModel::query()->find($id);
@@ -139,7 +151,7 @@ class EloquentCatalogQueries implements CatalogQueries
private function toServiceUnitSummary(ServiceUnitModel $model): ServiceUnitSummary private function toServiceUnitSummary(ServiceUnitModel $model): ServiceUnitSummary
{ {
return new ServiceUnitSummary($model->id, $model->name, $model->is_shared, $model->is_active); return new ServiceUnitSummary($model->id, $model->name, $model->is_shared, $model->is_active, $model->uses_stock);
} }
private function toServiceSummary(ServiceModel $model): ServiceSummary private function toServiceSummary(ServiceModel $model): ServiceSummary
@@ -24,6 +24,7 @@ class EloquentServiceUnitRepository implements ServiceUnitRepository
$model->fill([ $model->fill([
'name' => $serviceUnit->name()->value, 'name' => $serviceUnit->name()->value,
'is_shared' => $serviceUnit->isShared(), 'is_shared' => $serviceUnit->isShared(),
'uses_stock' => $serviceUnit->usesStock(),
'is_active' => $serviceUnit->isActive(), 'is_active' => $serviceUnit->isActive(),
'sort_order' => $serviceUnit->sortOrder(), 'sort_order' => $serviceUnit->sortOrder(),
])->save(); ])->save();
@@ -56,6 +57,6 @@ class EloquentServiceUnitRepository implements ServiceUnitRepository
private function toEntity(ServiceUnitModel $model): ServiceUnit private function toEntity(ServiceUnitModel $model): ServiceUnit
{ {
return ServiceUnit::reconstitute($model->id, new CatalogName($model->name), $model->is_shared, $model->is_active, $model->sort_order); return ServiceUnit::reconstitute($model->id, new CatalogName($model->name), $model->is_shared, $model->is_active, $model->sort_order, $model->uses_stock);
} }
} }
@@ -3,10 +3,12 @@
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories; namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries; use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries;
use App\Modules\Catalog\Application\DTOs\WorkflowStepMaterialSummary;
use App\Modules\Catalog\Application\DTOs\WorkflowStepSummary; use App\Modules\Catalog\Application\DTOs\WorkflowStepSummary;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateDetails; use App\Modules\Catalog\Application\DTOs\WorkflowTemplateDetails;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateSummary; use App\Modules\Catalog\Application\DTOs\WorkflowTemplateSummary;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateModel; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepMaterialModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepModel; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
@@ -93,6 +95,7 @@ class EloquentWorkflowTemplateQueries implements WorkflowTemplateQueries
} }
$steps = WorkflowTemplateStepModel::query() $steps = WorkflowTemplateStepModel::query()
->with('materials')
->whereIn('workflow_template_id', $models->pluck('id')) ->whereIn('workflow_template_id', $models->pluck('id'))
->orderBy('sort_order') ->orderBy('sort_order')
->get() ->get()
@@ -119,6 +122,10 @@ class EloquentWorkflowTemplateQueries implements WorkflowTemplateQueries
$step->work_type_id, $step->work_type_id,
$step->work_type_id ?? $model->work_type_id, $step->work_type_id ?? $model->work_type_id,
$step->work_type_id === null ? $workTypeName : (string) $workTypeNames->get($step->work_type_id), $step->work_type_id === null ? $workTypeName : (string) $workTypeNames->get($step->work_type_id),
$step->materials
->map(fn (WorkflowTemplateStepMaterialModel $material): WorkflowStepMaterialSummary => new WorkflowStepMaterialSummary($material->stock_item_id, $material->quantity_milli))
->values()
->all(),
)) ))
->values() ->values()
->all(), ->all(),
@@ -6,15 +6,17 @@ use App\Modules\Catalog\Domain\Contracts\WorkflowTemplateRepository;
use App\Modules\Catalog\Domain\Entities\WorkflowTemplate; use App\Modules\Catalog\Domain\Entities\WorkflowTemplate;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName; use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStep; use App\Modules\Catalog\Domain\ValueObjects\WorkflowStep;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepMaterial;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepTitle; use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepTitle;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateModel; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepMaterialModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepModel; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepModel;
class EloquentWorkflowTemplateRepository implements WorkflowTemplateRepository class EloquentWorkflowTemplateRepository implements WorkflowTemplateRepository
{ {
public function findById(int $id): ?WorkflowTemplate public function findById(int $id): ?WorkflowTemplate
{ {
$model = WorkflowTemplateModel::query()->with('steps')->find($id); $model = WorkflowTemplateModel::query()->with('steps.materials')->find($id);
return $model === null ? null : $this->toEntity($model); return $model === null ? null : $this->toEntity($model);
} }
@@ -33,16 +35,25 @@ class EloquentWorkflowTemplateRepository implements WorkflowTemplateRepository
WorkflowTemplateStepModel::query()->where('workflow_template_id', $model->id)->delete(); WorkflowTemplateStepModel::query()->where('workflow_template_id', $model->id)->delete();
foreach ($template->steps() as $index => $step) { foreach ($template->steps() as $index => $step) {
WorkflowTemplateStepModel::query()->create([ $stepModel = WorkflowTemplateStepModel::query()->create([
'workflow_template_id' => $model->id, 'workflow_template_id' => $model->id,
'work_type_id' => $step->workTypeId, 'work_type_id' => $step->workTypeId,
'title' => $step->title->value, 'title' => $step->title->value,
'description' => $step->description, 'description' => $step->description,
'sort_order' => $index + 1, 'sort_order' => $index + 1,
]); ]);
foreach ($step->materials as $materialIndex => $material) {
WorkflowTemplateStepMaterialModel::query()->create([
'workflow_template_step_id' => $stepModel->id,
'stock_item_id' => $material->stockItemId,
'quantity_milli' => $material->quantityMilli,
'sort_order' => $materialIndex + 1,
]);
}
} }
return $this->toEntity($model->load('steps')); return $this->toEntity($model->load('steps.materials'));
} }
public function isNameTaken(int $workTypeId, string $name, ?int $exceptId = null): bool public function isNameTaken(int $workTypeId, string $name, ?int $exceptId = null): bool
@@ -66,6 +77,10 @@ class EloquentWorkflowTemplateRepository implements WorkflowTemplateRepository
new WorkflowStepTitle($step->title), new WorkflowStepTitle($step->title),
$step->description, $step->description,
$step->work_type_id, $step->work_type_id,
$step->materials
->map(fn (WorkflowTemplateStepMaterialModel $material): WorkflowStepMaterial => new WorkflowStepMaterial($material->stock_item_id, $material->quantity_milli))
->values()
->all(),
)) ))
->values() ->values()
->all(), ->all(),
@@ -6,6 +6,7 @@ use App\Modules\Catalog\Application\DTOs\WorkflowStepData;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateData; use App\Modules\Catalog\Application\DTOs\WorkflowTemplateData;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound; use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName; use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepMaterial;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle; use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle;
use App\Modules\Catalog\Domain\Exceptions\WorkflowStepWorkTypeNotAllowed; use App\Modules\Catalog\Domain\Exceptions\WorkflowStepWorkTypeNotAllowed;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNameTaken; use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNameTaken;
@@ -24,16 +25,34 @@ class WorkflowTemplateForm extends Form
public string $work_type_id = ''; public string $work_type_id = '';
/** /**
* @var list<array{key: int, title: string, work_type_id: string, description: string}> * @var list<array{key: int, title: string, work_type_id: string, description: string, materials: list<array{key: int, stock_item_id: string, quantity: string}>}>
*/ */
public array $steps = []; public array $steps = [];
public int $nextKey = 1; public int $nextKey = 1;
public function addStep(string $title = '', string $workTypeId = '', string $description = ''): int /**
* @param list<array{stock_item_id: string, quantity: string}> $materials
*/
public function addStep(string $title = '', string $workTypeId = '', string $description = '', array $materials = []): int
{ {
$key = $this->nextKey++; $key = $this->nextKey++;
$this->steps[] = ['key' => $key, 'title' => $title, 'work_type_id' => $workTypeId, 'description' => $description]; $this->steps[] = ['key' => $key, 'title' => $title, 'work_type_id' => $workTypeId, 'description' => $description, 'materials' => []];
foreach ($materials as $material) {
$this->addMaterial(count($this->steps) - 1, $material['stock_item_id'], $material['quantity']);
}
return $key;
}
/**
* Adds a default material row to a step and returns its key.
*/
public function addMaterial(int $stepIndex, string $stockItemId = '', string $quantity = '1'): int
{
$key = $this->nextKey++;
$this->steps[$stepIndex]['materials'][] = ['key' => $key, 'stock_item_id' => $stockItemId, 'quantity' => $quantity];
return $key; return $key;
} }
@@ -60,6 +79,7 @@ class WorkflowTemplateForm extends Form
$exception instanceof CatalogItemNotFound => ['work_type_id', 'catalog.errors.work_type_unavailable'], $exception instanceof CatalogItemNotFound => ['work_type_id', 'catalog.errors.work_type_unavailable'],
$exception instanceof WorkflowTemplateNeedsSteps => ['steps', 'catalog.workflows.errors.steps_required'], $exception instanceof WorkflowTemplateNeedsSteps => ['steps', 'catalog.workflows.errors.steps_required'],
$exception instanceof InvalidWorkflowStepTitle => ['steps.'.($exception->stepIndex ?? 0).'.title', 'catalog.workflows.errors.invalid_step_title'], $exception instanceof InvalidWorkflowStepTitle => ['steps.'.($exception->stepIndex ?? 0).'.title', 'catalog.workflows.errors.invalid_step_title'],
$exception instanceof InvalidWorkflowStepMaterial => ['steps.'.($exception->stepIndex ?? 0).'.materials.'.($exception->materialIndex ?? 0).'.quantity', 'catalog.workflows.errors.invalid_material'],
$exception instanceof WorkflowStepWorkTypeNotAllowed => ['steps.'.$exception->stepIndex.'.work_type_id', 'catalog.workflows.errors.step_work_type_not_allowed'], $exception instanceof WorkflowStepWorkTypeNotAllowed => ['steps.'.$exception->stepIndex.'.work_type_id', 'catalog.workflows.errors.step_work_type_not_allowed'],
default => throw $exception, default => throw $exception,
}; };
@@ -79,6 +99,9 @@ class WorkflowTemplateForm extends Form
'steps.*.title' => ['required', 'string', 'max:255'], 'steps.*.title' => ['required', 'string', 'max:255'],
'steps.*.work_type_id' => ['nullable', 'integer'], 'steps.*.work_type_id' => ['nullable', 'integer'],
'steps.*.description' => ['nullable', 'string', 'max:5000'], 'steps.*.description' => ['nullable', 'string', 'max:5000'],
'steps.*.materials' => ['array'],
'steps.*.materials.*.stock_item_id' => ['nullable', 'integer'],
'steps.*.materials.*.quantity' => ['nullable', 'string', 'max:20'],
]; ];
} }
@@ -98,6 +121,8 @@ class WorkflowTemplateForm extends Form
'steps.*.title.max' => __('catalog.workflows.errors.invalid_step_title'), 'steps.*.title.max' => __('catalog.workflows.errors.invalid_step_title'),
'steps.*.work_type_id.integer' => __('catalog.workflows.errors.step_work_type_not_allowed'), 'steps.*.work_type_id.integer' => __('catalog.workflows.errors.step_work_type_not_allowed'),
'steps.*.description.max' => __('catalog.workflows.errors.description_too_long'), 'steps.*.description.max' => __('catalog.workflows.errors.description_too_long'),
'steps.*.materials.*.stock_item_id.integer' => __('catalog.workflows.errors.invalid_material'),
'steps.*.materials.*.quantity.max' => __('catalog.workflows.errors.invalid_material'),
]; ];
} }
} }
@@ -114,13 +114,13 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4"> <div class="flex flex-wrap items-center justify-between gap-4">
<h1 class="text-2xl font-semibold">{{ __('catalog.title') }}</h1> <x-page-title icon="squares-plus">{{ __('catalog.title') }}</x-page-title>
<x-button :href="route('catalog.service-units.create')" wire:navigate icon="plus" :text="__('catalog.actions.add_service_unit')" /> <x-button :href="route('catalog.service-units.create')" wire:navigate icon="plus" :text="__('catalog.actions.add_service_unit')" />
</div> </div>
<div class="space-y-1 text-sm"> <div class="space-y-1 text-sm">
<p class="text-zinc-600 dark:text-zinc-300">{{ __('catalog.intro') }}</p> <p class="text-zinc-600 dark:text-zinc-200">{{ __('catalog.intro') }}</p>
<p><x-link :href="route('catalog.prices')" navigate>{{ __('catalog.prices_link') }}</x-link></p> <p><x-link :href="route('catalog.prices')" navigate>{{ __('catalog.prices_link') }}</x-link></p>
<p><x-link :href="route('catalog.workflow-templates')" navigate>{{ __('catalog.workflows_link') }}</x-link></p> <p><x-link :href="route('catalog.workflow-templates')" navigate>{{ __('catalog.workflows_link') }}</x-link></p>
</div> </div>
@@ -139,7 +139,7 @@ new class extends Component
<section <section
wire:key="service-unit-{{ $unit->id }}" wire:key="service-unit-{{ $unit->id }}"
aria-labelledby="service-unit-{{ $unit->id }}-heading" aria-labelledby="service-unit-{{ $unit->id }}-heading"
class="space-y-4 rounded-lg border border-zinc-200 p-4 dark:border-zinc-700" class="card space-y-4"
> >
<div class="flex flex-wrap items-center justify-between gap-3"> <div class="flex flex-wrap items-center justify-between gap-3">
<h2 id="service-unit-{{ $unit->id }}-heading" class="text-xl font-semibold break-words"> <h2 id="service-unit-{{ $unit->id }}-heading" class="text-xl font-semibold break-words">
@@ -159,7 +159,14 @@ new class extends Component
</div> </div>
@if ($unit->isShared) @if ($unit->isShared)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.shared') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.shared') }}</p>
@endif
@if ($unit->usesStock)
<p class="flex items-center gap-1 text-sm text-zinc-600 dark:text-zinc-200">
<x-icon name="archive-box" class="size-4" aria-hidden="true" />
{{ __('catalog.service_units.uses_stock_on') }}
</p>
@endif @endif
@foreach ($node->services as $serviceNode) @foreach ($node->services as $serviceNode)
@@ -121,16 +121,16 @@ new class extends Component
?> ?>
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6"> <div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ __('catalog.prices.title') }}</h1> <x-page-title icon="tag">{{ __('catalog.prices.title') }}</x-page-title>
<section aria-labelledby="consumer-products-heading" class="space-y-4"> <section aria-labelledby="consumer-products-heading" class="space-y-4">
<div class="space-y-1"> <div class="space-y-1">
<h2 id="consumer-products-heading" class="text-xl font-semibold">{{ __('catalog.price_list.consumer_products') }}</h2> <h2 id="consumer-products-heading" class="text-xl font-semibold">{{ __('catalog.price_list.consumer_products') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.price_list.consumer_help') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.price_list.consumer_help') }}</p>
</div> </div>
@if ($this->consumerProducts === []) @if ($this->consumerProducts === [])
<p class="text-sm">{{ __('catalog.products.none') }}</p> <x-empty-state icon="tag">{{ __('catalog.products.none') }}</x-empty-state>
@else @else
<x-table :headers="$this->consumerHeaders()" :rows="$this->consumerProducts"> <x-table :headers="$this->consumerHeaders()" :rows="$this->consumerProducts">
@interact('column_name', $product) @interact('column_name', $product)
@@ -156,7 +156,7 @@ new class extends Component
<section aria-labelledby="hourly-rates-heading" class="space-y-4"> <section aria-labelledby="hourly-rates-heading" class="space-y-4">
<div class="space-y-1"> <div class="space-y-1">
<h2 id="hourly-rates-heading" class="text-xl font-semibold">{{ __('catalog.prices.hourly_rates') }}</h2> <h2 id="hourly-rates-heading" class="text-xl font-semibold">{{ __('catalog.prices.hourly_rates') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.price_list.hourly_help') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.price_list.hourly_help') }}</p>
</div> </div>
@foreach ($this->hourlyRates as $group) @foreach ($this->hourlyRates as $group)
@@ -173,7 +173,7 @@ new class extends Component
<tr wire:key="rate-{{ $row->workTypeId }}" class="border-b border-zinc-200 dark:border-zinc-700"> <tr wire:key="rate-{{ $row->workTypeId }}" class="border-b border-zinc-200 dark:border-zinc-700">
<th scope="row" class="py-2 pr-3 text-left font-normal break-words"> <th scope="row" class="py-2 pr-3 text-left font-normal break-words">
@if ($row->serviceName !== null) @if ($row->serviceName !== null)
<span class="text-zinc-600 dark:text-zinc-300">{{ $row->serviceName }}:</span> <span class="text-zinc-600 dark:text-zinc-200">{{ $row->serviceName }}:</span>
@endif @endif
{{ $row->name }} {{ $row->name }}
</th> </th>
@@ -191,7 +191,7 @@ new class extends Component
<h2 id="other-products-heading" class="text-xl font-semibold">{{ __('catalog.price_list.other_products') }}</h2> <h2 id="other-products-heading" class="text-xl font-semibold">{{ __('catalog.price_list.other_products') }}</h2>
@if ($this->otherProducts === []) @if ($this->otherProducts === [])
<p class="text-sm">{{ __('catalog.products.none') }}</p> <x-empty-state icon="tag">{{ __('catalog.products.none') }}</x-empty-state>
@else @else
<x-table :headers="$this->otherHeaders()" :rows="$this->otherProducts"> <x-table :headers="$this->otherHeaders()" :rows="$this->otherProducts">
@interact('column_name', $product) @interact('column_name', $product)
@@ -217,7 +217,7 @@ new class extends Component
@endif @endif
</section> </section>
<section aria-labelledby="mileage-heading" class="space-y-2"> <section aria-labelledby="mileage-heading" class="card space-y-2">
<h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.mileage.title') }}</h2> <h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.mileage.title') }}</h2>
<p> <p>
{{ $this->mileageRateCents === null {{ $this->mileageRateCents === null
@@ -226,6 +226,6 @@ new class extends Component
</p> </p>
</section> </section>
@else @else
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.price_list.no_permission') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.price_list.no_permission') }}</p>
@endif @endif
</div> </div>
@@ -346,8 +346,8 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6"> <div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<div class="space-y-2"> <div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('catalog.prices.title') }}</h1> <x-page-title icon="tag">{{ __('catalog.prices.title') }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.prices.intro') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.prices.intro') }}</p>
</div> </div>
@if (session('status')) @if (session('status'))
@@ -364,7 +364,7 @@ new class extends Component
<section aria-labelledby="hourly-rates-heading" class="space-y-4"> <section aria-labelledby="hourly-rates-heading" class="space-y-4">
<div class="space-y-1"> <div class="space-y-1">
<h2 id="hourly-rates-heading" class="text-xl font-semibold">{{ __('catalog.prices.hourly_rates') }}</h2> <h2 id="hourly-rates-heading" class="text-xl font-semibold">{{ __('catalog.prices.hourly_rates') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.prices.hourly_rates_help') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.prices.hourly_rates_help') }}</p>
</div> </div>
@foreach ($this->hourlyRates as $group) @foreach ($this->hourlyRates as $group)
@@ -388,7 +388,7 @@ new class extends Component
<tr wire:key="rate-{{ $row->workTypeId }}" class="border-b border-zinc-200 align-top dark:border-zinc-700"> <tr wire:key="rate-{{ $row->workTypeId }}" class="border-b border-zinc-200 align-top dark:border-zinc-700">
<th scope="row" class="py-2 pr-3 text-left font-normal break-words"> <th scope="row" class="py-2 pr-3 text-left font-normal break-words">
@if ($row->serviceName !== null) @if ($row->serviceName !== null)
<span class="text-zinc-600 dark:text-zinc-300">{{ $row->serviceName }}:</span> <span class="text-zinc-600 dark:text-zinc-200">{{ $row->serviceName }}:</span>
@endif @endif
{{ $row->name }} {{ $row->name }}
@unless ($row->isActive) @unless ($row->isActive)
@@ -405,7 +405,7 @@ new class extends Component
wire:change="saveRate({{ $row->workTypeId }}, $event.target.value)" wire:change="saveRate({{ $row->workTypeId }}, $event.target.value)"
aria-label="{{ __('catalog.prices.rate_label', ['name' => ($row->serviceName !== null ? $row->serviceName.': ' : '').$row->name, 'unit' => $group->serviceUnitName]) }}" aria-label="{{ __('catalog.prices.rate_label', ['name' => ($row->serviceName !== null ? $row->serviceName.': ' : '').$row->name, 'unit' => $group->serviceUnitName]) }}"
@error('rates.'.$row->workTypeId) aria-invalid="true" aria-describedby="rate-{{ $row->workTypeId }}-error" @enderror @error('rates.'.$row->workTypeId) aria-invalid="true" aria-describedby="rate-{{ $row->workTypeId }}-error" @enderror
class="w-24 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400" class="w-24 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400"
/> />
@error('rates.'.$row->workTypeId) @error('rates.'.$row->workTypeId)
<p id="rate-{{ $row->workTypeId }}-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p> <p id="rate-{{ $row->workTypeId }}-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@@ -424,10 +424,10 @@ new class extends Component
<h2 id="products-heading" class="text-xl font-semibold">{{ __('catalog.products.title') }}</h2> <h2 id="products-heading" class="text-xl font-semibold">{{ __('catalog.products.title') }}</h2>
<x-button :href="route('catalog.products.create')" wire:navigate icon="plus" :text="__('catalog.products.add')" /> <x-button :href="route('catalog.products.create')" wire:navigate icon="plus" :text="__('catalog.products.add')" />
</div> </div>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.help') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.products.help') }}</p>
@if ($this->products === []) @if ($this->products === [])
<p class="text-sm">{{ __('catalog.products.none') }}</p> <x-empty-state icon="tag">{{ __('catalog.products.none') }}</x-empty-state>
@else @else
<x-table :headers="$this->productHeaders()" :rows="$this->products"> <x-table :headers="$this->productHeaders()" :rows="$this->products">
@interact('column_name', $product) @interact('column_name', $product)
@@ -444,14 +444,14 @@ new class extends Component
@interact('column_net', $product) @interact('column_net', $product)
<span class="whitespace-nowrap">{{ $this->money($product->netCents) }}</span> <span class="whitespace-nowrap">{{ $this->money($product->netCents) }}</span>
@unless ($product->priceIncludesVat) @unless ($product->priceIncludesVat)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.entered') }}</span> <span class="block text-xs text-zinc-600 dark:text-zinc-200">{{ __('catalog.products.entered') }}</span>
@endunless @endunless
@endinteract @endinteract
@interact('column_gross', $product) @interact('column_gross', $product)
<span class="whitespace-nowrap">{{ $this->money($product->grossCents) }}</span> <span class="whitespace-nowrap">{{ $this->money($product->grossCents) }}</span>
@if ($product->priceIncludesVat) @if ($product->priceIncludesVat)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.entered') }}</span> <span class="block text-xs text-zinc-600 dark:text-zinc-200">{{ __('catalog.products.entered') }}</span>
@endif @endif
@endinteract @endinteract
@@ -467,7 +467,7 @@ new class extends Component
@if ($product->durationQuarters > 0) @if ($product->durationQuarters > 0)
{{ __('catalog.products.duration_value', ['hours' => $this->duration($product->durationQuarters)]) }} {{ __('catalog.products.duration_value', ['hours' => $this->duration($product->durationQuarters)]) }}
@if ($product->workTypeName !== null) @if ($product->workTypeName !== null)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ $product->workTypeName }}</span> <span class="block text-xs text-zinc-600 dark:text-zinc-200">{{ $product->workTypeName }}</span>
@endif @endif
@else @else
{{ __('catalog.products.no_duration') }} {{ __('catalog.products.no_duration') }}
@@ -492,7 +492,7 @@ new class extends Component
<h2 id="vat-rates-heading" class="text-xl font-semibold">{{ __('catalog.vat_rates.title') }}</h2> <h2 id="vat-rates-heading" class="text-xl font-semibold">{{ __('catalog.vat_rates.title') }}</h2>
<x-button :href="route('catalog.vat-rates.create')" wire:navigate icon="plus" :text="__('catalog.vat_rates.add')" /> <x-button :href="route('catalog.vat-rates.create')" wire:navigate icon="plus" :text="__('catalog.vat_rates.add')" />
</div> </div>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.vat_rates.help') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.vat_rates.help') }}</p>
<x-table :headers="$this->vatRateHeaders()" :rows="$this->vatRates"> <x-table :headers="$this->vatRateHeaders()" :rows="$this->vatRates">
@interact('column_name', $vatRate) @interact('column_name', $vatRate)
@@ -522,7 +522,7 @@ new class extends Component
</x-table> </x-table>
</section> </section>
<section aria-labelledby="mileage-heading" class="space-y-4"> <section aria-labelledby="mileage-heading" class="card space-y-4">
<h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.expense_markup.section') }}</h2> <h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.expense_markup.section') }}</h2>
<form wire:submit="saveMileageRate" class="flex max-w-md flex-wrap items-end gap-3" novalidate> <form wire:submit="saveMileageRate" class="flex max-w-md flex-wrap items-end gap-3" novalidate>
@@ -552,7 +552,7 @@ new class extends Component
</form> </form>
</section> </section>
<section aria-labelledby="internal-cost-heading" class="space-y-4"> <section aria-labelledby="internal-cost-heading" class="card space-y-4">
<h2 id="internal-cost-heading" class="text-xl font-semibold">{{ __('catalog.internal_cost.section') }}</h2> <h2 id="internal-cost-heading" class="text-xl font-semibold">{{ __('catalog.internal_cost.section') }}</h2>
<form wire:submit="saveInternalHourlyCost" class="flex max-w-md flex-wrap items-end gap-3" novalidate> <form wire:submit="saveInternalHourlyCost" class="flex max-w-md flex-wrap items-end gap-3" novalidate>
@@ -179,9 +179,9 @@ new class extends Component
?> ?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="cube">{{ $this->heading() }}</x-page-title>
<form wire:submit="save" class="space-y-6" novalidate> <form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required /> <x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
@@ -193,7 +193,7 @@ new class extends Component
<div class="space-y-1"> <div class="space-y-1">
<x-checkbox id="product-consumer" wire:model.live="form.is_consumer_product" :label="__('catalog.products.consumer')" /> <x-checkbox id="product-consumer" wire:model.live="form.is_consumer_product" :label="__('catalog.products.consumer')" />
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.consumer_help') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.products.consumer_help') }}</p>
</div> </div>
<x-select.native wire:model.live="form.vat_rate_id" :label="__('catalog.products.vat_rate')" :aria-label="__('catalog.products.vat_rate')"> <x-select.native wire:model.live="form.vat_rate_id" :label="__('catalog.products.vat_rate')" :aria-label="__('catalog.products.vat_rate')">
@@ -249,4 +249,10 @@ new class extends Component
<x-button :href="route('catalog.prices')" wire:navigate subtle color="black" :text="__('catalog.cancel')" /> <x-button :href="route('catalog.prices')" wire:navigate subtle color="black" :text="__('catalog.cancel')" />
</div> </div>
</form> </form>
@if ($productId !== null && $form->is_consumer_product)
@can('machines.manage')
<livewire:machines::production-process :product-id="$productId" :wire:key="'process-'.$productId" />
@endcan
@endif
</div> </div>
@@ -87,13 +87,13 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1"> <div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="rectangle-stack">{{ $this->heading() }}</x-page-title>
@if ($unitName !== '') @if ($unitName !== '')
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.fields.service_unit') }}: {{ $unitName }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.fields.service_unit') }}: {{ $unitName }}</p>
@endif @endif
</div> </div>
<form wire:submit="save" class="space-y-6" novalidate> <form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required /> <x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
<div class="flex flex-wrap gap-3"> <div class="flex flex-wrap gap-3">
@@ -3,6 +3,7 @@
use App\Modules\Catalog\Application\Contracts\CatalogQueries; use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\UseCases\AddServiceUnit; use App\Modules\Catalog\Application\UseCases\AddServiceUnit;
use App\Modules\Catalog\Application\UseCases\RenameCatalogItem; use App\Modules\Catalog\Application\UseCases\RenameCatalogItem;
use App\Modules\Catalog\Application\UseCases\SetServiceUnitUsesStock;
use App\Modules\Catalog\Domain\Enums\CatalogLevel; use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound; use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Presentation\Livewire\Forms\CatalogItemForm; use App\Modules\Catalog\Presentation\Livewire\Forms\CatalogItemForm;
@@ -11,7 +12,8 @@ use Livewire\Attributes\Locked;
use Livewire\Component; use Livewire\Component;
/** /**
* Add page (no {serviceUnit}) and edit page (with {serviceUnit}) of a service unit. * Add page (no {serviceUnit}) and edit page (with {serviceUnit}) of a service unit:
* its name and whether stock and machine features are used in it (spec 19).
*/ */
new class extends Component new class extends Component
{ {
@@ -21,6 +23,11 @@ new class extends Component
#[Locked] #[Locked]
public string $unitName = ''; public string $unitName = '';
#[Locked]
public bool $isShared = false;
public bool $usesStock = false;
public CatalogItemForm $form; public CatalogItemForm $form;
public function mount(CatalogQueries $catalogQueries, ?int $serviceUnit = null): void public function mount(CatalogQueries $catalogQueries, ?int $serviceUnit = null): void
@@ -37,9 +44,11 @@ new class extends Component
$this->serviceUnitId = $summary->id; $this->serviceUnitId = $summary->id;
$this->form->name = $summary->name; $this->form->name = $summary->name;
$this->isShared = $summary->isShared;
$this->usesStock = $summary->usesStock;
} }
public function save(AddServiceUnit $addServiceUnit, RenameCatalogItem $renameItem): void public function save(AddServiceUnit $addServiceUnit, RenameCatalogItem $renameItem, SetServiceUnitUsesStock $setUsesStock): void
{ {
$this->authorize('catalog.manage'); $this->authorize('catalog.manage');
@@ -47,10 +56,12 @@ new class extends Component
try { try {
if ($this->serviceUnitId === null) { if ($this->serviceUnitId === null) {
$addServiceUnit->execute($name); $id = $addServiceUnit->execute($name);
$setUsesStock->execute($id, $this->usesStock);
session()->flash('status', __('catalog.status.created', ['name' => trim($name)])); session()->flash('status', __('catalog.status.created', ['name' => trim($name)]));
} else { } else {
$renameItem->execute(CatalogLevel::ServiceUnit, $this->serviceUnitId, $name); $renameItem->execute(CatalogLevel::ServiceUnit, $this->serviceUnitId, $name);
$setUsesStock->execute($this->serviceUnitId, $this->usesStock && ! $this->isShared);
session()->flash('status', __('catalog.status.updated', ['name' => trim($name)])); session()->flash('status', __('catalog.status.updated', ['name' => trim($name)]));
} }
} catch (CatalogItemNotFound) { } catch (CatalogItemNotFound) {
@@ -78,13 +89,20 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1"> <div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="building-office">{{ $this->heading() }}</x-page-title>
</div> </div>
<form wire:submit="save" class="space-y-6" novalidate> <form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required /> <x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
@unless ($isShared)
<div class="space-y-1">
<x-checkbox id="uses-stock" wire:model="usesStock" :label="__('catalog.service_units.uses_stock')" />
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.service_units.uses_stock_hint') }}</p>
</div>
@endunless
<div class="flex flex-wrap gap-3"> <div class="flex flex-wrap gap-3">
<x-button submit :text="__('catalog.save')" /> <x-button submit :text="__('catalog.save')" />
<x-button :href="route('catalog.index')" wire:navigate subtle color="black" :text="__('catalog.cancel')" /> <x-button :href="route('catalog.index')" wire:navigate subtle color="black" :text="__('catalog.cancel')" />
@@ -103,13 +103,13 @@ new class extends Component
?> ?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="receipt-percent">{{ $this->heading() }}</x-page-title>
@if ($vatRateId !== null) @if ($vatRateId !== null)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.vat_rates.change_help') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.vat_rates.change_help') }}</p>
@endif @endif
<form wire:submit="save" class="space-y-6" novalidate> <form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="name" :label="__('catalog.fields.name')" :hint="__('catalog.vat_rates.name_help')" autocomplete="off" required /> <x-input wire:model="name" :label="__('catalog.fields.name')" :hint="__('catalog.vat_rates.name_help')" autocomplete="off" required />
<x-input <x-input
@@ -126,7 +126,7 @@ new class extends Component
@else @else
<div class="space-y-1"> <div class="space-y-1">
<x-checkbox id="vat-rate-default" wire:model="makeDefault" :label="__('catalog.vat_rates.make_default')" /> <x-checkbox id="vat-rate-default" wire:model="makeDefault" :label="__('catalog.vat_rates.make_default')" />
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.vat_rates.make_default_help') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.vat_rates.make_default_help') }}</p>
</div> </div>
@endif @endif
@@ -106,13 +106,13 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1"> <div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="wrench-screwdriver">{{ $this->heading() }}</x-page-title>
@if ($unitName !== '') @if ($unitName !== '')
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.fields.service_unit') }}: {{ $unitName }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.fields.service_unit') }}: {{ $unitName }}</p>
@endif @endif
</div> </div>
<form wire:submit="save" class="space-y-6" novalidate> <form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required /> <x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
@if ($this->services !== []) @if ($this->services !== [])
@@ -7,6 +7,8 @@ use App\Modules\Catalog\Application\UseCases\AddWorkflowTemplate;
use App\Modules\Catalog\Application\UseCases\UpdateWorkflowTemplate; use App\Modules\Catalog\Application\UseCases\UpdateWorkflowTemplate;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNotFound; use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNotFound;
use App\Modules\Catalog\Presentation\Livewire\Forms\WorkflowTemplateForm; use App\Modules\Catalog\Presentation\Livewire\Forms\WorkflowTemplateForm;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Shared\Domain\Exceptions\DomainException; use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Attributes\Computed; use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked; use Livewire\Attributes\Locked;
@@ -15,7 +17,8 @@ use Livewire\Component;
/** /**
* Add page and edit page (with {template}) of a workflow template: its name, * Add page and edit page (with {template}) of a workflow template: its name,
* work type and steps. Steps are added, moved and removed with buttons, and * work type and steps. Steps are added, moved and removed with buttons, and
* everything is saved at once. * everything is saved at once. A step whose work type's service unit uses
* stock may have default materials, suggested on its tasks (spec 19.4).
*/ */
new class extends Component new class extends Component
{ {
@@ -54,7 +57,15 @@ new class extends Component
$this->storedWorkTypeIds = [$details->workTypeId]; $this->storedWorkTypeIds = [$details->workTypeId];
foreach ($details->steps as $step) { foreach ($details->steps as $step) {
$this->form->addStep($step->title, $step->workTypeId === null ? '' : (string) $step->workTypeId, $step->description ?? ''); $this->form->addStep(
$step->title,
$step->workTypeId === null ? '' : (string) $step->workTypeId,
$step->description ?? '',
array_map(fn ($material): array => [
'stock_item_id' => (string) $material->stockItemId,
'quantity' => rtrim(rtrim(number_format($material->quantityMilli / 1000, 3, ',', ''), '0'), ','),
], $step->materials),
);
if ($step->workTypeId !== null) { if ($step->workTypeId !== null) {
$this->storedWorkTypeIds[] = $step->workTypeId; $this->storedWorkTypeIds[] = $step->workTypeId;
@@ -87,6 +98,77 @@ new class extends Component
return $workType === null ? [] : $this->groups($catalog->activeWorkTypesFor([$workType->serviceUnitId])); return $workType === null ? [] : $this->groups($catalog->activeWorkTypesFor([$workType->serviceUnitId]));
} }
/**
* Stock items in use, for default materials.
*
* @return list<StockItemSummary>
*/
#[Computed]
public function stockItems(): array
{
return app(StockQueries::class)->items();
}
/**
* Whether the step's work type (or the template's) belongs to a service
* unit that uses stock; a shared work type follows the template's unit.
*/
public function stepUsesStock(int $index): bool
{
$catalog = app(CatalogQueries::class);
$stockUnitIds = $catalog->stockServiceUnitIds();
if ($stockUnitIds === [] || $this->stockItems === []) {
return false;
}
$templateWorkType = $this->form->work_type_id === '' ? null : $catalog->findWorkType((int) $this->form->work_type_id);
$stepWorkTypeId = $this->form->steps[$index]['work_type_id'] ?? '';
$workType = $stepWorkTypeId === '' ? $templateWorkType : $catalog->findWorkType((int) $stepWorkTypeId);
if ($workType === null) {
return false;
}
$unitId = ($catalog->findServiceUnit($workType->serviceUnitId)?->isShared ?? false)
? $templateWorkType?->serviceUnitId
: $workType->serviceUnitId;
return $unitId !== null && in_array($unitId, $stockUnitIds, true);
}
public function addMaterial(int $index): void
{
$this->authorize('catalog.manage');
if (! isset($this->form->steps[$index])) {
return;
}
$key = $this->form->addMaterial($index);
$this->statusMessage = __('catalog.workflows.status.material_added', ['number' => $index + 1]);
$this->js("document.getElementById('material-{$key}-item')?.focus()");
}
public function removeMaterial(int $index, int $materialIndex): void
{
$this->authorize('catalog.manage');
$materials = array_values($this->form->steps[$index]['materials'] ?? []);
if (! isset($materials[$materialIndex])) {
return;
}
array_splice($materials, $materialIndex, 1);
$this->form->steps[$index]['materials'] = $materials;
$this->resetErrorBag();
$this->statusMessage = __('catalog.workflows.status.material_removed', ['number' => $index + 1]);
$stepKey = $this->form->steps[$index]['key'];
$this->js("document.getElementById('step-{$stepKey}-add-material')?.focus()");
}
public function addStep(): void public function addStep(): void
{ {
$this->authorize('catalog.manage'); $this->authorize('catalog.manage');
@@ -229,9 +311,9 @@ new class extends Component
?> ?>
<div class="mx-auto max-w-3xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="queue-list">{{ $this->heading() }}</x-page-title>
<form wire:submit="save" class="space-y-6" novalidate> <form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" :hint="__('catalog.workflows.name_help')" autocomplete="off" required /> <x-input wire:model="form.name" :label="__('catalog.fields.name')" :hint="__('catalog.workflows.name_help')" autocomplete="off" required />
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
@@ -252,10 +334,10 @@ new class extends Component
@endforeach @endforeach
</x-select.native> </x-select.native>
<section aria-labelledby="steps-heading" class="space-y-4"> <section aria-labelledby="steps-heading" class="space-y-4 rounded-lg border border-zinc-200 bg-zinc-50 p-4 dark:border-zinc-700 dark:bg-zinc-800/50">
<div class="space-y-1"> <div class="space-y-1">
<h2 id="steps-heading" class="text-xl font-semibold">{{ __('catalog.workflows.steps') }}</h2> <h2 id="steps-heading" class="text-xl font-semibold">{{ __('catalog.workflows.steps') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.workflows.steps_help') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.workflows.steps_help') }}</p>
</div> </div>
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p> <p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
@@ -268,7 +350,7 @@ new class extends Component
@foreach ($form->steps as $index => $step) @foreach ($form->steps as $index => $step)
{{-- The index is part of the key: a moved step is rendered anew, so its fields bind to their new position. --}} {{-- The index is part of the key: a moved step is rendered anew, so its fields bind to their new position. --}}
<li wire:key="step-{{ $step['key'] }}-{{ $index }}"> <li wire:key="step-{{ $step['key'] }}-{{ $index }}">
<fieldset class="space-y-4 rounded-lg border border-zinc-200 bg-white p-4 dark:border-zinc-700 dark:bg-black"> <fieldset class="space-y-4 rounded-lg border border-zinc-200 bg-white p-4 dark:border-zinc-700 dark:bg-zinc-900">
<legend class="px-1 font-medium">{{ __('catalog.workflows.step_legend', ['number' => $index + 1]) }}</legend> <legend class="px-1 font-medium">{{ __('catalog.workflows.step_legend', ['number' => $index + 1]) }}</legend>
<x-input <x-input
@@ -303,6 +385,59 @@ new class extends Component
resize-auto resize-auto
/> />
@if ($this->stepUsesStock($index) || ($step['materials'] ?? []) !== [])
<fieldset class="space-y-3">
<legend class="text-sm font-semibold">{{ __('catalog.workflows.materials') }}</legend>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.workflows.materials_help') }}</p>
@foreach ($step['materials'] ?? [] as $materialIndex => $material)
<div wire:key="material-{{ $material['key'] }}-{{ $materialIndex }}" class="flex flex-wrap items-end gap-2">
<div class="min-w-48 flex-1">
<x-select.native
id="material-{{ $material['key'] }}-item"
wire:model="form.steps.{{ $index }}.materials.{{ $materialIndex }}.stock_item_id"
:label="__('catalog.workflows.material_item')"
:aria-label="__('catalog.workflows.material_item_named', ['step' => $index + 1, 'number' => $materialIndex + 1])"
>
<option value="">{{ __('catalog.workflows.choose_material') }}</option>
@foreach ($this->stockItems as $stockItem)
<option value="{{ $stockItem->id }}">{{ $stockItem->name }} ({{ __('inventory.units.'.$stockItem->unit->value) }})</option>
@endforeach
</x-select.native>
</div>
<div class="w-28">
<x-input
id="material-{{ $material['key'] }}-quantity"
wire:model="form.steps.{{ $index }}.materials.{{ $materialIndex }}.quantity"
inputmode="decimal"
:label="__('catalog.workflows.material_quantity')"
autocomplete="off"
/>
</div>
<x-button
wire:click="removeMaterial({{ $index }}, {{ $materialIndex }})"
subtle
color="black"
sm
icon="trash"
:aria-label="__('catalog.workflows.remove_material_named', ['step' => $index + 1, 'number' => $materialIndex + 1])"
/>
</div>
@endforeach
<x-button
id="step-{{ $step['key'] }}-add-material"
wire:click="addMaterial({{ $index }})"
subtle
color="black"
sm
icon="plus"
:text="__('catalog.workflows.add_material')"
:aria-label="__('catalog.workflows.add_material_named', ['number' => $index + 1])"
/>
</fieldset>
@endif
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<x-button <x-button
id="step-{{ $step['key'] }}-up" id="step-{{ $step['key'] }}-up"
@@ -82,13 +82,13 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4"> <div class="flex flex-wrap items-center justify-between gap-4">
<h1 class="text-2xl font-semibold">{{ __('catalog.workflows.title') }}</h1> <x-page-title icon="queue-list">{{ __('catalog.workflows.title') }}</x-page-title>
<x-button :href="route('catalog.workflow-templates.create')" wire:navigate icon="plus" :text="__('catalog.workflows.add')" /> <x-button :href="route('catalog.workflow-templates.create')" wire:navigate icon="plus" :text="__('catalog.workflows.add')" />
</div> </div>
<div class="space-y-1 text-sm"> <div class="space-y-1 text-sm">
<p class="text-zinc-600 dark:text-zinc-300">{{ __('catalog.workflows.intro') }}</p> <p class="text-zinc-600 dark:text-zinc-200">{{ __('catalog.workflows.intro') }}</p>
<p><x-link :href="route('catalog.index')" navigate>{{ __('catalog.workflows.back_to_catalog') }}</x-link></p> <p><x-link :href="route('catalog.index')" navigate>{{ __('catalog.workflows.back_to_catalog') }}</x-link></p>
</div> </div>
@@ -138,7 +138,7 @@ new class extends Component
wire:click="toggleActive({{ $template->id }})" wire:click="toggleActive({{ $template->id }})"
@checked($template->isActive) @checked($template->isActive)
aria-label="{{ __('catalog.actions.active_named', ['name' => $template->name]) }}" aria-label="{{ __('catalog.actions.active_named', ['name' => $template->name]) }}"
class="size-4 rounded border-zinc-400 text-primary-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-500 dark:bg-zinc-800" class="size-4 rounded border-zinc-400 text-primary-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 dark:border-zinc-500 dark:bg-zinc-800"
/> />
<span aria-hidden="true">{{ __('catalog.actions.active') }}</span> <span aria-hidden="true">{{ __('catalog.actions.active') }}</span>
</label> </label>
@@ -147,6 +147,6 @@ new class extends Component
</x-table> </x-table>
</section> </section>
@empty @empty
<p>{{ __('catalog.workflows.none') }}</p> <x-empty-state icon="tag">{{ __('catalog.workflows.none') }}</x-empty-state>
@endforelse @endforelse
</div> </div>
@@ -25,6 +25,14 @@ interface CustomerQueries
*/ */
public function namesByIds(array $ids): array; public function namesByIds(array $ids): array;
/**
* Card header colours (#rrggbb, null = default colour) by customer id.
*
* @param list<int> $ids
* @return array<int, string|null>
*/
public function headerColorsByIds(array $ids): array;
/** /**
* The company's own internal customer, whose jobs hold internal work * The company's own internal customer, whose jobs hold internal work
* and the yearly quick sale job. * and the yearly quick sale job.
@@ -22,6 +22,7 @@ final readonly class CustomerSummary
public ?string $businessId, public ?string $businessId,
public ?string $personalIdentityCodeMasked = null, public ?string $personalIdentityCodeMasked = null,
public bool $isInternal = false, public bool $isInternal = false,
public ?string $headerColor = null,
) {} ) {}
public function hasPersonalIdentityCode(): bool public function hasPersonalIdentityCode(): bool
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidHexColor;
use App\Modules\Shared\Domain\ValueObjects\HexColor;
/**
* Sets the customer's colour, shared by its Kanban cards and its time sheet
* rows. Null returns to the default colour.
*/
final class ChangeCustomerHeaderColor
{
public function __construct(
private CustomerRepository $customers,
private TransactionManager $transactions,
) {}
/**
* @throws CustomerNotFound
* @throws InvalidHexColor
*/
public function execute(int $customerId, ?string $color): void
{
$headerColor = $color === null || trim($color) === '' ? null : new HexColor($color);
$this->transactions->run(function () use ($customerId, $headerColor): void {
$customer = $this->customers->findById($customerId) ?? throw new CustomerNotFound($customerId);
$customer->changeHeaderColor($headerColor);
$this->customers->save($customer);
});
}
}
@@ -11,6 +11,7 @@ use App\Modules\Customers\Domain\Exceptions\InternalCustomerMustBeCompany;
use App\Modules\Customers\Domain\ValueObjects\CustomerName; use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode; use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use App\Modules\Shared\Domain\ValueObjects\BusinessId; use App\Modules\Shared\Domain\ValueObjects\BusinessId;
use App\Modules\Shared\Domain\ValueObjects\HexColor;
/** /**
* A customer of the company: a business or a private consumer. * A customer of the company: a business or a private consumer.
@@ -27,6 +28,7 @@ final class Customer
private ?BusinessId $businessId, private ?BusinessId $businessId,
private ?PersonalIdentityCode $personalIdentityCode, private ?PersonalIdentityCode $personalIdentityCode,
private bool $internal = false, private bool $internal = false,
private ?HexColor $headerColor = null,
) { ) {
self::ensureIdentifiersFitType($type, $businessId, $personalIdentityCode); self::ensureIdentifiersFitType($type, $businessId, $personalIdentityCode);
self::ensureInternalIsCompany($internal, $type); self::ensureInternalIsCompany($internal, $type);
@@ -54,8 +56,9 @@ final class Customer
?BusinessId $businessId, ?BusinessId $businessId,
?PersonalIdentityCode $personalIdentityCode = null, ?PersonalIdentityCode $personalIdentityCode = null,
bool $internal = false, bool $internal = false,
?HexColor $headerColor = null,
): self { ): self {
return new self($id, $name, $type, $businessId, $personalIdentityCode, $internal); return new self($id, $name, $type, $businessId, $personalIdentityCode, $internal, $headerColor);
} }
/** /**
@@ -81,6 +84,20 @@ final class Customer
$this->personalIdentityCode = $personalIdentityCode; $this->personalIdentityCode = $personalIdentityCode;
} }
/**
* The colour of the customer's card headers on the Kanban board and of
* its rows on the time sheet. Null uses the default colour.
*/
public function changeHeaderColor(?HexColor $color): void
{
$this->headerColor = $color;
}
public function headerColor(): ?HexColor
{
return $this->headerColor;
}
public function removePersonalIdentityCode(): void public function removePersonalIdentityCode(): void
{ {
$this->personalIdentityCode = null; $this->personalIdentityCode = null;
@@ -23,9 +23,10 @@ use Illuminate\Database\Eloquent\Model;
* @property string|null $personal_identity_code Decrypted by the cast; sensitive. * @property string|null $personal_identity_code Decrypted by the cast; sensitive.
* @property string|null $personal_identity_code_hash * @property string|null $personal_identity_code_hash
* @property bool $is_internal * @property bool $is_internal
* @property string|null $header_color #rrggbb
*/ */
#[Table('customers')] #[Table('customers')]
#[Fillable(['name', 'type', 'business_id', 'personal_identity_code', 'personal_identity_code_hash'])] #[Fillable(['name', 'type', 'business_id', 'personal_identity_code', 'personal_identity_code_hash', 'header_color'])]
#[Hidden(['personal_identity_code', 'personal_identity_code_hash'])] #[Hidden(['personal_identity_code', 'personal_identity_code_hash'])]
#[UseFactory(CustomerFactory::class)] #[UseFactory(CustomerFactory::class)]
class CustomerModel extends Model class CustomerModel extends Model
@@ -27,6 +27,11 @@ class EloquentCustomerQueries implements CustomerQueries
return $ids === [] ? [] : CustomerModel::query()->whereIn('id', $ids)->pluck('name', 'id')->all(); return $ids === [] ? [] : CustomerModel::query()->whereIn('id', $ids)->pluck('name', 'id')->all();
} }
public function headerColorsByIds(array $ids): array
{
return $ids === [] ? [] : CustomerModel::query()->whereIn('id', $ids)->pluck('header_color', 'id')->all();
}
public function internalCustomerId(): ?int public function internalCustomerId(): ?int
{ {
$id = CustomerModel::query()->where('is_internal', true)->orderBy('id')->value('id'); $id = CustomerModel::query()->where('is_internal', true)->orderBy('id')->value('id');
@@ -118,7 +123,7 @@ class EloquentCustomerQueries implements CustomerQueries
? null ? null
: (new PersonalIdentityCode($model->personal_identity_code))->masked(); : (new PersonalIdentityCode($model->personal_identity_code))->masked();
return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id, $masked, (bool) $model->is_internal); return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id, $masked, (bool) $model->is_internal, $model->header_color);
} }
private function toContactSummary(CustomerContactModel $model): ContactSummary private function toContactSummary(CustomerContactModel $model): ContactSummary
@@ -10,6 +10,7 @@ use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel; use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Customers\Infrastructure\Persistence\PersonalIdentityCodeHasher; use App\Modules\Customers\Infrastructure\Persistence\PersonalIdentityCodeHasher;
use App\Modules\Shared\Domain\ValueObjects\BusinessId; use App\Modules\Shared\Domain\ValueObjects\BusinessId;
use App\Modules\Shared\Domain\ValueObjects\HexColor;
use Illuminate\Database\QueryException; use Illuminate\Database\QueryException;
class EloquentCustomerRepository implements CustomerRepository class EloquentCustomerRepository implements CustomerRepository
@@ -35,6 +36,7 @@ class EloquentCustomerRepository implements CustomerRepository
'business_id' => $customer->businessId()?->value, 'business_id' => $customer->businessId()?->value,
'personal_identity_code' => $customer->personalIdentityCode()?->value, 'personal_identity_code' => $customer->personalIdentityCode()?->value,
'personal_identity_code_hash' => $customer->personalIdentityCode() === null ? null : $this->hasher->hash($customer->personalIdentityCode()), 'personal_identity_code_hash' => $customer->personalIdentityCode() === null ? null : $this->hasher->hash($customer->personalIdentityCode()),
'header_color' => $customer->headerColor()?->value,
])->save(); ])->save();
return $this->toEntity($model); return $this->toEntity($model);
@@ -83,6 +85,7 @@ class EloquentCustomerRepository implements CustomerRepository
$model->business_id === null ? null : new BusinessId($model->business_id), $model->business_id === null ? null : new BusinessId($model->business_id),
$model->personal_identity_code === null ? null : new PersonalIdentityCode($model->personal_identity_code), $model->personal_identity_code === null ? null : new PersonalIdentityCode($model->personal_identity_code),
(bool) $model->is_internal, (bool) $model->is_internal,
$model->header_color === null ? null : new HexColor($model->header_color),
); );
} }
} }
@@ -91,14 +91,14 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1"> <div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="building-office-2">{{ $this->heading() }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-300"> <p class="text-sm text-zinc-600 dark:text-zinc-200">
{{ __('customers.customer_label') }}: {{ __('customers.customer_label') }}:
<x-link :href="route('customers.show', $customerId)" navigate>{{ $customerName }}</x-link> <x-link :href="route('customers.show', $customerId)" navigate>{{ $customerName }}</x-link>
</p> </p>
</div> </div>
<form wire:submit="save" class="space-y-6" novalidate> <form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('customers.billing_units.fields.name')" :hint="__('customers.billing_units.fields.name_description')" autocomplete="off" required /> <x-input wire:model="form.name" :label="__('customers.billing_units.fields.name')" :hint="__('customers.billing_units.fields.name_description')" autocomplete="off" required />
<x-textarea wire:model="form.billing_address" :label="__('customers.billing_units.fields.billing_address')" :hint="__('customers.billing_units.fields.billing_address_description')" resize-auto /> <x-textarea wire:model="form.billing_address" :label="__('customers.billing_units.fields.billing_address')" :hint="__('customers.billing_units.fields.billing_address_description')" resize-auto />
@@ -88,14 +88,14 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1"> <div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="user">{{ $this->heading() }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-300"> <p class="text-sm text-zinc-600 dark:text-zinc-200">
{{ __('customers.customer_label') }}: {{ __('customers.customer_label') }}:
<x-link :href="route('customers.show', $customerId)" navigate>{{ $customerName }}</x-link> <x-link :href="route('customers.show', $customerId)" navigate>{{ $customerName }}</x-link>
</p> </p>
</div> </div>
<form wire:submit="save" class="space-y-6" novalidate> <form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('customers.contacts.fields.name')" autocomplete="off" required /> <x-input wire:model="form.name" :label="__('customers.contacts.fields.name')" autocomplete="off" required />
<x-input wire:model="form.title" :label="__('customers.contacts.fields.title')" :hint="__('customers.contacts.fields.title_description')" autocomplete="off" /> <x-input wire:model="form.title" :label="__('customers.contacts.fields.title')" :hint="__('customers.contacts.fields.title_description')" autocomplete="off" />
@@ -120,11 +120,11 @@ new class extends Component
?> ?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold"> <x-page-title icon="user-group">
{{ __($customerId === null ? 'customers.create_title' : 'customers.edit_title') }} {{ __($customerId === null ? 'customers.create_title' : 'customers.edit_title') }}
</h1> </x-page-title>
<form wire:submit="save" class="space-y-6" novalidate> <form wire:submit="save" class="card space-y-6" novalidate>
<x-input <x-input
wire:model="form.name" wire:model="form.name"
:label="__('customers.fields.name')" :label="__('customers.fields.name')"
@@ -63,7 +63,7 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4"> <div class="flex flex-wrap items-center justify-between gap-4">
<h1 class="text-2xl font-semibold">{{ __('customers.title') }}</h1> <x-page-title icon="user-group">{{ __('customers.title') }}</x-page-title>
<x-button :href="route('customers.create')" wire:navigate icon="plus" :text="__('customers.new')" /> <x-button :href="route('customers.create')" wire:navigate icon="plus" :text="__('customers.new')" />
</div> </div>
@@ -80,12 +80,12 @@ new class extends Component
:hint="__('customers.search_description')" :hint="__('customers.search_description')"
/> />
<p role="status" aria-live="polite" aria-atomic="true" class="text-sm text-zinc-600 dark:text-zinc-300"> <p role="status" aria-live="polite" aria-atomic="true" class="text-sm text-zinc-600 dark:text-zinc-100">
{{ trans_choice('customers.result_count', $this->customers->total(), ['count' => $this->customers->total()]) }} {{ trans_choice('customers.result_count', $this->customers->total(), ['count' => $this->customers->total()]) }}
</p> </p>
@if ($this->customers->total() === 0) @if ($this->customers->total() === 0)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('customers.empty') }}</p> <x-empty-state icon="user-group">{{ __('customers.empty') }}</x-empty-state>
@else @else
<x-table :headers="$this->headers()" :rows="$this->customers" paginate> <x-table :headers="$this->headers()" :rows="$this->customers" paginate>
@interact('column_name', $customer) @interact('column_name', $customer)
@@ -5,6 +5,7 @@ use App\Modules\Customers\Application\DTOs\BillingUnitSummary;
use App\Modules\Customers\Application\DTOs\ContactSummary; use App\Modules\Customers\Application\DTOs\ContactSummary;
use App\Modules\Customers\Application\DTOs\CustomerSummary; use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Application\Services\CustomerRemoval; use App\Modules\Customers\Application\Services\CustomerRemoval;
use App\Modules\Customers\Application\UseCases\ChangeCustomerHeaderColor;
use App\Modules\Customers\Application\UseCases\RemoveBillingUnit; use App\Modules\Customers\Application\UseCases\RemoveBillingUnit;
use App\Modules\Customers\Application\UseCases\RemoveContact; use App\Modules\Customers\Application\UseCases\RemoveContact;
use App\Modules\Customers\Application\UseCases\RemoveCustomer; use App\Modules\Customers\Application\UseCases\RemoveCustomer;
@@ -16,6 +17,7 @@ use App\Modules\Customers\Domain\Exceptions\CustomerInUse;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound; use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\Exceptions\InternalCustomerCannotBeRemoved; use App\Modules\Customers\Domain\Exceptions\InternalCustomerCannotBeRemoved;
use App\Modules\Customers\Domain\Enums\CustomerType; use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Shared\Domain\Exceptions\InvalidHexColor;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed; use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked; use Livewire\Attributes\Locked;
@@ -71,6 +73,27 @@ new class extends Component
return $this->customerQueries->findSummary($this->customerId) ?? abort(404); return $this->customerQueries->findSummary($this->customerId) ?? abort(404);
} }
/**
* The colour picker's "Use colour", or "Restore default colour" with null.
*/
public function setHeaderColor(?string $color, ChangeCustomerHeaderColor $changeColor): void
{
$this->authorize('customers.use');
try {
$changeColor->execute($this->customerId, $color);
} catch (InvalidHexColor) {
$this->statusMessage = __('customers.errors.invalid_header_color');
return;
} catch (CustomerNotFound) {
abort(404);
}
unset($this->customer);
$this->statusMessage = __('customers.header_color_saved');
}
/** /**
* The personal identity code as this user may see it: in full for admins * The personal identity code as this user may see it: in full for admins
* and management, masked for others. Computed, so the full code is never * and management, masked for others. Computed, so the full code is never
@@ -211,8 +234,11 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6"> <div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<div class="space-y-4"> <div class="space-y-4">
<a href="{{ route('customers.index') }}" wire:navigate class="inline-flex min-h-6 items-center gap-1 rounded-md text-sm font-medium text-primary-700 underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:text-primary-100 dark:focus-visible:outline-primary-300">
<x-icon name="arrow-left" class="size-4" aria-hidden="true" />{{ __('customers.title') }}
</a>
<div class="flex flex-wrap items-center justify-between gap-4"> <div class="flex flex-wrap items-center justify-between gap-4">
<h1 id="customer-heading" tabindex="-1" class="text-2xl font-semibold break-words focus:outline-none">{{ $this->customer->name }}</h1> <x-page-title icon="user-group" id="customer-heading" tabindex="-1" class="focus:outline-none">{{ $this->customer->name }}</x-page-title>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<x-button <x-button
@@ -224,6 +250,14 @@ new class extends Component
:text="__('customers.edit_details')" :text="__('customers.edit_details')"
/> />
<x-button
subtle
color="black"
icon="swatch"
:text="__('customers.fields.header_color')"
x-on:click="$dispatch('color-picker:open', {{ Js::from(['id' => 'colour-picker', 'title' => __('customers.header_color_title', ['name' => $this->customer->name]), 'color' => $this->customer->headerColor ?? '#23476a', 'method' => 'setHeaderColor', 'args' => [], 'resettable' => $this->customer->headerColor !== null]) }})"
/>
@if ($this->canBeRemoved) @if ($this->canBeRemoved)
<x-button <x-button
wire:click="confirmRemoval('customer', {{ $customerId }})" wire:click="confirmRemoval('customer', {{ $customerId }})"
@@ -240,7 +274,7 @@ new class extends Component
<x-alert role="status" color="green" light icon="check-circle" :text="session('status')" /> <x-alert role="status" color="green" light icon="check-circle" :text="session('status')" />
@endif @endif
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]"> <dl class="card grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]">
<dt class="font-medium">{{ __('customers.fields.type') }}</dt> <dt class="font-medium">{{ __('customers.fields.type') }}</dt>
<dd> <dd>
{{ __('customers.types.'.$this->customer->type->value) }} {{ __('customers.types.'.$this->customer->type->value) }}
@@ -272,7 +306,7 @@ new class extends Component
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p> <p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
</div> </div>
<section aria-labelledby="contacts-heading" class="space-y-4"> <section aria-labelledby="contacts-heading" class="card space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4"> <div class="flex flex-wrap items-center justify-between gap-4">
<h2 id="contacts-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none"> <h2 id="contacts-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">
{{ __('customers.contacts.title') }} {{ __('customers.contacts.title') }}
@@ -287,7 +321,7 @@ new class extends Component
</div> </div>
@if ($this->contacts === []) @if ($this->contacts === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('customers.contacts.empty') }}</p> <x-empty-state icon="user-group">{{ __('customers.contacts.empty') }}</x-empty-state>
@else @else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-200 dark:divide-zinc-700 dark:border-zinc-700"> <ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-200 dark:divide-zinc-700 dark:border-zinc-700">
@foreach ($this->contacts as $contact) @foreach ($this->contacts as $contact)
@@ -314,7 +348,7 @@ new class extends Component
@endif @endif
@if ($contact->note !== null) @if ($contact->note !== null)
<p class="whitespace-pre-line text-zinc-600 dark:text-zinc-300">{{ $contact->note }}</p> <p class="whitespace-pre-line text-zinc-600 dark:text-zinc-200">{{ $contact->note }}</p>
@endif @endif
</div> </div>
@@ -345,7 +379,7 @@ new class extends Component
@endif @endif
</section> </section>
<section aria-labelledby="billing-units-heading" class="space-y-4"> <section aria-labelledby="billing-units-heading" class="card space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4"> <div class="flex flex-wrap items-center justify-between gap-4">
<h2 id="billing-units-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none"> <h2 id="billing-units-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">
{{ __('customers.billing_units.title') }} {{ __('customers.billing_units.title') }}
@@ -360,7 +394,7 @@ new class extends Component
</div> </div>
@if ($this->billingUnits === []) @if ($this->billingUnits === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('customers.billing_units.empty') }}</p> <x-empty-state icon="user-group">{{ __('customers.billing_units.empty') }}</x-empty-state>
@else @else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-200 dark:divide-zinc-700 dark:border-zinc-700"> <ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-200 dark:divide-zinc-700 dark:border-zinc-700">
@foreach ($this->billingUnits as $billingUnit) @foreach ($this->billingUnits as $billingUnit)
@@ -427,4 +461,6 @@ new class extends Component
<x-button wire:click="remove" color="red" icon="trash" :text="__('customers.remove')" /> <x-button wire:click="remove" color="red" icon="trash" :text="__('customers.remove')" />
</x-slot:actions> </x-slot:actions>
</x-confirm-dialog> </x-confirm-dialog>
<x-color-picker />
</div> </div>
@@ -5,8 +5,8 @@ declare(strict_types=1);
namespace App\Modules\Dashboard\Application\Contracts; namespace App\Modules\Dashboard\Application\Contracts;
/** /**
* What the management panel needs from Billing, Sales, Users and the * What the management panel needs from Billing, Sales, Users, Machines,
* holiday calendar. Days are Y-m-d. * Inventory and the holiday calendar. Days are Y-m-d.
*/ */
interface DashboardAdmin interface DashboardAdmin
{ {
@@ -35,4 +35,16 @@ interface DashboardAdmin
* @return list<string> * @return list<string>
*/ */
public function holidaysBetween(string $from, string $to): array; public function holidaysBetween(string $from, string $to): array;
/**
* Machine maintenance that is late (maintenance requests), by machine.
*
* @return list<array{machineId: int, machine: string, item: string}>
*/
public function lateMaintenance(): array;
/**
* How many stock items are at or below their reorder level.
*/
public function stockItemsToOrder(): int;
} }
@@ -22,6 +22,7 @@ final readonly class ManagementOverview
* @param array<string, int> $jobCounts * @param array<string, int> $jobCounts
* @param list<WorkTask> $oldestOverdueTasks * @param list<WorkTask> $oldestOverdueTasks
* @param list<PersonLoad> $workloads * @param list<PersonLoad> $workloads
* @param list<array{machineId: int, machine: string, item: string}> $lateMaintenance
*/ */
public function __construct( public function __construct(
public array $pendingApprovals, public array $pendingApprovals,
@@ -42,5 +43,7 @@ final readonly class ManagementOverview
public string $thisMonday, public string $thisMonday,
public string $nextMonday, public string $nextMonday,
public array $workloads, public array $workloads,
public array $lateMaintenance = [],
public int $stockItemsToOrder = 0,
) {} ) {}
} }
@@ -62,6 +62,8 @@ final readonly class ManagementOverviewQuery
$thisMonday->format('Y-m-d'), $thisMonday->format('Y-m-d'),
$nextMonday->format('Y-m-d'), $nextMonday->format('Y-m-d'),
$this->workloads($thisMonday, $nextMonday), $this->workloads($thisMonday, $nextMonday),
$this->admin->lateMaintenance(),
$this->admin->stockItemsToOrder(),
); );
} }
@@ -5,14 +5,18 @@ namespace App\Modules\Dashboard\Infrastructure\Adapters;
use App\Modules\Billing\Application\Contracts\BillingQueries; use App\Modules\Billing\Application\Contracts\BillingQueries;
use App\Modules\Billing\Domain\Enums\ExportStatus; use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Dashboard\Application\Contracts\DashboardAdmin; use App\Modules\Dashboard\Application\Contracts\DashboardAdmin;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Machines\Application\Contracts\MaintenanceQueries;
use App\Modules\Machines\Domain\Enums\MaintenanceLevel;
use App\Modules\Sales\Application\Contracts\QuickSaleQueries; use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
use App\Modules\Shared\Application\UseCases\HolidayCalendar; use App\Modules\Shared\Application\UseCases\HolidayCalendar;
use App\Modules\Users\Application\Contracts\UserAccountQueries; use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Domain\Enums\Role; use App\Modules\Users\Domain\Enums\Role;
/** /**
* Billing drafts, cash days, people and holidays for the management panel * Billing drafts, cash days, people, holidays, late maintenance and stock
* through the Billing, Sales, Users and Shared modules. * to order for the management panel through the Billing, Sales, Users,
* Shared, Machines and Inventory modules.
*/ */
class AdminForDashboard implements DashboardAdmin class AdminForDashboard implements DashboardAdmin
{ {
@@ -21,6 +25,8 @@ class AdminForDashboard implements DashboardAdmin
private QuickSaleQueries $sales, private QuickSaleQueries $sales,
private UserAccountQueries $users, private UserAccountQueries $users,
private HolidayCalendar $holidays, private HolidayCalendar $holidays,
private MaintenanceQueries $maintenance,
private StockQueries $stock,
) {} ) {}
public function openDraftId(): ?int public function openDraftId(): ?int
@@ -56,4 +62,22 @@ class AdminForDashboard implements DashboardAdmin
{ {
return $this->holidays->activeDatesBetween($from, $to); return $this->holidays->activeDatesBetween($from, $to);
} }
public function lateMaintenance(): array
{
$late = [];
foreach ($this->maintenance->due() as $item) {
if ($item->level === MaintenanceLevel::Overdue) {
$late[] = ['machineId' => $item->machineId, 'machine' => $item->machineName, 'item' => $item->name];
}
}
return $late;
}
public function stockItemsToOrder(): int
{
return count($this->stock->items(onlyReorder: true));
}
} }
@@ -54,33 +54,42 @@ new class extends Component
}; };
?> ?>
<div class="mx-auto max-w-7xl space-y-8 p-4 sm:p-6"> <x-page width="wide">
<h1 class="text-2xl font-semibold">{{ __('dashboard.greeting', ['name' => auth()->user()->name]) }}</h1> <x-page-header :title="__('dashboard.greeting', ['name' => auth()->user()->name])" />
@php($overview = $this->overview) @php($overview = $this->overview)
<nav aria-label="{{ __('dashboard.links.title') }}"> <nav aria-label="{{ __('dashboard.links.title') }}">
<ul class="flex flex-wrap gap-2"> <ul class="grid grid-cols-1 gap-3 min-[400px]:grid-cols-2 sm:grid-cols-3 lg:grid-cols-5">
@foreach ($this->quickLinks() as $link) @foreach ($this->quickLinks() as $link)
<li><x-button :href="route($link['route'])" wire:navigate :icon="$link['icon']" :text="$link['label']" /></li> <li>
<a
href="{{ route($link['route']) }}"
wire:navigate
class="group flex h-full min-h-16 items-center gap-3 rounded-xl border border-zinc-200 bg-white p-3 text-sm font-medium shadow-sm transition hover:border-primary-400 hover:shadow-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:border-zinc-700 dark:bg-zinc-900 dark:hover:border-primary-300 dark:focus-visible:outline-primary-300"
>
<span class="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary-600 text-white group-hover:bg-primary-700 dark:bg-primary-500" aria-hidden="true">
<x-icon :name="$link['icon']" class="size-5" />
</span>
<span class="min-w-0 break-words">{{ $link['label'] }}</span>
</a>
</li>
@endforeach @endforeach
</ul> </ul>
</nav> </nav>
<div class="grid gap-6 lg:grid-cols-2"> <div class="grid gap-6 lg:grid-cols-2">
<section aria-labelledby="tasks-heading" class="space-y-4 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900"> <x-panel :title="__('dashboard.tasks.title')" icon="clipboard-document-list" heading-id="tasks-heading">
<h2 id="tasks-heading" class="text-xl font-semibold">{{ __('dashboard.tasks.title') }}</h2>
@if (! $overview->hasTasks()) @if (! $overview->hasTasks())
<p class="text-sm">{{ __('dashboard.tasks.none') }}</p> <x-empty-state icon="check-badge">{{ __('dashboard.tasks.none') }}</x-empty-state>
@endif @endif
@foreach (['overdue' => $overview->overdue, 'soon' => $overview->soon, 'this_week' => $overview->thisWeek] as $group => $tasks) @foreach (['overdue' => $overview->overdue, 'soon' => $overview->soon, 'this_week' => $overview->thisWeek] as $group => $tasks)
@if ($tasks !== []) @if ($tasks !== [])
<div class="space-y-2"> <div @class(['space-y-2', 'rounded-lg border border-red-200 bg-red-50 p-3 dark:border-red-400/30 dark:bg-red-400/10' => $group === 'overdue'])>
<h3 class="flex items-center gap-2 font-semibold"> <h3 @class(['flex items-center gap-2 font-semibold', 'text-red-800 dark:text-red-200' => $group === 'overdue'])>
@if ($group === 'overdue') @if ($group === 'overdue')
<x-icon name="exclamation-triangle" class="size-5 text-red-700 dark:text-red-400" aria-hidden="true" /> <x-icon name="exclamation-triangle" class="size-5" aria-hidden="true" />
@endif @endif
{{ __('dashboard.tasks.groups.'.$group, ['count' => count($tasks)]) }} {{ __('dashboard.tasks.groups.'.$group, ['count' => count($tasks)]) }}
</h3> </h3>
@@ -88,9 +97,9 @@ new class extends Component
@foreach ($tasks as $task) @foreach ($tasks as $task)
<li wire:key="task-{{ $task->taskId }}" class="py-2 text-sm"> <li wire:key="task-{{ $task->taskId }}" class="py-2 text-sm">
<x-link :href="route('jobs.show', $task->jobId).'#task-'.$task->taskId" navigate class="font-medium">{{ $task->title }}</x-link> <x-link :href="route('jobs.show', $task->jobId).'#task-'.$task->taskId" navigate class="font-medium">{{ $task->title }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300">{{ $task->jobNumber }} {{ $task->jobName }}</span> <span class="block text-zinc-600 dark:text-zinc-200">{{ $task->jobNumber }} {{ $task->jobName }}</span>
<span class="flex flex-wrap gap-x-3 text-zinc-700 dark:text-zinc-200"> <span class="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-zinc-700 dark:text-zinc-200">
<span>{{ __('jobs.tasks.statuses.'.$task->status) }}</span> <x-jobs.task-status :status="$task->status" />
@if ($task->dueOn !== null) @if ($task->dueOn !== null)
<span>{{ __('dashboard.tasks.due', ['date' => $this->dateLabel($task->dueOn)]) }}</span> <span>{{ __('dashboard.tasks.due', ['date' => $this->dateLabel($task->dueOn)]) }}</span>
@endif @endif
@@ -98,9 +107,7 @@ new class extends Component
<span>{{ __('dashboard.tasks.starts', ['date' => $this->dateLabel($task->plannedFrom)]) }}</span> <span>{{ __('dashboard.tasks.starts', ['date' => $this->dateLabel($task->plannedFrom)]) }}</span>
@endif @endif
@if ($task->isLate) @if ($task->isLate)
<span class="inline-flex items-center gap-1 font-medium text-red-700 dark:text-red-400"> <x-status-badge tone="danger" icon="exclamation-triangle">{{ __('jobs.late') }}</x-status-badge>
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('jobs.late') }}
</span>
@endif @endif
</span> </span>
</li> </li>
@@ -114,12 +121,12 @@ new class extends Component
<p class="text-sm">{{ trans_choice('dashboard.tasks.later', $overview->laterCount, ['count' => $overview->laterCount]) }}</p> <p class="text-sm">{{ trans_choice('dashboard.tasks.later', $overview->laterCount, ['count' => $overview->laterCount]) }}</p>
<p class="text-sm"><x-link :href="route('jobs.calendar')" navigate>{{ __('dashboard.tasks.to_calendar') }}</x-link></p> <p class="text-sm"><x-link :href="route('jobs.calendar')" navigate>{{ __('dashboard.tasks.to_calendar') }}</x-link></p>
@endif @endif
</section> </x-panel>
<div class="space-y-6"> <div class="space-y-6">
<section aria-labelledby="week-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900"> <x-panel :title="__('dashboard.week.title')" icon="clock" heading-id="week-heading">
<h2 id="week-heading" class="text-xl font-semibold">{{ __('dashboard.week.title') }}</h2> {{-- The bars are decoration; the hours are the table's text. A full day (7.5 h) or the week's longest day fills a bar. --}}
@php($dayMax = max(30, ...array_values($overview->week->days)))
<table class="w-full text-sm"> <table class="w-full text-sm">
<caption class="sr-only">{{ __('dashboard.week.caption', ['from' => $this->dateLabel($overview->week->monday)]) }}</caption> <caption class="sr-only">{{ __('dashboard.week.caption', ['from' => $this->dateLabel($overview->week->monday)]) }}</caption>
<thead> <thead>
@@ -127,7 +134,7 @@ new class extends Component
@foreach (array_keys($overview->week->days) as $day) @foreach (array_keys($overview->week->days) as $day)
<th scope="col" class="py-1 text-center font-medium"> <th scope="col" class="py-1 text-center font-medium">
{{ $this->dayName($day) }} {{ $this->dayName($day) }}
<span class="block text-xs font-normal text-zinc-600 dark:text-zinc-300">{{ (new DateTimeImmutable($day))->format('j.n.') }}</span> <span class="block text-xs font-normal text-zinc-600 dark:text-zinc-200">{{ (new DateTimeImmutable($day))->format('j.n.') }}</span>
</th> </th>
@endforeach @endforeach
</tr> </tr>
@@ -135,45 +142,43 @@ new class extends Component
<tbody> <tbody>
<tr> <tr>
@foreach ($overview->week->days as $quarters) @foreach ($overview->week->days as $quarters)
<td class="py-1 text-center">{{ $this->hours($quarters) }}</td> <td class="px-0.5 pt-2 text-center align-bottom">
<span class="mx-auto flex h-14 w-full max-w-8 items-end overflow-hidden rounded-md bg-zinc-100 dark:bg-zinc-800" aria-hidden="true">
<span class="block w-full bg-primary-500 dark:bg-primary-400" style="height: {{ round(min(1, $quarters / $dayMax) * 100) }}%"></span>
</span>
<span class="mt-1 block tabular-nums">{{ $this->hours($quarters) }}</span>
</td>
@endforeach @endforeach
</tr> </tr>
</tbody> </tbody>
</table> </table>
<p class="text-sm"> <p class="flex flex-wrap items-center gap-2 text-sm">
{{ __('dashboard.week.total', ['hours' => $this->hours($overview->week->totalQuarters)]) }} <span class="font-semibold">{{ __('dashboard.week.total', ['hours' => $this->hours($overview->week->totalQuarters)]) }}</span>
@if ($overview->week->unapprovedQuarters > 0) @if ($overview->week->unapprovedQuarters > 0)
<span class="inline-flex items-center gap-1"> <x-status-badge tone="warning" icon="exclamation-circle">{{ __('dashboard.week.unapproved', ['hours' => $this->hours($overview->week->unapprovedQuarters)]) }}</x-status-badge>
<x-icon name="exclamation-circle" class="size-4" aria-hidden="true" />
{{ __('dashboard.week.unapproved', ['hours' => $this->hours($overview->week->unapprovedQuarters)]) }}
</span>
@endif @endif
</p> </p>
<p class="text-sm"><x-link :href="route('time.week')" navigate>{{ __('dashboard.week.open') }}</x-link></p> <p class="text-sm"><x-link :href="route('time.week')" navigate>{{ __('dashboard.week.open') }}</x-link></p>
</section> </x-panel>
<section aria-labelledby="jobs-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h2 id="jobs-heading" class="text-xl font-semibold">{{ __('dashboard.jobs.title') }}</h2>
<x-panel :title="__('dashboard.jobs.title')" icon="briefcase" heading-id="jobs-heading">
@if ($overview->jobs === []) @if ($overview->jobs === [])
<p class="text-sm">{{ __('dashboard.jobs.none') }}</p> <x-empty-state icon="briefcase">{{ __('dashboard.jobs.none') }}</x-empty-state>
@else @else
<ul class="divide-y divide-zinc-200 dark:divide-zinc-700"> <ul class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($overview->jobs as $job) @foreach ($overview->jobs as $job)
<li wire:key="job-{{ $job->id }}" class="py-2 text-sm"> <li wire:key="job-{{ $job->id }}" class="py-2 text-sm">
<x-link :href="route('jobs.show', $job->id)" navigate class="font-medium">{{ $job->number }} {{ $job->name }}</x-link> <x-link :href="route('jobs.show', $job->id)" navigate class="font-medium">{{ $job->number }} {{ $job->name }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300">{{ $job->customerName }}</span> <span class="block text-zinc-600 dark:text-zinc-200">{{ $job->customerName }}</span>
<span class="flex flex-wrap items-center gap-x-3 text-zinc-700 dark:text-zinc-200"> <span class="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-zinc-700 dark:text-zinc-200">
<span>{{ __('jobs.statuses.'.$job->status) }}</span> <x-jobs.status :status="$job->status" />
<x-jobs.priority :priority="\App\Modules\Jobs\Domain\Enums\Priority::from($job->priority)" /> <x-jobs.priority :priority="\App\Modules\Jobs\Domain\Enums\Priority::from($job->priority)" />
@if ($job->dueOn !== null) @if ($job->dueOn !== null)
<span>{{ __('dashboard.jobs.due', ['date' => $this->dateLabel($job->dueOn)]) }}</span> <span>{{ __('dashboard.jobs.due', ['date' => $this->dateLabel($job->dueOn)]) }}</span>
@endif @endif
@if ($job->isLate) @if ($job->isLate)
<span class="inline-flex items-center gap-1 font-medium text-red-700 dark:text-red-400"> <x-status-badge tone="danger" icon="exclamation-triangle">{{ __('jobs.late') }}</x-status-badge>
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('jobs.late') }}
</span>
@endif @endif
</span> </span>
</li> </li>
@@ -184,7 +189,7 @@ new class extends Component
<p class="text-sm"> <p class="text-sm">
<x-link :href="route('jobs.index')" navigate>{{ trans_choice('dashboard.jobs.all', $overview->jobCount, ['count' => $overview->jobCount]) }}</x-link> <x-link :href="route('jobs.index')" navigate>{{ trans_choice('dashboard.jobs.all', $overview->jobCount, ['count' => $overview->jobCount]) }}</x-link>
</p> </p>
</section> </x-panel>
</div> </div>
</div> </div>
@@ -192,4 +197,4 @@ new class extends Component
{{-- Loaded right after the page, not only when scrolled to. --}} {{-- Loaded right after the page, not only when scrolled to. --}}
<livewire:dashboard::management lazy="on-load" /> <livewire:dashboard::management lazy="on-load" />
@endcan @endcan
</div> </x-page>
@@ -32,7 +32,7 @@ new class extends Component
public function placeholder(): string public function placeholder(): string
{ {
return '<section class="rounded-lg border border-zinc-300 p-4 dark:border-zinc-600"><p role="status" class="text-sm">'.e(__('dashboard.management.loading')).'</p></section>'; return '<section class="rounded-xl border border-zinc-200 bg-white p-4 shadow-sm dark:border-zinc-700 dark:bg-zinc-900"><p role="status" class="text-sm">'.e(__('dashboard.management.loading')).'</p></section>';
} }
/** /**
@@ -66,12 +66,13 @@ new class extends Component
<section aria-labelledby="management-heading" class="space-y-6"> <section aria-labelledby="management-heading" class="space-y-6">
@php($overview = $this->overview) @php($overview = $this->overview)
<h2 id="management-heading" class="text-xl font-semibold">{{ __('dashboard.management.title') }}</h2> <h2 id="management-heading" class="flex items-center gap-2 border-t border-zinc-200 pt-6 text-xl font-semibold dark:border-zinc-700">
<x-icon name="presentation-chart-line" class="size-6 text-primary-700 dark:text-primary-300" aria-hidden="true" />
{{ __('dashboard.management.title') }}
</h2>
<div class="grid gap-6 lg:grid-cols-2"> <div class="grid gap-6 lg:grid-cols-2">
<section aria-labelledby="todo-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900"> <x-panel :title="__('dashboard.todo.title')" icon="inbox-stack" :level="3" heading-id="todo-heading">
<h3 id="todo-heading" class="text-lg font-semibold">{{ __('dashboard.todo.title') }}</h3>
<ul class="space-y-2 text-sm"> <ul class="space-y-2 text-sm">
@can('time.approve-others') @can('time.approve-others')
<li> <li>
@@ -104,18 +105,40 @@ new class extends Component
</li> </li>
@endif @endif
@endcan @endcan
@can('machines.use')
@if ($overview->lateMaintenance !== [])
<li>
<x-link :href="route('machines.show', $overview->lateMaintenance[0]['machineId']).'#maintenance-heading'" navigate>
{{ trans_choice('dashboard.todo.maintenance', count($overview->lateMaintenance), ['count' => count($overview->lateMaintenance)]) }}
</x-link>
<ul class="mt-1 ml-4 list-disc">
@foreach ($overview->lateMaintenance as $late)
<li>{{ __('dashboard.todo.maintenance_line', ['machine' => $late['machine'], 'item' => $late['item']]) }}</li>
@endforeach
</ul>
</li>
@endif
@endcan
@can('inventory.view')
@if ($overview->stockItemsToOrder > 0)
<li>
<x-link :href="route('inventory.index', ['tilattavat' => 1])" navigate>
{{ trans_choice('dashboard.todo.stock', $overview->stockItemsToOrder, ['count' => $overview->stockItemsToOrder]) }}
</x-link>
</li>
@endif
@endcan
@can('reports.view') @can('reports.view')
<li> <li>
<x-link :href="route('reports.unbilled')" navigate>{{ __('dashboard.todo.unbilled', ['amount' => $this->money($overview->unbilledValueCents)]) }}</x-link> <x-link :href="route('reports.unbilled')" navigate>{{ __('dashboard.todo.unbilled', ['amount' => $this->money($overview->unbilledValueCents)]) }}</x-link>
</li> </li>
@endcan @endcan
</ul> </ul>
</section> </x-panel>
@can('reports.view') @can('reports.view')
<section aria-labelledby="month-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900"> <x-panel :title="__('dashboard.month.title')" icon="chart-bar" :level="3" heading-id="month-heading">
<h3 id="month-heading" class="text-lg font-semibold">{{ __('dashboard.month.title') }}</h3> <p class="text-sm text-zinc-600 dark:text-zinc-200">
<p class="text-sm text-zinc-600 dark:text-zinc-300">
{{ __('dashboard.month.period', [ {{ __('dashboard.month.period', [
'from' => $this->dateLabel($overview->monthFrom), 'to' => $this->dateLabel($overview->monthTo), 'from' => $this->dateLabel($overview->monthFrom), 'to' => $this->dateLabel($overview->monthTo),
'previous_from' => $this->dateLabel($overview->previousFrom), 'previous_to' => $this->dateLabel($overview->previousTo), 'previous_from' => $this->dateLabel($overview->previousFrom), 'previous_to' => $this->dateLabel($overview->previousTo),
@@ -132,25 +155,32 @@ new class extends Component
['label' => 'margin', 'value' => $month->marginCents === null ? __('dashboard.month.no_cost') : $this->money($month->marginCents), 'current' => $month->marginCents, 'previous' => $previous->marginCents, 'route' => 'reports.profitability'], ['label' => 'margin', 'value' => $month->marginCents === null ? __('dashboard.month.no_cost') : $this->money($month->marginCents), 'current' => $month->marginCents, 'previous' => $previous->marginCents, 'route' => 'reports.profitability'],
['label' => 'sales', 'value' => $this->money($month->salesCents), 'current' => $month->salesCents, 'previous' => $previous->salesCents, 'route' => 'reports.sales'], ['label' => 'sales', 'value' => $this->money($month->salesCents), 'current' => $month->salesCents, 'previous' => $previous->salesCents, 'route' => 'reports.sales'],
] as $figure) ] as $figure)
<div class="rounded border border-zinc-200 p-3 dark:border-zinc-700"> @php($ratio = $figure['current'] !== null && $figure['previous'] !== null ? (new \App\Modules\Dashboard\Domain\ValueObjects\Change($figure['current'], $figure['previous']))->ratio() : null)
<div class="rounded-lg border border-zinc-200 bg-zinc-50 p-3 dark:border-zinc-700 dark:bg-zinc-800/60">
<dt class="text-sm"> <dt class="text-sm">
<x-link :href="route($figure['route'])" navigate>{{ __('dashboard.month.'.$figure['label']) }}</x-link> <x-link :href="route($figure['route'])" navigate>{{ __('dashboard.month.'.$figure['label']) }}</x-link>
</dt> </dt>
<dd class="text-lg font-semibold">{{ $figure['value'] }}</dd> <dd class="text-xl font-semibold tabular-nums">{{ $figure['value'] }}</dd>
@if ($figure['current'] !== null && $figure['previous'] !== null) @if ($figure['current'] !== null && $figure['previous'] !== null)
<dd class="text-sm text-zinc-700 dark:text-zinc-200">{{ $this->change($figure['current'], $figure['previous']) }}</dd> <dd class="flex items-center gap-1 text-sm text-zinc-700 dark:text-zinc-200">
@if ($ratio !== null && $ratio > 0)
<x-icon name="arrow-trending-up" class="size-4 text-emerald-700 dark:text-emerald-300" aria-hidden="true" />
@elseif ($ratio !== null && $ratio < 0)
<x-icon name="arrow-trending-down" class="size-4 text-red-700 dark:text-red-300" aria-hidden="true" />
@endif
{{ $this->change($figure['current'], $figure['previous']) }}
</dd>
@endif @endif
</div> </div>
@endforeach @endforeach
</dl> </dl>
<p class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('dashboard.month.billing_note') }}</p> <p class="text-xs text-zinc-600 dark:text-zinc-200">{{ __('dashboard.month.billing_note') }}</p>
</section> </x-panel>
@endcan @endcan
</div> </div>
<div class="grid gap-6 lg:grid-cols-2"> <div class="grid gap-6 lg:grid-cols-2">
<section aria-labelledby="jobs-overview-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900"> <x-panel :title="__('dashboard.stock.title')" icon="briefcase" :level="3" heading-id="jobs-overview-heading">
<h3 id="jobs-overview-heading" class="text-lg font-semibold">{{ __('dashboard.stock.title') }}</h3>
<table class="w-full text-sm"> <table class="w-full text-sm">
<caption class="sr-only">{{ __('dashboard.stock.caption') }}</caption> <caption class="sr-only">{{ __('dashboard.stock.caption') }}</caption>
@@ -163,10 +193,12 @@ new class extends Component
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700"> <tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($overview->jobCounts as $status => $count) @foreach ($overview->jobCounts as $status => $count)
<tr wire:key="status-{{ $status }}"> <tr wire:key="status-{{ $status }}">
<th scope="row" class="py-1 text-left font-normal"> <th scope="row" class="py-1.5 text-left font-normal">
<x-link :href="route('jobs.index', ['status' => $status, 'mine' => 0])" navigate>{{ __('jobs.statuses.'.$status) }}</x-link> <a href="{{ route('jobs.index', ['status' => $status, 'mine' => 0]) }}" wire:navigate class="rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">
<x-jobs.status :status="$status" class="underline-offset-2 hover:underline" />
</a>
</th> </th>
<td class="py-1 text-right">{{ $count }}</td> <td class="py-1.5 text-right font-semibold tabular-nums">{{ $count }}</td>
</tr> </tr>
@endforeach @endforeach
</tbody> </tbody>
@@ -191,7 +223,7 @@ new class extends Component
@foreach ($overview->oldestOverdueTasks as $task) @foreach ($overview->oldestOverdueTasks as $task)
<li wire:key="late-{{ $task->taskId }}" class="py-2"> <li wire:key="late-{{ $task->taskId }}" class="py-2">
<x-link :href="route('jobs.show', $task->jobId).'#task-'.$task->taskId" navigate class="font-medium">{{ $task->title }}</x-link> <x-link :href="route('jobs.show', $task->jobId).'#task-'.$task->taskId" navigate class="font-medium">{{ $task->title }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300"> <span class="block text-zinc-600 dark:text-zinc-200">
{{ $task->jobNumber }} {{ $task->jobName }} · {{ $task->assigneeName ?? __('dashboard.stock.no_assignee') }} {{ $task->jobNumber }} {{ $task->jobName }} · {{ $task->assigneeName ?? __('dashboard.stock.no_assignee') }}
· {{ __('dashboard.tasks.due', ['date' => $this->dateLabel((string) $task->dueOn)]) }} · {{ __('dashboard.tasks.due', ['date' => $this->dateLabel((string) $task->dueOn)]) }}
</span> </span>
@@ -199,13 +231,11 @@ new class extends Component
@endforeach @endforeach
</ul> </ul>
@endif @endif
</section> </x-panel>
<section aria-labelledby="load-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h3 id="load-heading" class="text-lg font-semibold">{{ __('dashboard.load.title') }}</h3>
<x-panel :title="__('dashboard.load.title')" icon="users" :level="3" heading-id="load-heading">
@if ($overview->workloads === []) @if ($overview->workloads === [])
<p class="text-sm">{{ __('dashboard.load.none') }}</p> <x-empty-state icon="users">{{ __('dashboard.load.none') }}</x-empty-state>
@else @else
<div class="overflow-x-auto rounded focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600" tabindex="0" role="region" aria-label="{{ __('dashboard.load.caption') }}"> <div class="overflow-x-auto rounded focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600" tabindex="0" role="region" aria-label="{{ __('dashboard.load.caption') }}">
<table class="w-full text-sm"> <table class="w-full text-sm">
@@ -239,6 +269,6 @@ new class extends Component
<p class="text-sm">{{ __('dashboard.load.note') }}</p> <p class="text-sm">{{ __('dashboard.load.note') }}</p>
<p class="text-sm"><x-link :href="route('jobs.calendar')" navigate>{{ __('dashboard.load.to_calendar') }}</x-link></p> <p class="text-sm"><x-link :href="route('jobs.calendar')" navigate>{{ __('dashboard.load.to_calendar') }}</x-link></p>
@endif @endif
</section> </x-panel>
</div> </div>
</section> </section>
@@ -34,7 +34,10 @@ class EloquentExpenseQueries implements ExpenseQueries
return $this->summaries(ExpenseModel::query() return $this->summaries(ExpenseModel::query()
->where('user_id', $userId) ->where('user_id', $userId)
->whereBetween('spent_on', [$start->toDateString(), $start->copy()->endOfMonth()->toDateString()])); // An upper bound before the next month: SQLite keeps date casts as "Y-m-d 00:00:00",
// which a between ending at the month's last "Y-m-d" would leave out.
->where('spent_on', '>=', $start->toDateString())
->where('spent_on', '<', $start->copy()->addMonth()->toDateString()));
} }
public function find(int $id): ?ExpenseSummary public function find(int $id): ?ExpenseSummary
@@ -227,17 +227,17 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1"> <div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1> <x-page-title icon="receipt-refund">{{ $this->heading() }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('expenses.fields.job') }}: {{ $job->label() }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('expenses.fields.job') }}: {{ $job->label() }}</p>
</div> </div>
@if ($job->isLocked) @if ($job->isLocked)
<p class="flex items-start gap-2 rounded-lg border border-zinc-300 p-3 text-sm dark:border-zinc-600"> <p class="flex items-start gap-2 rounded-lg border border-amber-700 bg-amber-50 p-3 text-sm text-amber-950 dark:border-amber-400 dark:bg-amber-400/10 dark:text-amber-100">
<x-icon name="lock-closed" class="size-5 shrink-0" aria-hidden="true" /> <x-icon name="lock-closed" class="size-5 shrink-0" aria-hidden="true" />
{{ __('expenses.locked') }} {{ __('expenses.locked') }}
</p> </p>
@else @else
<form wire:submit="save" class="space-y-6" novalidate> <form wire:submit="save" class="card space-y-6" novalidate>
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native wire:model.live="form.category" :label="__('expenses.fields.category')" :aria-label="__('expenses.fields.category')"> <x-select.native wire:model.live="form.category" :label="__('expenses.fields.category')" :aria-label="__('expenses.fields.category')">
@foreach (ExpenseCategory::cases() as $category) @foreach (ExpenseCategory::cases() as $category)
@@ -281,7 +281,7 @@ new class extends Component
<x-input wire:model.live.blur="form.cost" inputmode="decimal" :label="__('expenses.fields.cost')" :hint="__('expenses.form.cost_help')" autocomplete="off" required /> <x-input wire:model.live.blur="form.cost" inputmode="decimal" :label="__('expenses.fields.cost')" :hint="__('expenses.form.cost_help')" autocomplete="off" required />
@endif @endif
<fieldset class="space-y-4 rounded-lg border border-zinc-200 p-4 dark:border-zinc-700"> <fieldset class="space-y-4 rounded-lg border border-zinc-200 bg-zinc-50 p-4 dark:border-zinc-700 dark:bg-zinc-800/50">
<legend class="px-1 font-medium">{{ __('expenses.form.billing') }}</legend> <legend class="px-1 font-medium">{{ __('expenses.form.billing') }}</legend>
<x-checkbox id="expense-billable" wire:model.live="form.is_billable" :label="__('expenses.fields.is_billable')" /> <x-checkbox id="expense-billable" wire:model.live="form.is_billable" :label="__('expenses.fields.is_billable')" />
@@ -0,0 +1,133 @@
<?php
use App\Modules\Expenses\Application\Contracts\ExpenseJobs;
use App\Modules\Expenses\Application\Contracts\ExpenseQueries;
use App\Modules\Expenses\Application\DTOs\ExpenseData;
use App\Modules\Expenses\Application\DTOs\ExpenseSummary;
use App\Modules\Expenses\Application\UseCases\RecordExpense;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Domain\Enums\ExpensePayer;
use App\Modules\Expenses\Domain\Exceptions\ExpenseJobNotFound;
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
use App\Modules\Expenses\Presentation\Livewire\Concerns\ShowsExpenses;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Users\Application\Contracts\Clock;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Quick expenses of a job in the board's job editor: a description and an
* amount without VAT, paid by the company, dated today. The list shows
* amounts only to those who may see them; the full form is on the job's
* expense page.
*/
new class extends Component
{
use ShowsExpenses;
#[Locked]
public int $jobId;
public string $description = '';
public string $cost = '';
public string $statusMessage = '';
public function mount(int $jobId): void
{
$this->authorize('expenses.use');
$this->jobId = $jobId;
}
/**
* @return list<ExpenseSummary>
*/
#[Computed]
public function expenses(): array
{
return app(ExpenseQueries::class)->forJob($this->jobId);
}
public function isLocked(): bool
{
return app(ExpenseJobs::class)->find($this->jobId)?->isLocked ?? true;
}
public function save(RecordExpense $record, Clock $clock): void
{
$this->authorize('expenses.record');
if (trim($this->description) === '') {
$this->addError('description', __('expenses.errors.description_required'));
return;
}
try {
$record->execute($this->jobId, new ExpenseData(
userId: (int) auth()->id(),
category: ExpenseCategory::Materials,
paidBy: ExpensePayer::Company,
spentOn: $clock->today()->format('Y-m-d'),
description: trim($this->description),
cost: $this->cost,
), (int) auth()->id());
} catch (ExpenseLocked) {
$this->addError('cost', __('expenses.quick.locked'));
return;
} catch (ExpenseJobNotFound) {
abort(404);
} catch (DomainException) {
$this->addError('cost', __('expenses.errors.invalid_amount'));
return;
}
$this->statusMessage = __('expenses.quick.added', ['description' => trim($this->description)]);
$this->reset('description', 'cost');
unset($this->expenses);
}
};
?>
<div class="space-y-2.5 text-xs">
@if (Gate::allows('expenses.record') && ! $this->isLocked())
<form wire:submit="save" class="grid gap-3 sm:grid-cols-12 sm:items-start">
<div class="sm:col-span-6">
<x-input id="quick-expense-description-{{ $jobId }}" wire:model="description" maxlength="255" :label="__('expenses.quick.description')" :placeholder="__('expenses.quick.description_placeholder')" autocomplete="off" />
</div>
<div class="sm:col-span-3">
<x-input id="quick-expense-cost-{{ $jobId }}" wire:model="cost" inputmode="decimal" :label="__('expenses.quick.amount')" placeholder="0,00" autocomplete="off" />
</div>
<div class="sm:col-span-3 sm:pt-6">
<x-button submit sm class="w-full" :text="__('expenses.quick.add')" />
</div>
</form>
@elseif ($this->isLocked())
<p class="font-semibold">{{ __('expenses.quick.locked') }}</p>
@endif
<p role="status" aria-live="polite" class="min-h-4 font-medium">{{ $statusMessage }}</p>
@if ($this->expenses === [])
<p>{{ __('expenses.quick.none') }}</p>
@else
<ul class="space-y-1">
@foreach ($this->expenses as $expense)
<li wire:key="quick-expense-{{ $expense->id }}" class="flex justify-between gap-2 rounded border border-neutral-200 bg-white px-2.5 py-1.5 dark:border-[#36393f] dark:bg-[#25272b]">
<span class="min-w-0 break-words">{{ $this->summaryText($expense) }}</span>
<span class="shrink-0 font-bold">{{ $this->amount($expense, $expense->costCents) }}</span>
</li>
@endforeach
</ul>
@endif
@can('expenses.record')
<x-link :href="route('expenses.job', $jobId)" navigate class="text-xs">{{ __('expenses.quick.all') }}</x-link>
@endcan
</div>
@@ -138,7 +138,7 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="space-y-2"> <div class="space-y-2">
<h1 class="text-2xl font-semibold break-words">{{ __('expenses.job_page.title', ['job' => $job->label()]) }}</h1> <x-page-title icon="receipt-refund">{{ __('expenses.job_page.title', ['job' => $job->label()]) }}</x-page-title>
<x-link :href="route('jobs.show', $job->id)" navigate class="text-sm">{{ __('expenses.job_page.back_to_job') }}</x-link> <x-link :href="route('jobs.show', $job->id)" navigate class="text-sm">{{ __('expenses.job_page.back_to_job') }}</x-link>
</div> </div>
@@ -161,11 +161,11 @@ new class extends Component
<h2 id="expenses-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">{{ __('expenses.job_page.list') }}</h2> <h2 id="expenses-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">{{ __('expenses.job_page.list') }}</h2>
@unless ($this->canSeeTotals) @unless ($this->canSeeTotals)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('expenses.amounts_hidden_help') }}</p> <p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('expenses.amounts_hidden_help') }}</p>
@endunless @endunless
@if ($this->expenses === []) @if ($this->expenses === [])
<p class="text-sm">{{ __('expenses.none') }}</p> <x-empty-state icon="receipt-refund">{{ __('expenses.none') }}</x-empty-state>
@else @else
<x-table :headers="$this->headers()" :rows="$this->expenses"> <x-table :headers="$this->headers()" :rows="$this->expenses">
@interact('column_spentOn', $expense) @interact('column_spentOn', $expense)
@@ -174,7 +174,7 @@ new class extends Component
@interact('column_what', $expense) @interact('column_what', $expense)
<span class="block font-medium break-words whitespace-normal">{{ $this->summaryText($expense) }}</span> <span class="block font-medium break-words whitespace-normal">{{ $this->summaryText($expense) }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-300"> <span class="block text-xs text-zinc-600 dark:text-zinc-200">
{{ __('expenses.categories.'.$expense->category->value) }}, {{ __('expenses.payers.'.$expense->paidBy->value) }} {{ __('expenses.categories.'.$expense->category->value) }}, {{ __('expenses.payers.'.$expense->paidBy->value) }}
</span> </span>
@endinteract @endinteract
@@ -101,8 +101,8 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6"> <div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="space-y-2"> <div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('expenses.mine.title') }}</h1> <x-page-title icon="receipt-refund">{{ __('expenses.mine.title') }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-300"> <p class="text-sm text-zinc-600 dark:text-zinc-200">
{{ __(auth()->user()?->can('expenses.record') ? 'expenses.mine.help' : 'expenses.mine.help_subcontractor') }} {{ __(auth()->user()?->can('expenses.record') ? 'expenses.mine.help' : 'expenses.mine.help_subcontractor') }}
</p> </p>
</div> </div>
@@ -117,7 +117,7 @@ new class extends Component
<h2 id="month-heading" class="text-xl font-semibold" aria-live="polite">{{ $this->monthLabel() }}</h2> <h2 id="month-heading" class="text-xl font-semibold" aria-live="polite">{{ $this->monthLabel() }}</h2>
@if ($this->expenses === []) @if ($this->expenses === [])
<p class="text-sm">{{ __('expenses.none') }}</p> <x-empty-state icon="receipt-refund">{{ __('expenses.none') }}</x-empty-state>
@else @else
<x-table :headers="$this->headers()" :rows="$this->expenses"> <x-table :headers="$this->headers()" :rows="$this->expenses">
@interact('column_spentOn', $expense) @interact('column_spentOn', $expense)
@@ -139,7 +139,7 @@ new class extends Component
@interact('column_what', $expense) @interact('column_what', $expense)
<span class="block break-words whitespace-normal">{{ $this->summaryText($expense) }}</span> <span class="block break-words whitespace-normal">{{ $this->summaryText($expense) }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-300"> <span class="block text-xs text-zinc-600 dark:text-zinc-200">
{{ __('expenses.categories.'.$expense->category->value) }}, {{ __('expenses.payers.'.$expense->paidBy->value) }} {{ __('expenses.categories.'.$expense->category->value) }}, {{ __('expenses.payers.'.$expense->paidBy->value) }}
</span> </span>
@endinteract @endinteract
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Application\DTOs\InventoryCountLine;
use App\Modules\Inventory\Application\DTOs\InventoryCountSummary;
interface InventoryCountQueries
{
/**
* @return list<InventoryCountSummary> Newest first.
*/
public function counts(): array;
public function findCount(int $id): ?InventoryCountSummary;
/**
* The items of the count in group order and by name: those in its
* groups that are in use, and every item counted in it.
*
* @return list<InventoryCountLine>
*/
public function lines(int $countId): array;
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
/**
* Keeps the image files of stock items, which help recognise them on a
* touch screen: an upright JPEG without metadata and its thumbnail.
*/
interface StockItemImages
{
/**
* @return array{path: string, thumbnailPath: string}
*
* @throws InvalidStockImage
*/
public function store(string $uploadedFilePath, int $itemId): array;
/**
* @param list<string> $paths
*/
public function delete(array $paths): void;
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
use App\Modules\Inventory\Application\DTOs\TaskMaterialSuggestion;
/**
* Reads stock items, groups and movements. Other modules (machines, quick
* sales, jobs' task material) read stock through this contract.
*/
interface StockQueries
{
/**
* @return list<StockGroupSummary> In order.
*/
public function groups(bool $includeInactive = true): array;
/**
* Items in group order and then by name. $search matches parts of the
* name or code regardless of case and Finnish letters.
*
* @return list<StockItemSummary>
*/
public function items(?string $search = null, ?int $groupId = null, bool $onlyReorder = false, bool $includeInactive = false): array;
public function findItem(int $id): ?StockItemSummary;
/**
* @param list<int> $ids
* @return array<int, StockItemSummary> By id.
*/
public function itemsByIds(array $ids): array;
/**
* The item's movements, newest first, with the balance after each.
*
* @return list<StockMovementSummary>
*/
public function movementsOf(int $itemId, int $limit = 200): array;
public function findMovement(int $id): ?StockMovementSummary;
/**
* Material recorded on a task: its use, write-offs and their reversals,
* newest first. The balance after each is not set (0).
*
* @return list<StockMovementSummary>
*/
public function taskMovements(int $taskId): array;
/**
* @return list<TaskMaterialSuggestion>
*/
public function taskSuggestions(int $taskId): array;
/**
* Items used most often on the machine in the last 90 days, then the
* ones used most recently, for the machine console (spec 19.6).
*
* @return array{frequent: list<int>, recent: list<int>}
*/
public function machineFavourites(int $machineId, int $limit = 8): array;
/**
* The private-disk path of the item's image or its thumbnail.
*/
public function imagePathOf(int $itemId, bool $thumbnail): ?string;
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Application\DTOs\StockUsageEntry;
use App\Modules\Inventory\Application\DTOs\StockValueEntry;
/**
* Stock figures for management's reports (spec 19.8). Days are Y-m-d.
*/
interface StockReportQueries
{
/**
* Use, write-offs and stock count corrections between the days.
*
* @return list<StockUsageEntry>
*/
public function usage(string $from, string $to): array;
/**
* Every item with movements up to the day, or in use, in group order.
*
* @return list<StockValueEntry>
*/
public function valueOn(string $day): array;
/**
* The value of the stock used and written off on jobs' tasks between
* the days, by job id (spec 19.8: material cost in profitability).
*
* @return array<int, int>
*/
public function materialCostsByJob(string $from, string $to): array;
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Application\DTOs\StockTaskContext;
/**
* Inventory's view of job tasks, read from the Jobs and Catalog modules.
*/
interface StockTasks
{
public function context(int $taskId): ?StockTaskContext;
/**
* Labels such as "2026-0005 Messuvideo – Tulostus" by task id.
*
* @param list<int> $taskIds
* @return array<int, string>
*/
public function labels(array $taskIds): array;
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
use App\Modules\Inventory\Domain\Enums\StockUnit;
/**
* An item on a stock count's list: its current balance and, once counted,
* the counted quantity and the book balance at the moment of counting.
* The unit cost is the one stored at confirmation, or the current average
* cost while the count is open.
*/
final readonly class InventoryCountLine
{
public function __construct(
public int $itemId,
public string $itemName,
public ?string $code,
public int $groupId,
public string $groupName,
public StockUnit $unit,
public int $currentBalanceMilli,
public ?int $bookMilli,
public ?int $countedMilli,
public int $unitCostHundredths,
public ?string $countedByName,
public ?string $countedAt,
) {}
public function isCounted(): bool
{
return $this->countedMilli !== null;
}
public function differenceMilli(): ?int
{
return $this->countedMilli === null || $this->bookMilli === null ? null : $this->countedMilli - $this->bookMilli;
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* A stock count as listed. $groupNames is empty for the whole stock;
* $confirmedAt is "Y-m-d H:i" in the company's time zone.
*/
final readonly class InventoryCountSummary
{
/**
* @param list<string> $groupNames
*/
public function __construct(
public int $id,
public string $countedOn,
public bool $isConfirmed,
public array $groupNames,
public string $startedByName,
public ?string $confirmedByName,
public ?string $confirmedAt,
public int $countedItems,
public ?int $valueBeforeCents,
public ?int $valueAfterCents,
) {}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* A purchase (hankinta) as entered: the day (Y-m-d), the quantity, and the
* price without VAT either in total or per unit (the other left empty).
*/
final readonly class PurchaseData
{
public function __construct(
public int $itemId,
public string $occurredOn,
public string $quantity,
public string $totalPrice = '',
public string $unitPrice = '',
public ?string $supplier = null,
public ?string $documentNumber = null,
) {}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
final readonly class StockGroupSummary
{
public function __construct(
public int $id,
public string $name,
public bool $isActive,
public int $itemCount = 0,
) {}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* A stock item's details as entered: the unit key and the reorder level
* as typed ("2,5"; empty for none).
*/
final readonly class StockItemData
{
public function __construct(
public int $groupId,
public string $name,
public string $unit,
public ?string $code = null,
public ?string $supplier = null,
public string $reorderLevel = '',
) {}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
use App\Modules\Inventory\Domain\Enums\StockUnit;
/**
* A stock item with its balance (in thousandths), moving average cost (in
* hundredths of a cent per unit) and stock value (in cents). Costs and
* values are shown only to those who may see them.
*/
final readonly class StockItemSummary
{
public function __construct(
public int $id,
public int $groupId,
public string $groupName,
public string $name,
public StockUnit $unit,
public ?string $code,
public ?string $supplier,
public ?int $reorderLevelMilli,
public int $balanceMilli,
public int $averageCostHundredths,
public int $valueCents,
public bool $hasImage,
public bool $isActive,
) {}
/**
* At or below the reorder level: to be ordered (tilattava).
*/
public function needsReorder(): bool
{
return $this->reorderLevelMilli !== null && $this->balanceMilli <= $this->reorderLevelMilli;
}
public function isNegative(): bool
{
return $this->balanceMilli < 0;
}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Domain\Enums\StockUnit;
/**
* A stock movement in an item's history: signed quantity and the balance
* after it (in thousandths), its value in cents, when and by whom, and
* what it was for. $recordedAt is "Y-m-d H:i" in the company's time zone.
*/
final readonly class StockMovementSummary
{
public function __construct(
public int $id,
public int $itemId,
public StockMovementKind $kind,
public int $quantityMilli,
public int $balanceAfterMilli,
public int $valueCents,
public string $occurredOn,
public string $recordedAt,
public int $userId,
public string $userName,
public ?int $taskId,
public ?int $jobId,
public ?int $machineId,
public ?int $orderLineId,
public ?int $maintenanceRecordId,
public ?int $inventoryCountId,
public ?string $reason,
public ?string $supplier,
public ?string $documentNumber,
public ?int $reversesMovementId,
public ?int $reversedByMovementId,
public string $itemName = '',
public ?StockUnit $unit = null,
) {}
public function canBeReversed(): bool
{
return $this->reversedByMovementId === null
&& $this->kind !== StockMovementKind::Reversal
&& $this->kind !== StockMovementKind::Adjustment;
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* A job's task as stock sees it: whether material may be recorded on it
* (its service unit uses stock, spec 19) and whether its job is locked.
*/
final readonly class StockTaskContext
{
public function __construct(
public int $taskId,
public int $jobId,
public string $label,
public bool $usesStock,
public bool $isLocked,
) {}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* Stock taken out in a period, summed by item, kind, machine and job: the
* quantity (in thousandths) and value (in cents) as positive amounts
* taken; a stock count correction that added stock is negative. Reversals
* count with the movement they reverse. $kind is consumption, write_off
* or adjustment.
*/
final readonly class StockUsageEntry
{
public function __construct(
public int $itemId,
public string $itemName,
public string $groupName,
public string $unit,
public string $kind,
public ?int $machineId,
public ?int $jobId,
public int $quantityMilli,
public int $valueCents,
) {}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* Stock used (käyttö) as entered: the quantity as typed and what it was
* used for; use without a target needs a reason.
*/
final readonly class StockUseData
{
public function __construct(
public int $itemId,
public string $quantity,
public ?int $taskId = null,
public ?int $jobId = null,
public ?int $machineId = null,
public ?int $orderLineId = null,
public ?int $maintenanceRecordId = null,
public ?string $reason = null,
) {}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* Recorded use or write-off: the movement, the item's name, the quantity
* taken and the item's new balance (in thousandths).
*/
final readonly class StockUseResult
{
public function __construct(
public int $movementId,
public string $itemName,
public int $quantityMilli,
public int $balanceMilli,
) {}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* An item's balance (in thousandths) and book value (in cents) at the end
* of a day: the sums of its movements up to the day, each at its own cost.
*/
final readonly class StockValueEntry
{
public function __construct(
public int $itemId,
public string $itemName,
public string $groupName,
public string $unit,
public int $balanceMilli,
public int $valueCents,
public ?int $reorderLevelMilli,
public bool $isActive,
) {}
public function needsReorder(): bool
{
return $this->reorderLevelMilli !== null && $this->balanceMilli <= $this->reorderLevelMilli;
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
use App\Modules\Inventory\Domain\Enums\StockUnit;
/**
* A default material suggested on a task, waiting to be confirmed.
*/
final readonly class TaskMaterialSuggestion
{
public function __construct(
public int $id,
public int $taskId,
public int $stockItemId,
public string $itemName,
public StockUnit $unit,
public int $quantityMilli,
) {}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Entities\StockItem;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Adds a stock item with a zero balance; stock comes in with purchases.
*/
final class AddStockItem
{
public function __construct(
private StockItemRepository $items,
private StockItemFields $fields,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws InvalidStockQuantity
* @throws StockItemGroupNotFound
* @throws StockNameTaken
*/
public function execute(StockItemData $data): int
{
$fields = $this->fields->parse($data);
return $this->transactions->run(function () use ($data, $fields): int {
$this->fields->check($data, $fields['name']);
$item = StockItem::create($data->groupId, $fields['name'], $fields['unit'], $data->code, $data->supplier, $fields['reorderLevelMilli']);
return (int) $this->items->save($item)->id();
});
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Entities\StockItemGroup;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Adds a stock item group last in order.
*/
final class AddStockItemGroup
{
public function __construct(
private StockItemGroupRepository $groups,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws StockNameTaken
*/
public function execute(string $name): int
{
$name = new StockName($name);
return $this->transactions->run(function () use ($name): int {
if ($this->groups->isNameTaken($name->value)) {
throw new StockNameTaken;
}
return (int) $this->groups->save(StockItemGroup::create($name, $this->groups->nextSortOrder()))->id();
});
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Renames a stock item group, moves it one place up or down, or takes it
* out of use or back. Groups are never deleted.
*/
final class ChangeStockItemGroup
{
public function __construct(
private StockItemGroupRepository $groups,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws StockNameTaken
* @throws StockItemGroupNotFound
*/
public function rename(int $groupId, string $name): void
{
$name = new StockName($name);
$this->transactions->run(function () use ($groupId, $name): void {
$group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound;
if ($this->groups->isNameTaken($name->value, $groupId)) {
throw new StockNameTaken;
}
$group->rename($name);
$this->groups->save($group);
});
}
/**
* @return bool False when the group already was first (up) or last.
*
* @throws StockItemGroupNotFound
*/
public function move(int $groupId, bool $up): bool
{
return $this->transactions->run(function () use ($groupId, $up): bool {
$group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound;
$neighbour = $this->groups->neighbour($group, $up);
if ($neighbour === null) {
return false;
}
$group->swapOrderWith($neighbour);
$this->groups->save($group);
$this->groups->save($neighbour);
return true;
});
}
/**
* @throws StockItemGroupNotFound
*/
public function setActive(int $groupId, bool $active): void
{
$this->transactions->run(function () use ($groupId, $active): void {
$group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound;
$active ? $group->activate() : $group->deactivate();
$this->groups->save($group);
});
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\Contracts\StockItemImages;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Sets or removes a stock item's image; the replaced files are deleted.
*/
final class ChangeStockItemImage
{
public function __construct(
private StockItemRepository $items,
private StockItemImages $images,
private TransactionManager $transactions,
) {}
/**
* @param string|null $uploadedFilePath Null removes the image.
*
* @throws StockItemNotFound
* @throws InvalidStockImage
*/
public function execute(int $itemId, ?string $uploadedFilePath): void
{
$this->items->findById($itemId) ?? throw new StockItemNotFound;
$stored = $uploadedFilePath === null ? null : $this->images->store($uploadedFilePath, $itemId);
/** @var list<string> $old */
$old = $this->transactions->run(function () use ($itemId, $stored): array {
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
$old = array_values(array_filter([$item->imagePath(), $item->thumbnailPath()]));
if ($stored === null) {
$item->removeImage();
} else {
$item->setImage($stored['path'], $stored['thumbnailPath']);
}
$this->items->save($item);
return $old;
});
$this->images->delete($old);
}
}
@@ -0,0 +1,129 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\InventoryCountRepository;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\InventoryCount;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\InventoryCountAlreadyOpen;
use App\Modules\Inventory\Domain\Exceptions\InventoryCountConfirmed;
use App\Modules\Inventory\Domain\Exceptions\InventoryCountNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotInCount;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Stock counts (inventaario, spec 19.3): management starts one for the
* whole stock or chosen groups (one open at a time), anyone using stock
* enters counted quantities, possibly in parts and on several devices,
* and management confirms it: every difference becomes an adjustment at
* the average cost, and the stock value before and after is stored.
* Items not counted are left as they are.
*/
final class InventoryCounts
{
public function __construct(
private InventoryCountRepository $counts,
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @param list<int> $groupIds Empty: the whole stock.
*
* @throws InventoryCountAlreadyOpen
*/
public function start(array $groupIds, int $actorUserId): int
{
return $this->transactions->run(function () use ($groupIds, $actorUserId): int {
if ($this->counts->hasOpen()) {
throw new InventoryCountAlreadyOpen;
}
return (int) $this->counts->save(InventoryCount::start($this->clock->today(), array_values(array_unique($groupIds)), $actorUserId))->id();
});
}
/**
* Enters a counted quantity with the item's book balance now; an empty
* value takes the item back to not counted.
*
* @return int|null The book balance stored with the count, null when cleared.
*
* @throws InventoryCountNotFound
* @throws InventoryCountConfirmed
* @throws StockItemNotFound
* @throws StockItemNotInCount
* @throws InvalidStockQuantity
*/
public function record(int $countId, int $itemId, string $counted, int $actorUserId): ?int
{
$quantity = StockQuantity::parse($counted);
return $this->transactions->run(function () use ($countId, $itemId, $quantity, $actorUserId): ?int {
$count = $this->counts->lockById($countId) ?? throw new InventoryCountNotFound;
$count->ensureOpen();
$item = $this->items->lockById($itemId) ?? throw new StockItemNotFound;
if (! $count->covers($item->groupId())) {
throw new StockItemNotInCount;
}
if ($quantity === null) {
$this->counts->removeLine($countId, $itemId);
return null;
}
$book = $this->movements->balanceOf($itemId);
$this->counts->recordLine($countId, $itemId, $book, $quantity->milli, $actorUserId, $this->clock->now());
return $book;
});
}
/**
* @return int The number of adjustments made.
*
* @throws InventoryCountNotFound
* @throws InventoryCountConfirmed
*/
public function confirm(int $countId, int $actorUserId): int
{
return $this->transactions->run(function () use ($countId, $actorUserId): int {
$count = $this->counts->lockById($countId) ?? throw new InventoryCountNotFound;
$count->ensureOpen();
$valueBefore = $this->items->stockValueCents();
$now = $this->clock->now();
$adjustments = 0;
foreach ($this->counts->lines($countId) as $line) {
$item = $this->items->lockById($line['itemId']) ?? throw new StockItemNotFound;
$this->counts->setLineUnitCost($countId, $line['itemId'], $item->averageCostHundredths());
$difference = $line['countedMilli'] - $line['bookMilli'];
if ($difference !== 0) {
$this->movements->add(StockMovement::adjustment($item, $difference, $countId, $count->countedOn(), $now, $actorUserId));
$adjustments++;
}
}
$count->confirm($actorUserId, $now, $valueBefore, $this->items->stockValueCents());
$this->counts->save($count);
return $adjustments;
});
}
}
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\PurchaseData;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockCost;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockDay;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Users\Application\Contracts\Clock;
use DateTimeImmutable;
/**
* Records a purchase (hankinta): stock comes in at its price without VAT,
* given in total or per unit, and the item's moving average cost is
* updated (spec 19.2).
*/
final class RecordStockPurchase
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int The movement's id.
*
* @throws StockItemNotFound
* @throws InvalidStockQuantity
* @throws InvalidStockCost
* @throws InvalidStockDay
*/
public function execute(PurchaseData $data, int $actorUserId): int
{
$quantity = StockQuantity::parsePositive($data->quantity);
$valueCents = $this->valueCents($data, $quantity);
$occurredOn = $this->day($data->occurredOn);
return $this->transactions->run(function () use ($data, $quantity, $valueCents, $occurredOn, $actorUserId): int {
$item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound;
$balance = $this->movements->balanceOf($data->itemId);
$movement = StockMovement::purchase($item, $quantity, $valueCents, $occurredOn, $this->clock->now(), $actorUserId, $data->supplier ?? $item->supplier(), $data->documentNumber);
$item->receive($balance, $quantity->milli, $valueCents);
$this->items->save($item);
return (int) $this->movements->add($movement)->id();
});
}
/**
* @throws InvalidStockCost
*/
private function valueCents(PurchaseData $data, StockQuantity $quantity): int
{
try {
$total = Money::parse($data->totalPrice);
} catch (InvalidMoneyAmount) {
throw new InvalidStockCost;
}
if ($total !== null) {
return $total->cents;
}
return StockValuation::valueCents($quantity->milli, $this->unitCostHundredths($data->unitPrice));
}
/**
* A unit price with up to four decimals ("0,0123") in hundredths of a cent.
*
* @throws InvalidStockCost
*/
private function unitCostHundredths(string $value): int
{
$value = str_replace(',', '.', preg_replace('/[\s\x{00A0}\x{202F}€]+/u', '', $value) ?? '');
if (preg_match('/^(\d{1,7})(?:\.(\d{1,4}))?$/', $value, $matches) !== 1) {
throw new InvalidStockCost;
}
return (int) $matches[1] * 10_000 + (int) str_pad($matches[2] ?? '', 4, '0');
}
/**
* @throws InvalidStockDay
*/
private function day(string $value): DateTimeImmutable
{
if ($value === '') {
return $this->clock->today();
}
$day = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if ($day === false || $day->format('Y-m-d') !== $value) {
throw new InvalidStockDay;
}
return $day;
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\DTOs\StockUseResult;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Records stock used (käyttö) today at the moving average cost, for a
* task, a machine, a quick sale order or a maintenance, or with a reason.
* Use is never refused for a low balance: a machine must not stop for the
* record, so the balance may go negative, which the stock list warns of
* (spec 19.2).
*/
final class RecordStockUse
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @throws StockItemNotFound
* @throws StockItemInactive
* @throws InvalidStockQuantity
* @throws StockReasonRequired
*/
public function execute(StockUseData $data, int $actorUserId): StockUseResult
{
$quantity = StockQuantity::parsePositive($data->quantity);
$target = new StockUseTarget($data->taskId, $data->jobId, $data->machineId, $data->orderLineId, $data->maintenanceRecordId, $data->reason);
return $this->transactions->run(function () use ($data, $quantity, $target, $actorUserId): StockUseResult {
$item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound;
$item->ensureUsable();
$movement = $this->movements->add(StockMovement::consumption($item, $quantity, $target, $this->clock->today(), $this->clock->now(), $actorUserId));
return new StockUseResult((int) $movement->id(), $item->name()->value, $quantity->milli, $this->movements->balanceOf($data->itemId));
});
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\DTOs\StockUseResult;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Records a write-off (hävikki / poisto) with its reason, e.g. damaged or
* expired stock, or a reprint in production; possibly for a target too.
*/
final class RecordStockWriteOff
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @throws StockItemNotFound
* @throws InvalidStockQuantity
* @throws StockReasonRequired
*/
public function execute(StockUseData $data, int $actorUserId): StockUseResult
{
$quantity = StockQuantity::parsePositive($data->quantity);
$reason = trim((string) $data->reason);
if ($reason === '') {
throw new StockReasonRequired;
}
$target = $data->taskId === null && $data->machineId === null && $data->orderLineId === null && $data->maintenanceRecordId === null
? null
: new StockUseTarget($data->taskId, $data->jobId, $data->machineId, $data->orderLineId, $data->maintenanceRecordId, $reason);
return $this->transactions->run(function () use ($data, $quantity, $reason, $target, $actorUserId): StockUseResult {
$item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound;
$movement = $this->movements->add(StockMovement::writeOff($item, $quantity, $reason, $this->clock->today(), $this->clock->now(), $actorUserId, $target));
return new StockUseResult((int) $movement->id(), $item->name()->value, $quantity->milli, $this->movements->balanceOf($data->itemId));
});
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Returns the stock a cancelled maintenance record used (spec 19.5): each
* of its use movements not yet reversed gets a reversal, recorded today.
*/
final class ReverseMaintenanceStockUse
{
public function __construct(
private StockMovementRepository $movements,
private ReverseStockMovement $reverse,
private TransactionManager $transactions,
) {}
/**
* @return int How many movements were reversed.
*
* @throws StockMovementNotFound
* @throws StockMovementNotReversible
* @throws StockMovementAlreadyReversed
* @throws StockReversalNotAllowed
*/
public function execute(int $maintenanceRecordId, int $actorUserId): int
{
return $this->transactions->run(function () use ($maintenanceRecordId, $actorUserId): int {
$movementIds = $this->movements->unreversedUseOfMaintenance($maintenanceRecordId);
foreach ($movementIds as $movementId) {
$this->reverse->execute($movementId, $actorUserId, true);
}
return count($movementIds);
});
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Reverses a movement (vastakirjaus): the same movement negated, referring
* to the original, recorded today. Users may reverse their own use on the
* day it was recorded; other corrections need the right to correct any
* movement (management). Reversing a purchase also takes it out of the
* moving average cost.
*/
final class ReverseStockMovement
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int The reversal's id.
*
* @throws StockMovementNotFound
* @throws StockMovementNotReversible
* @throws StockMovementAlreadyReversed
* @throws StockReversalNotAllowed
*/
public function execute(int $movementId, int $actorUserId, bool $mayReverseAny): int
{
$today = $this->clock->today();
return $this->transactions->run(function () use ($movementId, $actorUserId, $mayReverseAny, $today): int {
$original = $this->movements->findById($movementId) ?? throw new StockMovementNotFound;
if (! $mayReverseAny && ! $original->isOwnUseOf($actorUserId, $today)) {
throw new StockReversalNotAllowed;
}
$item = $this->items->lockById($original->itemId()) ?? throw new StockItemNotFound;
if ($this->movements->isReversed($movementId)) {
throw new StockMovementAlreadyReversed;
}
$reversal = StockMovement::reversalOf($original, $today, $this->clock->now(), $actorUserId);
if ($original->kind() === StockMovementKind::Purchase) {
$item->receive($this->movements->balanceOf($item->id() ?? 0), $reversal->quantityMilli(), $reversal->valueCents());
$this->items->save($item);
}
return (int) $this->movements->add($reversal)->id();
});
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Takes a stock item out of use, or back. An item out of use cannot be
* used, but its movements stay.
*/
final class SetStockItemActive
{
public function __construct(
private StockItemRepository $items,
private TransactionManager $transactions,
) {}
/**
* @throws StockItemNotFound
*/
public function execute(int $itemId, bool $active): void
{
$this->transactions->run(function () use ($itemId, $active): void {
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
$active ? $item->activate() : $item->deactivate();
$this->items->save($item);
});
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
/**
* Checks a stock item's entered details, shared by adding and updating.
*/
final class StockItemFields
{
public function __construct(
private StockItemRepository $items,
private StockItemGroupRepository $groups,
) {}
/**
* @return array{name: StockName, unit: StockUnit, reorderLevelMilli: ?int}
*
* @throws InvalidStockName
* @throws InvalidStockQuantity
*/
public function parse(StockItemData $data): array
{
return [
'name' => new StockName($data->name),
'unit' => StockUnit::tryFrom($data->unit) ?? StockUnit::Piece,
'reorderLevelMilli' => StockQuantity::parse($data->reorderLevel)?->milli,
];
}
/**
* A new item needs a group in use; an existing item may stay in its
* group after the group is taken out of use.
*
* @throws StockItemGroupNotFound
* @throws StockNameTaken
*/
public function check(StockItemData $data, StockName $name, ?int $exceptItemId = null): void
{
$group = $this->groups->findById($data->groupId);
if ($group === null || ($exceptItemId === null && ! $group->isActive())) {
throw new StockItemGroupNotFound;
}
if ($this->items->isNameTaken($name->value, $exceptItemId)) {
throw new StockNameTaken;
}
}
}
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\Contracts\StockTasks;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\DTOs\StockUseResult;
use App\Modules\Inventory\Domain\Contracts\TaskMaterialSuggestionRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockTaskNotAvailable;
use App\Modules\Inventory\Domain\Exceptions\StockTaskSuggestionNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Material used on a job's task (Käytetty materiaali, spec 19.4): recorded
* from a search, or from the default materials suggested by the workflow
* step the task was made of. Material is recorded only on tasks whose
* service unit uses stock and whose job is not locked.
*/
final class TaskMaterials
{
public function __construct(
private RecordStockUse $recordUse,
private StockTasks $tasks,
private TaskMaterialSuggestionRepository $suggestions,
private TransactionManager $transactions,
) {}
/**
* Stores a workflow step's default materials as suggestions.
*
* @param list<array{stockItemId: int, quantityMilli: int}> $materials
*/
public function suggest(int $taskId, array $materials): void
{
$this->transactions->run(function () use ($taskId, $materials): void {
foreach ($materials as $material) {
$this->suggestions->add($taskId, $material['stockItemId'], $material['quantityMilli']);
}
});
}
/**
* @throws StockTaskNotAvailable
* @throws StockItemNotFound
* @throws StockItemInactive
* @throws InvalidStockQuantity
*/
public function record(int $taskId, int $stockItemId, string $quantity, int $actorUserId): StockUseResult
{
$context = $this->tasks->context($taskId);
if ($context === null || ! $context->usesStock || $context->isLocked) {
throw new StockTaskNotAvailable;
}
return $this->recordUse->execute(new StockUseData($stockItemId, $quantity, taskId: $taskId, jobId: $context->jobId), $actorUserId);
}
/**
* Records a suggested material with the quantity confirmed (possibly
* changed) and removes the suggestion.
*
* @throws StockTaskSuggestionNotFound
* @throws StockTaskNotAvailable
* @throws StockItemNotFound
* @throws StockItemInactive
* @throws InvalidStockQuantity
*/
public function confirm(int $taskId, int $suggestionId, string $quantity, int $actorUserId): StockUseResult
{
return $this->transactions->run(function () use ($taskId, $suggestionId, $quantity, $actorUserId): StockUseResult {
$suggestion = $this->suggestions->find($suggestionId);
if ($suggestion === null || $suggestion['taskId'] !== $taskId) {
throw new StockTaskSuggestionNotFound;
}
$result = $this->record($taskId, $suggestion['stockItemId'], $quantity, $actorUserId);
$this->suggestions->remove($suggestionId);
return $result;
});
}
/**
* @throws StockTaskSuggestionNotFound
*/
public function dismiss(int $taskId, int $suggestionId): void
{
$suggestion = $this->suggestions->find($suggestionId);
if ($suggestion === null || $suggestion['taskId'] !== $taskId) {
throw new StockTaskSuggestionNotFound;
}
$this->suggestions->remove($suggestionId);
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Changes a stock item's details. Its movements and balance stay.
*/
final class UpdateStockItem
{
public function __construct(
private StockItemRepository $items,
private StockItemFields $fields,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws InvalidStockQuantity
* @throws StockItemGroupNotFound
* @throws StockItemNotFound
* @throws StockNameTaken
*/
public function execute(int $itemId, StockItemData $data): void
{
$fields = $this->fields->parse($data);
$this->transactions->run(function () use ($itemId, $data, $fields): void {
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
$this->fields->check($data, $fields['name'], $itemId);
$item->change($data->groupId, $fields['name'], $fields['unit'], $data->code, $data->supplier, $fields['reorderLevelMilli']);
$this->items->save($item);
});
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\InventoryCount;
use DateTimeImmutable;
interface InventoryCountRepository
{
public function findById(int $id): ?InventoryCount;
/**
* The count, locked until the end of the transaction.
*/
public function lockById(int $id): ?InventoryCount;
public function hasOpen(): bool;
public function save(InventoryCount $count): InventoryCount;
/**
* Stores a counted quantity with the book balance of the moment; a
* recount replaces the line.
*/
public function recordLine(int $countId, int $itemId, int $bookMilli, int $countedMilli, int $userId, DateTimeImmutable $at): void;
public function removeLine(int $countId, int $itemId): void;
/**
* @return list<array{itemId: int, bookMilli: int, countedMilli: int}>
*/
public function lines(int $countId): array;
public function setLineUnitCost(int $countId, int $itemId, int $unitCostHundredths): void;
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\StockItemGroup;
interface StockItemGroupRepository
{
public function findById(int $id): ?StockItemGroup;
public function save(StockItemGroup $group): StockItemGroup;
public function isNameTaken(string $name, ?int $exceptId = null): bool;
public function nextSortOrder(): int;
/**
* The group just before ($up) or after it in order, if any.
*/
public function neighbour(StockItemGroup $group, bool $up): ?StockItemGroup;
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\StockItem;
interface StockItemRepository
{
public function findById(int $id): ?StockItem;
/**
* The item, locked until the end of the transaction, so that its
* balance and average cost change one movement at a time.
*/
public function lockById(int $id): ?StockItem;
public function save(StockItem $item): StockItem;
public function isNameTaken(string $name, ?int $exceptId = null): bool;
/**
* The value of all stock: each item's balance at its average cost.
*/
public function stockValueCents(): int;
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\StockMovement;
interface StockMovementRepository
{
public function add(StockMovement $movement): StockMovement;
public function findById(int $id): ?StockMovement;
public function isReversed(int $movementId): bool;
/**
* The ids of a maintenance record's use movements that are not reversed.
*
* @return list<int>
*/
public function unreversedUseOfMaintenance(int $maintenanceRecordId): array;
/**
* The item's balance in thousandths: the sum of its movements.
*/
public function balanceOf(int $itemId): int;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
/**
* Default materials of workflow steps waiting on the tasks made of them,
* until the assignee records or dismisses them (spec 19.4).
*/
interface TaskMaterialSuggestionRepository
{
public function add(int $taskId, int $stockItemId, int $quantityMilli): void;
/**
* @return array{id: int, taskId: int, stockItemId: int, quantityMilli: int}|null
*/
public function find(int $id): ?array;
public function remove(int $id): void;
}
@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\Exceptions\InventoryCountConfirmed;
use DateTimeImmutable;
/**
* A stock count (inventaario, spec 19.3) of the whole stock or of chosen
* item groups. It is open while counted and confirmed once by management;
* a confirmed count is never changed.
*/
final class InventoryCount
{
/**
* @param list<int>|null $groupIds Null: the whole stock.
*/
private function __construct(
private ?int $id,
private DateTimeImmutable $countedOn,
private ?array $groupIds,
private int $startedBy,
private ?int $confirmedBy,
private ?DateTimeImmutable $confirmedAt,
private ?int $valueBeforeCents,
private ?int $valueAfterCents,
) {}
/**
* @param list<int>|null $groupIds
*/
public static function start(DateTimeImmutable $countedOn, ?array $groupIds, int $startedBy): self
{
return new self(null, $countedOn, $groupIds === [] ? null : $groupIds, $startedBy, null, null, null, null);
}
/**
* @param list<int>|null $groupIds
*/
public static function reconstitute(int $id, DateTimeImmutable $countedOn, ?array $groupIds, int $startedBy, ?int $confirmedBy, ?DateTimeImmutable $confirmedAt, ?int $valueBeforeCents, ?int $valueAfterCents): self
{
return new self($id, $countedOn, $groupIds, $startedBy, $confirmedBy, $confirmedAt, $valueBeforeCents, $valueAfterCents);
}
/**
* @throws InventoryCountConfirmed
*/
public function ensureOpen(): void
{
if ($this->isConfirmed()) {
throw new InventoryCountConfirmed;
}
}
/**
* @throws InventoryCountConfirmed
*/
public function confirm(int $userId, DateTimeImmutable $at, int $valueBeforeCents, int $valueAfterCents): void
{
$this->ensureOpen();
$this->confirmedBy = $userId;
$this->confirmedAt = $at;
$this->valueBeforeCents = $valueBeforeCents;
$this->valueAfterCents = $valueAfterCents;
}
public function covers(int $groupId): bool
{
return $this->groupIds === null || in_array($groupId, $this->groupIds, true);
}
public function isConfirmed(): bool
{
return $this->confirmedAt !== null;
}
public function id(): ?int
{
return $this->id;
}
public function countedOn(): DateTimeImmutable
{
return $this->countedOn;
}
/**
* @return list<int>|null
*/
public function groupIds(): ?array
{
return $this->groupIds;
}
public function startedBy(): int
{
return $this->startedBy;
}
public function confirmedBy(): ?int
{
return $this->confirmedBy;
}
public function confirmedAt(): ?DateTimeImmutable
{
return $this->confirmedAt;
}
public function valueBeforeCents(): ?int
{
return $this->valueBeforeCents;
}
public function valueAfterCents(): ?int
{
return $this->valueAfterCents;
}
}
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
/**
* A stock item (nimike), e.g. a photo paper or an ink, counted in its unit.
* Its balance is the sum of its movements and is not kept here; the item
* keeps its moving average cost, which only purchases change. Items are
* never deleted: one taken out of use cannot be used, but its movements
* stay.
*/
final class StockItem
{
private function __construct(
private ?int $id,
private int $groupId,
private StockName $name,
private StockUnit $unit,
private ?string $code,
private ?string $supplier,
private ?int $reorderLevelMilli,
private int $averageCostHundredths,
private ?string $imagePath,
private ?string $thumbnailPath,
private bool $active,
) {}
public static function create(int $groupId, StockName $name, StockUnit $unit, ?string $code, ?string $supplier, ?int $reorderLevelMilli): self
{
return new self(null, $groupId, $name, $unit, self::text($code), self::text($supplier), $reorderLevelMilli, 0, null, null, true);
}
public static function reconstitute(
int $id,
int $groupId,
StockName $name,
StockUnit $unit,
?string $code,
?string $supplier,
?int $reorderLevelMilli,
int $averageCostHundredths,
?string $imagePath,
?string $thumbnailPath,
bool $active,
): self {
return new self($id, $groupId, $name, $unit, $code, $supplier, $reorderLevelMilli, $averageCostHundredths, $imagePath, $thumbnailPath, $active);
}
public function change(int $groupId, StockName $name, StockUnit $unit, ?string $code, ?string $supplier, ?int $reorderLevelMilli): void
{
$this->groupId = $groupId;
$this->name = $name;
$this->unit = $unit;
$this->code = self::text($code);
$this->supplier = self::text($supplier);
$this->reorderLevelMilli = $reorderLevelMilli;
}
/**
* Updates the moving average cost for a purchase (or, with a negative
* quantity and value, the reversal of one) received on top of the
* given balance.
*/
public function receive(int $balanceMilli, int $quantityMilli, int $valueCents): void
{
$this->averageCostHundredths = StockValuation::averageAfterPurchase($balanceMilli, $this->averageCostHundredths, $quantityMilli, $valueCents);
}
/**
* @throws StockItemInactive
*/
public function ensureUsable(): void
{
if (! $this->active) {
throw new StockItemInactive;
}
}
public function setImage(string $imagePath, string $thumbnailPath): void
{
$this->imagePath = $imagePath;
$this->thumbnailPath = $thumbnailPath;
}
public function removeImage(): void
{
$this->imagePath = null;
$this->thumbnailPath = null;
}
public function activate(): void
{
$this->active = true;
}
public function deactivate(): void
{
$this->active = false;
}
public function id(): ?int
{
return $this->id;
}
public function groupId(): int
{
return $this->groupId;
}
public function name(): StockName
{
return $this->name;
}
public function unit(): StockUnit
{
return $this->unit;
}
public function code(): ?string
{
return $this->code;
}
public function supplier(): ?string
{
return $this->supplier;
}
public function reorderLevelMilli(): ?int
{
return $this->reorderLevelMilli;
}
public function averageCostHundredths(): int
{
return $this->averageCostHundredths;
}
public function imagePath(): ?string
{
return $this->imagePath;
}
public function thumbnailPath(): ?string
{
return $this->thumbnailPath;
}
public function isActive(): bool
{
return $this->active;
}
private static function text(?string $value): ?string
{
$value = $value === null ? '' : trim($value);
return $value === '' ? null : mb_substr($value, 0, 150);
}
}
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
/**
* A group of stock items (nimikeryhmä), e.g. Paperit ja kartongit. Groups
* are ordered, and never deleted, only taken out of use.
*/
final class StockItemGroup
{
private function __construct(
private ?int $id,
private StockName $name,
private int $sortOrder,
private bool $active,
) {}
public static function create(StockName $name, int $sortOrder): self
{
return new self(null, $name, $sortOrder, true);
}
public static function reconstitute(int $id, StockName $name, int $sortOrder, bool $active): self
{
return new self($id, $name, $sortOrder, $active);
}
public function rename(StockName $name): void
{
$this->name = $name;
}
public function activate(): void
{
$this->active = true;
}
public function deactivate(): void
{
$this->active = false;
}
public function swapOrderWith(self $other): void
{
[$this->sortOrder, $other->sortOrder] = [$other->sortOrder, $this->sortOrder];
}
public function id(): ?int
{
return $this->id;
}
public function name(): StockName
{
return $this->name;
}
public function sortOrder(): int
{
return $this->sortOrder;
}
public function isActive(): bool
{
return $this->active;
}
}
@@ -0,0 +1,225 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use DateTimeImmutable;
/**
* A change in an item's balance (varastotapahtuma, spec 19.2). Movements
* are never changed or deleted: a mistake is corrected with a reversal,
* the same movement negated, which refers to the original. The quantity
* is signed (in thousandths) and the value is at the unit cost of the
* moment: the purchase price for a purchase, the moving average cost
* otherwise.
*/
final class StockMovement
{
private function __construct(
private ?int $id,
private int $itemId,
private StockMovementKind $kind,
private int $quantityMilli,
private int $unitCostHundredths,
private int $valueCents,
private DateTimeImmutable $occurredOn,
private DateTimeImmutable $recordedAt,
private int $userId,
private ?StockUseTarget $target,
private ?string $reason,
private ?string $supplier,
private ?string $documentNumber,
private ?int $inventoryCountId,
private ?int $reversesMovementId,
) {}
public static function purchase(StockItem $item, StockQuantity $quantity, int $valueCents, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId, ?string $supplier, ?string $documentNumber): self
{
return new self(
null, (int) $item->id(), StockMovementKind::Purchase, $quantity->milli,
StockValuation::unitCostOf($quantity->milli, $valueCents), $valueCents,
$occurredOn, $recordedAt, $userId, null, null, self::text($supplier), self::text($documentNumber), null, null,
);
}
public static function consumption(StockItem $item, StockQuantity $quantity, StockUseTarget $target, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
{
return self::outgoing(StockMovementKind::Consumption, $item, $quantity, $target, $target->reason, $occurredOn, $recordedAt, $userId);
}
/**
* @throws StockReasonRequired
*/
public static function writeOff(StockItem $item, StockQuantity $quantity, string $reason, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId, ?StockUseTarget $target = null): self
{
$reason = self::text($reason) ?? throw new StockReasonRequired;
return self::outgoing(StockMovementKind::WriteOff, $item, $quantity, $target, $reason, $occurredOn, $recordedAt, $userId);
}
/**
* A stock count's correction: a signed difference at the average cost.
*/
public static function adjustment(StockItem $item, int $differenceMilli, int $inventoryCountId, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
{
$cost = $item->averageCostHundredths();
return new self(
null, (int) $item->id(), StockMovementKind::Adjustment, $differenceMilli, $cost,
StockValuation::valueCents($differenceMilli, $cost),
$occurredOn, $recordedAt, $userId, null, null, null, null, $inventoryCountId, null,
);
}
/**
* @throws StockMovementNotReversible
*/
public static function reversalOf(self $original, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
{
if (! $original->isReversible()) {
throw new StockMovementNotReversible;
}
return new self(
null, $original->itemId, StockMovementKind::Reversal, -$original->quantityMilli,
$original->unitCostHundredths, -$original->valueCents,
$occurredOn, $recordedAt, $userId, $original->target, $original->reason, null, null, null, $original->id,
);
}
public static function reconstitute(
int $id,
int $itemId,
StockMovementKind $kind,
int $quantityMilli,
int $unitCostHundredths,
int $valueCents,
DateTimeImmutable $occurredOn,
DateTimeImmutable $recordedAt,
int $userId,
?StockUseTarget $target,
?string $reason,
?string $supplier,
?string $documentNumber,
?int $inventoryCountId,
?int $reversesMovementId,
): self {
return new self($id, $itemId, $kind, $quantityMilli, $unitCostHundredths, $valueCents, $occurredOn, $recordedAt, $userId, $target, $reason, $supplier, $documentNumber, $inventoryCountId, $reversesMovementId);
}
public function isReversible(): bool
{
return $this->kind !== StockMovementKind::Reversal && $this->kind !== StockMovementKind::Adjustment;
}
/**
* Whether the user may reverse this movement without the right to
* correct anyone's: their own use, on the day it was recorded.
*/
public function isOwnUseOf(int $userId, DateTimeImmutable $today): bool
{
return $this->kind === StockMovementKind::Consumption
&& $this->userId === $userId
&& $this->occurredOn->format('Y-m-d') === $today->format('Y-m-d');
}
public function id(): ?int
{
return $this->id;
}
public function itemId(): int
{
return $this->itemId;
}
public function kind(): StockMovementKind
{
return $this->kind;
}
public function quantityMilli(): int
{
return $this->quantityMilli;
}
public function unitCostHundredths(): int
{
return $this->unitCostHundredths;
}
public function valueCents(): int
{
return $this->valueCents;
}
public function occurredOn(): DateTimeImmutable
{
return $this->occurredOn;
}
public function recordedAt(): DateTimeImmutable
{
return $this->recordedAt;
}
public function userId(): int
{
return $this->userId;
}
public function target(): ?StockUseTarget
{
return $this->target;
}
public function reason(): ?string
{
return $this->reason;
}
public function supplier(): ?string
{
return $this->supplier;
}
public function documentNumber(): ?string
{
return $this->documentNumber;
}
public function inventoryCountId(): ?int
{
return $this->inventoryCountId;
}
public function reversesMovementId(): ?int
{
return $this->reversesMovementId;
}
private static function outgoing(StockMovementKind $kind, StockItem $item, StockQuantity $quantity, ?StockUseTarget $target, ?string $reason, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
{
$cost = $item->averageCostHundredths();
return new self(
null, (int) $item->id(), $kind, -$quantity->milli, $cost,
StockValuation::valueCents(-$quantity->milli, $cost),
$occurredOn, $recordedAt, $userId, $target, $reason, null, null, null, null,
);
}
private static function text(?string $value): ?string
{
$value = $value === null ? '' : trim($value);
return $value === '' ? null : mb_substr($value, 0, 255);
}
}

Some files were not shown because too many files have changed in this diff Show More