resource-engine-devtools 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. resource_engine_devtools/__init__.py +6 -0
  2. resource_engine_devtools/ai/__init__.py +1 -0
  3. resource_engine_devtools/ai/example.py +66 -0
  4. resource_engine_devtools/ai/installer.py +424 -0
  5. resource_engine_devtools/ai/skill/SKILL.md +130 -0
  6. resource_engine_devtools/ai/skill/examples/README.md +7 -0
  7. resource_engine_devtools/ai/skill/examples/invoices/__init__.py +0 -0
  8. resource_engine_devtools/ai/skill/examples/invoices/app.py +245 -0
  9. resource_engine_devtools/ai/skill/examples/invoices/application/__init__.py +0 -0
  10. resource_engine_devtools/ai/skill/examples/invoices/application/actions.py +61 -0
  11. resource_engine_devtools/ai/skill/examples/invoices/application/balances.py +51 -0
  12. resource_engine_devtools/ai/skill/examples/invoices/application/customers.py +35 -0
  13. resource_engine_devtools/ai/skill/examples/invoices/application/hooks.py +61 -0
  14. resource_engine_devtools/ai/skill/examples/invoices/application/processes.py +80 -0
  15. resource_engine_devtools/ai/skill/examples/invoices/application/resource.py +112 -0
  16. resource_engine_devtools/ai/skill/examples/invoices/application/schemas.py +164 -0
  17. resource_engine_devtools/ai/skill/examples/invoices/application/tags.py +77 -0
  18. resource_engine_devtools/ai/skill/examples/invoices/authz.py +126 -0
  19. resource_engine_devtools/ai/skill/examples/invoices/bootstrap.py +80 -0
  20. resource_engine_devtools/ai/skill/examples/invoices/domain/__init__.py +0 -0
  21. resource_engine_devtools/ai/skill/examples/invoices/domain/entities.py +112 -0
  22. resource_engine_devtools/ai/skill/examples/invoices/domain/events.py +22 -0
  23. resource_engine_devtools/ai/skill/examples/invoices/domain/state_machine.py +88 -0
  24. resource_engine_devtools/ai/skill/examples/invoices/infrastructure/__init__.py +0 -0
  25. resource_engine_devtools/ai/skill/examples/invoices/infrastructure/persistence.py +121 -0
  26. resource_engine_devtools/ai/skill/examples/invoices/locale/en/LC_MESSAGES/messages.po +682 -0
  27. resource_engine_devtools/ai/skill/examples/invoices/locale/es/LC_MESSAGES/messages.po +685 -0
  28. resource_engine_devtools/ai/skill/examples/invoices/notifications.py +47 -0
  29. resource_engine_devtools/ai/skill/examples/invoices/templates/email/base.html +7 -0
  30. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.html +5 -0
  31. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.subject.txt +1 -0
  32. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.txt +5 -0
  33. resource_engine_devtools/ai/skill/examples/invoices/tests/conftest.py +40 -0
  34. resource_engine_devtools/ai/skill/examples/invoices/tests/test_invoices_engine.py +241 -0
  35. resource_engine_devtools/ai/skill/examples/invoices/worker.py +53 -0
  36. resource_engine_devtools/ai/skill/llms.txt +25 -0
  37. resource_engine_devtools/ai/skill/references/anti-patterns.md +209 -0
  38. resource_engine_devtools/ai/skill/references/docstrings.md +97 -0
  39. resource_engine_devtools/ai/skill/references/errors.md +81 -0
  40. resource_engine_devtools/ai/skill/references/lifecycle.md +118 -0
  41. resource_engine_devtools/ai/skill/references/permissions.md +111 -0
  42. resource_engine_devtools/ai/skill/references/resource.md +301 -0
  43. resource_engine_devtools/ai/skill/references/state-machines.md +126 -0
  44. resource_engine_devtools/ai/skill/references/testing.md +80 -0
  45. resource_engine_devtools/ai/templates/agents_block.md +26 -0
  46. resource_engine_devtools/ai/templates/cursor_rule.mdc +7 -0
  47. resource_engine_devtools/check.py +67 -0
  48. resource_engine_devtools/cli.py +1112 -0
  49. resource_engine_devtools/consumer_scaffold.py +715 -0
  50. resource_engine_devtools/contracts.py +471 -0
  51. resource_engine_devtools/db.py +132 -0
  52. resource_engine_devtools/declarations_check.py +116 -0
  53. resource_engine_devtools/documentation/__init__.py +10 -0
  54. resource_engine_devtools/documentation/docstrings.py +72 -0
  55. resource_engine_devtools/documentation/generators/__init__.py +9 -0
  56. resource_engine_devtools/documentation/generators/ai_context.py +121 -0
  57. resource_engine_devtools/documentation/generators/api.py +63 -0
  58. resource_engine_devtools/documentation/generators/json.py +12 -0
  59. resource_engine_devtools/documentation/generators/markdown.py +687 -0
  60. resource_engine_devtools/documentation/generators/mermaid.py +22 -0
  61. resource_engine_devtools/documentation/generators/site.py +379 -0
  62. resource_engine_devtools/documentation/generators/site_assets/site.css +62 -0
  63. resource_engine_devtools/documentation/generators/site_assets/site.js +54 -0
  64. resource_engine_devtools/documentation/i18n.py +185 -0
  65. resource_engine_devtools/documentation/introspector.py +563 -0
  66. resource_engine_devtools/documentation/locale/ca/LC_MESSAGES/docs.po +628 -0
  67. resource_engine_devtools/documentation/locale/es/LC_MESSAGES/docs.po +627 -0
  68. resource_engine_devtools/documentation/model.py +311 -0
  69. resource_engine_devtools/documentation/validator.py +128 -0
  70. resource_engine_devtools/emails.py +172 -0
  71. resource_engine_devtools/events_check.py +124 -0
  72. resource_engine_devtools/gates_check.py +133 -0
  73. resource_engine_devtools/hooks_check.py +287 -0
  74. resource_engine_devtools/i18n.py +312 -0
  75. resource_engine_devtools/loader.py +93 -0
  76. resource_engine_devtools/logic_check.py +136 -0
  77. resource_engine_devtools/mcp_server.py +685 -0
  78. resource_engine_devtools/py.typed +0 -0
  79. resource_engine_devtools/scaffold.py +805 -0
  80. resource_engine_devtools/scaffold_parts.py +637 -0
  81. resource_engine_devtools/source_edit.py +424 -0
  82. resource_engine_devtools/templates_check.py +59 -0
  83. resource_engine_devtools/worker.py +68 -0
  84. resource_engine_devtools-0.1.0.dist-info/METADATA +38 -0
  85. resource_engine_devtools-0.1.0.dist-info/RECORD +88 -0
  86. resource_engine_devtools-0.1.0.dist-info/WHEEL +4 -0
  87. resource_engine_devtools-0.1.0.dist-info/entry_points.txt +2 -0
  88. resource_engine_devtools-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,164 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import date, datetime
