Add customer jobs with numbering, members, tags, links and history

Phase 1, item 4. New Jobs module:
- Customer jobs with the spec's fields except money (phase 2): yearly
  running numbers (2026-0001) from a locked counter row, service units,
  schedule, kind, status, priority, payment basis, estimated hours,
  PO reference, instructions, members (responsible, contact person,
  customer contact, biller, billing unit, other members), tags shared
  across jobs, and links.
- Every change is recorded field by field and shown on the job page with
  names and Finnish dates.
- References to other modules are checked through their query
  contracts: contact and billing unit must be the customer's own;
  service units and users must be in use unless already on the job.
- Job list with search, filters and "my jobs" on by default; job form
  with an accessible customer search and quick add; job page.
- Access: subcontractors see only jobs they are members of, read only;
  billing statuses for management and the job's biller; archiving for
  management.

Related changes:
- Customers: one internal customer (created by a migration) for internal
  work; contacts and billing units used by a job cannot be removed.
- Users and Catalog: batch name lookups and active user options with
  roles for other modules.
- <x-checkbox-group> component; spec and CLAUDE.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-23 18:57:18 +02:00
co-authored by Claude Opus 5.5
parent 51b2d4a252
commit 70e107f6e2
95 changed files with 4631 additions and 26 deletions
+71
View File
@@ -0,0 +1,71 @@
<?php
use App\Models\User;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->user = User::factory()->management()->create(['name' => 'Johanna Johto']);
$this->actingAs($this->user);
$this->customer = CustomerModel::factory()->create(['name' => 'Mainos Oy']);
$this->job = CustomerJobModel::factory()->create([
'name' => 'Messuvideo',
'customer_id' => $this->customer->id,
'responsible_user_id' => $this->user->id,
'priority' => 'immediate',
'due_on' => now()->subDay()->toDateString(),
'instructions' => 'Kuvaus klo 9.',
]);
DB::table('customer_job_links')->insert(['customer_job_id' => $this->job->id, 'title' => 'Briiffi', 'url' => 'https://drive.example.test/b', 'sort_order' => 1]);
});
it('has no accessibility issues on the job pages', function (string $page, string $device, string $colorScheme) {
$url = match ($page) {
'list' => route('jobs.index'),
'new job' => route('jobs.create'),
'edit job' => route('jobs.edit', $this->job->id),
'job page' => route('jobs.show', $this->job->id),
};
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['list', 'new job', 'edit job', 'job page'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('shows the form errors without accessibility issues', function (string $colorScheme) {
$page = visit(route('jobs.create'));
$page = $colorScheme === 'dark' ? $page->inDarkMode() : $page->inLightMode();
$page->press('Tallenna')
->assertSee('Anna asiakastyön nimi.')
->assertSee('Valitse vähintään yksi palveluyksikkö.')
->assertNoAccessibilityIssues(level: 2);
})->with(['light', 'dark']);
it('finds and picks a customer, and adds and removes a tag, with the keyboard', function () {
visit(route('jobs.create'))
->type('#customer-search', 'Mainos')
->assertSee('1 osuma.')
->keys('[aria-label="Valitse Mainos Oy"]', 'Enter')
->assertSee('Vaihda asiakas')
->assertScript('document.activeElement.id', 'change-customer')
->type('#new-tag', 'messut')
->keys('#new-tag', 'Enter')
->assertSee('Tagi messut lisätty.')
->keys('[aria-label="Poista tagi messut"]', 'Enter')
->assertSee('Tagi messut poistettu.')
->assertScript('document.activeElement.id', 'new-tag')
->assertNoAccessibilityIssues(level: 2);
});
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace Tests\Fakes;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\DTOs\ServiceSummary;
use App\Modules\Catalog\Application\DTOs\ServiceUnitSummary;
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
/**
* Service units for unit tests of other modules.
*/
class FakeCatalogQueries implements CatalogQueries
{
/** @var array<int, ServiceUnitSummary> */
public array $serviceUnits = [];
public function addServiceUnit(int $id, string $name, bool $active = true, bool $shared = false): void
{
$this->serviceUnits[$id] = new ServiceUnitSummary($id, $name, $shared, $active);
}
public function tree(bool $includeInactive = true): array
{
return [];
}
public function activeServiceUnits(): array
{
return array_values(array_filter($this->serviceUnits, fn (ServiceUnitSummary $unit): bool => $unit->isActive && ! $unit->isShared));
}
public function activeWorkTypesFor(array $serviceUnitIds): array
{
return [];
}
public function findServiceUnit(int $id): ?ServiceUnitSummary
{
return $this->serviceUnits[$id] ?? null;
}
public function serviceUnitNames(array $ids): array
{
return array_map(fn (ServiceUnitSummary $unit): string => $unit->name, array_intersect_key($this->serviceUnits, array_flip($ids)));
}
public function findService(int $id): ?ServiceSummary
{
return null;
}
public function findWorkType(int $id): ?WorkTypeSummary
{
return null;
}
public function servicesOf(int $serviceUnitId): array
{
return [];
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace Tests\Fakes;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\DTOs\BillingUnitSummary;
use App\Modules\Customers\Application\DTOs\ContactSummary;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Domain\Enums\CustomerType;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use LogicException;
/**
* Customers for unit tests of other modules: names by id, contacts and
* billing units as [customerId, id, name].
*/
class FakeCustomerQueries implements CustomerQueries
{
/** @var array<int, string> */
public array $customers = [];
/** @var list<array{int, int, string}> */
public array $contacts = [];
/** @var list<array{int, int, string}> */
public array $billingUnits = [];
public function findSummary(int $id): ?CustomerSummary
{
return isset($this->customers[$id]) ? new CustomerSummary($id, $this->customers[$id], CustomerType::Company, null) : null;
}
public function namesByIds(array $ids): array
{
return array_intersect_key($this->customers, array_flip($ids));
}
public function personalIdentityCodeOf(int $customerId): ?string
{
return null;
}
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator
{
throw new LogicException('Not needed in unit tests.');
}
public function search(string $term, int $limit = 10): array
{
return [];
}
public function contactsOf(int $customerId): array
{
return [];
}
public function findContact(int $customerId, int $contactId): ?ContactSummary
{
foreach ($this->contacts as [$ownerId, $id, $name]) {
if ($ownerId === $customerId && $id === $contactId) {
return new ContactSummary($id, $ownerId, $name, null, null, null, null);
}
}
return null;
}
public function billingUnitsOf(int $customerId): array
{
return [];
}
public function findBillingUnit(int $customerId, int $billingUnitId): ?BillingUnitSummary
{
foreach ($this->billingUnits as [$ownerId, $id, $name]) {
if ($ownerId === $customerId && $id === $billingUnitId) {
return new BillingUnitSummary($id, $ownerId, $name, null, null, null, null);
}
}
return null;
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace Tests\Fakes;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
class FakeCustomerRowUsage implements CustomerRowUsage
{
/** @var list<int> */
public array $contactsInUse = [];
/** @var list<int> */
public array $billingUnitsInUse = [];
public function isContactInUse(int $contactId): bool
{
return in_array($contactId, $this->contactsInUse, true);
}
public function isBillingUnitInUse(int $billingUnitId): bool
{
return in_array($billingUnitId, $this->billingUnitsInUse, true);
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Tests\Fakes;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserOption;
use App\Modules\Users\Application\DTOs\UserSummary;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use LogicException;
/**
* Users for unit tests of other modules.
*/
class FakeUserAccountQueries implements UserAccountQueries
{
/** @var array<int, array{string, Role, bool}> name, role, active */
public array $users = [];
public function addUser(int $id, string $name, Role $role = Role::Employee, bool $active = true): void
{
$this->users[$id] = [$name, $role, $active];
}
public function findSummary(int $id): ?UserSummary
{
throw new LogicException('Not needed in unit tests.');
}
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator
{
throw new LogicException('Not needed in unit tests.');
}
public function supervisorOptions(?int $exceptUserId = null): array
{
return [];
}
public function activeUserOptions(): array
{
$options = [];
foreach ($this->users as $id => [$name, $role, $active]) {
if ($active) {
$options[] = new UserOption($id, $name, $role);
}
}
return $options;
}
public function namesByIds(array $ids): array
{
return array_map(fn (array $user): string => $user[0], array_intersect_key($this->users, array_flip($ids)));
}
}
@@ -0,0 +1,61 @@
<?php
namespace Tests\Fakes;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\JobNumberSequence;
use App\Modules\Jobs\Domain\Entities\CustomerJob;
use App\Modules\Jobs\Domain\ValueObjects\FieldChange;
use App\Modules\Jobs\Domain\ValueObjects\JobNumber;
/**
* Customer jobs, their history and the yearly numbering, in memory.
*/
class InMemoryCustomerJobRepository implements CustomerJobRepository, JobNumberSequence
{
/** @var array<int, CustomerJob> */
public array $jobs = [];
/** @var list<array{int, int, FieldChange}> job id, user id, change */
public array $changes = [];
/** @var array<int, int> */
private array $lastNumbers = [];
private int $nextId = 1;
public function findById(int $id): ?CustomerJob
{
return isset($this->jobs[$id]) ? clone $this->jobs[$id] : null;
}
public function save(CustomerJob $job): CustomerJob
{
$id = $job->id() ?? $this->nextId++;
$this->jobs[$id] = CustomerJob::reconstitute($id, $job->number(), $job->details(), $job->createdBy());
return clone $this->jobs[$id];
}
public function recordChanges(int $jobId, int $userId, array $changes): void
{
foreach ($changes as $change) {
$this->changes[] = [$jobId, $userId, $change];
}
}
public function next(int $year): JobNumber
{
$this->lastNumbers[$year] = ($this->lastNumbers[$year] ?? 0) + 1;
return new JobNumber($year, $this->lastNumbers[$year]);
}
/**
* @return list<string>
*/
public function changedFields(int $jobId): array
{
return array_values(array_map(fn (array $row): string => $row[2]->field, array_filter($this->changes, fn (array $row): bool => $row[0] === $jobId)));
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ class InMemoryCustomerRepository implements CustomerRepository
public function save(Customer $customer): Customer
{
$id = $customer->id() ?? $this->nextId++;
$stored = Customer::reconstitute($id, $customer->name(), $customer->type(), $customer->businessId(), $customer->personalIdentityCode());
$stored = Customer::reconstitute($id, $customer->name(), $customer->type(), $customer->businessId(), $customer->personalIdentityCode(), $customer->isInternal());
$this->customers[$id] = $stored;
@@ -36,9 +36,9 @@ it('registers a company customer', function () {
->set('form.business_id', '0737546-2')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('customers.show', CustomerModel::query()->sole()->id));
->assertRedirect(route('customers.show', CustomerModel::query()->where('is_internal', false)->sole()->id));
$customer = CustomerModel::query()->sole();
$customer = CustomerModel::query()->where('is_internal', false)->sole();
expect($customer->name)->toBe('Mainos Oy')
->and($customer->type)->toBe(CustomerType::Company)
@@ -53,7 +53,7 @@ it('ignores a business id typed before switching to consumer', function () {
->call('save')
->assertHasNoErrors();
expect(CustomerModel::query()->sole()->business_id)->toBeNull();
expect(CustomerModel::query()->where('is_internal', false)->sole()->business_id)->toBeNull();
});
it('shows validation and business rule errors on the fields', function (array $input, string $field, string $message) {
@@ -65,7 +65,7 @@ it('shows validation and business rule errors on the fields', function (array $i
->assertHasErrors([$field])
->assertSee($message);
expect(CustomerModel::query()->count())->toBe(1);
expect(CustomerModel::query()->where('is_internal', false)->count())->toBe(1);
})->with([
'missing name' => [['form.name' => ''], 'form.name', 'Anna asiakkaan nimi.'],
'bad check digit' => [['form.name' => 'Mainos Oy', 'form.business_id' => '0737546-3'], 'form.business_id', 'Y-tunnus ei ole kelvollinen.'],
@@ -30,8 +30,8 @@ it('updates a stored customer', function () {
$customer->changeDetails(new CustomerName('Maija Meikäläinen'), CustomerType::Consumer, null);
$repository->save($customer);
expect(CustomerModel::query()->count())->toBe(1)
->and(CustomerModel::query()->sole()->type)->toBe(CustomerType::Consumer);
expect(CustomerModel::query()->where('is_internal', false)->count())->toBe(1)
->and(CustomerModel::query()->where('is_internal', false)->sole()->type)->toBe(CustomerType::Consumer);
});
it('tells whether another customer has the business id', function () {
@@ -52,6 +52,6 @@ it('returns summaries filtered by name or business id, ordered by name', functio
expect(array_map(fn ($summary) => $summary->name, $queries->search('media')))->toBe(['Alfa Media Oy', 'Bravo Media Oy'])
->and($queries->paginate('0737546')->total())->toBe(1)
->and($queries->paginate(null)->total())->toBe(3)
->and($queries->paginate(null)->total())->toBe(4) // and the internal customer
->and($queries->search('100%'))->toBe([]);
});
@@ -0,0 +1,206 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\BillingUnitModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerContactModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->employee = User::factory()->create(['name' => 'Eero Työntekijä']);
$this->actingAs($this->employee);
$this->customer = CustomerModel::factory()->create(['name' => 'Mainos Oy']);
$this->media = ServiceUnitModel::query()->where('name', 'Mediatuotanto')->sole();
});
/**
* Fills the job form with the required fields.
*/
function fillJobForm(mixed $form, int $customerId, int $serviceUnitId): mixed
{
return $form
->set('form.name', 'Messuvideo')
->call('selectCustomer', $customerId)
->set('form.service_unit_ids', [(string) $serviceUnitId]);
}
it('creates a job with the next number of the year and its history', function () {
$this->travelTo(now()->setDate(2026, 3, 1));
fillJobForm(Livewire::test('jobs::form'), $this->customer->id, $this->media->id)
->set('form.tags', ['messut'])
->set('form.links', [['title' => 'Briiffi', 'url' => 'https://drive.example.test/briiffi']])
->call('save')
->assertHasNoErrors();
fillJobForm(Livewire::test('jobs::form'), $this->customer->id, $this->media->id)->call('save')->assertHasNoErrors();
$jobs = CustomerJobModel::query()->orderBy('id')->get();
expect($jobs->pluck('number')->all())->toBe(['2026-0001', '2026-0002'])
->and($jobs[0]->responsible_user_id)->toBe($this->employee->id)
->and(DB::table('tags')->pluck('name')->all())->toBe(['messut'])
->and(DB::table('customer_job_changes')->where('customer_job_id', $jobs[0]->id)->value('field'))->toBe('created');
$this->get(route('jobs.show', $jobs[0]->id))
->assertOk()
->assertSee('2026-0001 Messuvideo')
->assertSee('Briiffi')
->assertSee('Eero Työntekijä loi työn 2026-0001.');
});
it('adds a new customer from the job form', function () {
Livewire::test('jobs::form')
->set('customerSearch', 'Uusi Asiakas Oy')
->assertSee('Lisää uusi asiakas: Uusi Asiakas Oy')
->call('createCustomer')
->assertSee('Asiakas Uusi Asiakas Oy lisätty ja valittu.');
$customer = CustomerModel::query()->where('name', 'Uusi Asiakas Oy')->sole();
expect($customer->type->value)->toBe('company');
});
it('finds customers by name and offers only their contacts and billing units', function () {
CustomerContactModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Maija']);
CustomerContactModel::factory()->create(['name' => 'Toisen kontakti']);
BillingUnitModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Mainos Oy, markkinointi']);
Livewire::test('jobs::form')
->set('customerSearch', 'main')
->assertSee('Valitse Mainos Oy')
->call('selectCustomer', $this->customer->id)
->assertSee('Maija')
->assertSee('Mainos Oy, markkinointi')
->assertDontSee('Toisen kontakti');
});
it('records changed fields and shows them in the history', function () {
$job = CustomerJobModel::factory()->create(['customer_id' => $this->customer->id, 'responsible_user_id' => $this->employee->id]);
Livewire::test('jobs::form', ['job' => $job->id])
->set('form.priority', 'urgent')
->set('form.due_on', '2026-06-30')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('jobs.show', $job->id));
$this->get(route('jobs.show', $job->id))
->assertSee('Prioriteetti: Normaali → Kiire')
->assertSee('Määräaika: – → 30.6.2026');
});
it('shows Finnish errors for dates and missing fields', function () {
Livewire::test('jobs::form')
->set('form.starts_on', '2026-05-10')
->set('form.due_on', '2026-05-01')
->call('selectCustomer', $this->customer->id)
->set('form.service_unit_ids', [(string) $this->media->id])
->set('form.name', 'Messuvideo')
->call('save')
->assertHasErrors(['form.due_on'])
->assertSee('Määräaika ei voi olla ennen alkamispäivää.');
Livewire::test('jobs::form')
->call('save')
->assertHasErrors(['form.name', 'form.customer_id', 'form.service_unit_ids'])
->assertSee('Valitse vähintään yksi palveluyksikkö.');
});
it('lists my jobs by default, and all jobs on request', function () {
$mine = CustomerJobModel::factory()->create(['name' => 'Oma työ', 'responsible_user_id' => $this->employee->id]);
$member = CustomerJobModel::factory()->withMembers([$this->employee->id])->create(['name' => 'Jäsenenä']);
CustomerJobModel::factory()->create(['name' => 'Muiden työ']);
CustomerJobModel::factory()->create(['name' => 'Arkistoitu työ', 'status' => 'archived', 'responsible_user_id' => $this->employee->id]);
Livewire::test('jobs::index')
->assertSee('Oma työ')
->assertSee('Jäsenenä')
->assertDontSee('Muiden työ')
->assertDontSee('Arkistoitu työ')
->set('mine', false)
->assertSee('Muiden työ')
->set('archived', true)
->assertSee('Arkistoitu työ')
->set('search', 'mainos')
->assertDontSee('Muiden työ');
expect($mine->id)->not->toBe($member->id);
});
it('lets a subcontractor see only the jobs they are a member of, read only', function () {
$subcontractor = User::factory()->subcontractor()->create();
$theirs = CustomerJobModel::factory()->withMembers([$subcontractor->id])->create(['name' => 'Alihankintatyö', 'instructions' => 'Kuvaus klo 9.']);
$other = CustomerJobModel::factory()->create(['name' => 'Muu työ']);
$this->actingAs($subcontractor);
$this->get(route('jobs.index'))->assertOk()->assertSee('Alihankintatyö')->assertDontSee('Muu työ')->assertDontSee('Uusi asiakastyö');
$this->get(route('jobs.show', $theirs->id))->assertOk()->assertSee('Kuvaus klo 9.')->assertDontSee('Muokkaa');
$this->get(route('jobs.show', $other->id))->assertForbidden();
$this->get(route('jobs.edit', $theirs->id))->assertForbidden();
$this->get(route('jobs.create'))->assertForbidden();
});
it('lets only management and the biller set billing statuses, and only management archive', function () {
$job = CustomerJobModel::factory()->create(['customer_id' => $this->customer->id, 'status' => 'done', 'responsible_user_id' => $this->employee->id]);
Livewire::test('jobs::form', ['job' => $job->id])
->assertDontSee('Lasku luotu')
->set('form.status', 'invoiced')
->call('save')
->assertHasErrors(['form.status']);
$job->update(['biller_user_id' => $this->employee->id]);
Livewire::test('jobs::form', ['job' => $job->id])
->assertSee('Lasku luotu')
->assertDontSee('Arkistoitu')
->set('form.status', 'invoiced')
->call('save')
->assertHasNoErrors();
Livewire::actingAs(User::factory()->management()->create())
->test('jobs::form', ['job' => $job->id])
->set('form.status', 'archived')
->call('save')
->assertHasNoErrors();
expect($job->fresh()->status->value)->toBe('archived');
});
it('blocks removing a billing unit or contact a job uses', function () {
$contact = CustomerContactModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Maija']);
$billingUnit = BillingUnitModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Mainos Oy']);
CustomerJobModel::factory()->create(['customer_id' => $this->customer->id, 'customer_contact_id' => $contact->id, 'billing_unit_id' => $billingUnit->id]);
Livewire::test('customers::show', ['customer' => $this->customer->id])
->call('confirmRemoval', 'billing_unit', $billingUnit->id)
->call('remove')
->assertSee('Laskutusyksikköä Mainos Oy ei poistettu')
->call('confirmRemoval', 'contact', $contact->id)
->call('remove')
->assertSee('Yhteyshenkilöä Maija ei poistettu');
expect($billingUnit->fresh())->not->toBeNull()
->and($contact->fresh())->not->toBeNull();
});
it('has the internal customer', function () {
expect(CustomerModel::query()->where('is_internal', true)->sole()->name)->toBe('Oma yritys (sisäinen)');
$this->get(route('customers.index'))->assertSee('(Sisäinen)');
});
it('does not let the job id be changed in the browser, and returns 404 for unknown jobs', function () {
$this->get(route('jobs.show', 999))->assertNotFound();
Livewire::test('jobs::form')->set('jobId', 1);
})->throws(CannotUpdateLockedPropertyException::class);
@@ -19,7 +19,7 @@ it('rolls back everything when the work fails', function () {
throw new RuntimeException('fail');
}))->toThrow(RuntimeException::class);
expect(CustomerModel::query()->count())->toBe(0);
expect(CustomerModel::query()->where('is_internal', false)->count())->toBe(0);
});
it('publishes events only after the transaction commits', function () {
@@ -10,12 +10,15 @@ use App\Modules\Customers\Application\UseCases\UpdateBillingUnit;
use App\Modules\Customers\Application\UseCases\UpdateContact;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\BillingUnitInUse;
use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound;
use App\Modules\Customers\Domain\Exceptions\ContactInUse;
use App\Modules\Customers\Domain\Exceptions\ContactNotFound;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\Exceptions\EInvoiceOperatorRequired;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use Tests\Fakes\FakeCustomerRowUsage;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryBillingUnitRepository;
use Tests\Fakes\InMemoryCustomerContactRepository;
@@ -29,10 +32,11 @@ beforeEach(function () {
$this->addContact = new AddContact($this->customers, $this->contacts, $transactions);
$this->updateContact = new UpdateContact($this->contacts, $transactions);
$this->removeContact = new RemoveContact($this->contacts, $transactions);
$this->usage = new FakeCustomerRowUsage;
$this->removeContact = new RemoveContact($this->contacts, $this->usage, $transactions);
$this->addBillingUnit = new AddBillingUnit($this->customers, $this->billingUnits, $transactions);
$this->updateBillingUnit = new UpdateBillingUnit($this->billingUnits, $transactions);
$this->removeBillingUnit = new RemoveBillingUnit($this->billingUnits, $transactions);
$this->removeBillingUnit = new RemoveBillingUnit($this->billingUnits, $this->usage, $transactions);
$this->customerId = $this->customers->save(Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company))->id();
$this->otherCustomerId = $this->customers->save(Customer::register(new CustomerName('Toinen Oy'), CustomerType::Company))->id();
@@ -102,3 +106,15 @@ it('does not touch a billing unit of another customer', function (string $action
'remove' => $this->removeBillingUnit->execute($this->customerId, $billingUnitId),
};
})->throws(BillingUnitNotFound::class)->with(['update', 'remove']);
it('does not remove a contact or billing unit that a customer job uses', function () {
$contactId = $this->addContact->execute($this->customerId, new ContactData('Maija'));
$billingUnitId = $this->addBillingUnit->execute($this->customerId, new BillingUnitData('Mainos Oy'));
$this->usage->contactsInUse = [$contactId];
$this->usage->billingUnitsInUse = [$billingUnitId];
expect(fn () => $this->removeContact->execute($this->customerId, $contactId))->toThrow(ContactInUse::class)
->and(fn () => $this->removeBillingUnit->execute($this->customerId, $billingUnitId))->toThrow(BillingUnitInUse::class)
->and($this->contacts->contacts)->toHaveCount(1)
->and($this->billingUnits->billingUnits)->toHaveCount(1);
});
@@ -0,0 +1,106 @@
<?php
use App\Modules\Jobs\Application\DTOs\CustomerJobData;
use App\Modules\Jobs\Application\Services\JobDetailsFactory;
use App\Modules\Jobs\Application\UseCases\ChangeJobStatus;
use App\Modules\Jobs\Application\UseCases\CreateCustomerJob;
use App\Modules\Jobs\Application\UseCases\UpdateCustomerJob;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference;
use App\Modules\Users\Domain\Enums\Role;
use Tests\Fakes\FakeCatalogQueries;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeCustomerQueries;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\FakeUserAccountQueries;
use Tests\Fakes\InMemoryCustomerJobRepository;
beforeEach(function () {
$this->jobs = new InMemoryCustomerJobRepository;
$this->customers = new FakeCustomerQueries;
$this->catalog = new FakeCatalogQueries;
$this->users = new FakeUserAccountQueries;
$this->clock = new FakeClock(new DateTimeImmutable('2026-12-31'));
$transactions = new FakeTransactionManager;
$this->customers->customers = [1 => 'Mainos Oy', 2 => 'Toinen Oy'];
$this->customers->contacts = [[1, 5, 'Maija'], [2, 6, 'Toisen kontakti']];
$this->catalog->addServiceUnit(1, 'Mediatuotanto');
$this->catalog->addServiceUnit(2, 'Markkinointi', active: false);
$this->catalog->addServiceUnit(9, 'Kaikille yhteiset', shared: true);
$this->users->addUser(10, 'Eero');
$this->users->addUser(11, 'Aino', Role::Subcontractor);
$this->users->addUser(12, 'Pois', active: false);
$factory = new JobDetailsFactory($this->customers, $this->catalog, $this->users);
$this->create = new CreateCustomerJob($this->jobs, $this->jobs, $factory, $transactions, $this->clock);
$this->update = new UpdateCustomerJob($this->jobs, $factory, $transactions);
$this->changeStatus = new ChangeJobStatus($this->jobs, $transactions);
});
/**
* @param array<string, mixed> $overrides
*/
function jobData(array $overrides = []): CustomerJobData
{
return new CustomerJobData(...array_merge([
'name' => 'Messuvideo',
'customerId' => 1,
'serviceUnitIds' => [1],
'responsibleUserId' => 10,
'kind' => 'one_off',
'status' => 'tentative',
'priority' => 'normal',
], $overrides));
}
it('numbers jobs per year and starts the history', function () {
$first = $this->create->execute(jobData(), 10);
$second = $this->create->execute(jobData(), 10);
$this->clock->today = new DateTimeImmutable('2027-01-01');
$nextYear = $this->create->execute(jobData(), 10);
expect($this->jobs->findById($first)?->number()->format())->toBe('2026-0001')
->and($this->jobs->findById($second)?->number()->format())->toBe('2026-0002')
->and($this->jobs->findById($nextYear)?->number()->format())->toBe('2027-0001')
->and($this->jobs->changedFields($first))->toBe(['created']);
});
it('rejects references that do not fit the job', function (array $overrides, string $field) {
try {
$this->create->execute(jobData($overrides), 10);
$this->fail('No exception');
} catch (InvalidJobReference $exception) {
expect($exception->field)->toBe($field);
}
})->with([
'unknown customer' => [['customerId' => 99], 'customer'],
'contact of another customer' => [['customerContactId' => 6], 'customer_contact'],
'inactive service unit' => [['serviceUnitIds' => [2]], 'service_units'],
'shared service unit' => [['serviceUnitIds' => [9]], 'service_units'],
'subcontractor as responsible' => [['responsibleUserId' => 11], 'responsible_user'],
'inactive member' => [['memberUserIds' => [12]], 'members'],
]);
it('keeps an inactive unit or user that is already on the job', function () {
$this->catalog->addServiceUnit(2, 'Markkinointi');
$this->users->addUser(12, 'Pois');
$jobId = $this->create->execute(jobData(['serviceUnitIds' => [1, 2], 'memberUserIds' => [12]]), 10);
$this->catalog->addServiceUnit(2, 'Markkinointi', active: false);
$this->users->addUser(12, 'Pois', active: false);
$this->update->execute($jobId, jobData(['name' => 'Messuvideo 2', 'serviceUnitIds' => [1, 2], 'memberUserIds' => [12]]), 10);
expect($this->jobs->findById($jobId)?->details()->name->value)->toBe('Messuvideo 2');
});
it('records each changed field, and nothing when nothing changed', function () {
$jobId = $this->create->execute(jobData(), 10);
$this->update->execute($jobId, jobData(['priority' => 'urgent', 'customerContactId' => 5, 'tags' => ['messut']]), 10);
$this->update->execute($jobId, jobData(['priority' => 'urgent', 'customerContactId' => 5, 'tags' => ['Messut']]), 10);
$this->changeStatus->execute($jobId, JobStatus::Order, 10);
expect($this->jobs->changedFields($jobId))->toBe(['created', 'priority', 'customer_contact', 'tags', 'status']);
});
@@ -0,0 +1,99 @@
<?php
use App\Modules\Jobs\Domain\Entities\CustomerJob;
use App\Modules\Jobs\Domain\Enums\JobKind;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\Priority;
use App\Modules\Jobs\Domain\Exceptions\DueBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobLink;
use App\Modules\Jobs\Domain\Exceptions\InvalidTag;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\ServiceUnitRequired;
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
use App\Modules\Jobs\Domain\ValueObjects\JobDetails;
use App\Modules\Jobs\Domain\ValueObjects\JobLink;
use App\Modules\Jobs\Domain\ValueObjects\JobName;
use App\Modules\Jobs\Domain\ValueObjects\JobNumber;
use App\Modules\Jobs\Domain\ValueObjects\Tag;
/**
* @param array<string, mixed> $overrides
*/
function jobDetails(array $overrides = []): JobDetails
{
return new JobDetails(...array_merge([
'name' => new JobName('Messuvideo'),
'description' => null,
'customerId' => 1,
'serviceUnitIds' => [1],
'startsOn' => null,
'dueOn' => null,
'plannedFrom' => null,
'plannedTo' => null,
'kind' => JobKind::OneOff,
'status' => JobStatus::Tentative,
'priority' => Priority::Normal,
'paymentBasis' => null,
'estimatedHours' => null,
'customerReference' => null,
'instructions' => null,
'responsibleUserId' => 10,
'contactUserId' => null,
'customerContactId' => null,
'billerUserId' => null,
'billingUnitId' => null,
'memberUserIds' => [],
'tags' => [],
'links' => [],
], $overrides));
}
it('formats and parses job numbers', function () {
expect((new JobNumber(2026, 42))->format())->toBe('2026-0042')
->and(JobNumber::fromString('2027-0001')->sequence)->toBe(1);
});
it('accepts estimated hours in quarters only', function () {
expect(EstimatedHours::fromString('7,25')->format())->toBe('7.25')
->and(EstimatedHours::fromString('8')->format())->toBe('8')
->and(fn () => EstimatedHours::fromString('1.1'))->toThrow(InvalidEstimatedHours::class)
->and(fn () => new EstimatedHours(-1))->toThrow(InvalidEstimatedHours::class);
});
it('accepts only http and https links with a title', function () {
expect((new JobLink(' Briiffi ', 'https://drive.example.test/x'))->title)->toBe('Briiffi')
->and(fn () => new JobLink('Tiedosto', 'javascript:alert(1)'))->toThrow(InvalidJobLink::class)
->and(fn () => new JobLink('', 'https://example.test'))->toThrow(InvalidJobLink::class)
->and(fn () => new Tag(str_repeat('a', 51)))->toThrow(InvalidTag::class);
});
it('checks the dates and service units of a job', function (array $overrides, string $exception) {
expect(fn () => jobDetails($overrides))->toThrow($exception);
})->with([
'due before start' => [['startsOn' => new DateTimeImmutable('2026-05-10'), 'dueOn' => new DateTimeImmutable('2026-05-09')], DueBeforeStart::class],
'plan ends before start' => [['plannedFrom' => new DateTimeImmutable('2026-05-10'), 'plannedTo' => new DateTimeImmutable('2026-05-01')], PlanEndsBeforeStart::class],
'no service unit' => [['serviceUnitIds' => []], ServiceUnitRequired::class],
]);
it('removes duplicate tags ignoring case, and sorts ids', function () {
$details = jobDetails(['tags' => [new Tag('Messut'), new Tag('messut'), new Tag('video')], 'memberUserIds' => [3, 1, 3]]);
expect(array_map(fn (Tag $tag) => $tag->value, $details->tags))->toBe(['Messut', 'video'])
->and($details->memberUserIds)->toBe([1, 3])
->and($details->involves(3))->toBeTrue()
->and($details->involves(99))->toBeFalse();
});
it('returns only the fields that changed', function () {
$job = CustomerJob::open(new JobNumber(2026, 1), jobDetails(), 10);
$changes = $job->changeDetails(jobDetails(['priority' => Priority::Urgent, 'tags' => [new Tag('messut')]]));
expect(array_map(fn ($change) => [$change->field, $change->oldValue, $change->newValue], $changes))->toBe([
['priority', 'normal', 'urgent'],
['tags', null, 'messut'],
])
->and($job->changeStatus(JobStatus::Tentative))->toBe([])
->and(JobStatus::kanbanStatuses())->not->toContain(JobStatus::Archived);
});