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.
- resource_engine_devtools/__init__.py +6 -0
- resource_engine_devtools/ai/__init__.py +1 -0
- resource_engine_devtools/ai/example.py +66 -0
- resource_engine_devtools/ai/installer.py +424 -0
- resource_engine_devtools/ai/skill/SKILL.md +130 -0
- resource_engine_devtools/ai/skill/examples/README.md +7 -0
- resource_engine_devtools/ai/skill/examples/invoices/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/app.py +245 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/actions.py +61 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/balances.py +51 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/customers.py +35 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/hooks.py +61 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/processes.py +80 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/resource.py +112 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/schemas.py +164 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/tags.py +77 -0
- resource_engine_devtools/ai/skill/examples/invoices/authz.py +126 -0
- resource_engine_devtools/ai/skill/examples/invoices/bootstrap.py +80 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/entities.py +112 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/events.py +22 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/state_machine.py +88 -0
- resource_engine_devtools/ai/skill/examples/invoices/infrastructure/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/infrastructure/persistence.py +121 -0
- resource_engine_devtools/ai/skill/examples/invoices/locale/en/LC_MESSAGES/messages.po +682 -0
- resource_engine_devtools/ai/skill/examples/invoices/locale/es/LC_MESSAGES/messages.po +685 -0
- resource_engine_devtools/ai/skill/examples/invoices/notifications.py +47 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/base.html +7 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.html +5 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.subject.txt +1 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.txt +5 -0
- resource_engine_devtools/ai/skill/examples/invoices/tests/conftest.py +40 -0
- resource_engine_devtools/ai/skill/examples/invoices/tests/test_invoices_engine.py +241 -0
- resource_engine_devtools/ai/skill/examples/invoices/worker.py +53 -0
- resource_engine_devtools/ai/skill/llms.txt +25 -0
- resource_engine_devtools/ai/skill/references/anti-patterns.md +209 -0
- resource_engine_devtools/ai/skill/references/docstrings.md +97 -0
- resource_engine_devtools/ai/skill/references/errors.md +81 -0
- resource_engine_devtools/ai/skill/references/lifecycle.md +118 -0
- resource_engine_devtools/ai/skill/references/permissions.md +111 -0
- resource_engine_devtools/ai/skill/references/resource.md +301 -0
- resource_engine_devtools/ai/skill/references/state-machines.md +126 -0
- resource_engine_devtools/ai/skill/references/testing.md +80 -0
- resource_engine_devtools/ai/templates/agents_block.md +26 -0
- resource_engine_devtools/ai/templates/cursor_rule.mdc +7 -0
- resource_engine_devtools/check.py +67 -0
- resource_engine_devtools/cli.py +1112 -0
- resource_engine_devtools/consumer_scaffold.py +715 -0
- resource_engine_devtools/contracts.py +471 -0
- resource_engine_devtools/db.py +132 -0
- resource_engine_devtools/declarations_check.py +116 -0
- resource_engine_devtools/documentation/__init__.py +10 -0
- resource_engine_devtools/documentation/docstrings.py +72 -0
- resource_engine_devtools/documentation/generators/__init__.py +9 -0
- resource_engine_devtools/documentation/generators/ai_context.py +121 -0
- resource_engine_devtools/documentation/generators/api.py +63 -0
- resource_engine_devtools/documentation/generators/json.py +12 -0
- resource_engine_devtools/documentation/generators/markdown.py +687 -0
- resource_engine_devtools/documentation/generators/mermaid.py +22 -0
- resource_engine_devtools/documentation/generators/site.py +379 -0
- resource_engine_devtools/documentation/generators/site_assets/site.css +62 -0
- resource_engine_devtools/documentation/generators/site_assets/site.js +54 -0
- resource_engine_devtools/documentation/i18n.py +185 -0
- resource_engine_devtools/documentation/introspector.py +563 -0
- resource_engine_devtools/documentation/locale/ca/LC_MESSAGES/docs.po +628 -0
- resource_engine_devtools/documentation/locale/es/LC_MESSAGES/docs.po +627 -0
- resource_engine_devtools/documentation/model.py +311 -0
- resource_engine_devtools/documentation/validator.py +128 -0
- resource_engine_devtools/emails.py +172 -0
- resource_engine_devtools/events_check.py +124 -0
- resource_engine_devtools/gates_check.py +133 -0
- resource_engine_devtools/hooks_check.py +287 -0
- resource_engine_devtools/i18n.py +312 -0
- resource_engine_devtools/loader.py +93 -0
- resource_engine_devtools/logic_check.py +136 -0
- resource_engine_devtools/mcp_server.py +685 -0
- resource_engine_devtools/py.typed +0 -0
- resource_engine_devtools/scaffold.py +805 -0
- resource_engine_devtools/scaffold_parts.py +637 -0
- resource_engine_devtools/source_edit.py +424 -0
- resource_engine_devtools/templates_check.py +59 -0
- resource_engine_devtools/worker.py +68 -0
- resource_engine_devtools-0.1.0.dist-info/METADATA +38 -0
- resource_engine_devtools-0.1.0.dist-info/RECORD +88 -0
- resource_engine_devtools-0.1.0.dist-info/WHEEL +4 -0
- resource_engine_devtools-0.1.0.dist-info/entry_points.txt +2 -0
- resource_engine_devtools-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""Runnable example: ``uv run uvicorn invoices.app:app --app-dir examples --reload``.
|
|
2
|
+
|
|
3
|
+
Every request needs a bearer token from Keycloak (``docker compose -f
|
|
4
|
+
compose.emulators.yaml up -d keycloak``; realm ``invoices``, users ``eli``,
|
|
5
|
+
``pau``, ``ada``, ``gina`` and ``root``, password ``dev``; see
|
|
6
|
+
docs/example-app.md). Records belong to the caller's organization (the token's
|
|
7
|
+
``organization`` claim): ACME users never see Globex records.
|
|
8
|
+
``KEYCLOAK_URL`` and ``KEYCLOAK_REALM`` point elsewhere.
|
|
9
|
+
|
|
10
|
+
Documents go to Garage/S3 when ``S3_ENDPOINT`` is set (see compose.emulators.yaml),
|
|
11
|
+
otherwise to an in-memory store (lost on restart; for trying things out only)::
|
|
12
|
+
|
|
13
|
+
S3_ENDPOINT=http://127.0.0.1:3910 S3_BUCKET=resource-engine \
|
|
14
|
+
AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... uv run uvicorn ...
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
from collections.abc import AsyncIterator, Callable
|
|
21
|
+
from contextlib import AbstractAsyncContextManager, asynccontextmanager
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from fastapi import FastAPI
|
|
25
|
+
from resource_engine import ResourceManager
|
|
26
|
+
from resource_engine.authz import ApiKeyAuthenticator, PolicyAuthorizer, system_principal
|
|
27
|
+
from resource_engine.cache import InMemoryCache
|
|
28
|
+
from resource_engine.generation import DocumentGenerator
|
|
29
|
+
from resource_engine.i18n import set_translations
|
|
30
|
+
from resource_engine.messaging import EventHub, EventPublishing, OutboxDelivery
|
|
31
|
+
from resource_engine.ports.cache import Cache
|
|
32
|
+
from resource_engine.ports.identity import Authenticator
|
|
33
|
+
from resource_engine.ports.storage import BlobStore
|
|
34
|
+
from resource_engine.processes import ProcessRunner
|
|
35
|
+
from resource_engine.ratelimit import (
|
|
36
|
+
InMemoryRateLimitStore,
|
|
37
|
+
Limit,
|
|
38
|
+
RateLimiter,
|
|
39
|
+
SlidingWindowLimiter,
|
|
40
|
+
)
|
|
41
|
+
from resource_engine_fastapi import (
|
|
42
|
+
bearer_actor,
|
|
43
|
+
install_locale,
|
|
44
|
+
mount_asyncapi,
|
|
45
|
+
mount_docs,
|
|
46
|
+
mount_explorer,
|
|
47
|
+
mount_resources,
|
|
48
|
+
)
|
|
49
|
+
from resource_engine_fastapi.explorer import OidcSignIn
|
|
50
|
+
from resource_engine_sqlalchemy import SqlAlchemyActivityLog, unit_of_work_factory
|
|
51
|
+
from sqlalchemy.ext.asyncio import (
|
|
52
|
+
AsyncEngine,
|
|
53
|
+
AsyncSession,
|
|
54
|
+
async_sessionmaker,
|
|
55
|
+
create_async_engine,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
from invoices.authz import seed
|
|
59
|
+
from invoices.bootstrap import authz, tenant_registry
|
|
60
|
+
from invoices.infrastructure.persistence import engine as engine_tables
|
|
61
|
+
from invoices.infrastructure.persistence import map_entities, metadata
|
|
62
|
+
from invoices.notifications import templates, translations
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def keycloak_authenticator() -> Authenticator:
|
|
66
|
+
"""Tokens of the example realm: roles from the realm, the tenant from the
|
|
67
|
+
user's organization."""
|
|
68
|
+
from resource_engine_oidc import keycloak
|
|
69
|
+
|
|
70
|
+
return keycloak(
|
|
71
|
+
os.getenv("KEYCLOAK_URL", "http://127.0.0.1:8180"),
|
|
72
|
+
os.getenv("KEYCLOAK_REALM", "invoices"),
|
|
73
|
+
audience="invoices-api",
|
|
74
|
+
tenant_claim="organization",
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def rate_limiter() -> RateLimiter:
|
|
79
|
+
"""Limits per caller, per anonymous address, on failed sign-ins (brute force)
|
|
80
|
+
and on creating invoices. Counters in Valkey/Redis when ``REDIS_URL`` is set
|
|
81
|
+
(shared by every instance), otherwise in this process."""
|
|
82
|
+
url = os.getenv("REDIS_URL")
|
|
83
|
+
if url:
|
|
84
|
+
from redis.asyncio import Redis
|
|
85
|
+
from resource_engine_redis import RedisRateLimitStore
|
|
86
|
+
|
|
87
|
+
store: Any = RedisRateLimitStore(Redis.from_url(url))
|
|
88
|
+
else:
|
|
89
|
+
store = InMemoryRateLimitStore()
|
|
90
|
+
return SlidingWindowLimiter(
|
|
91
|
+
store,
|
|
92
|
+
default=Limit(600, per=60),
|
|
93
|
+
anonymous=Limit(60, per=60),
|
|
94
|
+
failed_auth=Limit(20, per=300),
|
|
95
|
+
actions={"invoices:create": Limit(120, per=60)},
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def record_cache() -> Cache:
|
|
100
|
+
"""The manager's record cache: Valkey/Redis when ``REDIS_URL`` is set
|
|
101
|
+
(shared, signed with ``CACHE_SECRET``), otherwise this process's memory."""
|
|
102
|
+
url = os.getenv("REDIS_URL")
|
|
103
|
+
if url:
|
|
104
|
+
from redis.asyncio import Redis
|
|
105
|
+
from resource_engine_redis import RedisCache
|
|
106
|
+
|
|
107
|
+
return RedisCache(Redis.from_url(url), secret=os.environ["CACHE_SECRET"])
|
|
108
|
+
return InMemoryCache()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def build_manager(
|
|
112
|
+
session_factory: async_sessionmaker[AsyncSession],
|
|
113
|
+
*,
|
|
114
|
+
blob_store: Any,
|
|
115
|
+
limiter: RateLimiter | None = None,
|
|
116
|
+
live: Any = None,
|
|
117
|
+
) -> ResourceManager:
|
|
118
|
+
"""The manager the app and the worker share: SQL, permissions, audit, and
|
|
119
|
+
events through the outbox (the worker feeds them to the processes)."""
|
|
120
|
+
registry = tenant_registry
|
|
121
|
+
uow = unit_of_work_factory(
|
|
122
|
+
session_factory,
|
|
123
|
+
registry,
|
|
124
|
+
outbox_table=engine_tables.outbox,
|
|
125
|
+
inbox_table=engine_tables.inbox,
|
|
126
|
+
idempotency_table=engine_tables.idempotency,
|
|
127
|
+
)
|
|
128
|
+
return ResourceManager(
|
|
129
|
+
registry,
|
|
130
|
+
uow,
|
|
131
|
+
blob_store=blob_store,
|
|
132
|
+
authorizer=PolicyAuthorizer(authz, uow), # system roles + policies as data
|
|
133
|
+
# events stored in the change's transaction; with `live` (an EventHub) also
|
|
134
|
+
# shown at once to this process's live subscribers (the explorer's SUB)
|
|
135
|
+
event_delivery=OutboxDelivery(live=live),
|
|
136
|
+
audit=True, # audit_log table, same transaction as each change
|
|
137
|
+
rate_limiter=limiter, # its per-action limits, whatever the adapter
|
|
138
|
+
cache=record_cache(), # records of resources with cache_ttl (customers)
|
|
139
|
+
# printouts (GET /invoices/{id}/printouts/invoice) from the documents/ templates
|
|
140
|
+
generator=DocumentGenerator(templates),
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def activity_log(session_factory: async_sessionmaker[AsyncSession]) -> SqlAlchemyActivityLog:
|
|
145
|
+
"""What the worker did (jobs, runs, consumers' deliveries), shared with the
|
|
146
|
+
explorer."""
|
|
147
|
+
return SqlAlchemyActivityLog(session_factory, engine_tables.activity)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def create_app(
|
|
151
|
+
engine: AsyncEngine | None = None, *, authenticator: Authenticator | None = None
|
|
152
|
+
) -> FastAPI:
|
|
153
|
+
map_entities()
|
|
154
|
+
registry = tenant_registry
|
|
155
|
+
engine = engine or create_async_engine(
|
|
156
|
+
os.getenv("DATABASE_URL", "sqlite+aiosqlite:///invoices.db"),
|
|
157
|
+
pool_pre_ping=True, # a database restart costs no failed request
|
|
158
|
+
)
|
|
159
|
+
session_factory = async_sessionmaker(engine, expire_on_commit=False)
|
|
160
|
+
|
|
161
|
+
@asynccontextmanager
|
|
162
|
+
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
163
|
+
async with engine.begin() as conn:
|
|
164
|
+
await conn.run_sync(metadata.create_all)
|
|
165
|
+
await seed(manager, system_principal("invoices-seed")) # roles and policies
|
|
166
|
+
yield
|
|
167
|
+
await engine.dispose()
|
|
168
|
+
|
|
169
|
+
blob_store, open_store = _blob_store()
|
|
170
|
+
|
|
171
|
+
@asynccontextmanager
|
|
172
|
+
async def lifespan_with_store(app: FastAPI) -> AsyncIterator[None]:
|
|
173
|
+
async with open_store(), lifespan(app):
|
|
174
|
+
yield
|
|
175
|
+
|
|
176
|
+
app = FastAPI(title="Invoices (Resource Engine example)", lifespan=lifespan_with_store)
|
|
177
|
+
limiter = rate_limiter()
|
|
178
|
+
hub = EventHub() if os.getenv("EXPLORER") else None
|
|
179
|
+
manager = build_manager(session_factory, blob_store=blob_store, limiter=limiter, live=hub)
|
|
180
|
+
app.state.manager = manager
|
|
181
|
+
# API keys (rek_...) for machine clients; every other token goes to Keycloak
|
|
182
|
+
keys = ApiKeyAuthenticator(
|
|
183
|
+
manager.uow_factory, fallback=authenticator or keycloak_authenticator()
|
|
184
|
+
)
|
|
185
|
+
# 429 with Retry-After; a token's locale claim sets the language of the answer
|
|
186
|
+
actor = bearer_actor(keys, rate_limiter=limiter, translations=translations)
|
|
187
|
+
mount_resources(app, registry, manager, actor_dependency=actor, access_log=True)
|
|
188
|
+
set_translations(translations) # Catalan by default; English and Spanish catalogues
|
|
189
|
+
install_locale(app, translations) # Accept-Language → error titles, Content-Language
|
|
190
|
+
site = os.getenv("DOCS_SITE") # resource-engine docs site --out site
|
|
191
|
+
if site:
|
|
192
|
+
mount_docs(app, site) # the functional documentation at /documentation/
|
|
193
|
+
if os.getenv("EXPLORER"): # off unless asked: /explorer/, like FastAPI's /docs
|
|
194
|
+
mount_explorer(
|
|
195
|
+
app,
|
|
196
|
+
manager,
|
|
197
|
+
actor_dependency=actor,
|
|
198
|
+
events=hub, # SUB: committed events, live
|
|
199
|
+
activity=activity_log(session_factory),
|
|
200
|
+
jobs=True, # CRON: the worker's jobs and the timed transitions
|
|
201
|
+
outbox=True, # OUTBOX and DLQ: what didn't arrive, and send again
|
|
202
|
+
# PUB: dry runs against the process managers; publishing for real only
|
|
203
|
+
# with EXPLORER_PUBLISH=1, and for roles granted events:publish:<Event>
|
|
204
|
+
publish=EventPublishing(
|
|
205
|
+
manager,
|
|
206
|
+
consumers=[ProcessRunner(manager).router()],
|
|
207
|
+
allow_publish=os.getenv("EXPLORER_PUBLISH") == "1",
|
|
208
|
+
),
|
|
209
|
+
# "Authorize": sign in with Keycloak's public client (PKCE)
|
|
210
|
+
oidc=OidcSignIn(
|
|
211
|
+
issuer=f"{os.getenv('KEYCLOAK_URL', 'http://127.0.0.1:8180')}/realms/"
|
|
212
|
+
f"{os.getenv('KEYCLOAK_REALM', 'invoices')}",
|
|
213
|
+
client_id="invoices-web",
|
|
214
|
+
scope="openid organization",
|
|
215
|
+
),
|
|
216
|
+
)
|
|
217
|
+
mount_asyncapi(app, registry) # GET /asyncapi.json: the events it publishes
|
|
218
|
+
return app
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _blob_store() -> tuple[BlobStore, Callable[[], AbstractAsyncContextManager[None]]]:
|
|
222
|
+
"""The store, and a context manager that connects it for the app's lifetime."""
|
|
223
|
+
endpoint = os.getenv("S3_ENDPOINT")
|
|
224
|
+
if not endpoint:
|
|
225
|
+
from contextlib import nullcontext
|
|
226
|
+
|
|
227
|
+
from resource_engine.testing import InMemoryBlobStore
|
|
228
|
+
|
|
229
|
+
return InMemoryBlobStore(), lambda: nullcontext()
|
|
230
|
+
|
|
231
|
+
from aiobotocore.session import get_session
|
|
232
|
+
from resource_engine_s3 import S3BlobStore, s3_client_options
|
|
233
|
+
|
|
234
|
+
store = S3BlobStore(None, os.getenv("S3_BUCKET", "resource-engine"))
|
|
235
|
+
|
|
236
|
+
@asynccontextmanager
|
|
237
|
+
async def connect() -> AsyncIterator[None]:
|
|
238
|
+
options = s3_client_options(
|
|
239
|
+
endpoint, region=os.getenv("S3_REGION", "garage"), path_style=True
|
|
240
|
+
)
|
|
241
|
+
async with get_session().create_client("s3", **options) as client:
|
|
242
|
+
store.client = client # the aiobotocore client must live in the app's loop
|
|
243
|
+
yield
|
|
244
|
+
|
|
245
|
+
return store, connect
|
|
File without changes
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
4
|
+
|
|
5
|
+
from resource_engine import Action, OperationContext
|
|
6
|
+
from resource_engine.documents import NewDocument
|
|
7
|
+
|
|
8
|
+
from invoices.application.schemas import ApplyDiscount
|
|
9
|
+
from invoices.domain.events import InvoiceTotalsRecalculated
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class RecalculateTotals(Action):
|
|
13
|
+
"""Aplica un descompte percentual a l'import d'una factura.
|
|
14
|
+
|
|
15
|
+
Preconditions:
|
|
16
|
+
La factura és un esborrany.
|
|
17
|
+
|
|
18
|
+
Postconditions:
|
|
19
|
+
L'import queda reduït pel percentatge indicat, arrodonit a cèntims.
|
|
20
|
+
|
|
21
|
+
Effects:
|
|
22
|
+
Emet l'esdeveniment ``InvoiceTotalsRecalculated``.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
input_schema = ApplyDiscount
|
|
26
|
+
|
|
27
|
+
async def execute(self, ctx: OperationContext) -> None:
|
|
28
|
+
invoice = ctx.entity
|
|
29
|
+
invoice.ensure_editable()
|
|
30
|
+
previous = invoice.amount
|
|
31
|
+
factor = (Decimal(100) - ctx.data.percent) / Decimal(100)
|
|
32
|
+
invoice.amount = (previous * factor).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
|
33
|
+
await ctx.repository().update(invoice)
|
|
34
|
+
ctx.record_event(
|
|
35
|
+
InvoiceTotalsRecalculated(
|
|
36
|
+
invoice_id=invoice.id, previous_amount=previous, new_amount=invoice.amount
|
|
37
|
+
)
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class RenderSummary(Action):
|
|
42
|
+
"""Genera un resum en Markdown de la factura i l'adjunta a la ranura ``summary``.
|
|
43
|
+
|
|
44
|
+
Postconditions:
|
|
45
|
+
La factura té un únic document ``summary`` amb les dades actuals.
|
|
46
|
+
|
|
47
|
+
Effects:
|
|
48
|
+
Desa el document al magatzem de fitxers i emet ``DocumentAttached``.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
async def execute(self, ctx: OperationContext) -> None:
|
|
52
|
+
invoice = ctx.entity
|
|
53
|
+
text = (
|
|
54
|
+
f"# Factura {invoice.id}\n\n"
|
|
55
|
+
f"- Client: {invoice.customer}\n"
|
|
56
|
+
f"- Import: {invoice.amount}\n"
|
|
57
|
+
f"- Estat: {invoice.status}\n"
|
|
58
|
+
)
|
|
59
|
+
await ctx.documents.attach(
|
|
60
|
+
NewDocument("summary", text.encode(), f"factura-{invoice.id}.md", "text/markdown")
|
|
61
|
+
)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from resource_engine import Aggregate, Count, Listing, Max, Reference, Resource, Sum
|
|
4
|
+
|
|
5
|
+
from invoices.application.schemas import CustomerBalanceRead
|
|
6
|
+
from invoices.domain.entities import CustomerBalance
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class CustomerBalanceResource(Resource):
|
|
10
|
+
"""Saldo de facturació de cada client, calculat a partir de les factures.
|
|
11
|
+
|
|
12
|
+
És una vista: només es consulta, i cada fila es recalcula amb les factures
|
|
13
|
+
del client (no es desa enlloc).
|
|
14
|
+
|
|
15
|
+
Business area:
|
|
16
|
+
Facturació
|
|
17
|
+
|
|
18
|
+
Actors:
|
|
19
|
+
- Administrador
|
|
20
|
+
- Emissor de factures
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
name = "customer_balances"
|
|
24
|
+
model = CustomerBalance
|
|
25
|
+
schemas = {"read": CustomerBalanceRead}
|
|
26
|
+
operations = ["list", "get"]
|
|
27
|
+
operation_docs = {
|
|
28
|
+
"list": "Llista els saldos dels clients amb factures, ordenables per import.",
|
|
29
|
+
"get": "Consulta el saldo d'un client.",
|
|
30
|
+
}
|
|
31
|
+
id_field = "customer_id"
|
|
32
|
+
# read-only rows computed from invoices: one GROUP BY query in SQL
|
|
33
|
+
view = Aggregate(
|
|
34
|
+
"invoices",
|
|
35
|
+
group_by=["customer_id", "organization"],
|
|
36
|
+
values={
|
|
37
|
+
"invoices": Count(),
|
|
38
|
+
"total": Sum("amount"),
|
|
39
|
+
"outstanding": Sum("amount", where={"status": ["pending", "approved"]}),
|
|
40
|
+
"paid": Sum("amount", where={"status": "paid"}),
|
|
41
|
+
"last_issue_date": Max("issue_date"),
|
|
42
|
+
},
|
|
43
|
+
)
|
|
44
|
+
references = {
|
|
45
|
+
"customer_id": Reference(
|
|
46
|
+
"customers", name="customer", related_name="balance", description="El client."
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
listing = Listing(
|
|
50
|
+
filterable=["customer_id"], sortable=["total", "outstanding", "paid", "last_issue_date"]
|
|
51
|
+
)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from resource_engine import CRUD, Cached, Listing, Resource
|
|
4
|
+
|
|
5
|
+
from invoices.application.schemas import CustomerCreate, CustomerRead, CustomerUpdate
|
|
6
|
+
from invoices.domain.entities import Customer
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class CustomerResource(Resource):
|
|
10
|
+
"""Clients als quals l'organització emet factures.
|
|
11
|
+
|
|
12
|
+
Les factures hi fan referència amb ``customer_id``; un client amb factures
|
|
13
|
+
no es pot eliminar.
|
|
14
|
+
|
|
15
|
+
Business area:
|
|
16
|
+
Facturació
|
|
17
|
+
|
|
18
|
+
Actors:
|
|
19
|
+
- Administrador
|
|
20
|
+
- Emissor de factures
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
model = Customer
|
|
24
|
+
schemas = {"create": CustomerCreate, "update": CustomerUpdate, "read": CustomerRead}
|
|
25
|
+
operations = CRUD
|
|
26
|
+
operation_docs = {
|
|
27
|
+
"list": "Llista els clients, filtrables per país i nom.",
|
|
28
|
+
"get": "Consulta un client.",
|
|
29
|
+
"create": "Dona d'alta un client.",
|
|
30
|
+
"update": "Modifica les dades d'un client.",
|
|
31
|
+
"delete": "Elimina un client que no té factures.",
|
|
32
|
+
}
|
|
33
|
+
# read often, changed rarely: kept in the manager's cache for 5 minutes
|
|
34
|
+
caching = Cached(ttl=300)
|
|
35
|
+
listing = Listing(filterable=["country", "name", "tax_id"], sortable=["id", "name"])
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
from resource_engine import OperationContext, external_effect, hook
|
|
6
|
+
from resource_engine.email import EmailRequested
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@hook.before("create")
|
|
12
|
+
@hook.after("update")
|
|
13
|
+
def validate_amount(ctx: OperationContext) -> None:
|
|
14
|
+
"""Rebutja factures amb import negatiu."""
|
|
15
|
+
ctx.entity.ensure_valid_amount()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@hook.before("update", "delete")
|
|
19
|
+
def ensure_editable(ctx: OperationContext) -> None:
|
|
20
|
+
"""Només es poden modificar o eliminar factures en esborrany."""
|
|
21
|
+
ctx.entity.ensure_editable()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@hook.after("transition:approve")
|
|
25
|
+
async def request_approval_email(ctx: OperationContext) -> None:
|
|
26
|
+
"""Demana el correu d'aprovació per al client registrat, si té adreça.
|
|
27
|
+
|
|
28
|
+
El correu es desa amb el canvi (outbox) i el worker l'envia quan la
|
|
29
|
+
transacció s'ha confirmat.
|
|
30
|
+
"""
|
|
31
|
+
invoice = ctx.entity
|
|
32
|
+
if invoice.customer_id is None:
|
|
33
|
+
return
|
|
34
|
+
customer = await ctx.repository("customers").get(invoice.customer_id)
|
|
35
|
+
if customer is None or not customer.email:
|
|
36
|
+
return
|
|
37
|
+
ctx.record_event(
|
|
38
|
+
EmailRequested(
|
|
39
|
+
template="invoice_approved",
|
|
40
|
+
to=[customer.email],
|
|
41
|
+
context={"number": invoice.id, "customer": customer.name, "amount": invoice.amount},
|
|
42
|
+
locale="ca",
|
|
43
|
+
resource="invoices",
|
|
44
|
+
entity_id=invoice.id,
|
|
45
|
+
)
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@hook.after_commit
|
|
50
|
+
@external_effect
|
|
51
|
+
async def notify_approval(ctx: OperationContext) -> None:
|
|
52
|
+
"""Notifica el client que la factura ha estat aprovada.
|
|
53
|
+
|
|
54
|
+
Effects:
|
|
55
|
+
Envia una notificació mitjançant el servei ``notifier``.
|
|
56
|
+
"""
|
|
57
|
+
if ctx.transition != "approve":
|
|
58
|
+
return
|
|
59
|
+
notifier = ctx.services.get("notifier")
|
|
60
|
+
if notifier is not None:
|
|
61
|
+
await notifier.send(f"Invoice {ctx.entity_id} approved")
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import timedelta
|
|
4
|
+
|
|
5
|
+
from resource_engine import Listing, Machine, OperationContext, Reference, Timer, hook
|
|
6
|
+
from resource_engine.processes import On, Process, ProcessStep
|
|
7
|
+
|
|
8
|
+
from invoices.application.schemas import PaymentRead, PaymentReceived, PaymentStart
|
|
9
|
+
from invoices.domain.entities import InvoicePayment
|
|
10
|
+
from invoices.domain.events import PaymentOverdue
|
|
11
|
+
from invoices.domain.state_machine import PaymentFlow
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def start_payment(step: ProcessStep) -> None:
|
|
15
|
+
"""Quan s'aprova una factura, comença a esperar-ne el cobrament."""
|
|
16
|
+
invoice = await step.manager.get("invoices", step.key, actor=step.actor)
|
|
17
|
+
await step.start({"amount": invoice.amount}, tenant=getattr(invoice, "organization", None))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def record_payment(step: ProcessStep) -> None:
|
|
21
|
+
"""Un cobrament del servei de pagaments tanca el procés i marca la factura com a cobrada."""
|
|
22
|
+
if not step.can("receive"):
|
|
23
|
+
return # already settled: a repeated notification
|
|
24
|
+
await step.transition("receive")
|
|
25
|
+
await step.manager.transition("invoices", step.key, "pay", actor=step.actor)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@hook.after("transition:expire")
|
|
29
|
+
def announce_overdue(ctx: OperationContext) -> None:
|
|
30
|
+
"""Emet ``PaymentOverdue`` perquè altres serveis (recordatoris) en tinguin notícia."""
|
|
31
|
+
ctx.record_event(PaymentOverdue(invoice_id=ctx.entity.invoice_id))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class InvoicePaymentProcess(Process):
|
|
35
|
+
"""Cobrament de les factures aprovades.
|
|
36
|
+
|
|
37
|
+
Comença quan s'aprova una factura, espera l'esdeveniment ``PaymentReceived``
|
|
38
|
+
del servei de pagaments i aleshores marca la factura com a cobrada. Si en 15
|
|
39
|
+
dies no arriba, passa a endarrerida i ho anuncia; un cobrament posterior el
|
|
40
|
+
tanca igualment.
|
|
41
|
+
|
|
42
|
+
Business area:
|
|
43
|
+
Facturació
|
|
44
|
+
|
|
45
|
+
Actors:
|
|
46
|
+
- Servei de pagaments
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
name = "invoice_payments"
|
|
50
|
+
model = InvoicePayment
|
|
51
|
+
schemas = {"create": PaymentStart, "read": PaymentRead}
|
|
52
|
+
operations = ["list", "get", "create"]
|
|
53
|
+
operation_docs = {
|
|
54
|
+
"list": "Llista els cobraments en curs i acabats.",
|
|
55
|
+
"get": "Consulta el cobrament d'una factura.",
|
|
56
|
+
"create": "El crea el procés quan s'aprova una factura.",
|
|
57
|
+
}
|
|
58
|
+
state_machine = Machine(PaymentFlow, since_field="status_changed_at")
|
|
59
|
+
timers = [
|
|
60
|
+
Timer(
|
|
61
|
+
"expire",
|
|
62
|
+
after=timedelta(days=15),
|
|
63
|
+
description="Sense cobrament en 15 dies, el cobrament queda endarrerit.",
|
|
64
|
+
)
|
|
65
|
+
]
|
|
66
|
+
hooks = [announce_overdue]
|
|
67
|
+
events = [PaymentOverdue]
|
|
68
|
+
references = {"invoice_id": Reference("invoices", related_name="payments")}
|
|
69
|
+
correlation = "invoice_id"
|
|
70
|
+
reacts = [
|
|
71
|
+
On(
|
|
72
|
+
"TransitionExecuted",
|
|
73
|
+
start_payment,
|
|
74
|
+
resource="invoices",
|
|
75
|
+
transition="approve",
|
|
76
|
+
start=True,
|
|
77
|
+
),
|
|
78
|
+
On("PaymentReceived", record_payment, key="invoice_id", payload=PaymentReceived),
|
|
79
|
+
]
|
|
80
|
+
listing = Listing(filterable=["status", "invoice_id"], sortable=["id"])
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import timedelta
|
|
4
|
+
|
|
5
|
+
from resource_engine import (
|
|
6
|
+
CRUD,
|
|
7
|
+
Access,
|
|
8
|
+
DocumentSlot,
|
|
9
|
+
Listing,
|
|
10
|
+
Machine,
|
|
11
|
+
Reference,
|
|
12
|
+
Resource,
|
|
13
|
+
Timer,
|
|
14
|
+
Versioned,
|
|
15
|
+
)
|
|
16
|
+
from resource_engine.generation import Printout
|
|
17
|
+
|
|
18
|
+
from invoices.application import hooks
|
|
19
|
+
from invoices.application.actions import RecalculateTotals, RenderSummary
|
|
20
|
+
from invoices.application.schemas import InvoiceCreate, InvoiceRead, InvoiceUpdate, RejectInvoice
|
|
21
|
+
from invoices.domain.entities import Invoice
|
|
22
|
+
from invoices.domain.events import InvoiceTotalsRecalculated
|
|
23
|
+
from invoices.domain.state_machine import InvoiceDelivery, InvoiceStateMachine
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class InvoiceResource(Resource):
|
|
27
|
+
"""Gestió de factures de l'organització.
|
|
28
|
+
|
|
29
|
+
Permet crear, consultar i modificar factures, així com gestionar-ne el
|
|
30
|
+
procés d'aprovació i cobrament.
|
|
31
|
+
|
|
32
|
+
Business area:
|
|
33
|
+
Facturació
|
|
34
|
+
|
|
35
|
+
Actors:
|
|
36
|
+
- Administrador
|
|
37
|
+
- Comptable
|
|
38
|
+
- Responsable
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
model = Invoice
|
|
42
|
+
schemas = {"create": InvoiceCreate, "update": InvoiceUpdate, "read": InvoiceRead}
|
|
43
|
+
operations = CRUD
|
|
44
|
+
operation_docs = {
|
|
45
|
+
"list": "Llista les factures, filtrables per estat i client.",
|
|
46
|
+
"get": "Consulta una factura.",
|
|
47
|
+
"create": "Crea una factura en estat esborrany.",
|
|
48
|
+
"update": "Modifica una factura mentre és un esborrany.",
|
|
49
|
+
"delete": "Elimina una factura en esborrany.",
|
|
50
|
+
}
|
|
51
|
+
# two independent state machines: approval (status) and delivery to the
|
|
52
|
+
# customer (delivery_status); since_field: when it entered its current
|
|
53
|
+
# approval state, stamped by the engine
|
|
54
|
+
machines = {
|
|
55
|
+
"approval": Machine(InvoiceStateMachine, field="status", since_field="status_changed_at"),
|
|
56
|
+
"delivery": Machine(InvoiceDelivery, field="delivery_status"),
|
|
57
|
+
}
|
|
58
|
+
timers = [
|
|
59
|
+
Timer(
|
|
60
|
+
"reject",
|
|
61
|
+
after=timedelta(days=30),
|
|
62
|
+
data={"reason": "Sense resposta en 30 dies"},
|
|
63
|
+
description="Les factures pendents d'aprovar més de 30 dies es rebutgen soles.",
|
|
64
|
+
)
|
|
65
|
+
]
|
|
66
|
+
transition_schemas = {"reject": RejectInvoice}
|
|
67
|
+
actions = [RecalculateTotals, RenderSummary]
|
|
68
|
+
events = [InvoiceTotalsRecalculated]
|
|
69
|
+
#: The invoice to send or print, rendered from the record when asked
|
|
70
|
+
#: (``documents/invoice.html`` and ``.md``), never stored.
|
|
71
|
+
printouts = {
|
|
72
|
+
"invoice": Printout(formats=("html", "md"), description="La factura per enviar o imprimir.")
|
|
73
|
+
}
|
|
74
|
+
documents = [
|
|
75
|
+
DocumentSlot(
|
|
76
|
+
"signed_pdf",
|
|
77
|
+
content_types=["application/pdf"],
|
|
78
|
+
max_bytes=10 * 1024 * 1024,
|
|
79
|
+
required_for=["approve"],
|
|
80
|
+
description="Factura signada pel client; cal per aprovar-la.",
|
|
81
|
+
),
|
|
82
|
+
DocumentSlot(
|
|
83
|
+
"attachments",
|
|
84
|
+
multiple=True,
|
|
85
|
+
max_bytes=25 * 1024 * 1024,
|
|
86
|
+
description="Justificants i altra documentació de suport.",
|
|
87
|
+
),
|
|
88
|
+
DocumentSlot(
|
|
89
|
+
"summary",
|
|
90
|
+
content_types=["text/markdown"],
|
|
91
|
+
upload="api",
|
|
92
|
+
description="Resum generat per l'acció render_summary.",
|
|
93
|
+
),
|
|
94
|
+
]
|
|
95
|
+
# every function marked with @hook in hooks.py, where it says it runs
|
|
96
|
+
hooks = [hooks]
|
|
97
|
+
# the registered customer; deleting a customer with invoices is refused (409)
|
|
98
|
+
references = {
|
|
99
|
+
"customer_id": Reference(
|
|
100
|
+
"customers",
|
|
101
|
+
name="customer_record",
|
|
102
|
+
description="Client registrat al qual s'emet la factura.",
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
listing = Listing(
|
|
106
|
+
filterable=["status", "delivery_status", "customer", "customer_id"],
|
|
107
|
+
sortable=["id", "amount", "issue_date"],
|
|
108
|
+
)
|
|
109
|
+
# internal notes: only roles granted invoices:read:notes / invoices:write:notes
|
|
110
|
+
access = Access(restricted_fields=["notes"])
|
|
111
|
+
# optimistic concurrency: ETag / If-Match, stale writes are refused (409)
|
|
112
|
+
concurrency = Versioned("version")
|