Files
toiminnanohjaus-django/CLAUDE.md
T
petriandClaude Opus 5.5 1ca03137fd 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]>
2026-11-29 14:38:42 +02:00

12 KiB
Raw Blame History

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project

Toiminnanohjaus is an ERP for a small (5–10 people) Finnish media and marketing company. It covers customers, customer jobs, tasks, time tracking, expenses, price lists, billing exports to Fennoa, quick sales and, later, inventory and machines.

  • Stack: Django 5.2 LTS, Python 3.14, MariaDB 10.11 (XAMPP in development), HTMX, Alpine.js, Tailwind CSS 4 and daisyUI 5.
  • Language: code (identifiers, tables, columns, enum keys) is in English. Specs, UI texts, docs and commit messages are in Finnish.

Current state: phase 1 items 1–4 are done.

  • shared and users: custom user model, login, password links, user management.
  • customers: customers, contacts, billing units, the internal customer, and the encrypted personal identity code.
  • catalog: service units, services and work types (base data page /catalog/, permission catalog.manage), seeded by catalog/migrations/0002_seed.py. Rows are never deleted, only taken out of use; CatalogQueries.work_type_options() is the read API for tasks and time tracking.
  • jobs: customer jobs without money fields (/jobs/, permissions jobs.view/jobs.edit/jobs.archive/jobs.invoice_status): yearly numbering VVVV-NNNN (job_number_sequences, locked with select_for_update), tags, links (dialog on the job page), members, change history and the list ("my jobs" by default). Who may set which status is jobs.domain.status_rules. CustomerJobQueries is the read API for later modules. The customer picker (jobs/partials/customer_picker.html, search and quick add by name) is meant for the quick intake too.
  • Cross-module wiring: jobs reads customers, users and catalog through their application query protocols; only apps/jobs/container.py calls the other modules' containers (import-linter enforces it). Names shown in lists come from those queries in batches (CustomerQueries.summaries, UserQueries.choices, CatalogQueries.service_units), never from joins across modules. The customer page's job list is a jobs view loaded with hx-get, so customers does not depend on jobs.

users and customers are the reference implementations; copy their patterns for new modules. The other modules in docs/architecture.md are not built yet. Next in the spec is phase 1 item 5: quick intake (/jobs/quick).

Source of truth

  • docs/maarittely.md is the specification: roles and the permission matrix, data model (section 14), phases (sections 15–19) and open questions. References like (K12) point to question numbers in docs/määrittely.txt, which holds the original Q&A and is kept only as history. When requirements change, update maarittely.md.
  • docs/architecture.md holds the architecture rules, the testing strategy, the UI and accessibility rules, and the Laravel → Django mapping. The spec and architecture were ported from an earlier Laravel/Livewire project, so translate any Laravel idiom you find instead of copying it.

Commands (PowerShell, from the repo root)

.venv\Scripts\python manage.py runserver          # dev server http://127.0.0.1:8000 (start MySQL in XAMPP Control Panel first)
npm run build                                      # vendor htmx/alpine + Tailwind/daisyUI -> static/dist (npm run dev = watch)
.venv\Scripts\python manage.py makemigrations <app> ; .venv\Scripts\python manage.py migrate
.venv\Scripts\python manage.py create_admin "Name" email   # prints a password link (email goes to console in dev)

.venv\Scripts\pytest apps                          # unit + integration tests (MariaDB test DB)
.venv\Scripts\pytest apps/users/tests/domain/test_user_account.py::TestCanLogIn::test_inactive_user_cannot_log_in
.venv\Scripts\pytest apps -m "not django_db"       # fast tests without DB
.venv\Scripts\pytest tests/browser -m browser      # Playwright + axe, light/dark, 1920/320 px; needs npm run build
.venv\Scripts\lint-imports                         # layer contracts in pyproject.toml
.venv\Scripts\mypy apps
.venv\Scripts\ruff check . ; .venv\Scripts\ruff format .

Translations: source strings are English; Finnish is in locale/fi/LC_MESSAGES/django.po. GNU gettext lives in %LOCALAPPDATA%\Programs\gettext-iconv\bin (prepend it to PATH if makemessages cannot find it). Run makemessages -l fi --ignore=.venv --ignore=node_modules --ignore=static, fill every new msgstr, then compilemessages -l fi --ignore=.venv. Tests assert Finnish texts, so stale .mo files make them fail.

Configuration

  • config/settings.py reads .env via python-dotenv. Variables: DJANGO_SECRET_KEY (required), DJANGO_DEBUG, DJANGO_ALLOWED_HOSTS, DB_NAME (default django-toiminnanohjaus), DB_USER, DB_PASSWORD, DB_HOST, DB_PORT. .env is gitignored; .env.example is the template.
  • The database engine is django.db.backends.mysql (mysqlclient), with utf8mb4 and STRICT_TRANS_TABLES. The database name contains a hyphen, so backtick-quote it in raw SQL.
  • Settings use LANGUAGE_CODE = "fi" and TIME_ZONE = "Europe/Helsinki". Templates go in templates/ plus app templates, static files in static/, and STATIC_ROOT is staticfiles/.
  • AUTH_USER_MODEL = "users.User" (apps/users/infrastructure/orm.py): email login, a role field, no PermissionsMixin and no Django admin. Permissions are role-based: apps/users/domain/permissions.py (role_has), PermissionRequiredMixin, and the template filter {% if request.user|can:"users.manage" %} ({% load users_tags %}).
  • LoginRequiredMiddleware is on, so mark public views with login_not_required. EnsureAccountIsUsable logs out deactivated users and interns past their end date on every request.
  • The cache is DatabaseCache (login throttling), so run createcachetable on new databases.
  • Personal identity code (henkilötunnus):
    • It is encrypted with Fernet (FIELD_ENCRYPTION_KEYS, comma-separated; the first key encrypts and all keys decrypt) and has an HMAC fingerprint (PERSONAL_ID_HASH_KEY) for duplicate checks. A system check fails if either key is missing.
    • Never change these keys in .env without rotating them; otherwise stored codes cannot be decrypted.
    • Only customers.infrastructure.vault touches plain codes. The domain PersonalIdentityCode hides the code in repr, and display uses masked.
  • Templates and tags:
    • Each module's templates live in apps/<module>/presentation/templates and are added to TEMPLATES['DIRS'] by a glob in settings.
    • Template tag libraries live in presentation/templatetags and must be registered in TEMPLATES['OPTIONS']['libraries'].
    • Shared layouts and components are in the project templates/ folder (base.html, layouts/auth.html, components/).
  • Forms: FORM_RENDERER (apps/shared/presentation/forms.py) renders every field with components/field.html. Forms should mix in DaisyFormMixin, which adds the daisyUI classes and aria-describedby/aria-invalid on errors and provides add_domain_error(error, ERROR_MESSAGES).