4
+ from decimal import Decimal
5
+
6
+ from pydantic import BaseModel, ConfigDict, Field
7
+
8
+ #: Tenant of every record of the module when tenancy is on (bootstrap.build_registry).
9
+ ORGANIZATION = "Organització propietària (tenant); la posa el motor a partir del token"
10
+
11
+
12
+ class CustomerCreate(BaseModel):
13
+ """Dades per donar d'alta un client."""
14
+
15
+ name: str = Field(min_length=1, description="Raó social")
16
+ tax_id: str = Field(min_length=3, max_length=20, description="NIF")
17
+ country: str = Field(default="ES", min_length=2, max_length=2, description="País (ISO 3166)")
18
+ email: str | None = Field(default=None, description="Adreça de facturació")
19
+
20
+
21
+ class CustomerUpdate(BaseModel):
22
+ """Camps modificables d'un client."""
23
+
24
+ name: str | None = Field(default=None, min_length=1)
25
+ country: str | None = Field(default=None, min_length=2, max_length=2)
26
+ email: str | None = None
27
+
28
+
29
+ class CustomerRead(BaseModel):
30
+ """Representació pública d'un client."""
31
+
32
+ model_config = ConfigDict(from_attributes=True)
33
+
34
+ id: int
35
+ organization: str | None = Field(default=None, description=ORGANIZATION)
36
+ name: str
37
+ tax_id: str
38
+ country: str
39
+ email: str | None
40
+
41
+
42
+ class TagCreate(BaseModel):
43
+ """Dades d'una etiqueta nova."""
44
+
45
+ name: str = Field(min_length=1, max_length=50, description="Nom visible")
46
+ color: str = Field(default="grey", max_length=20, description="Color a la interfície")
47
+
48
+
49
+ class TagRead(TagCreate):
50
+ """Representació pública d'una etiqueta."""
51
+
52
+ model_config = ConfigDict(from_attributes=True)
53
+
54
+ id: int
55
+ organization: str | None = Field(default=None, description=ORGANIZATION)
56
+
57
+
58
+ class InvoiceTagCreate(BaseModel):
59
+ """Etiqueta assignada a una factura."""
60
+
61
+ invoice_id: int = Field(description="Factura")
62
+ tag_id: int = Field(description="Etiqueta")
63
+
64
+
65
+ class InvoiceTagRead(InvoiceTagCreate):
66
+ """Assignació d'una etiqueta a una factura."""
67
+
68
+ model_config = ConfigDict(from_attributes=True)
69
+
70
+ id: int
71
+ organization: str | None = Field(default=None, description=ORGANIZATION)
72
+
73
+
74
+ class PaymentStart(BaseModel):
75
+ """Dades amb què comença el procés de cobrament."""
76
+
77
+ invoice_id: int = Field(description="Factura aprovada")
78
+ amount: Decimal = Field(description="Import a cobrar")
79
+
80
+
81
+ class PaymentRead(PaymentStart):
82
+ """Estat del cobrament d'una factura."""
83
+
84
+ model_config = ConfigDict(from_attributes=True)
85
+
86
+ id: int
87
+ status: str = Field(description="awaiting, overdue o settled")
88
+ status_changed_at: datetime | None = Field(default=None, description="Últim canvi d'estat")
89
+ organization: str | None = Field(default=None, description=ORGANIZATION)
90
+
91
+
92
+ class PaymentReceived(BaseModel):
93
+ """Esdeveniment del servei de pagaments: s'ha cobrat una factura."""
94
+
95
+ invoice_id: int
96
+ amount: Decimal
97
+
98
+
99
+ CUSTOMER_ID = "Client registrat (customers); el nom de `customer` es manté per compatibilitat"
100
+
101
+
102
+ class InvoiceCreate(BaseModel):
103
+ """Dades per crear una factura."""
104
+
105
+ customer: str = Field(min_length=1, description="Nom del client")
106
+ amount: Decimal = Field(description="Import total")
107
+ issue_date: date | None = Field(default=None, description="Data d'emissió")
108
+ customer_id: int | None = Field(default=None, description=CUSTOMER_ID)
109
+ notes: str | None = None
110
+
111
+
112
+ class InvoiceUpdate(BaseModel):
113
+ """Camps modificables d'una factura en esborrany."""
114
+
115
+ customer: str | None = Field(default=None, min_length=1)
116
+ amount: Decimal | None = None
117
+ issue_date: date | None = None
118
+ customer_id: int | None = None
119
+ notes: str | None = None
120
+
121
+
122
+ class InvoiceRead(BaseModel):
123
+ """Representació pública d'una factura."""
124
+
125
+ model_config = ConfigDict(from_attributes=True)
126
+
127
+ id: int
128
+ customer: str
129
+ amount: Decimal
130
+ issue_date: date | None
131
+ customer_id: int | None = Field(default=None, description=CUSTOMER_ID)
132
+ notes: str | None
133
+ status: str
134
+ rejection_reason: str | None
135
+ status_changed_at: datetime | None = Field(
136
+ default=None, description="Quan va entrar a l'estat actual (el posa el motor)"
137
+ )
138
+ delivery_status: str = Field(
139
+ default="unsent", description="Estat de l'enviament al client (màquina delivery)"
140
+ )
141
+ version: int = Field(description="Versió del registre (ETag); envia-la a If-Match")
142
+ organization: str | None = Field(default=None, description=ORGANIZATION)
143
+
144
+
145
+ class RejectInvoice(BaseModel):
146
+ reason: str = Field(min_length=3, description="Motiu del rebuig")
147
+
148
+
149
+ class ApplyDiscount(BaseModel):
150
+ percent: Decimal = Field(gt=0, le=100)
151
+
152
+
153
+ class CustomerBalanceRead(BaseModel):
154
+ """Saldo d'un client: les seves factures sumades per estat."""
155
+
156
+ model_config = ConfigDict(from_attributes=True)
157
+
158
+ customer_id: int = Field(description="Client (customers)")
159
+ organization: str | None = Field(default=None, description=ORGANIZATION)
160
+ invoices: int = Field(description="Nombre de factures")
161
+ total: Decimal = Field(description="Import total de les factures")
162
+ outstanding: Decimal = Field(description="Import pendent d'aprovar o de cobrar")
163
+ paid: Decimal = Field(description="Import cobrat")
164
+ last_issue_date: date | None = Field(description="Data d'emissió més recent")
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+
3
+ from resource_engine import CRUD, Listing, ListQuery, OperationContext, Reference, Resource, hook
4
+ from resource_engine.domain import DomainError
5
+
6
+ from invoices.application.schemas import InvoiceTagCreate, InvoiceTagRead, TagCreate, TagRead
7
+ from invoices.domain.entities import InvoiceTag, Tag
8
+
9
+
10
+ class TagResource(Resource):
11
+ """Etiquetes per classificar factures.
12
+
13
+ Business area:
14
+ Facturació
15
+
16
+ Actors:
17
+ - Emissor de factures
18
+ """
19
+
20
+ model = Tag
21
+ schemas = {"create": TagCreate, "update": TagCreate, "read": TagRead}
22
+ operations = CRUD
23
+ operation_docs = {
24
+ "list": "Llista les etiquetes.",
25
+ "get": "Consulta una etiqueta.",
26
+ "create": "Crea una etiqueta.",
27
+ "update": "Canvia el nom o el color d'una etiqueta.",
28
+ "delete": "Elimina una etiqueta i les seves assignacions.",
29
+ }
30
+ listing = Listing(filterable=["name"], sortable=["name"])
31
+
32
+
33
+ @hook.before("create")
34
+ async def ensure_not_tagged(ctx: OperationContext) -> None:
35
+ """Refusa assignar a una factura una etiqueta que ja té.
36
+
37
+ Exceptions:
38
+ DomainError: la factura ja té l'etiqueta.
39
+ """
40
+ entity = ctx.entity
41
+ page = await ctx.repository().list(
42
+ ListQuery(filters={"invoice_id": entity.invoice_id, "tag_id": entity.tag_id}, limit=1)
43
+ )
44
+ if page.total:
45
+ raise DomainError("The invoice already has this tag", code="INVOICE_TAG")
46
+
47
+
48
+ class InvoiceTagResource(Resource):
49
+ """Etiquetes assignades a factures (molts a molts).
50
+
51
+ Les factures tenen la relació ``tags`` i les etiquetes la relació
52
+ ``invoices``; assignar i treure etiquetes és crear i eliminar aquests
53
+ registres.
54
+
55
+ Business area:
56
+ Facturació
57
+
58
+ Actors:
59
+ - Emissor de factures
60
+ """
61
+
62
+ model = InvoiceTag
63
+ schemas = {"create": InvoiceTagCreate, "read": InvoiceTagRead}
64
+ operations = ["list", "get", "create", "delete"]
65
+ operation_docs = {
66
+ "list": "Llista les assignacions d'etiquetes.",
67
+ "get": "Consulta una assignació.",
68
+ "create": "Assigna una etiqueta a una factura.",
69
+ "delete": "Treu una etiqueta d'una factura.",
70
+ }
71
+ references = {
72
+ "invoice_id": Reference("invoices", on_delete="cascade", reverse=False),
73
+ "tag_id": Reference("tags", on_delete="cascade", reverse=False),
74
+ }
75
+ link = ("invoice_id", "tag_id") # invoices get `tags`, tags get `invoices`
76
+ hooks = [ensure_not_tagged]
77
+ listing = Listing(filterable=["invoice_id", "tag_id"])
@@ -0,0 +1,126 @@
1
+ """Example policies, as a front end would create them (data, not code)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ APPROVER_POLICIES: list[dict[str, Any]] = [
8
+ {
9
+ "name": "Approvers see pending invoices",
10
+ "effect": "allow",
11
+ "subjects": {"roles": ["approver"]},
12
+ "actions": ["invoices:list", "invoices:get", "invoices:download:*"],
13
+ "condition": {"in": [{"attr": "resource.status"}, ["pending", "approved"]]},
14
+ },
15
+ {
16
+ "name": "Approvers decide invoices under 10,000",
17
+ "effect": "allow",
18
+ "subjects": {"roles": ["approver"]},
19
+ "actions": ["invoices:transition:approve", "invoices:transition:reject"],
20
+ "condition": {"lt": [{"attr": "resource.amount"}, 10000]},
21
+ },
22
+ {
23
+ "name": "Approvers see customers",
24
+ "effect": "allow",
25
+ "subjects": {"roles": ["approver"]},
26
+ "actions": ["customers:list", "customers:get"],
27
+ },
28
+ {
29
+ "name": "Approvers see tags",
30
+ "effect": "allow",
31
+ "subjects": {"roles": ["approver"]},
32
+ "actions": [
33
+ "tags:list",
34
+ "tags:get",
35
+ "invoice_tags:list",
36
+ "invoice_tags:get",
37
+ "invoice_payments:list",
38
+ "invoice_payments:get",
39
+ ],
40
+ },
41
+ {
42
+ "name": "Approvers read internal notes",
43
+ "effect": "allow",
44
+ "subjects": {"roles": ["approver"]},
45
+ "actions": ["invoices:read:notes"],
46
+ },
47
+ {
48
+ "name": "Amounts are frozen once submitted",
49
+ "effect": "deny",
50
+ "subjects": {"everyone": True},
51
+ "actions": ["invoices:write:amount"],
52
+ "condition": {"ne": [{"attr": "resource.status"}, "draft"]},
53
+ },
54
+ ]
55
+
56
+
57
+ ISSUER_POLICIES: list[dict[str, Any]] = [
58
+ {
59
+ "name": "Issuers manage invoices",
60
+ "effect": "allow",
61
+ "subjects": {"roles": ["issuer"]},
62
+ "actions": [
63
+ "invoices:list",
64
+ "invoices:get",
65
+ "invoices:create",
66
+ "invoices:update",
67
+ "invoices:delete",
68
+ "invoices:transition:submit",
69
+ "invoices:transition:reopen",
70
+ "invoices:transition:pay",
71
+ "invoices:transition:send",
72
+ "invoices:transition:bounce",
73
+ "invoices:transition:resend",
74
+ "invoices:action:*",
75
+ "invoices:attach:*",
76
+ "invoices:detach:*",
77
+ "invoices:download:*",
78
+ ],
79
+ },
80
+ {
81
+ "name": "Issuers manage tags",
82
+ "effect": "allow",
83
+ "subjects": {"roles": ["issuer"]},
84
+ "actions": ["tags:*", "invoice_tags:*", "invoice_payments:list", "invoice_payments:get"],
85
+ },
86
+ {
87
+ "name": "Issuers manage customers",
88
+ "effect": "allow",
89
+ "subjects": {"roles": ["issuer"]},
90
+ "actions": [
91
+ "customers:list",
92
+ "customers:get",
93
+ "customers:create",
94
+ "customers:update",
95
+ "customers:delete",
96
+ "customer_balances:list",
97
+ "customer_balances:get",
98
+ ],
99
+ },
100
+ ]
101
+
102
+ #: Every policy the example creates; ``resource-engine check`` reads it
103
+ #: (``[tool.resource-engine] policies``) to find operations nobody can perform.
104
+ SEED_POLICIES = APPROVER_POLICIES + ISSUER_POLICIES
105
+ SEED_ROLES = ["approver", "issuer"]
106
+
107
+
108
+ async def seed(manager: Any, admin: Any) -> None:
109
+ """Create the custom roles and their policies (idempotent by name)."""
110
+ for role in SEED_ROLES:
111
+ if not await _role_exists(manager, admin, role):
112
+ await manager.create("authz_roles", {"name": role}, actor=admin)
113
+ existing = {p.name for p in (await manager.list("authz_policies", actor=admin)).items}
114
+ for policy in SEED_POLICIES:
115
+ if policy["name"] not in existing:
116
+ await manager.create("authz_policies", policy, actor=admin)
117
+
118
+
119
+ async def _role_exists(manager: Any, admin: Any, role: str) -> bool:
120
+ from resource_engine.errors import EntityNotFound
121
+
122
+ try:
123
+ await manager.get("authz_roles", role, actor=admin)
124
+ except EntityNotFound:
125
+ return False
126
+ return True
@@ -0,0 +1,80 @@
1
+ """Composition root of the example application."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+
7
+ from resource_engine import Resource, ResourceRegistry
8
+ from resource_engine.authz import AuthzConfig, IdpRoleSource, SystemRole
9
+ from resource_engine.explorer import register_explorer
10
+
11
+ from invoices.application.balances import CustomerBalanceResource
12
+ from invoices.application.customers import CustomerResource
13
+ from invoices.application.processes import InvoicePaymentProcess
14
+ from invoices.application.resource import InvoiceResource
15
+ from invoices.application.tags import InvoiceTagResource, TagResource
16
+
17
+ #: Records of these resources belong to an organization when tenancy is on.
18
+ TENANT_FIELD = "organization"
19
+ MODULE = (
20
+ CustomerResource,
21
+ InvoiceResource,
22
+ TagResource,
23
+ InvoiceTagResource,
24
+ InvoicePaymentProcess,
25
+ CustomerBalanceResource,
26
+ )
27
+
28
+
29
+ def build_registry(*, tenant_scoped: bool = False) -> ResourceRegistry:
30
+ """The module's resources and the engine's (documents, permissions, audit).
31
+
32
+ With ``tenant_scoped`` every module resource is confined to the caller's
33
+ organization (``Access(tenant_field="organization")``, from the Keycloak token):
34
+ the application (``invoices.app``) runs that way. Without it the same
35
+ resources ignore tenants, which keeps engine tests short.
36
+ """
37
+ registry = ResourceRegistry()
38
+ for resource in MODULE:
39
+ registry.register(_tenant_scoped(resource) if tenant_scoped else resource)
40
+ registry.register_documents()
41
+ registry.register_authz()
42
+ registry.register_api_keys() # keys for machine clients (Bearer rek_...)
43
+ registry.register_audit()
44
+ # the explorer's permissions (events:read, jobs:read, jobs:run...): the admin
45
+ # role holds them; publishing events by hand is granted to no one
46
+ register_explorer(registry)
47
+ return registry
48
+
49
+
50
+ def _tenant_scoped(resource: type[Resource]) -> type[Resource]:
51
+ return type(
52
+ resource.__name__,
53
+ (resource,),
54
+ {
55
+ "__doc__": resource.__doc__,
56
+ "__module__": resource.__module__,
57
+ "name": resource.definition().name,
58
+ "access": replace(resource.access, tenant_field=TENANT_FIELD),
59
+ },
60
+ )
61
+
62
+
63
+ registry = build_registry()
64
+ #: What the application serves: every module record belongs to an organization.
65
+ tenant_registry = build_registry(tenant_scoped=True)
66
+
67
+ # Permissions: system roles are fixed here; everything else is policies created
68
+ # from the front end (see invoices.authz for the seed used by tests and demos).
69
+ authz = AuthzConfig(
70
+ system_roles=[SystemRole.admin(), SystemRole.viewer()],
71
+ role_source=IdpRoleSource(
72
+ {
73
+ "invoices-admin": "admin",
74
+ "accountant": "viewer",
75
+ "approver": "approver",
76
+ "issuer": "issuer",
77
+ }
78
+ ),
79
+ bootstrap={"platform-admin": "admin"},
80
+ )
@@ -0,0 +1,112 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from datetime import date, datetime
5
+ from decimal import Decimal
6
+
7
+ from resource_engine.domain import DomainError
8
+
9
+
10
+ class InvoiceError(DomainError):
11
+ code = "INVOICE"
12
+
13
+
14
+ @dataclass
15
+ class Customer:
16
+ """Client de l'organització al qual s'emeten factures.
17
+
18
+ Business Rules:
19
+ - El NIF identifica el client; no es pot repetir.
20
+ - No es pot eliminar un client que encara té factures.
21
+ """
22
+
23
+ name: str
24
+ tax_id: str
25
+ country: str = "ES"
26
+ email: str | None = None
27
+ organization: str | None = None
28
+ id: int | None = field(default=None)
29
+
30
+
31
+ @dataclass
32
+ class Tag:
33
+ """Etiqueta per classificar factures (urgent, revisar, client nou...)."""
34
+
35
+ name: str
36
+ color: str = "grey"
37
+ organization: str | None = None
38
+ id: int | None = field(default=None)
39
+
40
+
41
+ @dataclass
42
+ class InvoiceTag:
43
+ """Assignació d'una etiqueta a una factura.
44
+
45
+ Business Rules:
46
+ - Una factura no pot tenir la mateixa etiqueta dues vegades.
47
+ """
48
+
49
+ invoice_id: int
50
+ tag_id: int
51
+ organization: str | None = None
52
+ id: int | None = field(default=None)
53
+
54
+
55
+ @dataclass
56
+ class InvoicePayment:
57
+ """Procés de cobrament d'una factura aprovada (una instància per factura).
58
+
59
+ Business Rules:
60
+ - Comença quan s'aprova la factura i acaba quan se'n rep el cobrament.
61
+ """
62
+
63
+ invoice_id: int
64
+ amount: Decimal
65
+ status: str | None = None
66
+ status_changed_at: datetime | None = None
67
+ organization: str | None = None
68
+ id: int | None = field(default=None)
69
+
70
+
71
+ @dataclass
72
+ class Invoice:
73
+ """Factura emesa a un client.
74
+
75
+ Business Rules:
76
+ - L'import total no pot ser negatiu.
77
+ - Una factura només es pot modificar mentre és un esborrany.
78
+ """
79
+
80
+ customer: str
81
+ amount: Decimal
82
+ issue_date: date | None = None
83
+ customer_id: int | None = None
84
+ notes: str | None = None
85
+ status: str | None = None
86
+ rejection_reason: str | None = None
87
+ status_changed_at: datetime | None = None
88
+ delivery_status: str | None = None
89
+ version: int | None = None
90
+ organization: str | None = None
91
+ id: int | None = field(default=None)
92
+
93
+ def ensure_editable(self) -> None:
94
+ if self.status not in (None, "draft"):
95
+ raise InvoiceError(f"Invoice {self.id} is {self.status} and can no longer be modified")
96
+
97
+ def ensure_valid_amount(self) -> None:
98
+ if self.amount < 0:
99
+ raise InvoiceError("Invoice amount cannot be negative")
100
+
101
+
102
+ @dataclass
103
+ class CustomerBalance:
104
+ """Saldo de facturació d'un client, calculat a partir de les seves factures."""
105
+
106
+ customer_id: int
107
+ invoices: int = 0
108
+ total: Decimal = Decimal(0)
109
+ outstanding: Decimal = Decimal(0)
110
+ paid: Decimal = Decimal(0)
111
+ last_issue_date: date | None = None
112
+ organization: str | None = None
@@ -0,0 +1,22 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from decimal import Decimal
5
+
6
+ from resource_engine.domain import DomainEvent
7
+
8
+
9
+ @dataclass(frozen=True, kw_only=True)
10
+ class InvoiceTotalsRecalculated(DomainEvent):
11
+ """L'import d'una factura s'ha recalculat aplicant un descompte."""
12
+
13
+ invoice_id: int
14
+ previous_amount: Decimal
15
+ new_amount: Decimal
16
+
17
+
18
+ @dataclass(frozen=True, kw_only=True)
19
+ class PaymentOverdue(DomainEvent):
20
+ """Una factura aprovada fa 15 dies que espera el cobrament."""
21
+
22
+ invoice_id: int
@@ -0,0 +1,88 @@
1
+ from __future__ import annotations
2
+
3
+ from statemachine import State, StateMachine
4
+
5
+
6
+ class InvoiceStateMachine(StateMachine):
7
+ """Procés d'aprovació i cobrament d'una factura.
8
+
9
+ States:
10
+ draft: Esborrany editable per l'emissor.
11
+ pending: Enviada a aprovació; ja no es pot modificar.
12
+ approved: Aprovada i pendent de cobrament.
13
+ rejected: Rebutjada pel responsable.
14
+ paid: Cobrada. Estat final.
15
+
16
+ Transitions:
17
+ submit: Envia l'esborrany a aprovació.
18
+ approve: Aprova una factura pendent.
19
+ reject: Rebutja una factura pendent indicant-ne el motiu.
20
+ reopen: Torna una factura rebutjada a esborrany.
21
+ pay: Registra el cobrament d'una factura aprovada.
22
+ """
23
+
24
+ draft = State("Esborrany", initial=True)
25
+ pending = State("Pendent")
26
+ approved = State("Aprovada")
27
+ rejected = State("Rebutjada")
28
+ paid = State("Cobrada", final=True)
29
+
30
+ submit = draft.to(pending)
31
+ approve = pending.to(approved)
32
+ reject = pending.to(rejected)
33
+ reopen = rejected.to(draft)
34
+ pay = approved.to(paid)
35
+
36
+ def on_reject(self, reason: str) -> None:
37
+ self.model.rejection_reason = reason
38
+
39
+ def on_reopen(self) -> None:
40
+ self.model.rejection_reason = None
41
+
42
+
43
+ class InvoiceDelivery(StateMachine):
44
+ """Enviament d'una factura al client, independent de la seva aprovació.
45
+
46
+ States:
47
+ unsent: Encara no s'ha enviat al client.
48
+ sent: Enviada al client.
49
+ returned: El correu ha rebotat; cal tornar-la a enviar.
50
+
51
+ Transitions:
52
+ send: Envia al client una factura aprovada o cobrada.
53
+ bounce: El correu d'enviament ha rebotat.
54
+ resend: Torna a enviar una factura retornada.
55
+ """
56
+
57
+ unsent = State("No enviada", initial=True)
58
+ sent = State("Enviada")
59
+ returned = State("Retornada")
60
+
61
+ send = unsent.to(sent, cond="invoice_approved")
62
+ bounce = sent.to(returned)
63
+ resend = returned.to(sent)
64
+
65
+ def invoice_approved(self) -> bool:
66
+ # a guard can read the other machine's state: only approved invoices go out
67
+ return self.model.status in ("approved", "paid")
68
+
69
+
70
+ class PaymentFlow(StateMachine):
71
+ """Cobrament d'una factura aprovada.
72
+
73
+ States:
74
+ awaiting: S'espera el cobrament del servei de pagaments.
75
+ overdue: Han passat 15 dies sense cobrament; encara es pot cobrar.
76
+ settled: Cobrada. Estat final.
77
+
78
+ Transitions:
79
+ receive: El servei de pagaments ha cobrat la factura.
80
+ expire: Han passat 15 dies sense cobrament.
81
+ """
82
+
83
+ awaiting = State("Pendent de cobrament", initial=True)
84
+ overdue = State("Endarrerida")
85
+ settled = State("Cobrada", final=True)
86
+
87
+ receive = awaiting.to(settled) | overdue.to(settled)
88
+ expire = awaiting.to(overdue)