from dataclasses import replace from datetime import date from decimal import Decimal from typing import Any import pytest from apps.jobs.application.dto import Actor, CustomerJobData, JobLinkData from apps.jobs.application.use_cases import ( AddJobLink, CreateCustomerJob, DeleteJobLink, UpdateCustomerJob, UpdateJobLink, ) from apps.jobs.domain.enums import JobStatus, Priority from apps.jobs.domain.exceptions import ( BillingUnitNotOfCustomer, ContactNotOfCustomer, CustomerJobNotFound, InvalidJobName, JobLinkNotFound, ServiceUnitNotSelectable, StatusNotAllowed, UnknownCustomer, UserNotSelectable, ) from apps.jobs.tests.fakes import ( FakeCatalogQueries, FakeCustomerQueries, FakeUserQueries, FixedClock, InMemoryJobRepository, InMemoryLinkRepository, ) from apps.shared.tests.fakes import FakeUnitOfWork from apps.users.domain.enums import Role EMPLOYEE = Actor(user_id=1, role=Role.EMPLOYEE) MANAGER = Actor(user_id=2, role=Role.MANAGEMENT) class World: def __init__(self) -> None: self.jobs = InMemoryJobRepository() self.links = InMemoryLinkRepository() self.uow = FakeUnitOfWork() self.customers = FakeCustomerQueries() self.customers.add(10, "Oy Asiakas Ab", contacts=[(100, "Maija")], units=[(200, "HQ")]) self.customers.add(11, "Toinen Oy", contacts=[(101, "Pekka")], units=[(201, "Konttori")]) self.users = FakeUserQueries() self.users.add(1, "Eero Työntekijä") self.users.add(2, "Johanna Johto", Role.MANAGEMENT) self.users.add(3, "Aili Alihankkija", Role.SUBCONTRACTOR) self.users.add(4, "Lauri Lähtenyt", active=False) self.catalog = FakeCatalogQueries() self.catalog.add(1, "Mediatuotanto") self.catalog.add(2, "Painotuotanto") self.catalog.add(3, "Yhteiset", shared=True) self.catalog.add(4, "Vanha", active=False) self.clock = FixedClock(date(2026, 11, 29)) def _deps(self) -> tuple[Any, ...]: return (self.jobs, self.uow, self.customers, self.users, self.catalog, self.clock) def create(self, actor: Actor = EMPLOYEE, **overrides: Any) -> Any: return CreateCustomerJob(*self._deps()).execute(actor, data(**overrides)) def update(self, job_id: int, actor: Actor = EMPLOYEE, **overrides: Any) -> None: UpdateCustomerJob(*self._deps()).execute(actor, job_id, data(**overrides)) def data(**overrides: Any) -> CustomerJobData: base = CustomerJobData( name="Esite", customer_id=10, service_unit_ids=(1,), responsible_user_id=1 ) return replace(base, **overrides) @pytest.fixture def world() -> World: return World() class TestCreate: def test_numbering_restarts_every_year(self, world: World) -> None: assert world.create().number == "2026-0001" assert world.create().number == "2026-0002" world.clock.set(date(2027, 1, 1)) assert world.create().number == "2027-0001" def test_defaults_and_creator(self, world: World) -> None: created = world.create() job = world.jobs.get(created.id) assert job is not None assert job.created_by == EMPLOYEE.user_id assert job.details.status is JobStatus.TENTATIVE assert job.details.priority is Priority.NORMAL assert world.uow.entered == 1 def test_invalid_input_fails_before_transaction(self, world: World) -> None: with pytest.raises(InvalidJobName): world.create(name=" ") assert world.uow.entered == 0 def test_unknown_customer(self, world: World) -> None: with pytest.raises(UnknownCustomer): world.create(customer_id=99) def test_contact_and_billing_unit_must_belong_to_customer(self, world: World) -> None: world.create(customer_contact_id=100, billing_unit_id=200) with pytest.raises(ContactNotOfCustomer): world.create(customer_contact_id=101) with pytest.raises(BillingUnitNotOfCustomer): world.create(billing_unit_id=201) @pytest.mark.parametrize("unit_id", [3, 4, 99]) def test_shared_inactive_or_unknown_unit_rejected(self, world: World, unit_id: int) -> None: with pytest.raises(ServiceUnitNotSelectable): world.create(service_unit_ids=(1, unit_id)) def test_subcontractor_not_in_role_fields_but_may_be_member(self, world: World) -> None: with pytest.raises(UserNotSelectable) as error: world.create(biller_user_id=3) assert error.value.field == "biller_user" world.create(member_ids=(3,)) def test_inactive_user_rejected(self, world: World) -> None: with pytest.raises(UserNotSelectable): world.create(responsible_user_id=4) with pytest.raises(UserNotSelectable): world.create(member_ids=(4,)) def test_status_rules(self, world: World) -> None: with pytest.raises(StatusNotAllowed): world.create(status=JobStatus.ARCHIVED) with pytest.raises(StatusNotAllowed): world.create(status=JobStatus.INVOICED) world.create(MANAGER, status=JobStatus.ARCHIVED) def test_subcontractor_cannot_create(self, world: World) -> None: with pytest.raises(StatusNotAllowed): world.create(Actor(user_id=3, role=Role.SUBCONTRACTOR)) class TestUpdate: def test_records_changes_with_display_values(self, world: World) -> None: job_id = world.create(member_ids=(1,), tags=("video",)).id world.update( job_id, name="Esite 2", customer_id=11, customer_contact_id=101, service_unit_ids=(1, 2), responsible_user_id=2, member_ids=(1, 2), tags=("Video", "Messut"), priority=Priority.URGENT, due_on=date(2026, 12, 24), estimated_hours=Decimal("7.5"), ) assert world.jobs.change_rows() == [ ("name", "Esite", "Esite 2"), ("customer", "Oy Asiakas Ab", "Toinen Oy"), ("service_units", "Mediatuotanto", "Mediatuotanto, Painotuotanto"), ("due_on", "", "2026-12-24"), ("priority", "normal", "urgent"), ("estimated_hours", "", "7.50"), ("responsible_user", "Eero Työntekijä", "Johanna Johto"), ("customer_contact", "", "Pekka"), ("members", "Eero Työntekijä", "Eero Työntekijä, Johanna Johto"), ("tags", "video", "Messut, Video"), ] assert all(user_id == EMPLOYEE.user_id for _, user_id, _ in world.jobs.changes) def test_no_change_records_nothing(self, world: World) -> None: job_id = world.create().id world.update(job_id) assert world.jobs.changes == [] def test_kept_inactive_people_and_units_stay_valid(self, world: World) -> None: job_id = world.create(member_ids=(1,)).id world.users.add(1, "Eero Työntekijä", active=False) world.catalog.units = [(u, False) if u.id == 1 else (u, a) for u, a in world.catalog.units] world.update(job_id, name="Uusi nimi", member_ids=(1,)) with pytest.raises(UserNotSelectable): world.update(job_id, contact_user_id=1) def test_biller_employee_may_set_invoice_status(self, world: World) -> None: job_id = world.create(biller_user_id=1).id world.update(job_id, biller_user_id=1, status=JobStatus.INVOICED) other = world.create().id with pytest.raises(StatusNotAllowed): world.update(other, status=JobStatus.BILLED) def test_employee_keeps_archived_status(self, world: World) -> None: job_id = world.create(MANAGER, status=JobStatus.ARCHIVED).id world.update(job_id, status=JobStatus.ARCHIVED, name="Korjattu") world.update(job_id, status=JobStatus.ORDER) with pytest.raises(StatusNotAllowed): world.update(job_id, status=JobStatus.ARCHIVED) def test_missing_job(self, world: World) -> None: with pytest.raises(CustomerJobNotFound): world.update(99) class TestLinks: def _cases(self, world: World) -> tuple[AddJobLink, UpdateJobLink, DeleteJobLink]: deps = (world.jobs, world.links, world.uow) return AddJobLink(*deps), UpdateJobLink(*deps), DeleteJobLink(*deps) def test_add_edit_delete_are_in_history(self, world: World) -> None: job_id = world.create().id add, update, delete = self._cases(world) link_id = add.execute(EMPLOYEE, job_id, JobLinkData("Aineisto", "https://a.test/1")) update.execute(EMPLOYEE, job_id, link_id, JobLinkData("Aineisto", "https://a.test/2")) update.execute(EMPLOYEE, job_id, link_id, JobLinkData("Aineisto", "https://a.test/2")) delete.execute(EMPLOYEE, job_id, link_id) assert world.links.links == {} assert world.jobs.change_rows() == [ ("links", "", "Aineisto (https://a.test/1)"), ("links", "Aineisto (https://a.test/1)", "Aineisto (https://a.test/2)"), ("links", "Aineisto (https://a.test/2)", ""), ] def test_link_of_another_job_not_found(self, world: World) -> None: first, second = world.create().id, world.create().id add, update, delete = self._cases(world) link_id = add.execute(EMPLOYEE, first, JobLinkData("", "https://a.test")) with pytest.raises(JobLinkNotFound): update.execute(EMPLOYEE, second, link_id, JobLinkData("", "https://b.test")) with pytest.raises(JobLinkNotFound): delete.execute(EMPLOYEE, second, link_id) with pytest.raises(CustomerJobNotFound): add.execute(EMPLOYEE, 99, JobLinkData("", "https://a.test"))