ApiLogicServer 16.0.2__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,1223 +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). **At scale, this means a typical 100-table enterprise system would require ~1,000 declarative rules vs. 40,000+ lines of procedural code.** More critically, those 40,000 lines would contain bugs in foreign key change handling that the rules engine prevents by construction.
316
-
317
- The engine provides automatic:
318
- - **Dependency tracking** - listens to SQLAlchemy ORM events at attribute level
319
- - **Cascading updates** - when Order.customer_id changes, adjusts BOTH old and new Customer.balance
320
- - **Transitive dependencies** - Item.quantity change cascades through Item.amount → Order.amount_total → Customer.balance
321
- - **Optimized execution** - uses deltas, not re-aggregation; automatic pruning
322
-
323
- **Why the Rules Engine is a Correctness Guarantee:**
324
-
325
- The "2 critical bugs" that even AI-generated procedural code missed:
326
- 1. **Changing Order.customer_id** - procedural code failed to adjust BOTH the old and new customer balances
327
- 2. **Changing Item.product_id** - procedural code failed to re-copy the unit_price from the new product
328
-
329
- These bugs illustrate why declarative rules are **mandatory, not optional**:
330
-
331
- **Dependency Chains:** In the logic above, `Customer.balance` has transitive dependencies:
332
- - Direct: `Order.amount_total`, `Order.date_shipped`
333
- - Through Order: `Item.amount` (affects Order.amount_total)
334
- - Through Item: `Item.quantity`, `Item.unit_price` (affect Item.amount)
335
- - Through Product: `Product.unit_price` (copied to Item.unit_price)
336
-
337
- **Automatic Completeness:** The declarative rules engine:
338
- - Listens to **SQLAlchemy ORM events** at the attribute level
339
- - When `Order.customer_id` changes, **automatically adjusts both old and new customer balances**
340
- - When `Item.product_id` changes, **automatically re-copies from the new product**
341
- - Uses **dependency ordering** to fire rules in correct sequence
342
- - Applies **optimized chaining** (uses deltas, not re-aggregation)
343
-
344
- **Why Procedural Code Fails:** Even AI-generated procedural code requires explicit handlers for EVERY possible change path. It's easy to miss:
345
- - Foreign key changes affecting multiple parents
346
- - Transitive dependencies through multiple tables
347
- - Where clause conditions that include/exclude rows
348
-
349
- The rules engine eliminates this entire class of bugs by automatically handling all change paths.
350
-
351
- See `logic/declarative-vs-procedural-comparison.md` for complete analysis.
352
-
353
- ### Discovery Systems
354
-
355
- **IMPORTANT**: The project uses automated discovery systems that:
356
-
357
- **Logic Discovery:**
358
- 1. **Automatically loads business logic** from `logic/logic_discovery/*.py`
359
- * **CRITICAL: Always create separate files named for each use case** (e.g., `check_credit.py`, `app_integration.py`)
360
- * **Never put multiple use cases in `use_case.py`** - that file is for templates/examples only
361
- 2. **Discovers rules at startup** via `logic/logic_discovery/auto_discovery.py`
362
- 3. **No manual rule loading required** - the `discover_logic()` function automatically finds and registers rules
363
-
364
- **API Discovery:**
365
- 1. **Automatically loads custom APIs** from `api/api_discovery/[service_name].py`
366
- 2. **Discovers services at startup** via `api/api_discovery/auto_discovery.py` (called from `api/customize_api.py`)
367
- 3. **No manual API registration required** - services are automatically discovered and exposed
368
-
369
- **Do NOT duplicate** by calling them manually. The discovery systems handle this automatically.
370
-
371
- **Implementation Locations**:
372
- - Business rules: `logic/logic_discovery/use_case.py`
373
- - Custom APIs: `api/api_discovery/[service_name].py`
374
- - System automatically discovers and loads both
375
-
376
- **Pattern**:
377
- ```python
378
- # logic/logic_discovery/use_case.py
379
- def declare_logic():
380
- """Business logic rules for the application"""
381
- Rule.sum(derive=Customer.balance, as_sum_of=Order.amount_total)
382
- Rule.constraint(validate=Customer, as_condition=lambda row: row.balance <= row.credit_limit)
383
- # ... other rules
384
- ```
385
-
386
- **PATTERN RECOGNITION for Business Logic**:
387
- When users provide natural language with multiple use cases like:
388
- - "Use case: Check Credit" + "Use case: App Integration"
389
-
390
- **ALWAYS create separate files**:
391
- - `logic/logic_discovery/check_credit.py` - for credit checking rules
392
- - `logic/logic_discovery/app_integration.py` - for integration rules
393
-
394
- **NEVER put everything in `use_case.py`** - that defeats the discovery system purpose.
395
-
396
- ### MCP Integration
397
-
398
- **You (GitHub Copilot) can serve as an MCP client** to query and update database entities using natural language!
399
-
400
- #### MCP Discovery Endpoint (CRITICAL)
401
-
402
- **ALWAYS start with the standard MCP discovery endpoint:**
403
-
404
- ```bash
405
- curl -X GET "http://localhost:5656/.well-known/mcp.json"
406
- ```
407
-
408
- This endpoint returns:
409
- - **Available resources** - Customer, Order, Item, Product, etc.
410
- - **Supported methods** - GET, PATCH, POST, DELETE per resource
411
- - **Filterable fields** - Which attributes can be used in filters
412
- - **Base URL and paths** - Resource endpoints like `/Customer`, `/Order`
413
- - **Learning prompts** - Instructions for MCP clients (fan-out patterns, email handling, response format)
414
-
415
- **MCP Discovery Pattern:**
416
- 1. **First**: Query `/.well-known/mcp.json` to discover available resources
417
- 2. **Then**: Use discovered schema to construct API calls
418
- 3. **Always**: Follow JSON:API format for CRUD operations
419
-
420
-
421
- **When users request data operations:**
422
-
423
- 1. **Authenticate first** - Login to obtain JWT token:
424
- ```bash
425
- curl -X POST http://localhost:5656/api/auth/login \
426
- -H "Content-Type: application/json" \
427
- -d '{"username":"admin","password":"p"}'
428
- ```
429
-
430
- 2. **Execute operations** - Use Bearer token for API calls:
431
- ```bash
432
- # Read: List entities
433
- curl -X GET http://localhost:5656/api/Customer/ \
434
- -H "Authorization: Bearer {token}"
435
-
436
- # Update: Change attributes (JSON:API format)
437
- curl -X PATCH http://localhost:5656/api/Customer/ALFKI/ \
438
- -H "Authorization: Bearer {token}" \
439
- -H "Content-Type: application/vnd.api+json" \
440
- -d '{"data": {"type": "Customer", "id": "ALFKI", "attributes": {"CreditLimit": 5000}}}'
441
- ```
442
-
443
- 3. **Handle constraint violations correctly** - Error code 2001 is SUCCESS!
444
- - When LogicBank prevents invalid updates, report as: "✅ Business logic working - constraint prevented invalid operation"
445
- - Example: "balance (2102.00) exceeds credit (1000.00)" = logic is protecting data integrity
446
-
447
- **Natural Language → API Translation:**
448
- - "List customers" → `GET /api/Customer/`
449
- - "Show customer ALFKI" → `GET /api/Customer/ALFKI/`
450
- - "Set ALFKI credit to 5000" → `PATCH /api/Customer/ALFKI/` with CreditLimit
451
- - "What's ALFKI's balance?" → `GET /api/Customer/ALFKI/` then extract Balance
452
-
453
- **Key Principle:** Constraint violations (code 2001) demonstrate that declarative business logic is working correctly - celebrate these as successes, not failures!
454
-
455
- See `docs/training/MCP_Copilot_Integration.md` for authentication workflows, JSON:API formats, and architecture details.
456
-
457
- ### API Interaction Best Practices
458
-
459
- **CRITICAL: Always Use API, Not Direct Database Access**
460
-
461
- When users request data operations (read, update, create, delete), **ALWAYS use the REST API** instead of direct database queries:
462
-
463
- ✅ **Correct Approach - Use API:**
464
- ```bash
465
- # Simple, readable commands that trigger business logic
466
- curl 'http://localhost:5656/api/Customer/?page[limit]=100'
467
- curl -X PATCH 'http://localhost:5656/api/Item/2/' \
468
- -H 'Content-Type: application/vnd.api+json' \
469
- -d '{"data": {"type": "Item", "id": "2", "attributes": {"quantity": 100}}}'
470
- ```
471
-
472
- ❌ **Wrong Approach - Direct Database:**
473
- ```bash
474
- # DON'T use sqlite3 commands for data operations
475
- sqlite3 database/db.sqlite "UPDATE item SET quantity=100 WHERE id=2"
476
- ```
477
-
478
- **Why API is Required:**
479
- 1. **Business Logic Execution** - Rules automatically fire (calculations, validations, constraints)
480
- 2. **Data Integrity** - Cascading updates handled correctly
481
- 3. **Audit Trail** - Operations logged through proper channels
482
- 4. **Security** - Authentication/authorization enforced
483
- 5. **Testing Reality** - Tests actual system behavior
484
-
485
- **Server Startup for API Operations:**
486
-
487
- When server needs to be started for API operations:
488
-
489
- ```bash
490
- # Option 1: Background process (for interactive testing)
491
- python api_logic_server_run.py &
492
- sleep 5 # Wait for full startup (not 3 seconds - too short!)
493
-
494
- # Option 2: Use existing terminal/process
495
- # Check if already running: lsof -i :5656
496
- ```
497
-
498
- **Common Mistakes to Avoid:**
499
-
500
- 1. ❌ **Insufficient startup wait**: `sleep 3` often fails
501
- - ✅ Use: `sleep 5` or check with `curl` in retry loop
502
-
503
- 2. ❌ **Complex inline Python**: Piping JSON to `python3 -c` with complex list comprehensions
504
- - ✅ Use: Simple `curl` commands, pipe to `jq` for filtering, or save to file first
505
-
506
- 3. ❌ **Database queries for CRUD**: Using `sqlite3` commands
507
- - ✅ Use: API endpoints that trigger business logic
508
-
509
- **Simple API Query Patterns:**
510
-
511
- ```bash
512
- # Get all records (simple, reliable)
513
- curl 'http://localhost:5656/api/Customer/'
514
-
515
- # Get specific record by ID
516
- curl 'http://localhost:5656/api/Customer/1/'
517
-
518
- # Get related records (follow relationships)
519
- curl 'http://localhost:5656/api/Customer/1/OrderList'
520
-
521
- # Filter results (use bracket notation)
522
- curl 'http://localhost:5656/api/Customer/?filter[name]=Alice'
523
-
524
- # Limit results
525
- curl 'http://localhost:5656/api/Customer/?page[limit]=10'
526
- ```
527
-
528
- **Parsing JSON Responses:**
529
-
530
- ```bash
531
- # Simple: Pipe to python -m json.tool for pretty printing
532
- curl 'http://localhost:5656/api/Customer/' | python3 -m json.tool
533
-
534
- # Better: Use jq if available
535
- curl 'http://localhost:5656/api/Customer/' | jq '.data[] | {id, name: .attributes.name}'
536
-
537
- # Alternative: Save to file first, then parse
538
- curl 'http://localhost:5656/api/Customer/' > customers.json
539
- python3 -c "import json; data=json.load(open('customers.json')); print(data['data'][0])"
540
- ```
541
-
542
- **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.
543
-
544
- ### Automated Testing
545
-
546
- **⚠️ BEFORE Creating Tests:**
547
-
548
- ```
549
- STOP ✋
550
- READ docs/training/testing.md FIRST (555 lines - comprehensive guide)
551
-
552
- This contains EVERY bug pattern from achieving 11/11 test success:
553
- - Rule #0: Test Repeatability (timestamps for uniqueness)
554
- - Rule #0.5: Behave Step Ordering (specific before general)
555
- - Top 5 Critical Bugs (common AI mistakes)
556
- - Filter format: filter[column]=value (NOT OData)
557
- - No circular imports (API only)
558
- - Null-safe constraints
559
- - Fresh test data (timestamps for uniqueness)
560
-
561
- THEN create tests following patterns exactly.
562
- ```
563
-
564
- **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.
565
-
566
- **`docs/training/testing.md`** explains how to create Behave tests from declarative rules, execute test suites, and generate automated documentation with complete logic traceability.
567
-
568
- **Key capabilities:**
569
- - **Create tests from rules** - Analyze declarative rules to generate appropriate test scenarios
570
- - **Execute test suite** - Run all tests with one command (Launch Configuration: "Behave Run")
571
- - **Generate documentation** - Auto-create wiki reports showing requirements, tests, rules used, and execution traces
572
- - **Requirements traceability** - Complete chain from business requirement → test → declarative rule → execution log
573
-
574
- **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).
575
-
576
- See `test/api_logic_server_behave/` for examples and [published report](https://apilogicserver.github.io/Docs/Behave-Logic-Report/).
577
-
578
- **Common Mistakes to Avoid (from testing.md):**
579
- 1. ❌ Wrong filter: `filter="name eq 'Alice'"` → ✅ Use: `filter[name]="Alice"`
580
- 2. ❌ Importing logic/database modules → ✅ Import only: behave, requests, test_utils
581
- 3. ❌ Unsafe constraints: `row.x <= row.y` → ✅ Use: `row.x is None or row.y is None or row.x <= row.y`
582
- 4. ❌ Step execution: `step_impl.execute_step()` → ✅ Use: `context.execute_steps('when Step')`
583
- 5. ❌ Reusing test data → ✅ Create fresh with: `f"{name} {int(time.time()*1000)}"`
584
-
585
- **For detailed test creation patterns, see `docs/training/testing.md` which documents all critical rules including Rule #0.5 (Behave Step Ordering).**
586
-
587
- #### Critical Learnings: Behave Logic Report Generation
588
-
589
- **PROBLEM**: Reports not showing logic details for test scenarios.
590
-
591
- **ROOT CAUSES DISCOVERED**:
592
-
593
- 1. **Empty behave.log** (Most Common Issue)
594
- - ❌ Running: `python behave_run.py`
595
- - ✅ Must run: `python behave_run.py --outfile=logs/behave.log`
596
- - Without `--outfile`, behave.log remains empty (0 bytes) and report has no content
597
-
598
- 2. **Scenario Name Mismatch**
599
- - Log files must match scenario names from .feature file
600
- - ❌ Using custom names: `scenario_name = f'B2B Order - {quantity} {product_name}'`
601
- - ✅ Use actual scenario: `scenario_name = context.scenario.name`
602
- - Report generator truncates to 25 chars and looks for matching .log files
603
-
604
- 3. **Report Generator Logic Bug**
605
- - Original code only showed logic when blank line followed "Then" step
606
- - Only worked for ~30% of scenarios (those with blank lines in behave.log)
607
- - ✅ Fixed: Trigger logic display when next scenario starts OR at end of file
608
-
609
- **CORRECT PATTERN FOR WHEN STEPS**:
610
-
611
- ```python
612
- @when('B2B order placed for "{customer_name}" with {quantity:d} {product_name}')
613
- def step_impl(context, customer_name, quantity, product_name):
614
- """
615
- Phase 2: CREATE using OrderB2B API - Tests OrderB2B integration
616
- """
617
- scenario_name = context.scenario.name # ← CRITICAL: Use actual scenario name
618
- test_utils.prt(f'\n{scenario_name}\n', scenario_name)
619
-
620
- # ... test implementation ...
621
- ```
622
-
623
- **WORKFLOW FOR REPORT GENERATION**:
624
-
625
- ```bash
626
- # 1. Run tests WITH outfile to generate behave.log
627
- python behave_run.py --outfile=logs/behave.log
628
-
629
- # 2. Generate report (reads behave.log + scenario_logic_logs/*.log)
630
- python behave_logic_report.py run
631
-
632
- # 3. View report
633
- open reports/Behave\ Logic\ Report.md
634
- ```
635
-
636
- **WHAT THE REPORT SHOWS**:
637
- - Each scenario gets a `<details>` section with:
638
- - **Rules Used**: Which declarative rules fired (numbered list)
639
- - **Logic Log**: Complete trace showing before→after values for all adjustments
640
- - Demonstrates the 44X code reduction by showing rule automation
641
-
642
- **LOGIC LOG FORMATTING**:
643
-
644
- **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:
645
- - Complete Logic Phase sections (ROW LOGIC, COMMIT LOGIC, AFTER_FLUSH LOGIC, COMPLETE)
646
- - All rule execution lines with full row details
647
- - "These Rules Fired" summary section
648
- - Format as code block for readability
649
-
650
- When displaying logic logs to users, format them with proper hierarchical indentation like the debug console (see https://apilogicserver.github.io/Docs/Logic-Debug/):
651
-
652
- ```
653
- Logic Phase: ROW LOGIC (session=0x...)
654
- ..Item[None] {Insert - client} id: None, order_id: 1, product_id: 6, quantity: 10
655
- ..Item[None] {Formula unit_price} unit_price: [None-->] 105.0
656
- ....SysSupplierReq[None] {Insert - Supplier AI Request} product_id: 6
657
- ....SysSupplierReq[None] {Event - calling AI} chosen_unit_price: [None-->] 105.0
658
- ..Item[None] {Formula amount} amount: [None-->] 1050.0
659
- ..Item[None] {adjust parent Order.amount_total}
660
- ....Order[1] {Update - Adjusting order: amount_total} amount_total: [300.0-->] 1350.0
661
- ```
662
-
663
- **Key formatting rules:**
664
- - `..` prefix = nesting level (2 dots = parent, 4 dots = child/nested object, 6 dots = deeper nesting)
665
- - **ONE LINE per rule execution** - no line wrapping
666
- - Each line shows: `Class[id] {action/reason} key_attributes`
667
- - Value changes shown as: `[old_value-->] new_value`
668
- - Hierarchical indentation (dots) shows call depth and parent-child relationships
669
- - Only show relevant attributes, not all row details
670
-
671
- **EXTRACTING CLEAN LOGIC LOGS**:
672
-
673
- To get properly formatted logs (one line per rule, no wrapping), use this command:
674
-
675
- ```bash
676
- # Extract clean logic log from server.log
677
- grep -A 100 "Logic Phase:.*ROW LOGIC" server.log | \
678
- awk -F' row: ' '{print $1}' | \
679
- grep -E "^\.\.|^Logic Phase:" | \
680
- head -50
681
- ```
682
-
683
- This removes verbose session/row details and prevents line wrapping.
684
-
685
- **DEBUGGING TIPS**:
686
-
687
- ```bash
688
- # Check if behave.log has content
689
- ls -lh logs/behave.log # Should be several KB, not 0 bytes
690
-
691
- # Check if scenario logs exist with correct names
692
- ls logs/scenario_logic_logs/ | head -10
693
-
694
- # Count detail sections in report (should equal number of scenarios)
695
- grep -c "<details markdown>" reports/Behave\ Logic\ Report.md
696
-
697
- # View a specific scenario's log directly
698
- cat logs/scenario_logic_logs/Delete_Item_Reduces_Order.log
699
- ```
700
-
701
- **KEY INSIGHT**: The report generator uses a two-step process:
702
- 1. Reads behave.log for scenario structure (Given/When/Then steps)
703
- 2. Matches scenario names to .log files in scenario_logic_logs/
704
- 3. Injects logic details at the right location in the report
705
-
706
- If scenario names don't match between behave.log and .log filenames, logic details won't appear!
707
-
708
- ### Adding MCP UI
709
-
710
- 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:
711
-
712
- ```bash
713
- genai-logic genai-add-mcp-client
714
- ```
715
-
716
- **CRITICAL DISTINCTION**:
717
- - **`integration/mcp/mcp_client_executor.py`** = MCP processing engine (already exists)
718
- - **`genai-logic genai-add-mcp-client`** = Command to add SysMcp table and UI infrastructure (must be run)
719
-
720
- **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.
721
-
722
- This command adds:
723
- 1. **SysMcp table** for business users to enter natural language requests
724
- 2. **Admin App integration** for MCP request interface
725
- 3. **Database infrastructure** for MCP client operations
726
-
727
- ### Configuring Admin UI
728
-
729
- This is built when project is created - no need to add it.
730
- Customize by editing the underlying yaml.
731
-
732
- ```yaml
733
- # Edit: ui/admin/admin.yaml
734
- resources:
735
- Customer:
736
- attributes:
737
- - name: CompanyName
738
- search: true
739
- sort: true
740
- ```
741
-
742
- ### Create and Customize React Apps
743
-
744
- **REQUIRED METHOD**: Complete customization is provided by generating a React Application (requires OpenAI key, Node):
745
-
746
- **DO NOT use `create-react-app` or `npx create-react-app`**
747
- **ALWAYS use this command instead:**
748
-
749
- ```bash
750
- # Create: ui/admin/my-app-name
751
- genai-logic genai-add-app --app-name=my-app-name --vibe
752
- ```
753
-
754
- Then, `npm install` and `npm start`
755
-
756
- Temporary restriction: security must be disabled.
757
-
758
- **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.
759
-
760
- Customize using CoPilot chat, with `docs/training`.
761
-
762
- #### React Component Development Best Practices
763
-
764
- **Critical Pattern for List/Card Views**: When implementing custom views (like card layouts) in React Admin components:
765
-
766
- 1. **Use `useListContext()` correctly**: Access `data` as an array, not as an object with `ids`
767
- ```javascript
768
- // CORRECT Pattern:
769
- const { data, isLoading } = useListContext();
770
- return (
771
- <Grid container spacing={2}>
772
- {data?.map(record => (
773
- <Grid item key={record.id}>
774
- <CustomCard record={record} />
775
- </Grid>
776
- ))}
777
- </Grid>
778
- );
779
-
780
- // AVOID: Trying to use data[id] pattern - this is for older React Admin versions
781
- ```
782
-
783
-
784
- 2. **Component Naming Consistency**: Ensure component names match their usage in JSX - mismatched names cause runtime errors.
785
-
786
- 3. **Simple Error Handling**: Use straightforward loading states rather than complex error checking:
787
- ```javascript
788
- if (isLoading) return <div>Loading...</div>;
789
- ```
790
-
791
- 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.
792
-
793
-
794
- **Common Mistakes to Avoid**:
795
- - Using `{ data, ids }` destructuring and trying to map over `ids` - this pattern is outdated
796
- - Creating complex error handling when simple loading checks suffice
797
- - Not referencing existing working implementations before creating new patterns
798
-
799
- ### Security - Role-Based Access Control
800
-
801
- Configure:
802
- ```
803
- genai-logic add-auth --provider-type=sql --db-url=
804
- genai-logic add-auth --provider-type=sql --db_url=postgresql://postgres:p@localhost/authdb
805
-
806
- genai-logic add-auth --provider-type=keycloak --db-url=localhost
807
- genai-logic add-auth --provider-type=keycloak --db-url=hardened
808
-
809
- genai-logic add-auth --provider-type=None # to disable
810
- ```
811
-
812
- Keycloak quick start [(more information here:)](https://apilogicserver.github.io/Docs/Security-Keycloak/)
813
- ```bash
814
- cd devops/keycloak
815
- docker compose up
816
- genai-logic add-auth --provider-type=keycloak --db-url=localhost
817
- ```
818
-
819
- For more on KeyCloak: https://apilogicserver.github.io/Docs/Security-Keycloak/
820
-
821
- Declaration:
822
- ```python
823
- # Edit: security/declare_security.py
824
- Grant(on_entity=Customer, to_role=sales, filter=lambda: Customer.SalesRep == current_user())
825
- ```
826
-
827
-
828
- #### Testing with Security Enabled
829
-
830
- **CRITICAL:** When `SECURITY_ENABLED=True`, test code must obtain and include JWT authentication tokens.
831
-
832
- **Pattern for test steps:**
833
- ```python
834
- from pathlib import Path
835
- import os
836
- from dotenv import load_dotenv
837
-
838
- # Load config to check SECURITY_ENABLED
839
- config_path = Path(__file__).parent.parent.parent.parent.parent / 'config' / 'default.env'
840
- load_dotenv(config_path)
841
-
842
- # Cache for auth token (obtained once per test session)
843
- _auth_token = None
844
-
845
- def get_auth_token():
846
- """Login and get JWT token if security is enabled"""
847
- global _auth_token
848
-
849
- if _auth_token is not None:
850
- return _auth_token
851
-
852
- # Login with default admin credentials
853
- login_url = f'{BASE_URL}/api/auth/login'
854
- login_data = {'username': 'admin', 'password': 'p'}
855
-
856
- response = requests.post(login_url, json=login_data)
857
- if response.status_code == 200:
858
- _auth_token = response.json().get('access_token')
859
- return _auth_token
860
- else:
861
- raise Exception(f"Login failed: {response.status_code}")
862
-
863
- def get_headers():
864
- """Get headers including auth token if security is enabled"""
865
- security_enabled = os.getenv('SECURITY_ENABLED', 'false').lower() not in ['false', 'no']
866
-
867
- headers = {'Content-Type': 'application/json'}
868
-
869
- if security_enabled:
870
- token = get_auth_token()
871
- if token:
872
- headers['Authorization'] = f'Bearer {token}'
873
-
874
- return headers
875
-
876
- # Use in all API requests
877
- response = requests.post(url=api_url, json=data, headers=get_headers())
878
- ```
879
-
880
- **Key points:**
881
- - Tests DO NOT automatically include auth headers - you must code this pattern
882
- - Token is cached to avoid repeated logins during test session
883
- - Pattern works for both `SECURITY_ENABLED=True` and `SECURITY_ENABLED=False`
884
- - See `test/api_logic_server_behave/features/steps/order_processing_steps.py` for complete example
885
- ### Adding Custom API Endpoints
886
-
887
- For simple endpoints:
888
- ```python
889
- # Edit: api/customize_api.py
890
- @app.route('/api/custom-endpoint')
891
- def my_endpoint():
892
- return {"message": "Custom endpoint"}
893
- ```
894
-
895
- ### Creating Advanced B2B Integration APIs with Natural Language
896
-
897
- Users can create sophisticated custom API endpoints for B2B integration using natural language. The system automatically generates and discovers:
898
-
899
- 1. **Custom API Service** (`api/api_discovery/[service_name].py`) - automatically discovered by `api/api_discovery/auto_discovery.py`
900
- 2. **Row Dict Mapper** (`integration/row_dict_maps/[MapperName].py`)
901
-
902
- **Example Implementation**: This project includes a working **OrderB2B API** that demonstrates the complete pattern:
903
- - **API**: `api/api_discovery/order_b2b_service.py`
904
- - **Mapper**: `integration/row_dict_maps/OrderB2BMapper.py`
905
- - **Test Cases**: `test_requests.http` and `test_b2b_order_api.py`
906
-
907
- **Pattern Recognition**: When users describe B2B integration scenarios involving:
908
- - External partner data formats (✅ Account → Customer lookup)
909
- - Field aliasing/renaming (✅ "Name" → Product.name, "QuantityOrdered" → Item.quantity)
910
- - Nested data structures (✅ Items array handling)
911
- - Lookups and joins (✅ Customer by name, Product by name)
912
- - Data transformation (✅ External format to internal models)
913
-
914
- Generate both the API service and corresponding Row Dict Mapper following these patterns:
915
-
916
- **API Service Template** (`api/api_discovery/[service_name].py`) - Keep it concise:
917
- ```python
918
- from flask import request
919
- from safrs import jsonapi_rpc
920
- import safrs
921
- from integration.row_dict_maps.OrderB2BMapper import OrderB2BMapper
922
- import logging
923
-
924
- app_logger = logging.getLogger("api_logic_server_app")
925
-
926
- def add_service(app, api, project_dir, swagger_host: str, PORT: str, method_decorators = []):
927
- api.expose_object(OrderB2BEndPoint)
928
-
929
- class OrderB2BEndPoint(safrs.JABase):
930
- @classmethod
931
- @jsonapi_rpc(http_methods=["POST"])
932
- def OrderB2B(self, *args, **kwargs): # yaml comment => swagger description
933
- """ # yaml creates Swagger description
934
- args :
935
- data:
936
- Account: "Alice"
937
- Notes: "Rush order for Q4 promotion"
938
- Items :
939
- - Name: "Widget"
940
- QuantityOrdered: 5
941
- - Name: "Gadget"
942
- QuantityOrdered: 3
943
- ---
944
-
945
- Creates B2B orders from external partner systems with automatic lookups and business logic.
946
- Features automatic customer/product lookups by name, unit price copying,
947
- amount calculations, customer balance updates, and credit limit validation.
948
- """
949
- db = safrs.DB
950
- session = db.session
951
-
952
- try:
953
- mapper_def = OrderB2BMapper()
954
- request_dict_data = request.json["meta"]["args"]["data"]
955
-
956
- app_logger.info(f"OrderB2B: Processing order for account: {request_dict_data.get('Account')}")
957
-
958
- sql_alchemy_row = mapper_def.dict_to_row(row_dict=request_dict_data, session=session)
959
-
960
- session.add(sql_alchemy_row)
961
- session.flush() # Ensures ID is generated before accessing it
962
-
963
- order_id = sql_alchemy_row.id
964
- customer_name = sql_alchemy_row.customer.name if sql_alchemy_row.customer else "Unknown"
965
- item_count = len(sql_alchemy_row.ItemList)
966
-
967
- return {
968
- "message": "B2B Order created successfully",
969
- "order_id": order_id,
970
- "customer": customer_name,
971
- "items_count": item_count
972
- }
973
-
974
- except Exception as e:
975
- app_logger.error(f"OrderB2B: Error creating order: {str(e)}")
976
- session.rollback()
977
- return {"error": "Failed to create B2B order", "details": str(e)}, 400
978
- ```
979
-
980
- **IMPORTANT**: The project includes a working B2B integration example:
981
- - **API Endpoint**: `OrderB2BEndPoint.OrderB2B` - Creates orders from external partner format
982
- - **Error Handling**: Proper exception handling with session rollback for failed operations
983
- - **Business Logic**: Automatic inheritance of all LogicBank rules (pricing, calculations, validation)
984
- - **Testing**: Comprehensive test suite demonstrating success and error scenarios
985
- - **Documentation**: Professional Swagger docs with YAML examples using real database data
986
-
987
- When creating new B2B APIs, follow this proven pattern:
988
- - Use `session.flush()` when you need generated IDs before commit
989
- - Include proper error handling with try/catch and session.rollback()
990
- - Provide meaningful success messages with key information (ID, customer, item count)
991
- - Use YAML format in docstrings for clean Swagger documentation
992
- - Always use actual database data in examples (check with sqlite3 queries)
993
-
994
- **AI Anti-Patterns to Avoid**:
995
- - **Don't assume CRUD operations**: If user asks for "create order API", only implement POST/insert (ask if they need GET/PUT/DELETE)
996
- - **Don't add "enterprise" features** unless specifically requested:
997
- - Detailed logging/monitoring beyond basic debugging
998
- - Complex response objects with metadata
999
- - Extensive documentation/comments
1000
- - HTTP status code handling beyond defaults
1001
- - **Don't import unused libraries**: Skip `logging`, `jsonify`, etc. unless actually needed
1002
- - **Don't over-engineer**: Simple success messages beat complex response objects
1003
-
1004
- **Swagger Examples Must Use Real Data**:
1005
- When creating YAML docstring examples, use actual database data. Check first:
1006
- ```bash
1007
- sqlite3 database/db.sqlite "SELECT name FROM customer LIMIT 3;"
1008
- sqlite3 database/db.sqlite "SELECT name FROM product LIMIT 3;"
1009
- ```
1010
-
1011
- **Getting Sample Data for Tests**:
1012
- ```bash
1013
- # Check actual customer names
1014
- sqlite3 database/db.sqlite "SELECT name FROM customer LIMIT 5;"
1015
-
1016
- # Check actual product names
1017
- sqlite3 database/db.sqlite "SELECT name FROM product LIMIT 5;"
1018
- ```
1019
- Never assume data from other databases (like Northwind's "ALFKI") - always use the current project's actual data.
1020
-
1021
- **Row Dict Mapper Template** (`integration/row_dict_maps/[MapperName].py`):
1022
- ```python
1023
- from integration.system.RowDictMapper import RowDictMapper
1024
- from database import models
1025
-
1026
- class OrderB2BMapper(RowDictMapper):
1027
- def __init__(self):
1028
- """
1029
- B2B Order API Mapper for external partner integration.
1030
-
1031
- Maps external B2B format to internal Order/Item structure:
1032
- - 'Account' field maps to Customer lookup by name
1033
- - 'Notes' field maps directly to Order notes
1034
- - 'Items' array with 'Name' and 'QuantityOrdered' maps to Item records
1035
- """
1036
- mapper = super(OrderB2BMapper, self).__init__(
1037
- model_class=models.Order,
1038
- alias="Order",
1039
- fields=[
1040
- (models.Order.notes, "Notes"),
1041
- # customer_id will be set via parent lookup
1042
- # amount_total will be calculated by business logic
1043
- # CreatedOn will be set by business logic
1044
- ],
1045
- parent_lookups=[
1046
- (models.Customer, [(models.Customer.name, 'Account')])
1047
- ],
1048
- related=[
1049
- ItemB2BMapper()
1050
- ]
1051
- )
1052
- return mapper
1053
-
1054
- class ItemB2BMapper(RowDictMapper):
1055
- def __init__(self):
1056
- """
1057
- B2B Item Mapper for order line items.
1058
-
1059
- Maps external item format to internal Item structure:
1060
- - 'Name' field maps to Product lookup by name
1061
- - 'QuantityOrdered' maps to Item quantity
1062
- """
1063
- mapper = super(ItemB2BMapper, self).__init__(
1064
- model_class=models.Item,
1065
- alias="Items",
1066
- fields=[
1067
- (models.Item.quantity, "QuantityOrdered"),
1068
- # unit_price will be copied from product by business logic
1069
- # amount will be calculated by business logic (quantity * unit_price)
1070
- ],
1071
- parent_lookups=[
1072
- (models.Product, [(models.Product.name, 'Name')])
1073
- ],
1074
- isParent=False
1075
- )
1076
- return mapper
1077
- ```
1078
-
1079
- **Key Components for Natural Language Processing**:
1080
- - **Field Aliasing**: `(models.Table.field, "ExternalName")`
1081
- - **Parent Lookups**: `(models.ParentTable, [(models.ParentTable.lookup_field, 'ExternalKey')])`
1082
- - **Related Entities**: Nested RowDictMapper instances for child records
1083
- - **Automatic Joins**: System handles foreign key relationships automatically
1084
-
1085
- **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.
1086
-
1087
- **Testing B2B APIs**: The project includes comprehensive testing infrastructure:
1088
- - **REST Client Tests**: `test_requests.http` - Test directly in VS Code with REST Client extension
1089
- - **Python Test Suite**: `test_b2b_order_api.py` - Automated testing with requests library
1090
- - **Swagger UI**: `http://localhost:5656/api` - Interactive API testing and documentation
1091
- - **Sample Requests**: `sample_b2b_request.json` - Copy-paste examples for testing
1092
-
1093
- **Working Example Results**: The OrderB2B API demonstrates:
1094
- - ✅ External format mapping (Account → Customer, Name → Product)
1095
- - ✅ Automatic lookups with error handling (missing customer/product detection)
1096
- - ✅ Business logic inheritance (unit price copying, amount calculations, balance updates)
1097
- - ✅ Professional Swagger documentation with YAML examples
1098
- - ✅ Complete test coverage (success cases and error scenarios)
1099
-
1100
- ### Customize Models - Add Tables, Attributes
1101
-
1102
- To add tables / columns to the database (highly impactful - request permission):
1103
-
1104
- 1. Update `database/models.py` with new models/columns
1105
- 2. Generate and apply Alembic migration (see database/alembic/readme.md):
1106
- ```bash
1107
- cd database
1108
- alembic revision --autogenerate -m "Description of changes"
1109
- ```
1110
- 3. **CRITICAL - Edit the migration file:**
1111
- - `alembic --autogenerate` detects ALL differences between models.py and database
1112
- - Open the generated file in `database/alembic/versions/`
1113
- - **Remove ALL unwanted changes** (ALTER TABLE on existing tables)
1114
- - **Keep ONLY your intended changes** (e.g., CREATE TABLE for new audit table)
1115
- - Simplify `downgrade()` function to reverse only your changes
1116
- 4. Apply the edited migration:
1117
- ```bash
1118
- alembic upgrade head
1119
- ```
1120
- 5. Offer to update ui/admin/admin.yaml to add the new table or column to the Admin UI.
1121
-
1122
- **General Migration Notes**:
1123
- - Stop the server before running migrations to avoid database locking
1124
- - When adding new models, follow existing patterns in models.py
1125
- - Models should not contain `__bind_key__`
1126
- - USER ACTION REQUIRED: Restart server after migrations
1127
-
1128
- See: https://apilogicserver.github.io/Docs/Database-Changes/#use-alembic-to-update-database-schema-from-model
1129
-
1130
- If altering `database/models.py`, be sure to follow the patterns shown in the existing models. Note they do not contain a `__bind_key__`.
1131
-
1132
- ### Addressing `Missing Attributes` during logic loading at project startup
1133
-
1134
- First, check for misspelling (logic vs `database/models.py`), and repair.
1135
-
1136
- If there are no obvious misspellings, ask for permission to add attributes; if granted, proceed as above.
1137
-
1138
- ### Customize Models - Add Derived attributes
1139
-
1140
- Here is a sample derived attribute, `proper_salary`:
1141
-
1142
- ```python
1143
-
1144
- # add derived attribute: https://github.com/thomaxxl/safrs/blob/master/examples/demo_pythonanywhere_com.py
1145
- @add_method(models.Employee)
1146
- @jsonapi_attr
1147
- def __proper_salary__(self): # type: ignore [no-redef]
1148
- import database.models as models
1149
- import decimal
1150
- if isinstance(self, models.Employee):
1151
- rtn_value = self.Salary
1152
- if rtn_value is None:
1153
- rtn_value = decimal.Decimal('0')
1154
- rtn_value = decimal.Decimal('1.25') * rtn_value
1155
- self._proper_salary = int(rtn_value)
1156
- return self._proper_salary
1157
- else:
1158
- rtn_value = decimal.Decimal('0')
1159
- self._proper_salary = int(rtn_value)
1160
- return self._proper_salary
1161
-
1162
- @add_method(models.Employee)
1163
- @__proper_salary__.setter
1164
- def _proper_salary(self, value): # type: ignore [no-redef]
1165
- self._proper_salary = value
1166
- print(f'_proper_salary={self._proper_salary}')
1167
- pass
1168
-
1169
- models.Employee.ProperSalary = __proper_salary__
1170
-
1171
- ```
1172
-
1173
- When customizing SQLAlchemy models:
1174
-
1175
- * Don't use direct comparisons with database fields in computed properties
1176
- * Convert to Python values first using float(), int(), str()
1177
- * Use property() function instead of @jsonapi_attr for computed properties
1178
- * Always add error handling for type conversions
1179
-
1180
- ### Adding events
1181
- 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):
1182
-
1183
- ```python
1184
- # Example: Log email activity after SysEmail is committed
1185
-
1186
- def sys_email_after_commit(row: models.SysEmail, old_row: models.SysEmail, logic_row: LogicRow):
1187
- """
1188
- After SysEmail is committed, log 'email sent'
1189
- unless the customer has opted out
1190
- """
1191
- if not row.customer.email_opt_out:
1192
- logic_row.log(f"📧 Email sent to {row.customer.name} - Subject: {row.subject}")
1193
- else:
1194
- logic_row.log(f"🚫 Email blocked for {row.customer.name} - Customer opted out")
1195
-
1196
- Rule.commit_row_event(on_class=SysEmail, calling=sys_email_after_commit)
1197
- ```
1198
-
1199
- LogicBank event types include:
1200
- - `Rule.commit_row_event()` - fires after transaction commits
1201
- - `Rule.after_insert()` - fires after row insert
1202
- - `Rule.after_update()` - fires after row update
1203
- - `Rule.after_delete()` - fires after row delete
1204
-
1205
- All events receive `(row, old_row, logic_row)` parameters and should use `logic_row.log()` for logging.
1206
-
1207
- ## 📁 Key Directories
1208
-
1209
- - `logic/` - Business rules (declarative)
1210
- - `api/` - REST API customization
1211
- - `security/` - Authentication/authorization
1212
- - `database/` - Data models and schemas
1213
- - `ui/admin/` - Admin interface configuration
1214
- - `ui/app/` - Alternative Angular admin app
1215
-
1216
- ## 💡 Helpful Context
1217
-
1218
- - This uses Flask + SQLAlchemy + SAFRS for JSON:API
1219
- - Admin UI is React-based with automatic CRUD generation
1220
- - Business logic uses LogicBank (declarative rule engine)
1221
- - Everything is auto-generated from database introspection
1222
- - Focus on CUSTOMIZATION, not re-creation
1223
- - Use CoPilot to assist with logic translation and API generation