sozsoft-platform/.github/instructions/ai.instructions.md
2026-03-25 08:52:55 +03:00

711 lines
18 KiB
Markdown

# Dynamic Low-Code Platform - AI Instruction and Operating Manual
## 1. Purpose
This document defines how AI should think, decide, and produce outputs for this platform.
Primary objective:
- Maximize delivery through runtime configuration.
- Minimize custom code.
- Preserve platform consistency, security, and tenant isolation.
Primary principle:
- Configuration first, code last.
---
## 2. Platform Scope
Core stack:
- Backend: C# .NET 9 + ABP 9.x
- Frontend: React 18 + DevExtreme
- Database: SQL Server (dynamic datasource support)
- Cache: Redis
- Background jobs: Hangfire + ABP Background Workers
System nature:
- Runtime configurable application engine
- Multi-tenant SaaS foundation
- Low-code / no-code first
---
## 3. Non-Negotiable Rules
1. Do not propose new custom React component/page development for standard feature requests.
2. Build new screens using platform configuration mechanisms.
3. Every proposal must include tenant and permission design.
4. Never bypass platform authorization patterns.
5. Never hardcode secrets, tenant ids, or connection strings.
Exception policy:
- Code-level React or backend development can be considered only if user explicitly requests code implementation and configuration path is insufficient.
- If exception is required, AI must explain why configuration-based options are not enough.
---
## 4. Decision Flow (Mandatory)
For every request, apply this order:
1. Dynamic configuration with existing ListForm ecosystem
2. SQL Query Manager + Custom Endpoint
3. Dynamic Service
4. Code change (last resort, justification required)
---
## 5. Architecture Guardrails
Backend (ABP):
- Respect modular boundaries.
- Prefer application services over ad-hoc endpoints.
- Keep permissions explicit and auditable.
Frontend (React + DevExtreme):
- Use existing dynamic view infrastructure.
- Keep component behavior metadata-driven.
- Preserve route, menu, and permission coherence.
Data:
- SQL-first for shaping, filtering, aggregation, reporting.
- Parameterized query patterns only.
- Ensure tenant-safe data access.
---
## 6. Dynamic Menu and Routing
- Menus are database driven.
- Routes are generated/managed dynamically.
- Each menu item should map to:
- Target component mode
- Data source or query context
- Endpoint/service target
- Permission contract
---
## 7. Dynamic List System
Driven by:
- ListForm
- ListFormFields
- ListFormCustomization (UserUiFilter, GridState, ServerJoin, ServerWhere)
- ListFormImport and ListFormImportExecute
- ListFormJsonRow operations
Capabilities:
- Dynamic columns, command column, banded columns
- Permission-aware visibility and action rendering
- Rich filtering, sorting, grouping, paging, searching
- Dynamic toolbar actions and URL/dialog/script command flows
- Lookup sources:
- StaticData
- Query
- WebService
- Cascading lookup parent-child behavior
- Dynamic validation, editor options, editor scripts
- Conditional formatting and style injection
- Grid state save/load/reset
- User filter save/apply/delete flows
- Import manager and export flows (xlsx, csv, pdf)
- SubForm integration from selected row context
- Remote operations and dynamic datasource rebinding
Supported editor types:
- dxAutocomplete
- dxCalendar
- dxCheckBox
- dxColorBox
- dxDateBox
- dxDateRangeBox
- dxDropDownBox
- dxGridBox
- dxHtmlEditor
- dxLookup
- dxNumberBox
- dxRadioGroup
- dxRangeSlider
- dxSelectBox
- dxSlider
- dxSwitch
- dxTagBox
- dxTextArea
- dxTextBox
---
## 8. Dynamic Form System
- DevExtreme Form-based runtime field generation
- Metadata-driven item groups/tabs
- Validation and conditional behavior
- CRUD integration
- Default value and runtime script handling
- Lookup-enabled field model
---
## 9. Dynamic UI Components
Supported component families:
- DataGrid
- PivotGrid
- Form
- Chart
- Scheduler
- Gantt
- TreeList / Tree view
- SubForm tabs (List, Tree, Gantt, Scheduler, Form, Chart)
- Widget Group (dashboard KPI cards)
Runtime UI capabilities:
- Per-list layout switching:
- Grid
- Pivot
- Tree
- Chart
- Gantt
- Scheduler
- Per-user layout persistence
- Lazy loading and view preloading
- Shared dynamic datasource pipeline across layouts
- Shared filter/search/deep-link behavior
- Runtime refresh and query rebind
- Runtime state lifecycle:
- Save state
- Load state
- Reset state
- Runtime import/export actions from UI flows
- Popup and fullscreen editing scenarios
- SubForm relation-aware context propagation and tab navigation
---
## 10. Dynamic Component Development Policy
Allowed approach:
- Configure and bind existing dynamic component infrastructure.
Disallowed by default:
- New custom React pages/components for normal business requirements.
If user requests custom code explicitly:
- Provide a warning that low-code path is preferred.
- Offer configuration-first alternative first.
---
## 11. Integrations
Notification channels:
- Sms
- Mail
- Rocket
- Desktop
- UiActivity
- UiToast
- WhatsApp
- Telegram
Sender module:
- Email (ABP Emailing + Amazon SES)
- SMS (ABP Sms + Posta Guvercini)
- Rocket.Chat (HTTP API)
- WhatsApp (HTTP API, template-based)
Notification routing model:
- Type + Channel routing
- Recipient targeting:
- All
- User
- Role
- OrganizationUnit
- Custom
MailQueue:
- Template-based body generation
- Attachment lifecycle
- File outputs (PDF, XLS, TXT)
- Queue execution and logging
AI workflow integration:
- n8n webhook chat endpoint
- LangChain agent flow + memory window
- Gemini chat model connector
---
## 12. Background Processing
Supported engines:
- Hangfire
- ABP Background Workers
Typical use cases:
- Scheduled SQL execution
- Notification dispatching
- Email and integration automation
---
## 13. Security and Compliance Rules
- Enforce RBAC and permission-driven visibility at all layers.
- Always include permission definitions in feature design.
- Never output real credentials, tokens, keys, or secrets.
- Use placeholders in examples.
- Maintain tenant isolation in every query and action.
---
## 14. Required AI Output Contract
For each implementation proposal, AI output must include:
1. Goal
2. Decision flow result (which step used)
3. Artifacts to configure
4. SQL/query/endpoint design (if needed)
5. Menu + route + component mapping
6. Permission and role mapping
7. Tenant isolation notes
8. Validation and test checklist
9. Rollback strategy
---
## 15. Quality Gate Checklist
Before finalizing any answer, verify all:
- No unnecessary custom code suggestion
- No forbidden React component proposal
- Tenant awareness is explicit
- Permission strategy is explicit
- Menu-route binding is explicit
- Data safety and SQL parameterization considered
- Background processing considered when async/scheduled
---
## 16. Anti-Patterns (Do Not Suggest)
- Writing controllers for flows already covered by dynamic infrastructure
- Hardcoded endpoint mapping without permission model
- Static UI screens disconnected from list/menu/route model
- Direct non-tenant-safe query patterns
- Copying secrets into examples
---
## 17. Example Request Types AI Must Handle
- Create customer list screen
- Build purchase module
- Create dashboard with charts
- Generate reporting screen
- Add approval workflow
- Add integration-triggered notification process
---
## 18. Escalation Strategy
When configuration cannot satisfy requirement:
1. Try SQL-based design
2. Try Custom Endpoint
3. Try Dynamic Service
4. Propose minimal code change with explicit justification
---
## 19. Final Rule
This platform is not a traditional code-first app.
It is a runtime configurable low-code engine.
AI must optimize for platform consistency, configurability, auditability, and safe scale.
---
## 20. Request Classification Matrix
Before proposing any solution, classify the request into one of these classes:
Class A - Pure configuration:
- Menu, route, list/form fields, validation, permissions, layout, filters
- Expected output: configuration-first plan only
Class B - Configuration + SQL:
- Reporting, complex filtering, aggregation, lookup dependencies
- Expected output: configuration + SQL + endpoint mapping
Class C - Configuration + Integration:
- Notification, sender, queue, webhook, workflow automation
- Expected output: configuration + integration contract + retry/fallback notes
Class D - Escalated code path:
- Only when A/B/C cannot satisfy requirement
- Expected output: explicit justification, minimal scope code plan, rollback plan
---
## 21. Response Playbooks
### 21.1 New Screen Playbook
1. Define business objective and actor roles.
2. Define ListForm and ListFormFields structure.
3. Define menu entry and route mapping.
4. Define permissions (R/C/U/D/E) and role mapping.
5. Define datasource and query strategy.
6. Define runtime filters, lookup, validations.
7. Define import/export and state requirements.
8. Define acceptance checklist.
### 21.2 Workflow/Approval Playbook
1. Define states and transition rules.
2. Define transition permissions by role.
3. Define transition side-effects (notification, queue, endpoint call).
4. Define audit log and failure handling.
5. Define rollback/compensation behavior.
### 21.3 Report/Dashboard Playbook
1. Define KPIs and dimensions.
2. Define SQL shaping and aggregation logic.
3. Define chart/pivot configuration.
4. Define date/tenant filters.
5. Define export needs and performance constraints.
---
## 22. Mandatory Acceptance Criteria Template
Every final proposal must include a clear, testable acceptance list:
1. Feature can be enabled via configuration.
2. Tenant boundaries are preserved.
3. Required permissions block unauthorized access.
4. Menu-route-screen path is navigable.
5. Data operations are parameterized and safe.
6. Runtime filters and state behaviors work.
7. Integration events (if any) are observable and retry-safe.
8. No unnecessary custom code introduced.
---
## 23. AI Output Templates
### 23.1 Configuration-only Output Template
1. Goal
2. Configuration artifacts
3. Menu/route mapping
4. Permission mapping
5. Validation checklist
### 23.2 Configuration + SQL Output Template
1. Goal
2. Required configuration artifacts
3. SQL design (inputs, outputs, filter parameters)
4. Endpoint/service mapping
5. Security and tenant notes
6. Validation checklist
### 23.3 Escalated Code Output Template
1. Why configuration is insufficient
2. Minimal code scope
3. Compatibility with existing dynamic architecture
4. Migration and rollback plan
5. Risk and test plan
---
## 24. Performance and Scalability Rules
- Prefer server-side filtering/sorting/paging for large datasets.
- Avoid unbounded result sets in dynamic queries.
- Use indexing-aware query patterns for reporting screens.
- Keep chart/pivot queries aggregation-focused.
- Separate interactive screen queries from heavy export queries.
- Use background jobs for long-running batch operations.
---
## 25. Observability and Audit Rules
- Log key operations at list/form/integration boundaries.
- Preserve who/when/what audit metadata for critical changes.
- Capture integration failures with retry reason and payload context.
- Keep user-facing messages simple, logs detailed.
- Ensure state changes are diagnosable for support teams.
---
## 26. Error Handling Policy
- Never expose raw secrets or internal stack details to end users.
- Return actionable, localized, user-level messages.
- Keep technical diagnostics in logs.
- For integration failures:
- Retry where safe
- Record dead-letter/failure state
- Provide manual replay strategy when needed
---
## 27. Change Management Policy
- Prefer additive changes over breaking modifications.
- Keep existing ListForm contracts backward compatible where possible.
- Document behavior changes in rollout notes.
- For destructive changes, require explicit migration path.
---
## 28. Definition of Done for AI Proposals
A proposal is complete only if all are present:
1. Decision flow step selected and justified.
2. Configuration artifacts clearly listed.
3. Permission and tenant design included.
4. Menu-route-component mapping included.
5. Validation checklist included.
6. Risk/rollback notes included.
---
## 29. Prohibited Suggestion Set
AI must not suggest:
- Quick custom React page as first solution
- Hardcoded tenant ids or environment secrets
- Direct SQL string concatenation with user input
- Endpoint exposure without permission definitions
- Bypassing platform menu-route model for business screens
---
## 30. Final Governance Statement
This manual is authoritative for AI behavior in this repository.
When in doubt, AI must choose the path that preserves:
- Low-code configurability
- Tenant safety
- Permission correctness
- Operational auditability
- Long-term maintainability
---
## 31. Seeder-Driven Low-Code Development Guide (Authoritative)
AI must learn and teach implementation flow primarily from these seed assets:
- api/src/Sozsoft.Platform.DbMigrator/Seeds/ListFormSeeder_Saas.cs
- api/src/Sozsoft.Platform.DbMigrator/Seeds/MenusData.json
- api/src/Sozsoft.Platform.DbMigrator/Seeds/PermissionsData.json
- api/src/Sozsoft.Platform.DbMigrator/Seeds/HostData.json
- api/src/Sozsoft.Platform.DbMigrator/Seeds/LanguagesData.json
If user asks "how to add a new module/screen", AI must answer with this exact operational sequence.
### 31.1 Step 1 - Create ListForm definition
Define a new `ListForm` with at least:
- `ListFormCode`, `Name`, `Title`
- `DataSourceCode`
- `SelectCommandType` + `SelectCommand`
- `KeyFieldName` + `KeyFieldDbSourceType`
- `PermissionJson` (create/read/update/delete/export/import/note)
- `EditingOptionJson` + `EditingFormJson`
- `FilterRowJson`, `HeaderFilterJson`, `SearchPanelJson`, `GroupPanelJson`
- `SelectionJson`, `ColumnOptionJson`, `PagerOptionJson`
- `InsertServiceAddress`, `UpdateServiceAddress`, `DeleteCommand`
For parent-child scenarios, define `SubFormsJson` relation mapping (ParentFieldName -> ChildFieldName, DbType).
### 31.2 Step 2 - Create ListFormFields
For each field, define runtime behavior through `ListFormField` records:
- Data binding: field name, db type, source
- UI behavior: visibility, order, width, grouping, fixed/band settings
- Editing behavior: editor type (`dxTextBox`, `dxSelectBox`, `dxNumberBox`, etc.), required, options
- Lookup behavior: data source type, display/value members, cascade rules
- Validation rules and default values
- Command/action columns where needed
AI must prioritize metadata-based field behavior instead of suggesting custom React forms.
### 31.3 Step 3 - Add menu and route mapping
From `MenusData.json` patterns, AI must define both:
- `Routes` entry:
- `key`, `path`, `componentPath`, `routeType`, `authority`
- `Menus` entry:
- `ParentCode`, `Code`, `DisplayName`, `Url`, `Icon`, `RequiredPermissionName`, `Order`
For dynamic list screens, base route pattern is:
- `/admin/list/{ListFormCode}`
AI must ensure menu URL and route path point to same screen contract.
### 31.4 Step 4 - Add permissions
From `PermissionsData.json` patterns, AI must define:
- Permission group (if missing)
- Permission definitions for feature root and actions
- Menu permission binding (`RequiredPermissionName`)
Minimum action set suggestion:
- `.Default`
- `.Create`
- `.Update`
- `.Delete`
- `.Export`
- `.Import`
- `.Note`
AI must never propose menu/route without permission contract.
### 31.5 Step 5 - Add settings/integration dependencies
From `HostData.json` patterns, AI must define required settings when feature depends on external services:
- Sender credentials and endpoints (sms/mail/whatsapp/rocket)
- AiBot integration endpoint and activation state
- Feature-specific setting keys, providers, encryption flags
If integration required and setting missing, AI must explicitly add "blocking prerequisite" note.
### 31.6 Step 6 - Data and service contract
AI must produce one of:
- Direct table/view select command
- Parameterized SQL via managed query
- Custom endpoint / dynamic service
AI must include tenant-safe filters and avoid string concatenation.
### 31.7 Step 7 - Delivery checklist
For every new low-code feature, AI output must list:
1. New `ListForm` code and purpose
2. `ListFormField` set (critical columns/editors/lookups)
3. Route record
4. Menu record
5. Permission records
6. Required settings/integrations
7. Validation and rollback notes
If this 7-item list is incomplete, proposal is not accepted.
### 31.8 AI response style for implementation requests
When user asks for a screen/module, AI must answer in this order:
1. Decision flow class (A/B/C/D)
2. Seeder-style artifacts to add (ListForm, Fields, Menu, Route, Permission, Setting)
3. If needed, SQL/endpoint contract
4. Test and rollback checklist
AI should produce practical, copy-adaptable artifact definitions and avoid abstract-only explanations.
---
## 32. Mandatory Default Behaviors (Do Not Ask Repeatedly)
The following defaults are mandatory unless user explicitly overrides them.
### 32.1 SQL Table Designer default column behavior
When user requests creating a table and only specifies business columns (for example `FullName`, `Phone`), AI must still ensure platform-standard technical columns are included by default in SQL Query Manager table design flow:
- `TenantId` (multi-tenant compatibility)
- Full audited set:
- `Id`
- `CreationTime`
- `CreatorId`
- `LastModificationTime`
- `LastModifierId`
- `IsDeleted`
- `DeletionTime`
- `DeleterId`
Rules:
- Do not require user to explicitly request these columns each time.
- If user explicitly says "no tenant" or "no audit", then respect that override.
- Primary key strategy must remain compatible with existing index/key policy.
### 32.2 Wizard menu parent fallback behavior
When creating menu via Wizard/ListForm and user does not explicitly specify parent menu:
- Do not auto-place under `Definitions` by default.
- Create (or use) a dedicated new top-level parent menu for that feature/module.
- Assign top-level menu `Order` as next available order (`max(Order) + 1`) among root menus.
- Place the generated list/menu item under this newly created parent.
Rules:
- `Definitions` can be used only when user explicitly selects it.
- Permission contract must be created/bound for both parent and child menu items.
- Route/menu consistency remains mandatory (`Url` and screen contract must match).
### 32.3 AI enforcement requirement
AI must proactively apply these defaults in:
- implementation proposals,
- code/seed changes,
- migration and wizard behavior recommendations.
If AI output omits these defaults without explicit user override, output is non-compliant.