ApiLogicServer 16.0.0__py3-none-any.whl → 16.0.3__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.
@@ -1,1221 +0,0 @@
1
- <!--
2
- ═══════════════════════════════════════════════════════════════════════════════
3
- 🚨 MANDATORY: READ THIS FIRST - NO EXCEPTIONS 🚨
4
- ═══════════════════════════════════════════════════════════════════════════════
5
-
6
- ⚠️ IF USER SAYS: "load .github/.copilot-instructions.md" OR ANY ACTIVATION PHRASE
7
- ⚠️ YOU MUST EXECUTE THIS EXACT SEQUENCE - NO DEVIATIONS:
8
-
9
- 1. Read .github/welcome.md (silently - do not mention this action)
10
- 2. Display ONLY the content from welcome.md
11
- 3. DO NOT say "I've loaded the instructions"
12
- 4. DO NOT display this .copilot-instructions.md file
13
- 5. DO NOT explain what you're doing
14
-
15
- THIS IS NOT A SUGGESTION - THIS IS A MANDATORY COMMAND
16
-
17
- ═══════════════════════════════════════════════════════════════════════════════
18
- -->
19
- ---
20
-
21
- ## 🚨 CRITICAL: User Activation Protocol
22
-
23
- **ACTIVATION TRIGGERS:**
24
- - "load .github/.copilot-instructions.md"
25
- - "load copilot instructions"
26
- - "help me get started"
27
- - "activate copilot"
28
- - Any similar startup phrase
29
-
30
- **MANDATORY RESPONSE SEQUENCE:**
31
-
32
- ```
33
- STEP 1: Read .github/welcome.md (silently)
34
- STEP 2: Display welcome.md content ONLY
35
- STEP 3: STOP - do nothing else
36
- ```
37
-
38
- ---
39
-
40
- ## 🎯 CRITICAL: Guided Tour Activation Protocol
41
-
42
- **ACTIVATION TRIGGERS:**
43
- - "guide me through"
44
- - "guide me"
45
- - "take the tour"
46
- - "walk me through"
47
- - "show me around"
48
- - Any similar tour/walkthrough request
49
-
50
- **MANDATORY RESPONSE SEQUENCE:**
51
-
52
- ```
53
- STEP 1: Read tutor.md COMPLETELY (silently)
54
- STEP 2: Follow tutor.md instructions EXACTLY
55
- STEP 3: Act as TOUR GUIDE (not passive assistant)
56
- STEP 4: Create manage_todo_list for tour sections
57
- STEP 5: Start with tutor.md Introduction section
58
- ```
59
-
60
- **✅ CORRECT EXECUTION:**
61
- ```
62
- User: "guide me"
63
-
64
- AI: [reads tutor.md completely - NO OUTPUT]
65
- AI: [creates todo list from tutor sections]
66
- AI: [follows tutor.md Introduction section exactly]
67
- AI: "I'll guide you through basic_demo - a 20-minute hands-on exploration..."
68
- ```
69
-
70
- **❌ FORBIDDEN BEHAVIORS:**
71
- ```
72
- User: "guide me"
73
-
74
- ❌ AI: Starts giving general guidance without reading tutor.md
75
- ❌ AI: Runs commands without following tutor choreography
76
- ❌ AI: Acts as passive assistant waiting for user direction
77
- ❌ AI: Skips sections or reorders steps
78
- ❌ AI: Offers option menus instead of directing the tour
79
- ❌ AI: Assumes server state or skips stop/start sequences
80
- ```
81
-
82
- **RATIONALE:**
83
- - tutor.md contains weeks of refined choreography
84
- - Every command, stop, start is precisely sequenced
85
- - Deviations break the learning experience
86
- - You are the DIRECTOR in tour mode, not a passive responder
87
- - The tour has been engineered for AI reliability through multiple iterations
88
-
89
- **✅ CORRECT EXECUTION:**
90
- ```
91
- User: "load .github/.copilot-instructions.md"
92
-
93
- AI: [reads welcome.md silently - NO OUTPUT]
94
- AI: [displays ONLY this]:
95
-
96
- ## Welcome
97
-
98
- **Welcome! This is your basic_demo project.**
99
-
100
- This is a complete, working microservice auto-generated from a database schema...
101
- [... rest of welcome.md content ...]
102
- ```
103
-
104
- **❌ FORBIDDEN BEHAVIORS:**
105
- ```
106
- User: "load .github/.copilot-instructions.md"
107
-
108
- ❌ AI: "I've loaded the instructions file..."
109
- ❌ AI: "Here are the contents of .copilot-instructions.md:"
110
- ❌ AI: [displays .copilot-instructions.md]
111
- ❌ AI: "I'll read the file for you..."
112
- ❌ AI: Any meta-commentary about loading or reading files
113
- ```
114
-
115
- **RATIONALE:**
116
- - Users want to see the **welcome message**, not technical instructions
117
- - This file (.copilot-instructions.md) is for AI context, not user display
118
- - Separation of concerns: welcome.md = user-facing, copilot-instructions.md = AI-facing
119
- - No meta-cognitive confusion about "instructions" vs "content"
120
-
121
- ---
122
-
123
- ## Capabilities Reference
124
-
125
- When user asks "what can I do here", list these capabilities:
126
-
127
- ### Here Are Some Things I Can Help You With
128
-
129
- 1. **Add business logic** - Describe requirements in natural language, I'll generate declarative rules (deterministic + AI-driven)
130
- 2. **Customize the API** - Add custom endpoints for your specific needs
131
- 3. **Create custom UIs** - Build React apps with `genai-logic genai-add-app --vibe`
132
- 4. **Add security** - Set up role-based access control with `genai-logic add-auth`
133
- 5. **Test your logic** - Create Behave tests with requirements traceability
134
- 6. **Configure Admin UI** - Customize the auto-generated admin interface
135
- 7. **Query via natural language** - Act as MCP client to read/update data
136
- 8. **Create B2B APIs** - Complex integration endpoints with partner systems
137
- 9. **Add events** - Integrate with Kafka, webhooks, or other event systems
138
- 10. **Customize models** - Add tables, attributes, or derived fields
139
- 11. **Discovery systems** - Auto-load logic and APIs from discovery folders
140
-
141
- ---
142
-
143
- ---
144
- title: Copilot Instructions for basic_demo GenAI-Logic Project
145
- Description: Project-level instructions for working with generated projects
146
- Source: ApiLogicServer-src/prototypes/base/.github/.copilot-instructions.md
147
- Propagation: CLI create command → created projects (non-basic_demo)
148
- Instrucions: Changes must be merged from api_logic_server_cli/prototypes/basic_demo/.github - see instructions there
149
- Usage: AI assistants read this when user opens any created project
150
- version: 3.1
151
- changelog:
152
- - 3.1 (Nov 20, 2025) - Improved activation instructions with visual markers and examples
153
- - 3.0 (Nov 17, 2025) - Major streamlining: removed duplicate sections, consolidated MCP content, simplified workflows
154
- - 2.9 (Nov 17, 2025) - MANDATORY training file reading workflow (STOP command)
155
- - 2.8 (Nov 16, 2025) - Probabilistic Logic support
156
- ---
157
-
158
- # GitHub Copilot Instructions for GenAI-Logic (aka API Logic Server) Projects
159
-
160
- ---
161
-
162
- ## 🔑 Key Technical Points
163
-
164
- **Critical Implementation Details:**
165
-
166
- 1. **Discovery Systems**:
167
- - **Logic Discovery**: Business rules automatically loaded from `logic/logic_discovery/use_case.py` via `logic/logic_discovery/auto_discovery.py`
168
- - **API Discovery**: Custom APIs automatically loaded from `api/api_discovery/[service_name].py` via `api/api_discovery/auto_discovery.py`
169
- - Do NOT manually duplicate rule calls or API registrations
170
-
171
- 2. **API Record ID Pattern**: When creating records via custom APIs, use `session.flush()` before accessing the ID to ensure it's generated:
172
- ```python
173
- session.add(sql_alchemy_row)
174
- session.flush() # Ensures ID is generated
175
- record_id = sql_alchemy_row.id
176
- return {"message": "Success", "record_id": record_id}
177
- ```
178
-
179
- 3. **Automatic Business Logic**: All APIs (standard and custom) automatically inherit LogicBank rules without additional code.
180
-
181
- 4. **CLI Commands**: Use `genai-logic --help` to see all available commands. When CLI commands exist for a task (e.g., `add-auth`, `genai-add-mcp-client`, `genai-add-app`), ALWAYS use them instead of manual configuration - they handle all setup correctly.
182
-
183
- > **📋 Testing:** For comprehensive testing conventions, patterns, and examples, see `docs/training/testing.md` (555 lines - I'll read this before we create any tests)
184
-
185
- ---
186
-
187
- ## Detailed Service Documentation
188
-
189
- The sections below provide complete details on each service. I'll reference these as needed when we work together.
190
-
191
- ### `venv` is required
192
-
193
- To establish the virtual environment:
194
-
195
- 1. Attempt to find a `venv` folder in the current project directory
196
- 2. If not found, check parent or grandparent directories
197
- 3. **If no venv is found:**
198
- - Ask the user for the venv location, OR
199
- - Offer to create one using `python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt`
200
-
201
- ### Starting the server
202
-
203
- **IMPORTANT:** Always activate the venv before starting the server.
204
-
205
- ```bash
206
- # Activate venv first
207
- source venv/bin/activate
208
-
209
- # Then start server
210
- python api_logic_server_run.py
211
- # Then open: http://localhost:5656
212
- ```
213
-
214
- **Server Management Best Practices:**
215
- - Before making structural changes (models, logic files), STOP the running server to avoid file locking issues
216
- - To stop server: `pkill -f "python api_logic_server_run.py"` or use Ctrl+C if running in foreground
217
- - USER ACTION: After making changes, user restarts server (e.g., `python api_logic_server_run.py &`)
218
- - Monitor startup output for errors, especially after database/model changes
219
- - If server fails to start after model changes, check that alembic migrations have been applied
220
-
221
- ### Adding Business Logic
222
- `docs/training` explains how to translate Natural Language logic into LogicBank (Python) rules like:
223
-
224
- ```python
225
- # Edit: logic/declare_logic.py
226
- Rule.sum(derive=Customer.Balance, as_sum_of=Order.AmountTotal)
227
- Rule.constraint(validate=Customer, as_condition=lambda row: row.Balance <= row.CreditLimit)
228
- ```
229
-
230
- **⚠️ CRITICAL: docs/training/ Folder Organization**
231
-
232
- The `docs/training/` folder contains ONLY universal, framework-level training materials:
233
- - ✅ **Universal patterns** → `genai_logic_patterns.md`
234
- - ✅ **Implementation patterns** → `probabilistic_logic_guide.md`
235
- - ✅ **Code templates** → `probabilistic_template.py`
236
- - ✅ **API references** → `.prompt` files (logic_bank_api.prompt, etc.)
237
-
238
- **DO NOT add project-specific content to docs/training/**:
239
- - ❌ Project-specific instructions or configurations
240
- - ❌ Alembic migration guides specific to this project
241
- - ❌ File structures specific to basic_demo
242
- - ❌ Copilot instructions that reference specific project paths
243
-
244
- **WHY:** This folder's content is designed to be reusable across ANY ApiLogicServer project using GenAI. Project-specific content should live in:
245
- - Logic implementation → `logic/logic_discovery/`
246
- - Project docs → `docs/` (outside training/)
247
- - Copilot instructions → `.github/.copilot-instructions.md`
248
-
249
- See `docs/training/README.md` for complete organization rules.
250
-
251
- **⚠️ MANDATORY WORKFLOW - BEFORE Implementing ANY Business Logic:**
252
-
253
- ```
254
- STOP ✋
255
-
256
- READ ALL TRAINING FILES IN ORDER (every single time):
257
-
258
- 1. docs/training/logic_bank_patterns.prompt (Foundation - ALWAYS READ FIRST)
259
- 2. docs/training/logic_bank_api.prompt (Deterministic rules - ALWAYS READ SECOND)
260
- 3. docs/training/probabilistic_logic.prompt (AI/Probabilistic rules - ALWAYS READ THIRD)
261
-
262
- ⚠️ CRITICAL REQUIREMENTS:
263
- - DO NOT skip any files, even if you think you know the pattern
264
- - DO NOT selectively read based on keywords in the user's request
265
- - READ ALL THREE FILES IN SEQUENCE before writing any code
266
- - These files contain failure patterns and correct implementations learned from production use
267
-
268
- THEN (and only then) implement the logic.
269
- ```
270
-
271
- **Training File Contents:**
272
-
273
- 1. **`docs/training/logic_bank_patterns.prompt`** - Foundation patterns for ALL rule types
274
- - Event handler signatures (row, old_row, logic_row) - REQUIRED READING
275
- - Logging with logic_row.log() vs app_logger
276
- - Request Pattern with new_logic_row()
277
- - Rule API syntax dos and don'ts
278
- - Common anti-patterns to avoid
279
-
280
- 2. **`docs/training/logic_bank_api.prompt`** - Deterministic rules API
281
- - Rule.sum(), Rule.count(), Rule.formula(), Rule.constraint(), etc.
282
- - Complete API signatures with all parameters
283
- - References patterns file for implementation details
284
-
285
- 3. **`docs/training/probabilistic_logic.prompt`** - Probabilistic (AI) rules API
286
- - populate_ai_values() utility for AI-driven value computation
287
- - Intelligent selection patterns (supplier optimization, dynamic pricing, route selection)
288
- - Automatic audit trails and graceful fallbacks when API unavailable
289
- - References patterns file for general implementations
290
- - Works seamlessly with deterministic rules
291
-
292
- **Example Natural Language Logic for basic_demo:**
293
-
294
- ```text
295
- Use case: Check Credit
296
- 1. Customer balance ≤ credit limit
297
- 2. Customer balance = sum of unshipped Order amount_total
298
- 3. Order amount_total = sum of Item amount
299
- 4. Item amount = quantity × unit_price
300
- 5. Item unit_price = copied from Product unit_price
301
-
302
- Use case: App Integration
303
- 1. Send Order to Kafka when date_shipped changes to non-null
304
- ```
305
-
306
- **Why Declarative Rules Matter:**
307
-
308
- For developers: Business logic is **typically half the system** in data-centric applications. The real pain with procedural code isn't just volume (200+ lines vs 5 rules) - it's **maintenance**:
309
- - **Finding insertion points** - you must analyze existing code to figure out where new logic goes
310
- - **Automatic ordering** - add rules anywhere that makes sense, confident they'll run in the right order
311
- - **Understanding intent** - you see WHAT it does (business rules) vs HOW (procedural steps)
312
-
313
- With declarative rules, you simply state business requirements. The engine handles dependencies, ordering, and optimization automatically.
314
-
315
- LogicBank provides **44X code reduction** (5 lines vs 220+ procedural) with automatic:
316
- - **Dependency tracking** - listens to SQLAlchemy ORM events at attribute level
317
- - **Cascading updates** - when Order.customer_id changes, adjusts BOTH old and new Customer.balance
318
- - **Transitive dependencies** - Item.quantity change cascades through Item.amount → Order.amount_total → Customer.balance
319
- - **Optimized execution** - uses deltas, not re-aggregation; automatic pruning
320
-
321
- **Why the Rules Engine is a Correctness Guarantee:**
322
-
323
- The "2 critical bugs" that even AI-generated procedural code missed:
324
- 1. **Changing Order.customer_id** - procedural code failed to adjust BOTH the old and new customer balances
325
- 2. **Changing Item.product_id** - procedural code failed to re-copy the unit_price from the new product
326
-
327
- These bugs illustrate why declarative rules are **mandatory, not optional**:
328
-
329
- **Dependency Chains:** In the logic above, `Customer.balance` has transitive dependencies:
330
- - Direct: `Order.amount_total`, `Order.date_shipped`
331
- - Through Order: `Item.amount` (affects Order.amount_total)
332
- - Through Item: `Item.quantity`, `Item.unit_price` (affect Item.amount)
333
- - Through Product: `Product.unit_price` (copied to Item.unit_price)
334
-
335
- **Automatic Completeness:** The declarative rules engine:
336
- - Listens to **SQLAlchemy ORM events** at the attribute level
337
- - When `Order.customer_id` changes, **automatically adjusts both old and new customer balances**
338
- - When `Item.product_id` changes, **automatically re-copies from the new product**
339
- - Uses **dependency ordering** to fire rules in correct sequence
340
- - Applies **optimized chaining** (uses deltas, not re-aggregation)
341
-
342
- **Why Procedural Code Fails:** Even AI-generated procedural code requires explicit handlers for EVERY possible change path. It's easy to miss:
343
- - Foreign key changes affecting multiple parents
344
- - Transitive dependencies through multiple tables
345
- - Where clause conditions that include/exclude rows
346
-
347
- The rules engine eliminates this entire class of bugs by automatically handling all change paths.
348
-
349
- See `logic/declarative-vs-procedural-comparison.md` for complete analysis.
350
-
351
- ### Discovery Systems
352
-
353
- **IMPORTANT**: The project uses automated discovery systems that:
354
-
355
- **Logic Discovery:**
356
- 1. **Automatically loads business logic** from `logic/logic_discovery/*.py`
357
- * **CRITICAL: Always create separate files named for each use case** (e.g., `check_credit.py`, `app_integration.py`)
358
- * **Never put multiple use cases in `use_case.py`** - that file is for templates/examples only
359
- 2. **Discovers rules at startup** via `logic/logic_discovery/auto_discovery.py`
360
- 3. **No manual rule loading required** - the `discover_logic()` function automatically finds and registers rules
361
-
362
- **API Discovery:**
363
- 1. **Automatically loads custom APIs** from `api/api_discovery/[service_name].py`
364
- 2. **Discovers services at startup** via `api/api_discovery/auto_discovery.py` (called from `api/customize_api.py`)
365
- 3. **No manual API registration required** - services are automatically discovered and exposed
366
-
367
- **Do NOT duplicate** by calling them manually. The discovery systems handle this automatically.
368
-
369
- **Implementation Locations**:
370
- - Business rules: `logic/logic_discovery/use_case.py`
371
- - Custom APIs: `api/api_discovery/[service_name].py`
372
- - System automatically discovers and loads both
373
-
374
- **Pattern**:
375
- ```python
376
- # logic/logic_discovery/use_case.py
377
- def declare_logic():
378
- """Business logic rules for the application"""
379
- Rule.sum(derive=Customer.balance, as_sum_of=Order.amount_total)
380
- Rule.constraint(validate=Customer, as_condition=lambda row: row.balance <= row.credit_limit)
381
- # ... other rules
382
- ```
383
-
384
- **PATTERN RECOGNITION for Business Logic**:
385
- When users provide natural language with multiple use cases like:
386
- - "Use case: Check Credit" + "Use case: App Integration"
387
-
388
- **ALWAYS create separate files**:
389
- - `logic/logic_discovery/check_credit.py` - for credit checking rules
390
- - `logic/logic_discovery/app_integration.py` - for integration rules
391
-
392
- **NEVER put everything in `use_case.py`** - that defeats the discovery system purpose.
393
-
394
- ### MCP Integration
395
-
396
- **You (GitHub Copilot) can serve as an MCP client** to query and update database entities using natural language!
397
-
398
- #### MCP Discovery Endpoint (CRITICAL)
399
-
400
- **ALWAYS start with the standard MCP discovery endpoint:**
401
-
402
- ```bash
403
- curl -X GET "http://localhost:5656/.well-known/mcp.json"
404
- ```
405
-
406
- This endpoint returns:
407
- - **Available resources** - Customer, Order, Item, Product, etc.
408
- - **Supported methods** - GET, PATCH, POST, DELETE per resource
409
- - **Filterable fields** - Which attributes can be used in filters
410
- - **Base URL and paths** - Resource endpoints like `/Customer`, `/Order`
411
- - **Learning prompts** - Instructions for MCP clients (fan-out patterns, email handling, response format)
412
-
413
- **MCP Discovery Pattern:**
414
- 1. **First**: Query `/.well-known/mcp.json` to discover available resources
415
- 2. **Then**: Use discovered schema to construct API calls
416
- 3. **Always**: Follow JSON:API format for CRUD operations
417
-
418
-
419
- **When users request data operations:**
420
-
421
- 1. **Authenticate first** - Login to obtain JWT token:
422
- ```bash
423
- curl -X POST http://localhost:5656/api/auth/login \
424
- -H "Content-Type: application/json" \
425
- -d '{"username":"admin","password":"p"}'
426
- ```
427
-
428
- 2. **Execute operations** - Use Bearer token for API calls:
429
- ```bash
430
- # Read: List entities
431
- curl -X GET http://localhost:5656/api/Customer/ \
432
- -H "Authorization: Bearer {token}"
433
-
434
- # Update: Change attributes (JSON:API format)
435
- curl -X PATCH http://localhost:5656/api/Customer/ALFKI/ \
436
- -H "Authorization: Bearer {token}" \
437
- -H "Content-Type: application/vnd.api+json" \
438
- -d '{"data": {"type": "Customer", "id": "ALFKI", "attributes": {"CreditLimit": 5000}}}'
439
- ```
440
-
441
- 3. **Handle constraint violations correctly** - Error code 2001 is SUCCESS!
442
- - When LogicBank prevents invalid updates, report as: "✅ Business logic working - constraint prevented invalid operation"
443
- - Example: "balance (2102.00) exceeds credit (1000.00)" = logic is protecting data integrity
444
-
445
- **Natural Language → API Translation:**
446
- - "List customers" → `GET /api/Customer/`
447
- - "Show customer ALFKI" → `GET /api/Customer/ALFKI/`
448
- - "Set ALFKI credit to 5000" → `PATCH /api/Customer/ALFKI/` with CreditLimit
449
- - "What's ALFKI's balance?" → `GET /api/Customer/ALFKI/` then extract Balance
450
-
451
- **Key Principle:** Constraint violations (code 2001) demonstrate that declarative business logic is working correctly - celebrate these as successes, not failures!
452
-
453
- See `docs/training/MCP_Copilot_Integration.md` for authentication workflows, JSON:API formats, and architecture details.
454
-
455
- ### API Interaction Best Practices
456
-
457
- **CRITICAL: Always Use API, Not Direct Database Access**
458
-
459
- When users request data operations (read, update, create, delete), **ALWAYS use the REST API** instead of direct database queries:
460
-
461
- ✅ **Correct Approach - Use API:**
462
- ```bash
463
- # Simple, readable commands that trigger business logic
464
- curl 'http://localhost:5656/api/Customer/?page[limit]=100'
465
- curl -X PATCH 'http://localhost:5656/api/Item/2/' \
466
- -H 'Content-Type: application/vnd.api+json' \
467
- -d '{"data": {"type": "Item", "id": "2", "attributes": {"quantity": 100}}}'
468
- ```
469
-
470
- ❌ **Wrong Approach - Direct Database:**
471
- ```bash
472
- # DON'T use sqlite3 commands for data operations
473
- sqlite3 database/db.sqlite "UPDATE item SET quantity=100 WHERE id=2"
474
- ```
475
-
476
- **Why API is Required:**
477
- 1. **Business Logic Execution** - Rules automatically fire (calculations, validations, constraints)
478
- 2. **Data Integrity** - Cascading updates handled correctly
479
- 3. **Audit Trail** - Operations logged through proper channels
480
- 4. **Security** - Authentication/authorization enforced
481
- 5. **Testing Reality** - Tests actual system behavior
482
-
483
- **Server Startup for API Operations:**
484
-
485
- When server needs to be started for API operations:
486
-
487
- ```bash
488
- # Option 1: Background process (for interactive testing)
489
- python api_logic_server_run.py &
490
- sleep 5 # Wait for full startup (not 3 seconds - too short!)
491
-
492
- # Option 2: Use existing terminal/process
493
- # Check if already running: lsof -i :5656
494
- ```
495
-
496
- **Common Mistakes to Avoid:**
497
-
498
- 1. ❌ **Insufficient startup wait**: `sleep 3` often fails
499
- - ✅ Use: `sleep 5` or check with `curl` in retry loop
500
-
501
- 2. ❌ **Complex inline Python**: Piping JSON to `python3 -c` with complex list comprehensions
502
- - ✅ Use: Simple `curl` commands, pipe to `jq` for filtering, or save to file first
503
-
504
- 3. ❌ **Database queries for CRUD**: Using `sqlite3` commands
505
- - ✅ Use: API endpoints that trigger business logic
506
-
507
- **Simple API Query Patterns:**
508
-
509
- ```bash
510
- # Get all records (simple, reliable)
511
- curl 'http://localhost:5656/api/Customer/'
512
-
513
- # Get specific record by ID
514
- curl 'http://localhost:5656/api/Customer/1/'
515
-
516
- # Get related records (follow relationships)
517
- curl 'http://localhost:5656/api/Customer/1/OrderList'
518
-
519
- # Filter results (use bracket notation)
520
- curl 'http://localhost:5656/api/Customer/?filter[name]=Alice'
521
-
522
- # Limit results
523
- curl 'http://localhost:5656/api/Customer/?page[limit]=10'
524
- ```
525
-
526
- **Parsing JSON Responses:**
527
-
528
- ```bash
529
- # Simple: Pipe to python -m json.tool for pretty printing
530
- curl 'http://localhost:5656/api/Customer/' | python3 -m json.tool
531
-
532
- # Better: Use jq if available
533
- curl 'http://localhost:5656/api/Customer/' | jq '.data[] | {id, name: .attributes.name}'
534
-
535
- # Alternative: Save to file first, then parse
536
- curl 'http://localhost:5656/api/Customer/' > customers.json
537
- python3 -c "import json; data=json.load(open('customers.json')); print(data['data'][0])"
538
- ```
539
-
540
- **Key Principle**: The API is not just a convenience - it's the **only correct way** to interact with data because it ensures business logic executes properly.
541
-
542
- ### Automated Testing
543
-
544
- **⚠️ BEFORE Creating Tests:**
545
-
546
- ```
547
- STOP ✋
548
- READ docs/training/testing.md FIRST (555 lines - comprehensive guide)
549
-
550
- This contains EVERY bug pattern from achieving 11/11 test success:
551
- - Rule #0: Test Repeatability (timestamps for uniqueness)
552
- - Rule #0.5: Behave Step Ordering (specific before general)
553
- - Top 5 Critical Bugs (common AI mistakes)
554
- - Filter format: filter[column]=value (NOT OData)
555
- - No circular imports (API only)
556
- - Null-safe constraints
557
- - Fresh test data (timestamps for uniqueness)
558
-
559
- THEN create tests following patterns exactly.
560
- ```
561
-
562
- **Why This Matters:** AI-generated tests fail 80% of the time without reading this guide first. The training material documents every common mistake (circular imports, wrong filter format, null-unsafe constraints, step ordering, etc.) with exact fixes. This guide achieved 11/11 test success (100%) and contains all discovered patterns.
563
-
564
- **`docs/training/testing.md`** explains how to create Behave tests from declarative rules, execute test suites, and generate automated documentation with complete logic traceability.
565
-
566
- **Key capabilities:**
567
- - **Create tests from rules** - Analyze declarative rules to generate appropriate test scenarios
568
- - **Execute test suite** - Run all tests with one command (Launch Configuration: "Behave Run")
569
- - **Generate documentation** - Auto-create wiki reports showing requirements, tests, rules used, and execution traces
570
- - **Requirements traceability** - Complete chain from business requirement → test → declarative rule → execution log
571
-
572
- **The Innovation:** Unlike traditional testing, Behave Logic Reports show **which declarative rules fired** during each test, providing complete transparency from requirement to execution. This solves the 44X advantage in testing - tests verify "what" (business rules) not "how" (procedural code).
573
-
574
- See `test/api_logic_server_behave/` for examples and [published report](https://apilogicserver.github.io/Docs/Behave-Logic-Report/).
575
-
576
- **Common Mistakes to Avoid (from testing.md):**
577
- 1. ❌ Wrong filter: `filter="name eq 'Alice'"` → ✅ Use: `filter[name]="Alice"`
578
- 2. ❌ Importing logic/database modules → ✅ Import only: behave, requests, test_utils
579
- 3. ❌ Unsafe constraints: `row.x <= row.y` → ✅ Use: `row.x is None or row.y is None or row.x <= row.y`
580
- 4. ❌ Step execution: `step_impl.execute_step()` → ✅ Use: `context.execute_steps('when Step')`
581
- 5. ❌ Reusing test data → ✅ Create fresh with: `f"{name} {int(time.time()*1000)}"`
582
-
583
- **For detailed test creation patterns, see `docs/training/testing.md` which documents all critical rules including Rule #0.5 (Behave Step Ordering).**
584
-
585
- #### Critical Learnings: Behave Logic Report Generation
586
-
587
- **PROBLEM**: Reports not showing logic details for test scenarios.
588
-
589
- **ROOT CAUSES DISCOVERED**:
590
-
591
- 1. **Empty behave.log** (Most Common Issue)
592
- - ❌ Running: `python behave_run.py`
593
- - ✅ Must run: `python behave_run.py --outfile=logs/behave.log`
594
- - Without `--outfile`, behave.log remains empty (0 bytes) and report has no content
595
-
596
- 2. **Scenario Name Mismatch**
597
- - Log files must match scenario names from .feature file
598
- - ❌ Using custom names: `scenario_name = f'B2B Order - {quantity} {product_name}'`
599
- - ✅ Use actual scenario: `scenario_name = context.scenario.name`
600
- - Report generator truncates to 25 chars and looks for matching .log files
601
-
602
- 3. **Report Generator Logic Bug**
603
- - Original code only showed logic when blank line followed "Then" step
604
- - Only worked for ~30% of scenarios (those with blank lines in behave.log)
605
- - ✅ Fixed: Trigger logic display when next scenario starts OR at end of file
606
-
607
- **CORRECT PATTERN FOR WHEN STEPS**:
608
-
609
- ```python
610
- @when('B2B order placed for "{customer_name}" with {quantity:d} {product_name}')
611
- def step_impl(context, customer_name, quantity, product_name):
612
- """
613
- Phase 2: CREATE using OrderB2B API - Tests OrderB2B integration
614
- """
615
- scenario_name = context.scenario.name # ← CRITICAL: Use actual scenario name
616
- test_utils.prt(f'\n{scenario_name}\n', scenario_name)
617
-
618
- # ... test implementation ...
619
- ```
620
-
621
- **WORKFLOW FOR REPORT GENERATION**:
622
-
623
- ```bash
624
- # 1. Run tests WITH outfile to generate behave.log
625
- python behave_run.py --outfile=logs/behave.log
626
-
627
- # 2. Generate report (reads behave.log + scenario_logic_logs/*.log)
628
- python behave_logic_report.py run
629
-
630
- # 3. View report
631
- open reports/Behave\ Logic\ Report.md
632
- ```
633
-
634
- **WHAT THE REPORT SHOWS**:
635
- - Each scenario gets a `<details>` section with:
636
- - **Rules Used**: Which declarative rules fired (numbered list)
637
- - **Logic Log**: Complete trace showing before→after values for all adjustments
638
- - Demonstrates the 44X code reduction by showing rule automation
639
-
640
- **LOGIC LOG FORMATTING**:
641
-
642
- **When user says "show me the logic log"**: Display the complete logic execution from the most recent terminal output, showing the full trace from "Logic Phase: ROW LOGIC" through "Logic Phase: COMPLETE" with all row details intact (do NOT use grep commands to extract). Include:
643
- - Complete Logic Phase sections (ROW LOGIC, COMMIT LOGIC, AFTER_FLUSH LOGIC, COMPLETE)
644
- - All rule execution lines with full row details
645
- - "These Rules Fired" summary section
646
- - Format as code block for readability
647
-
648
- When displaying logic logs to users, format them with proper hierarchical indentation like the debug console (see https://apilogicserver.github.io/Docs/Logic-Debug/):
649
-
650
- ```
651
- Logic Phase: ROW LOGIC (session=0x...)
652
- ..Item[None] {Insert - client} id: None, order_id: 1, product_id: 6, quantity: 10
653
- ..Item[None] {Formula unit_price} unit_price: [None-->] 105.0
654
- ....SysSupplierReq[None] {Insert - Supplier AI Request} product_id: 6
655
- ....SysSupplierReq[None] {Event - calling AI} chosen_unit_price: [None-->] 105.0
656
- ..Item[None] {Formula amount} amount: [None-->] 1050.0
657
- ..Item[None] {adjust parent Order.amount_total}
658
- ....Order[1] {Update - Adjusting order: amount_total} amount_total: [300.0-->] 1350.0
659
- ```
660
-
661
- **Key formatting rules:**
662
- - `..` prefix = nesting level (2 dots = parent, 4 dots = child/nested object, 6 dots = deeper nesting)
663
- - **ONE LINE per rule execution** - no line wrapping
664
- - Each line shows: `Class[id] {action/reason} key_attributes`
665
- - Value changes shown as: `[old_value-->] new_value`
666
- - Hierarchical indentation (dots) shows call depth and parent-child relationships
667
- - Only show relevant attributes, not all row details
668
-
669
- **EXTRACTING CLEAN LOGIC LOGS**:
670
-
671
- To get properly formatted logs (one line per rule, no wrapping), use this command:
672
-
673
- ```bash
674
- # Extract clean logic log from server.log
675
- grep -A 100 "Logic Phase:.*ROW LOGIC" server.log | \
676
- awk -F' row: ' '{print $1}' | \
677
- grep -E "^\.\.|^Logic Phase:" | \
678
- head -50
679
- ```
680
-
681
- This removes verbose session/row details and prevents line wrapping.
682
-
683
- **DEBUGGING TIPS**:
684
-
685
- ```bash
686
- # Check if behave.log has content
687
- ls -lh logs/behave.log # Should be several KB, not 0 bytes
688
-
689
- # Check if scenario logs exist with correct names
690
- ls logs/scenario_logic_logs/ | head -10
691
-
692
- # Count detail sections in report (should equal number of scenarios)
693
- grep -c "<details markdown>" reports/Behave\ Logic\ Report.md
694
-
695
- # View a specific scenario's log directly
696
- cat logs/scenario_logic_logs/Delete_Item_Reduces_Order.log
697
- ```
698
-
699
- **KEY INSIGHT**: The report generator uses a two-step process:
700
- 1. Reads behave.log for scenario structure (Given/When/Then steps)
701
- 2. Matches scenario names to .log files in scenario_logic_logs/
702
- 3. Injects logic details at the right location in the report
703
-
704
- If scenario names don't match between behave.log and .log filenames, logic details won't appear!
705
-
706
- ### Adding MCP UI
707
-
708
- The API is automatically MCP-enabled. The project includes a comprehensive MCP client executor at `integration/mcp/mcp_client_executor.py`, but to enable the **user interface** for MCP requests, you must run this command:
709
-
710
- ```bash
711
- genai-logic genai-add-mcp-client
712
- ```
713
-
714
- **CRITICAL DISTINCTION**:
715
- - **`integration/mcp/mcp_client_executor.py`** = MCP processing engine (already exists)
716
- - **`genai-logic genai-add-mcp-client`** = Command to add SysMcp table and UI infrastructure (must be run)
717
-
718
- **When users ask to "Create the MCP client executor"**, they mean run the `genai-logic genai-add-mcp-client` command, NOT recreate the existing processing engine.
719
-
720
- This command adds:
721
- 1. **SysMcp table** for business users to enter natural language requests
722
- 2. **Admin App integration** for MCP request interface
723
- 3. **Database infrastructure** for MCP client operations
724
-
725
- ### Configuring Admin UI
726
-
727
- This is built when project is created - no need to add it.
728
- Customize by editing the underlying yaml.
729
-
730
- ```yaml
731
- # Edit: ui/admin/admin.yaml
732
- resources:
733
- Customer:
734
- attributes:
735
- - name: CompanyName
736
- search: true
737
- sort: true
738
- ```
739
-
740
- ### Create and Customize React Apps
741
-
742
- **REQUIRED METHOD**: Complete customization is provided by generating a React Application (requires OpenAI key, Node):
743
-
744
- **DO NOT use `create-react-app` or `npx create-react-app`**
745
- **ALWAYS use this command instead:**
746
-
747
- ```bash
748
- # Create: ui/admin/my-app-name
749
- genai-logic genai-add-app --app-name=my-app-name --vibe
750
- ```
751
-
752
- Then, `npm install` and `npm start`
753
-
754
- Temporary restriction: security must be disabled.
755
-
756
- **IMPORTANT**: When working with React apps, ALWAYS read `docs/training` first. This file contains critical data access provider configuration that was built when the project was created. The data provider handles JSON:API communication and record context - ignore this at your peril.
757
-
758
- Customize using CoPilot chat, with `docs/training`.
759
-
760
- #### React Component Development Best Practices
761
-
762
- **Critical Pattern for List/Card Views**: When implementing custom views (like card layouts) in React Admin components:
763
-
764
- 1. **Use `useListContext()` correctly**: Access `data` as an array, not as an object with `ids`
765
- ```javascript
766
- // CORRECT Pattern:
767
- const { data, isLoading } = useListContext();
768
- return (
769
- <Grid container spacing={2}>
770
- {data?.map(record => (
771
- <Grid item key={record.id}>
772
- <CustomCard record={record} />
773
- </Grid>
774
- ))}
775
- </Grid>
776
- );
777
-
778
- // AVOID: Trying to use data[id] pattern - this is for older React Admin versions
779
- ```
780
-
781
-
782
- 2. **Component Naming Consistency**: Ensure component names match their usage in JSX - mismatched names cause runtime errors.
783
-
784
- 3. **Simple Error Handling**: Use straightforward loading states rather than complex error checking:
785
- ```javascript
786
- if (isLoading) return <div>Loading...</div>;
787
- ```
788
-
789
- 4. 🃏 Card View Action Links (Show, Edit, Delete) **IMPORTANT:** All card views (e.g., Product cards) must include action links or buttons for **Show**, **Edit**, and **Delete** for each record (not just the display fields), matching the functionality of the table/list view.
790
-
791
-
792
- **Common Mistakes to Avoid**:
793
- - Using `{ data, ids }` destructuring and trying to map over `ids` - this pattern is outdated
794
- - Creating complex error handling when simple loading checks suffice
795
- - Not referencing existing working implementations before creating new patterns
796
-
797
- ### Security - Role-Based Access Control
798
-
799
- Configure:
800
- ```
801
- genai-logic add-auth --provider-type=sql --db-url=
802
- genai-logic add-auth --provider-type=sql --db_url=postgresql://postgres:p@localhost/authdb
803
-
804
- genai-logic add-auth --provider-type=keycloak --db-url=localhost
805
- genai-logic add-auth --provider-type=keycloak --db-url=hardened
806
-
807
- genai-logic add-auth --provider-type=None # to disable
808
- ```
809
-
810
- Keycloak quick start [(more information here:)](https://apilogicserver.github.io/Docs/Security-Keycloak/)
811
- ```bash
812
- cd devops/keycloak
813
- docker compose up
814
- genai-logic add-auth --provider-type=keycloak --db-url=localhost
815
- ```
816
-
817
- For more on KeyCloak: https://apilogicserver.github.io/Docs/Security-Keycloak/
818
-
819
- Declaration:
820
- ```python
821
- # Edit: security/declare_security.py
822
- Grant(on_entity=Customer, to_role=sales, filter=lambda: Customer.SalesRep == current_user())
823
- ```
824
-
825
-
826
- #### Testing with Security Enabled
827
-
828
- **CRITICAL:** When `SECURITY_ENABLED=True`, test code must obtain and include JWT authentication tokens.
829
-
830
- **Pattern for test steps:**
831
- ```python
832
- from pathlib import Path
833
- import os
834
- from dotenv import load_dotenv
835
-
836
- # Load config to check SECURITY_ENABLED
837
- config_path = Path(__file__).parent.parent.parent.parent.parent / 'config' / 'default.env'
838
- load_dotenv(config_path)
839
-
840
- # Cache for auth token (obtained once per test session)
841
- _auth_token = None
842
-
843
- def get_auth_token():
844
- """Login and get JWT token if security is enabled"""
845
- global _auth_token
846
-
847
- if _auth_token is not None:
848
- return _auth_token
849
-
850
- # Login with default admin credentials
851
- login_url = f'{BASE_URL}/api/auth/login'
852
- login_data = {'username': 'admin', 'password': 'p'}
853
-
854
- response = requests.post(login_url, json=login_data)
855
- if response.status_code == 200:
856
- _auth_token = response.json().get('access_token')
857
- return _auth_token
858
- else:
859
- raise Exception(f"Login failed: {response.status_code}")
860
-
861
- def get_headers():
862
- """Get headers including auth token if security is enabled"""
863
- security_enabled = os.getenv('SECURITY_ENABLED', 'false').lower() not in ['false', 'no']
864
-
865
- headers = {'Content-Type': 'application/json'}
866
-
867
- if security_enabled:
868
- token = get_auth_token()
869
- if token:
870
- headers['Authorization'] = f'Bearer {token}'
871
-
872
- return headers
873
-
874
- # Use in all API requests
875
- response = requests.post(url=api_url, json=data, headers=get_headers())
876
- ```
877
-
878
- **Key points:**
879
- - Tests DO NOT automatically include auth headers - you must code this pattern
880
- - Token is cached to avoid repeated logins during test session
881
- - Pattern works for both `SECURITY_ENABLED=True` and `SECURITY_ENABLED=False`
882
- - See `test/api_logic_server_behave/features/steps/order_processing_steps.py` for complete example
883
- ### Adding Custom API Endpoints
884
-
885
- For simple endpoints:
886
- ```python
887
- # Edit: api/customize_api.py
888
- @app.route('/api/custom-endpoint')
889
- def my_endpoint():
890
- return {"message": "Custom endpoint"}
891
- ```
892
-
893
- ### Creating Advanced B2B Integration APIs with Natural Language
894
-
895
- Users can create sophisticated custom API endpoints for B2B integration using natural language. The system automatically generates and discovers:
896
-
897
- 1. **Custom API Service** (`api/api_discovery/[service_name].py`) - automatically discovered by `api/api_discovery/auto_discovery.py`
898
- 2. **Row Dict Mapper** (`integration/row_dict_maps/[MapperName].py`)
899
-
900
- **Example Implementation**: This project includes a working **OrderB2B API** that demonstrates the complete pattern:
901
- - **API**: `api/api_discovery/order_b2b_service.py`
902
- - **Mapper**: `integration/row_dict_maps/OrderB2BMapper.py`
903
- - **Test Cases**: `test_requests.http` and `test_b2b_order_api.py`
904
-
905
- **Pattern Recognition**: When users describe B2B integration scenarios involving:
906
- - External partner data formats (✅ Account → Customer lookup)
907
- - Field aliasing/renaming (✅ "Name" → Product.name, "QuantityOrdered" → Item.quantity)
908
- - Nested data structures (✅ Items array handling)
909
- - Lookups and joins (✅ Customer by name, Product by name)
910
- - Data transformation (✅ External format to internal models)
911
-
912
- Generate both the API service and corresponding Row Dict Mapper following these patterns:
913
-
914
- **API Service Template** (`api/api_discovery/[service_name].py`) - Keep it concise:
915
- ```python
916
- from flask import request
917
- from safrs import jsonapi_rpc
918
- import safrs
919
- from integration.row_dict_maps.OrderB2BMapper import OrderB2BMapper
920
- import logging
921
-
922
- app_logger = logging.getLogger("api_logic_server_app")
923
-
924
- def add_service(app, api, project_dir, swagger_host: str, PORT: str, method_decorators = []):
925
- api.expose_object(OrderB2BEndPoint)
926
-
927
- class OrderB2BEndPoint(safrs.JABase):
928
- @classmethod
929
- @jsonapi_rpc(http_methods=["POST"])
930
- def OrderB2B(self, *args, **kwargs): # yaml comment => swagger description
931
- """ # yaml creates Swagger description
932
- args :
933
- data:
934
- Account: "Alice"
935
- Notes: "Rush order for Q4 promotion"
936
- Items :
937
- - Name: "Widget"
938
- QuantityOrdered: 5
939
- - Name: "Gadget"
940
- QuantityOrdered: 3
941
- ---
942
-
943
- Creates B2B orders from external partner systems with automatic lookups and business logic.
944
- Features automatic customer/product lookups by name, unit price copying,
945
- amount calculations, customer balance updates, and credit limit validation.
946
- """
947
- db = safrs.DB
948
- session = db.session
949
-
950
- try:
951
- mapper_def = OrderB2BMapper()
952
- request_dict_data = request.json["meta"]["args"]["data"]
953
-
954
- app_logger.info(f"OrderB2B: Processing order for account: {request_dict_data.get('Account')}")
955
-
956
- sql_alchemy_row = mapper_def.dict_to_row(row_dict=request_dict_data, session=session)
957
-
958
- session.add(sql_alchemy_row)
959
- session.flush() # Ensures ID is generated before accessing it
960
-
961
- order_id = sql_alchemy_row.id
962
- customer_name = sql_alchemy_row.customer.name if sql_alchemy_row.customer else "Unknown"
963
- item_count = len(sql_alchemy_row.ItemList)
964
-
965
- return {
966
- "message": "B2B Order created successfully",
967
- "order_id": order_id,
968
- "customer": customer_name,
969
- "items_count": item_count
970
- }
971
-
972
- except Exception as e:
973
- app_logger.error(f"OrderB2B: Error creating order: {str(e)}")
974
- session.rollback()
975
- return {"error": "Failed to create B2B order", "details": str(e)}, 400
976
- ```
977
-
978
- **IMPORTANT**: The project includes a working B2B integration example:
979
- - **API Endpoint**: `OrderB2BEndPoint.OrderB2B` - Creates orders from external partner format
980
- - **Error Handling**: Proper exception handling with session rollback for failed operations
981
- - **Business Logic**: Automatic inheritance of all LogicBank rules (pricing, calculations, validation)
982
- - **Testing**: Comprehensive test suite demonstrating success and error scenarios
983
- - **Documentation**: Professional Swagger docs with YAML examples using real database data
984
-
985
- When creating new B2B APIs, follow this proven pattern:
986
- - Use `session.flush()` when you need generated IDs before commit
987
- - Include proper error handling with try/catch and session.rollback()
988
- - Provide meaningful success messages with key information (ID, customer, item count)
989
- - Use YAML format in docstrings for clean Swagger documentation
990
- - Always use actual database data in examples (check with sqlite3 queries)
991
-
992
- **AI Anti-Patterns to Avoid**:
993
- - **Don't assume CRUD operations**: If user asks for "create order API", only implement POST/insert (ask if they need GET/PUT/DELETE)
994
- - **Don't add "enterprise" features** unless specifically requested:
995
- - Detailed logging/monitoring beyond basic debugging
996
- - Complex response objects with metadata
997
- - Extensive documentation/comments
998
- - HTTP status code handling beyond defaults
999
- - **Don't import unused libraries**: Skip `logging`, `jsonify`, etc. unless actually needed
1000
- - **Don't over-engineer**: Simple success messages beat complex response objects
1001
-
1002
- **Swagger Examples Must Use Real Data**:
1003
- When creating YAML docstring examples, use actual database data. Check first:
1004
- ```bash
1005
- sqlite3 database/db.sqlite "SELECT name FROM customer LIMIT 3;"
1006
- sqlite3 database/db.sqlite "SELECT name FROM product LIMIT 3;"
1007
- ```
1008
-
1009
- **Getting Sample Data for Tests**:
1010
- ```bash
1011
- # Check actual customer names
1012
- sqlite3 database/db.sqlite "SELECT name FROM customer LIMIT 5;"
1013
-
1014
- # Check actual product names
1015
- sqlite3 database/db.sqlite "SELECT name FROM product LIMIT 5;"
1016
- ```
1017
- Never assume data from other databases (like Northwind's "ALFKI") - always use the current project's actual data.
1018
-
1019
- **Row Dict Mapper Template** (`integration/row_dict_maps/[MapperName].py`):
1020
- ```python
1021
- from integration.system.RowDictMapper import RowDictMapper
1022
- from database import models
1023
-
1024
- class OrderB2BMapper(RowDictMapper):
1025
- def __init__(self):
1026
- """
1027
- B2B Order API Mapper for external partner integration.
1028
-
1029
- Maps external B2B format to internal Order/Item structure:
1030
- - 'Account' field maps to Customer lookup by name
1031
- - 'Notes' field maps directly to Order notes
1032
- - 'Items' array with 'Name' and 'QuantityOrdered' maps to Item records
1033
- """
1034
- mapper = super(OrderB2BMapper, self).__init__(
1035
- model_class=models.Order,
1036
- alias="Order",
1037
- fields=[
1038
- (models.Order.notes, "Notes"),
1039
- # customer_id will be set via parent lookup
1040
- # amount_total will be calculated by business logic
1041
- # CreatedOn will be set by business logic
1042
- ],
1043
- parent_lookups=[
1044
- (models.Customer, [(models.Customer.name, 'Account')])
1045
- ],
1046
- related=[
1047
- ItemB2BMapper()
1048
- ]
1049
- )
1050
- return mapper
1051
-
1052
- class ItemB2BMapper(RowDictMapper):
1053
- def __init__(self):
1054
- """
1055
- B2B Item Mapper for order line items.
1056
-
1057
- Maps external item format to internal Item structure:
1058
- - 'Name' field maps to Product lookup by name
1059
- - 'QuantityOrdered' maps to Item quantity
1060
- """
1061
- mapper = super(ItemB2BMapper, self).__init__(
1062
- model_class=models.Item,
1063
- alias="Items",
1064
- fields=[
1065
- (models.Item.quantity, "QuantityOrdered"),
1066
- # unit_price will be copied from product by business logic
1067
- # amount will be calculated by business logic (quantity * unit_price)
1068
- ],
1069
- parent_lookups=[
1070
- (models.Product, [(models.Product.name, 'Name')])
1071
- ],
1072
- isParent=False
1073
- )
1074
- return mapper
1075
- ```
1076
-
1077
- **Key Components for Natural Language Processing**:
1078
- - **Field Aliasing**: `(models.Table.field, "ExternalName")`
1079
- - **Parent Lookups**: `(models.ParentTable, [(models.ParentTable.lookup_field, 'ExternalKey')])`
1080
- - **Related Entities**: Nested RowDictMapper instances for child records
1081
- - **Automatic Joins**: System handles foreign key relationships automatically
1082
-
1083
- **Business Logic Integration**: All generated APIs automatically inherit the full LogicBank rule engine through the discovery systems (`logic/logic_discovery/auto_discovery.py` and `api/api_discovery/auto_discovery.py`), ensuring data integrity, calculations, and constraints without additional code. Rules are automatically loaded from `logic/logic_discovery/use_case.py` and APIs from `api/api_discovery/[service_name].py` at startup.
1084
-
1085
- **Testing B2B APIs**: The project includes comprehensive testing infrastructure:
1086
- - **REST Client Tests**: `test_requests.http` - Test directly in VS Code with REST Client extension
1087
- - **Python Test Suite**: `test_b2b_order_api.py` - Automated testing with requests library
1088
- - **Swagger UI**: `http://localhost:5656/api` - Interactive API testing and documentation
1089
- - **Sample Requests**: `sample_b2b_request.json` - Copy-paste examples for testing
1090
-
1091
- **Working Example Results**: The OrderB2B API demonstrates:
1092
- - ✅ External format mapping (Account → Customer, Name → Product)
1093
- - ✅ Automatic lookups with error handling (missing customer/product detection)
1094
- - ✅ Business logic inheritance (unit price copying, amount calculations, balance updates)
1095
- - ✅ Professional Swagger documentation with YAML examples
1096
- - ✅ Complete test coverage (success cases and error scenarios)
1097
-
1098
- ### Customize Models - Add Tables, Attributes
1099
-
1100
- To add tables / columns to the database (highly impactful - request permission):
1101
-
1102
- 1. Update `database/models.py` with new models/columns
1103
- 2. Generate and apply Alembic migration (see database/alembic/readme.md):
1104
- ```bash
1105
- cd database
1106
- alembic revision --autogenerate -m "Description of changes"
1107
- ```
1108
- 3. **CRITICAL - Edit the migration file:**
1109
- - `alembic --autogenerate` detects ALL differences between models.py and database
1110
- - Open the generated file in `database/alembic/versions/`
1111
- - **Remove ALL unwanted changes** (ALTER TABLE on existing tables)
1112
- - **Keep ONLY your intended changes** (e.g., CREATE TABLE for new audit table)
1113
- - Simplify `downgrade()` function to reverse only your changes
1114
- 4. Apply the edited migration:
1115
- ```bash
1116
- alembic upgrade head
1117
- ```
1118
- 5. Offer to update ui/admin/admin.yaml to add the new table or column to the Admin UI.
1119
-
1120
- **General Migration Notes**:
1121
- - Stop the server before running migrations to avoid database locking
1122
- - When adding new models, follow existing patterns in models.py
1123
- - Models should not contain `__bind_key__`
1124
- - USER ACTION REQUIRED: Restart server after migrations
1125
-
1126
- See: https://apilogicserver.github.io/Docs/Database-Changes/#use-alembic-to-update-database-schema-from-model
1127
-
1128
- If altering `database/models.py`, be sure to follow the patterns shown in the existing models. Note they do not contain a `__bind_key__`.
1129
-
1130
- ### Addressing `Missing Attributes` during logic loading at project startup
1131
-
1132
- First, check for misspelling (logic vs `database/models.py`), and repair.
1133
-
1134
- If there are no obvious misspellings, ask for permission to add attributes; if granted, proceed as above.
1135
-
1136
- ### Customize Models - Add Derived attributes
1137
-
1138
- Here is a sample derived attribute, `proper_salary`:
1139
-
1140
- ```python
1141
-
1142
- # add derived attribute: https://github.com/thomaxxl/safrs/blob/master/examples/demo_pythonanywhere_com.py
1143
- @add_method(models.Employee)
1144
- @jsonapi_attr
1145
- def __proper_salary__(self): # type: ignore [no-redef]
1146
- import database.models as models
1147
- import decimal
1148
- if isinstance(self, models.Employee):
1149
- rtn_value = self.Salary
1150
- if rtn_value is None:
1151
- rtn_value = decimal.Decimal('0')
1152
- rtn_value = decimal.Decimal('1.25') * rtn_value
1153
- self._proper_salary = int(rtn_value)
1154
- return self._proper_salary
1155
- else:
1156
- rtn_value = decimal.Decimal('0')
1157
- self._proper_salary = int(rtn_value)
1158
- return self._proper_salary
1159
-
1160
- @add_method(models.Employee)
1161
- @__proper_salary__.setter
1162
- def _proper_salary(self, value): # type: ignore [no-redef]
1163
- self._proper_salary = value
1164
- print(f'_proper_salary={self._proper_salary}')
1165
- pass
1166
-
1167
- models.Employee.ProperSalary = __proper_salary__
1168
-
1169
- ```
1170
-
1171
- When customizing SQLAlchemy models:
1172
-
1173
- * Don't use direct comparisons with database fields in computed properties
1174
- * Convert to Python values first using float(), int(), str()
1175
- * Use property() function instead of @jsonapi_attr for computed properties
1176
- * Always add error handling for type conversions
1177
-
1178
- ### Adding events
1179
- LogicBank rules are the preferred approach to logic, but you will sometimes need to add events. This is done in `logic/declare_logic.py` (important: the function MUST come first):
1180
-
1181
- ```python
1182
- # Example: Log email activity after SysEmail is committed
1183
-
1184
- def sys_email_after_commit(row: models.SysEmail, old_row: models.SysEmail, logic_row: LogicRow):
1185
- """
1186
- After SysEmail is committed, log 'email sent'
1187
- unless the customer has opted out
1188
- """
1189
- if not row.customer.email_opt_out:
1190
- logic_row.log(f"📧 Email sent to {row.customer.name} - Subject: {row.subject}")
1191
- else:
1192
- logic_row.log(f"🚫 Email blocked for {row.customer.name} - Customer opted out")
1193
-
1194
- Rule.commit_row_event(on_class=SysEmail, calling=sys_email_after_commit)
1195
- ```
1196
-
1197
- LogicBank event types include:
1198
- - `Rule.commit_row_event()` - fires after transaction commits
1199
- - `Rule.after_insert()` - fires after row insert
1200
- - `Rule.after_update()` - fires after row update
1201
- - `Rule.after_delete()` - fires after row delete
1202
-
1203
- All events receive `(row, old_row, logic_row)` parameters and should use `logic_row.log()` for logging.
1204
-
1205
- ## 📁 Key Directories
1206
-
1207
- - `logic/` - Business rules (declarative)
1208
- - `api/` - REST API customization
1209
- - `security/` - Authentication/authorization
1210
- - `database/` - Data models and schemas
1211
- - `ui/admin/` - Admin interface configuration
1212
- - `ui/app/` - Alternative Angular admin app
1213
-
1214
- ## 💡 Helpful Context
1215
-
1216
- - This uses Flask + SQLAlchemy + SAFRS for JSON:API
1217
- - Admin UI is React-based with automatic CRUD generation
1218
- - Business logic uses LogicBank (declarative rule engine)
1219
- - Everything is auto-generated from database introspection
1220
- - Focus on CUSTOMIZATION, not re-creation
1221
- - Use CoPilot to assist with logic translation and API generation