Vaihe 1/4: asiakastyöt (numerointi, tagit, linkit, jäsenet, muutoshistoria)
- Uusi jobs-moduuli: asiakastyön kentät ilman rahakenttiä, juokseva vuosinumero VVVV-NNNN (laskuririvi lukitaan), tagit, linkit dialogissa, jäsenet ja muutoshistoria nimiarvoineen. - Tilojen oikeudet: lasku luotu / laskutettu johto tai työn laskuttaja, arkistointi vain johto; alihankkija näkee vain jäsenyystyönsä eikä muokkaa. - Lista ja haku (numero, nimi, asiakas), suodattimet, omat työt oletuksena, arkistoidut piilossa, myöhässä tekstinä ja kuvakkeena. - Asiakasvalitsin hakuineen ja pikalisäyksineen (myös pikavastaanottoa varten). - Asiakkaan sivulle asiakastyöt-osio; valikkoon Asiakastyöt. - Lukurajapinnat muihin moduuleihin: UserQueries.choices, CustomerQueries.summaries, CatalogQueries.service_units; jobs.*-oikeudet. - Import-linter-sopimukset, käännökset, testit (domain, application, integraatio, selain) sekä määrittelyn ja CLAUDE.md:n päivitys. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,236 @@
|
||||
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"))
|
||||
@@ -0,0 +1,153 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.jobs.domain.entities import JobFields
|
||||
from apps.jobs.domain.enums import JobKind, JobStatus, PaymentBasis, Priority
|
||||
from apps.jobs.domain.exceptions import (
|
||||
DueBeforeStart,
|
||||
InvalidEstimatedHours,
|
||||
InvalidJobName,
|
||||
InvalidJobNumber,
|
||||
InvalidLinkUrl,
|
||||
InvalidTagName,
|
||||
PlannedRangeInvalid,
|
||||
ServiceUnitRequired,
|
||||
)
|
||||
from apps.jobs.domain.status_rules import allowed_statuses, can_set_status
|
||||
from apps.jobs.domain.value_objects import (
|
||||
EstimatedHours,
|
||||
JobName,
|
||||
JobNumber,
|
||||
LinkTarget,
|
||||
TagName,
|
||||
)
|
||||
from apps.users.domain.enums import Role
|
||||
|
||||
|
||||
def fields(**overrides: object) -> JobFields:
|
||||
values: dict[str, object] = {
|
||||
"name": JobName("Esite"),
|
||||
"customer_id": 1,
|
||||
"service_unit_ids": frozenset({1}),
|
||||
}
|
||||
values.update(overrides)
|
||||
return JobFields(**values) # type: ignore[arg-type]
|
||||
|
||||
|
||||
class TestJobNumber:
|
||||
def test_format_pads_sequence(self) -> None:
|
||||
assert str(JobNumber(2026, 42)) == "2026-0042"
|
||||
assert str(JobNumber(2027, 1)) == "2027-0001"
|
||||
|
||||
def test_sequence_over_9999_keeps_growing(self) -> None:
|
||||
assert str(JobNumber(2026, 10000)) == "2026-10000"
|
||||
|
||||
def test_parse_round_trip(self) -> None:
|
||||
assert JobNumber.parse("2026-0042") == JobNumber(2026, 42)
|
||||
|
||||
@pytest.mark.parametrize("value", ["", "2026", "26-0001", "2026-0000", "abcd-0001"])
|
||||
def test_invalid(self, value: str) -> None:
|
||||
with pytest.raises(InvalidJobNumber):
|
||||
JobNumber.parse(value)
|
||||
|
||||
|
||||
class TestValueObjects:
|
||||
def test_name_is_normalized_and_required(self) -> None:
|
||||
assert JobName(" Uusi esite ").value == "Uusi esite"
|
||||
with pytest.raises(InvalidJobName):
|
||||
JobName(" ")
|
||||
with pytest.raises(InvalidJobName):
|
||||
JobName("x" * 201)
|
||||
|
||||
@pytest.mark.parametrize("value", ["0", "1.5", "9999.99"])
|
||||
def test_hours_accepted(self, value: str) -> None:
|
||||
assert EstimatedHours(Decimal(value)).value == Decimal(value).quantize(Decimal("0.01"))
|
||||
|
||||
@pytest.mark.parametrize("value", ["-1", "10000", "1.255"])
|
||||
def test_hours_rejected(self, value: str) -> None:
|
||||
with pytest.raises(InvalidEstimatedHours):
|
||||
EstimatedHours(Decimal(value))
|
||||
|
||||
def test_tag_rules(self) -> None:
|
||||
assert TagName(" Video tuotanto ").value == "Video tuotanto"
|
||||
assert TagName("Video").key == TagName("video").key
|
||||
for bad in ("", "a,b", "x" * 51):
|
||||
with pytest.raises(InvalidTagName):
|
||||
TagName(bad)
|
||||
|
||||
def test_link_requires_http_url_and_defaults_title(self) -> None:
|
||||
link = LinkTarget(title="", url=" https://drive.example.test/x ")
|
||||
assert link.url == "https://drive.example.test/x"
|
||||
assert link.title == link.url
|
||||
assert (
|
||||
str(LinkTarget(title="Aineisto", url="https://a.test")) == "Aineisto (https://a.test)"
|
||||
)
|
||||
for bad in ("javascript:alert(1)", "ftp://a.test", "drive.example.test", ""):
|
||||
with pytest.raises(InvalidLinkUrl):
|
||||
LinkTarget(title="x", url=bad)
|
||||
|
||||
|
||||
class TestJobFields:
|
||||
def test_defaults_of_a_new_job(self) -> None:
|
||||
f = fields()
|
||||
assert f.status is JobStatus.TENTATIVE
|
||||
assert f.priority is Priority.NORMAL
|
||||
assert f.kind is JobKind.ONE_OFF
|
||||
assert f.payment_basis is PaymentBasis.HOURLY
|
||||
|
||||
def test_needs_a_service_unit(self) -> None:
|
||||
with pytest.raises(ServiceUnitRequired):
|
||||
fields(service_unit_ids=frozenset())
|
||||
|
||||
def test_planned_range_in_order(self) -> None:
|
||||
with pytest.raises(PlannedRangeInvalid):
|
||||
fields(planned_from=date(2026, 5, 2), planned_to=date(2026, 5, 1))
|
||||
fields(planned_from=date(2026, 5, 1), planned_to=date(2026, 5, 1))
|
||||
|
||||
def test_due_not_before_start(self) -> None:
|
||||
with pytest.raises(DueBeforeStart):
|
||||
fields(starts_on=date(2026, 5, 2), due_on=date(2026, 5, 1))
|
||||
|
||||
def test_tags_unique_case_insensitively_and_sorted(self) -> None:
|
||||
f = fields(tags=(TagName("video"), TagName("Esite"), TagName("Video")))
|
||||
assert [t.value for t in f.tags] == ["Esite", "video"]
|
||||
|
||||
def test_changed_fields(self) -> None:
|
||||
before = fields(tags=(TagName("a"),), member_ids=frozenset({1, 2}))
|
||||
after = fields(name=JobName("Esite 2"), tags=(TagName("A"),), member_ids=frozenset({2, 1}))
|
||||
assert after.changed_fields(before) == ["name"]
|
||||
other_tags = fields(tags=(TagName("b"),), member_ids=frozenset({1, 2}))
|
||||
assert other_tags.changed_fields(before) == ["tags"]
|
||||
|
||||
def test_user_ids(self) -> None:
|
||||
f = fields(responsible_user_id=1, biller_user_id=2, member_ids=frozenset({2, 3}))
|
||||
assert f.user_ids == {1, 2, 3}
|
||||
|
||||
|
||||
class TestStatusRules:
|
||||
@pytest.mark.parametrize("role", [Role.ADMIN, Role.MANAGEMENT, Role.EMPLOYEE, Role.INTERN])
|
||||
def test_editors_reach_done(self, role: Role) -> None:
|
||||
assert can_set_status(role, JobStatus.DONE)
|
||||
assert can_set_status(role, JobStatus.ON_HOLD)
|
||||
|
||||
def test_subcontractor_sets_nothing(self) -> None:
|
||||
assert allowed_statuses(Role.SUBCONTRACTOR) == []
|
||||
|
||||
@pytest.mark.parametrize("target", [JobStatus.INVOICED, JobStatus.BILLED])
|
||||
def test_invoice_statuses(self, target: JobStatus) -> None:
|
||||
assert can_set_status(Role.MANAGEMENT, target)
|
||||
assert can_set_status(Role.ADMIN, target)
|
||||
assert not can_set_status(Role.EMPLOYEE, target)
|
||||
assert can_set_status(Role.EMPLOYEE, target, is_biller=True)
|
||||
assert not can_set_status(Role.INTERN, target, is_biller=True)
|
||||
|
||||
def test_archive_only_management(self) -> None:
|
||||
assert can_set_status(Role.MANAGEMENT, JobStatus.ARCHIVED)
|
||||
assert not can_set_status(Role.EMPLOYEE, JobStatus.ARCHIVED, is_biller=True)
|
||||
|
||||
def test_current_status_may_always_stay(self) -> None:
|
||||
assert can_set_status(Role.EMPLOYEE, JobStatus.ARCHIVED, current=JobStatus.ARCHIVED)
|
||||
assert JobStatus.ARCHIVED in allowed_statuses(Role.INTERN, current=JobStatus.ARCHIVED)
|
||||
assert JobStatus.ARCHIVED not in allowed_statuses(Role.INTERN)
|
||||
@@ -0,0 +1,164 @@
|
||||
"""In-memory test doubles for the jobs application layer (no database)."""
|
||||
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
|
||||
from apps.catalog.application.dto import ServiceUnitSummary
|
||||
from apps.customers.application.dto import CustomerSummary
|
||||
from apps.customers.domain.enums import CustomerType
|
||||
from apps.jobs.domain.entities import ChangeRecord, CustomerJob, JobLink
|
||||
from apps.jobs.domain.value_objects import JobNumber
|
||||
from apps.users.application.dto import UserChoice
|
||||
from apps.users.domain.enums import Role
|
||||
|
||||
|
||||
class InMemoryJobRepository:
|
||||
def __init__(self) -> None:
|
||||
self.jobs: dict[int, CustomerJob] = {}
|
||||
self.counters: dict[int, int] = {}
|
||||
self.changes: list[tuple[int, int, ChangeRecord]] = []
|
||||
self._next = 1
|
||||
|
||||
def get(self, job_id: int) -> CustomerJob | None:
|
||||
return self.jobs.get(job_id)
|
||||
|
||||
def save(self, job: CustomerJob) -> CustomerJob:
|
||||
if job.id is None:
|
||||
job = job.with_id(self._next)
|
||||
self._next += 1
|
||||
assert job.id is not None
|
||||
self.jobs[job.id] = job
|
||||
return job
|
||||
|
||||
def next_number(self, year: int) -> JobNumber:
|
||||
self.counters[year] = self.counters.get(year, 0) + 1
|
||||
return JobNumber(year, self.counters[year])
|
||||
|
||||
def record_changes(self, job_id: int, user_id: int, changes: Sequence[ChangeRecord]) -> None:
|
||||
self.changes.extend((job_id, user_id, c) for c in changes)
|
||||
|
||||
def change_rows(self) -> list[tuple[str, str, str]]:
|
||||
return [(c.field, c.old_value, c.new_value) for _, _, c in self.changes]
|
||||
|
||||
|
||||
class InMemoryLinkRepository:
|
||||
def __init__(self) -> None:
|
||||
self.links: dict[int, JobLink] = {}
|
||||
self._next = 1
|
||||
|
||||
def get(self, link_id: int) -> JobLink | None:
|
||||
return self.links.get(link_id)
|
||||
|
||||
def save(self, link: JobLink) -> JobLink:
|
||||
if link.id is None:
|
||||
link = link.with_id(self._next)
|
||||
self._next += 1
|
||||
assert link.id is not None
|
||||
self.links[link.id] = link
|
||||
return link
|
||||
|
||||
def delete(self, link_id: int) -> None:
|
||||
del self.links[link_id]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Row:
|
||||
id: int
|
||||
name: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeCustomerQueries:
|
||||
"""Customers with their contacts and billing units, as the customers module shows them."""
|
||||
|
||||
customers: dict[int, str] = field(default_factory=dict)
|
||||
contacts_by_customer: dict[int, list[_Row]] = field(default_factory=dict)
|
||||
units_by_customer: dict[int, list[_Row]] = field(default_factory=dict)
|
||||
|
||||
def add(
|
||||
self,
|
||||
customer_id: int,
|
||||
name: str,
|
||||
*,
|
||||
contacts: Iterable[tuple[int, str]] = (),
|
||||
units: Iterable[tuple[int, str]] = (),
|
||||
) -> None:
|
||||
self.customers[customer_id] = name
|
||||
self.contacts_by_customer[customer_id] = [_Row(i, n) for i, n in contacts]
|
||||
self.units_by_customer[customer_id] = [_Row(i, n) for i, n in units]
|
||||
|
||||
def _summary(self, customer_id: int) -> CustomerSummary:
|
||||
return CustomerSummary(
|
||||
id=customer_id,
|
||||
name=self.customers[customer_id],
|
||||
type=CustomerType.COMPANY,
|
||||
business_id=None,
|
||||
is_internal=False,
|
||||
)
|
||||
|
||||
def get_summary(self, customer_id: int) -> CustomerSummary | None:
|
||||
return self._summary(customer_id) if customer_id in self.customers else None
|
||||
|
||||
def summaries(self, customer_ids: Iterable[int]) -> dict[int, CustomerSummary]:
|
||||
return {i: self._summary(i) for i in customer_ids if i in self.customers}
|
||||
|
||||
def contacts(self, customer_id: int) -> list[_Row]:
|
||||
return self.contacts_by_customer.get(customer_id, [])
|
||||
|
||||
def billing_units(self, customer_id: int) -> list[_Row]:
|
||||
return self.units_by_customer.get(customer_id, [])
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeUserQueries:
|
||||
users: dict[int, UserChoice] = field(default_factory=dict)
|
||||
|
||||
def add(self, user_id: int, name: str, role: Role = Role.EMPLOYEE, active: bool = True) -> None:
|
||||
self.users[user_id] = UserChoice(id=user_id, name=name, role=role, is_active=active)
|
||||
|
||||
def choices(
|
||||
self,
|
||||
ids: Iterable[int] | None = None,
|
||||
*,
|
||||
active_only: bool = False,
|
||||
exclude_roles: Iterable[Role] = (),
|
||||
) -> list[UserChoice]:
|
||||
wanted = set(ids) if ids is not None else None
|
||||
excluded = set(exclude_roles)
|
||||
return sorted(
|
||||
(
|
||||
u
|
||||
for u in self.users.values()
|
||||
if (wanted is None or u.id in wanted)
|
||||
and (u.is_active or not active_only)
|
||||
and u.role not in excluded
|
||||
),
|
||||
key=lambda u: u.name,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeCatalogQueries:
|
||||
units: list[tuple[ServiceUnitSummary, bool]] = field(default_factory=list) # (unit, active)
|
||||
|
||||
def add(self, unit_id: int, name: str, *, shared: bool = False, active: bool = True) -> None:
|
||||
self.units.append((ServiceUnitSummary(id=unit_id, name=name, is_shared=shared), active))
|
||||
|
||||
def active_service_units(self) -> list[ServiceUnitSummary]:
|
||||
return [u for u, active in self.units if active]
|
||||
|
||||
def service_units(self, ids: Iterable[int]) -> list[ServiceUnitSummary]:
|
||||
wanted = set(ids)
|
||||
return [u for u, _ in self.units if u.id in wanted]
|
||||
|
||||
|
||||
class FixedClock:
|
||||
def __init__(self, today: date) -> None:
|
||||
self._today = today
|
||||
|
||||
def today(self) -> date:
|
||||
return self._today
|
||||
|
||||
def set(self, today: date) -> None:
|
||||
self._today = today
|
||||
@@ -0,0 +1,356 @@
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
from django.test import Client
|
||||
|
||||
from apps.catalog.infrastructure.orm import ServiceUnitModel
|
||||
from apps.customers.infrastructure.orm import BillingUnitModel, ContactModel, CustomerModel
|
||||
from apps.jobs.infrastructure.orm import (
|
||||
CustomerJobModel,
|
||||
JobChangeModel,
|
||||
JobLinkModel,
|
||||
JobNumberSequenceModel,
|
||||
TagModel,
|
||||
)
|
||||
from apps.jobs.infrastructure.repositories import DjangoCustomerJobRepository
|
||||
from apps.users.infrastructure.orm import User
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
HX = {"HX-Request": "true"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def employee(make_user: Callable[..., User]) -> User:
|
||||
return make_user(name="Eero Työntekijä", role="employee")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def employee_client(client: Client, employee: User) -> Client:
|
||||
client.force_login(employee)
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def customer() -> CustomerModel:
|
||||
return CustomerModel.objects.create(name="Oy Asiakas Ab", type="company")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def unit() -> ServiceUnitModel:
|
||||
return ServiceUnitModel.objects.filter(is_shared=False, is_active=True).order_by("id").first()
|
||||
|
||||
|
||||
def job_data(customer: CustomerModel, unit: ServiceUnitModel, **extra: Any) -> dict[str, Any]:
|
||||
data = {
|
||||
"customer": customer.pk,
|
||||
"name": "Esite",
|
||||
"service_units": [unit.pk],
|
||||
"kind": "one_off",
|
||||
"status": "tentative",
|
||||
"priority": "normal",
|
||||
"payment_basis": "hourly",
|
||||
}
|
||||
data.update(extra)
|
||||
return data
|
||||
|
||||
|
||||
def create(client: Client, customer: CustomerModel, unit: ServiceUnitModel, **extra: Any) -> Any:
|
||||
return client.post("/jobs/new/", job_data(customer, unit, **extra))
|
||||
|
||||
|
||||
class TestNumbering:
|
||||
def test_sequential_numbers_per_year(
|
||||
self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel
|
||||
) -> None:
|
||||
with mock.patch(
|
||||
"apps.shared.infrastructure.clock.DjangoClock.today", return_value=date(2026, 3, 1)
|
||||
):
|
||||
create(employee_client, customer, unit)
|
||||
create(employee_client, customer, unit, name="Toinen")
|
||||
with mock.patch(
|
||||
"apps.shared.infrastructure.clock.DjangoClock.today", return_value=date(2027, 1, 2)
|
||||
):
|
||||
create(employee_client, customer, unit, name="Kolmas")
|
||||
numbers = list(CustomerJobModel.objects.order_by("id").values_list("number", flat=True))
|
||||
assert numbers == ["2026-0001", "2026-0002", "2027-0001"]
|
||||
assert JobNumberSequenceModel.objects.get(year=2026).last_number == 2
|
||||
|
||||
def test_counter_row_is_created_once(self) -> None:
|
||||
repo = DjangoCustomerJobRepository()
|
||||
assert str(repo.next_number(2030)) == "2030-0001"
|
||||
assert str(repo.next_number(2030)) == "2030-0002"
|
||||
assert JobNumberSequenceModel.objects.filter(year=2030).count() == 1
|
||||
|
||||
|
||||
class TestCreateAndEdit:
|
||||
def test_create_with_defaults_tags_and_members(
|
||||
self,
|
||||
employee_client: Client,
|
||||
employee: User,
|
||||
customer: CustomerModel,
|
||||
unit: ServiceUnitModel,
|
||||
make_user: Callable[..., User],
|
||||
) -> None:
|
||||
page = employee_client.get(f"/jobs/new/?customer={customer.pk}")
|
||||
assert page.status_code == 200
|
||||
html = page.content.decode()
|
||||
assert 'value="tentative" selected' in html
|
||||
assert "Oy Asiakas Ab" in html
|
||||
# The shared service unit is not offered for jobs.
|
||||
shared = ServiceUnitModel.objects.get(is_shared=True)
|
||||
assert f'name="service_units" value="{unit.pk}"' in html
|
||||
assert f'name="service_units" value="{shared.pk}"' not in html
|
||||
|
||||
sub = make_user(role="subcontractor", name="Aili Alihankkija")
|
||||
response = create(
|
||||
employee_client,
|
||||
customer,
|
||||
unit,
|
||||
responsible_user=employee.pk,
|
||||
members=[sub.pk],
|
||||
tags=["Video", "messut"],
|
||||
estimated_hours="7,5",
|
||||
)
|
||||
assert response.status_code == 302
|
||||
job = CustomerJobModel.objects.get()
|
||||
assert response["Location"] == f"/jobs/{job.pk}/"
|
||||
assert job.created_by_id == employee.pk
|
||||
assert str(job.estimated_hours) == "7.50"
|
||||
assert set(TagModel.objects.values_list("name", flat=True)) == {"Video", "messut"}
|
||||
detail = employee_client.get(f"/jobs/{job.pk}/").content.decode()
|
||||
assert "Aili Alihankkija" in detail
|
||||
assert "Alustava" in detail and "Normaali" in detail
|
||||
|
||||
def test_existing_tag_is_reused_ignoring_case(
|
||||
self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel
|
||||
) -> None:
|
||||
TagModel.objects.create(name="Video")
|
||||
create(employee_client, customer, unit, tags=["video"])
|
||||
assert TagModel.objects.count() == 1
|
||||
|
||||
def test_validation_errors_are_422(
|
||||
self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel
|
||||
) -> None:
|
||||
response = create(
|
||||
employee_client,
|
||||
customer,
|
||||
unit,
|
||||
name="",
|
||||
planned_from="2026-05-02",
|
||||
planned_to="2026-05-01",
|
||||
)
|
||||
assert response.status_code == 422
|
||||
response = create(
|
||||
employee_client, customer, unit, planned_from="2026-05-02", planned_to="2026-05-01"
|
||||
)
|
||||
assert response.status_code == 422
|
||||
assert (
|
||||
"Suunniteltu loppu ei voi olla ennen suunniteltua alkua." in response.content.decode()
|
||||
)
|
||||
assert not CustomerJobModel.objects.exists()
|
||||
|
||||
def test_contact_of_another_customer_is_rejected(
|
||||
self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel
|
||||
) -> None:
|
||||
other = CustomerModel.objects.create(name="Toinen Oy", type="company")
|
||||
contact = ContactModel.objects.create(customer=other, name="Pekka")
|
||||
response = create(employee_client, customer, unit, customer_contact=contact.pk)
|
||||
assert response.status_code == 422
|
||||
assert not CustomerJobModel.objects.exists()
|
||||
|
||||
def test_employee_cannot_archive(
|
||||
self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel
|
||||
) -> None:
|
||||
response = create(employee_client, customer, unit, status="archived")
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_edit_records_history(
|
||||
self,
|
||||
employee_client: Client,
|
||||
customer: CustomerModel,
|
||||
unit: ServiceUnitModel,
|
||||
) -> None:
|
||||
create(employee_client, customer, unit)
|
||||
job = CustomerJobModel.objects.get()
|
||||
contact = ContactModel.objects.create(customer=customer, name="Maija")
|
||||
billing = BillingUnitModel.objects.create(customer=customer, name="HQ")
|
||||
response = employee_client.post(
|
||||
f"/jobs/{job.pk}/edit/",
|
||||
job_data(
|
||||
customer,
|
||||
unit,
|
||||
name="Esite 2",
|
||||
priority="urgent",
|
||||
due_on="2026-12-24",
|
||||
customer_contact=contact.pk,
|
||||
billing_unit=billing.pk,
|
||||
),
|
||||
)
|
||||
assert response.status_code == 302
|
||||
rows = list(JobChangeModel.objects.order_by("id").values_list("field", "new_value"))
|
||||
assert rows == [
|
||||
("name", "Esite 2"),
|
||||
("due_on", "2026-12-24"),
|
||||
("priority", "urgent"),
|
||||
("customer_contact", "Maija"),
|
||||
("billing_unit", "HQ"),
|
||||
]
|
||||
page = employee_client.get(f"/jobs/{job.pk}/").content.decode()
|
||||
assert "Muutoshistoria" in page
|
||||
assert "Kiire" in page # the stored key is shown translated
|
||||
assert "24.12.2026" in page
|
||||
|
||||
def test_referenced_contact_cannot_be_deleted(
|
||||
self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel
|
||||
) -> None:
|
||||
contact = ContactModel.objects.create(customer=customer, name="Maija")
|
||||
create(employee_client, customer, unit, customer_contact=contact.pk)
|
||||
employee_client.post(f"/customers/{customer.pk}/contacts/{contact.pk}/delete/")
|
||||
assert ContactModel.objects.filter(pk=contact.pk).exists()
|
||||
page = employee_client.get(f"/customers/{customer.pk}/").content.decode()
|
||||
assert "Poista asiakas" not in page
|
||||
|
||||
|
||||
class TestListAndVisibility:
|
||||
def test_my_jobs_by_default_and_search_by_customer_name(
|
||||
self,
|
||||
employee_client: Client,
|
||||
employee: User,
|
||||
customer: CustomerModel,
|
||||
unit: ServiceUnitModel,
|
||||
make_user: Callable[..., User],
|
||||
) -> None:
|
||||
other = make_user()
|
||||
create(employee_client, customer, unit, name="Oma työ", responsible_user=employee.pk)
|
||||
create(employee_client, customer, unit, name="Muiden työ", responsible_user=other.pk)
|
||||
mine = employee_client.get("/jobs/").content.decode()
|
||||
assert "Oma työ" in mine and "Muiden työ" not in mine
|
||||
everything = employee_client.get("/jobs/?scope=all").content.decode()
|
||||
assert "Muiden työ" in everything
|
||||
found = employee_client.get("/jobs/?scope=all&q=asiakas", headers=HX).content.decode()
|
||||
assert "Oma työ" in found and "Muiden työ" in found
|
||||
none = employee_client.get("/jobs/?scope=all&q=xyz", headers=HX).content.decode()
|
||||
assert "Oma työ" not in none
|
||||
|
||||
def test_archived_hidden_unless_asked(
|
||||
self,
|
||||
client: Client,
|
||||
make_user: Callable[..., User],
|
||||
customer: CustomerModel,
|
||||
unit: ServiceUnitModel,
|
||||
) -> None:
|
||||
manager = make_user(role="management")
|
||||
client.force_login(manager)
|
||||
create(client, customer, unit, name="Vanha työ", status="archived")
|
||||
assert "Vanha työ" not in client.get("/jobs/?scope=all").content.decode()
|
||||
assert "Vanha työ" in client.get("/jobs/?scope=all&archived=on").content.decode()
|
||||
assert "Vanha työ" in client.get("/jobs/?scope=all&status=archived").content.decode()
|
||||
|
||||
def test_late_job_shows_text(
|
||||
self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel
|
||||
) -> None:
|
||||
create(employee_client, customer, unit, due_on="2020-01-01")
|
||||
assert "Myöhässä" in employee_client.get("/jobs/?scope=all").content.decode()
|
||||
|
||||
def test_subcontractor_sees_only_member_jobs_read_only(
|
||||
self,
|
||||
employee_client: Client,
|
||||
customer: CustomerModel,
|
||||
unit: ServiceUnitModel,
|
||||
make_user: Callable[..., User],
|
||||
) -> None:
|
||||
sub = make_user(role="subcontractor")
|
||||
create(employee_client, customer, unit, name="Liitetty", members=[sub.pk])
|
||||
create(employee_client, customer, unit, name="Muu")
|
||||
mine, other = CustomerJobModel.objects.order_by("id")
|
||||
c = Client()
|
||||
c.force_login(sub)
|
||||
listing = c.get("/jobs/?scope=all").content.decode()
|
||||
assert "Liitetty" in listing and "Muu" not in listing
|
||||
assert c.get(f"/jobs/{mine.pk}/").status_code == 200
|
||||
assert c.get(f"/jobs/{other.pk}/").status_code == 404
|
||||
assert c.get(f"/jobs/{mine.pk}/edit/").status_code == 403
|
||||
assert c.get("/jobs/new/").status_code == 403
|
||||
assert "Muokkaa" not in c.get(f"/jobs/{mine.pk}/").content.decode()
|
||||
|
||||
def test_customer_page_section(
|
||||
self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel
|
||||
) -> None:
|
||||
create(employee_client, customer, unit, name="Asiakkaan työ")
|
||||
html = employee_client.get(f"/jobs/for-customer/{customer.pk}/", headers=HX)
|
||||
assert html.status_code == 200
|
||||
assert "Asiakkaan työ" in html.content.decode()
|
||||
assert f"/jobs/new/?customer={customer.pk}" in html.content.decode()
|
||||
assert (
|
||||
f"/jobs/for-customer/{customer.pk}/"
|
||||
in employee_client.get(f"/customers/{customer.pk}/").content.decode()
|
||||
)
|
||||
|
||||
|
||||
class TestLinks:
|
||||
def test_add_edit_delete_in_dialog(
|
||||
self, employee_client: Client, customer: CustomerModel, unit: ServiceUnitModel
|
||||
) -> None:
|
||||
create(employee_client, customer, unit)
|
||||
job = CustomerJobModel.objects.get()
|
||||
base = f"/jobs/{job.pk}/links"
|
||||
invalid = employee_client.post(f"{base}/new/", {"url": "javascript:alert(1)"}, headers=HX)
|
||||
assert invalid.status_code == 422
|
||||
response = employee_client.post(
|
||||
f"{base}/new/", {"title": "Aineisto", "url": "https://drive.example.test/a"}, headers=HX
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response["HX-Retarget"] == "#links-section"
|
||||
trigger = json.loads(response["HX-Trigger-After-Settle"])
|
||||
assert trigger["itemSaved"]["message"] == "Linkki tallennettu."
|
||||
assert 'hx-swap-oob="true"' in response.content.decode() # history refreshed too
|
||||
link = JobLinkModel.objects.get()
|
||||
employee_client.post(
|
||||
f"{base}/{link.pk}/edit/", {"title": "Uusi", "url": link.url}, headers=HX
|
||||
)
|
||||
employee_client.post(f"{base}/{link.pk}/delete/", headers=HX)
|
||||
assert not JobLinkModel.objects.exists()
|
||||
assert list(JobChangeModel.objects.order_by("id").values_list("field", flat=True)) == [
|
||||
"links",
|
||||
"links",
|
||||
"links",
|
||||
]
|
||||
|
||||
|
||||
class TestCustomerPicker:
|
||||
def test_search_keeps_selected_first(
|
||||
self, employee_client: Client, customer: CustomerModel
|
||||
) -> None:
|
||||
CustomerModel.objects.create(name="Asiakas Kaksi", type="company")
|
||||
html = employee_client.get(
|
||||
f"/jobs/customer-picker/search/?customer_q=asiakas&customer={customer.pk}", headers=HX
|
||||
).content.decode()
|
||||
assert html.index("Oy Asiakas Ab") < html.index("Asiakas Kaksi")
|
||||
assert f'value="{customer.pk}" checked' in html
|
||||
assert "uudeksi asiakkaaksi" in html
|
||||
|
||||
def test_quick_add_selects_new_customer(self, employee_client: Client) -> None:
|
||||
response = employee_client.post(
|
||||
"/jobs/customer-picker/add/",
|
||||
{"customer_q": "Uusi Kuluttaja", "new_customer_type": "consumer"},
|
||||
headers=HX,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
new = CustomerModel.objects.get(name="Uusi Kuluttaja")
|
||||
assert new.type == "consumer"
|
||||
assert f'value="{new.pk}" checked' in response.content.decode()
|
||||
assert "notify" in response["HX-Trigger-After-Settle"]
|
||||
|
||||
def test_customer_fields_follow_customer(
|
||||
self, employee_client: Client, customer: CustomerModel
|
||||
) -> None:
|
||||
ContactModel.objects.create(customer=customer, name="Maija")
|
||||
html = employee_client.get(
|
||||
f"/jobs/customer-fields/?customer={customer.pk}", headers=HX
|
||||
).content.decode()
|
||||
assert "Maija" in html
|
||||
Reference in New Issue
Block a user