Architecture (see docs/architecture.md)

The project is a modular monolith. Each business area is a Django app under apps/<module>/ (planned: shared, users, customers, jobs, tasks, time_tracking, expenses, catalog, sales, billing, later inventory, machines). Each app has Clean Architecture layers:

  • domain/ holds pure Python with no django imports: dataclass entities (register() / reconstitute()), frozen value objects that validate themselves, StrEnum enums, DomainError subclasses carrying a code, events, and repository Protocols.
  • application/ holds use cases (one class, one execute(), with dependencies injected through the constructor), frozen dataclass DTOs and query Protocols. Query protocols are the module's public read API. This layer has no django imports.
  • infrastructure/ holds the Django models (named …Model, in orm.py and re-exported from the app's models.py; set Meta.db_table to the table names in spec section 14), the repository implementations and the query implementations, which return DTOs straight from the ORM.
  • presentation/ holds thin views, Django Forms and templates. Forms validate input shape and build DTOs. Domain errors are turned into field errors with form.add_error(). HTMX requests get partial templates.
  • container.py is the composition root, with factory functions that wire the use cases. There is no DI framework. Presentation reaches infrastructure only through the container (import-linter enforces this; add every new module to the contracts in pyproject.toml).
  • Tests live in apps/<module>/tests/{domain,application,integration}. Application tests use in-memory fakes (apps/<module>/tests/fakes.py; FakeUnitOfWork is in apps/shared/tests/fakes.py) and need no DB. The shared pytest fixtures (make_user, admin, admin_client) are in apps/conftest.py, and the browser test helpers (themed_page, ALL, assert_accessible, login) are in tests/browser/conftest.py.
  • Deletion guards are generic. apps/customers/infrastructure/references.py (is_referenced) checks every reverse relation. When a new module adds a ForeignKey(..., on_delete=PROTECT) to customers, contacts or billing units, the delete buttons and use cases block deletion automatically, so don't add cross-module checks. Copy the pattern for other modules' entities.

Cross-cutting rules:

  • Cross-module access: modules never touch another module's ORM models, infrastructure or presentation. They read through the other module's application query interface and react to its domain events. Foreign keys to another module's table are allowed, but queries across that relation are not.
  • Shared role enum: users.domain.enums.Role is the one shared domain type that every module may use.
  • Transactions: the use case is the transaction boundary (UnitOfWork wraps transaction.atomic; ATOMIC_REQUESTS is not used). Events are published with transaction.on_commit and subscribed in AppConfig.ready(). Django signals are not used for domain events.
  • Background work: django-q2 runs background jobs. Scheduled jobs are management commands.
  • Data conventions: money is stored as integer cents (*_cents), VAT as basis points, hours as Decimal(6,2). Quantities in the inventory phase are stored as integer thousandths (*_milli).

UI and accessibility

WCAG 2.2 AA / EN 301 549 is the contract's acceptance criterion for the whole UI.

  • Colour: colour never carries information alone. Priority, status and "late" are always also shown as text and an icon.
  • Interaction and focus: everything must work from the keyboard, and drag and drop always has a button alternative.
    • After an HTMX swap, move focus deliberately and announce the change in an aria-live / role="status" region.
    • Dialogs use <dialog> (the daisyUI modal).
  • Layout: no horizontal page scrolling from 320 px up to FullHD. The machine console needs touch targets of at least 44 × 44 px.
  • Implementation: use daisyUI classes and the shared partials in templates/components/. Alpine.js is for local UI state only, never for business logic.
  • Colours: daisyUI's default text colours fail WCAG contrast in places. static/src/app.css overrides soft alerts and badges, .menu-title, and the light theme's error and success colours. Use link rather than link-primary for text links. The browser tests (axe) catch regressions.
  • Dialog forms (customers module pattern):
    • The form is loaded with hx-get into the shared <dialog>.
    • When the form is invalid, the server returns the form with status 422. static/src/app.js makes HTMX swap 422 responses and focuses the first aria-invalid field.
    • When the form is valid, the server re-renders the section with HX-Retarget/HX-Reswap. It sets HX-Trigger-After-Settle: {"itemSaved": {"message", "focus"}} (the handler in app.js closes the dialog, moves focus and announces the message) and adds any changed header actions as an out-of-band swap.
  • Assets: no CDN in production; build the assets with npm.
  • Texts: all UI text goes through gettext / {% translate %}.