diff --git a/README.md b/README.md index 72fcb566..ebe19338 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,109 @@ -# fiskaltrust interface documentation +# fiskaltrust Interface Documentation _Welcome to the open-source documentation of the fiskaltrust interface!_ -This repository aims to provide a detailed technical specification of the fiskaltrust data interface used by POS-Systems to interact with the fiskaltrust.Middleware, so that PosCreators can integrate the fiskaltrust.Middleware into their systems without further support in most cases. +This repository provides a comprehensive technical specification of the fiskaltrust data interface used by POS-Systems to interact with the fiskaltrust.Middleware. Our goal is to enable PosCreators to integrate the fiskaltrust.Middleware into their systems efficiently and independently. -The technical specification of the data interface described in this document provides information regarding the following areas: -1. Access to the fiskaltrust.Middleware -2. Integration into the receipt based cash register workflow -3. The data structure -4. Function structure of the interface -5. Types of communication with fiskaltrust.Middleware -6. Operating categories -Interface specification is provided by fiskaltrust.Interface NuGet package, which can be found at https://www.nuget.org/packages/fiskaltrust.interface +## Quick Links +- [Getting Started Guide](doc/general/getting-started.md) +- [POS System API](doc/general/pos-system-api.md) +- [API Reference](doc/general/api-reference.md) +- [Troubleshooting Guide](doc/general/troubleshooting.md) +- [Style Guide](doc/templates/style-guide.md) -Official PDF documents that are built from the source in this repository can be found on the [Releases page](https://github.com/fiskaltrust/interface-doc/releases). +## Documentation Structure + +### General Documentation +- Installation and Setup +- Configuration Options +- Security Guidelines +- Performance Optimization +- Testing and Certification + +### API Documentation +- [POS System API](doc/general/pos-system-api.md) + - Receipt Signing + - Journal Operations + - Configuration Management + - Error Handling +- Integration Patterns +- Authentication +- Versioning + +### Country-Specific Documentation +- [Austria (AT-RKSV)](doc/middleware-at-rksv/) +- [Germany (DE-KassenSichV)](doc/middleware-de-kassensichv/) +- [France (FR-BOI-TVA-DECL)](doc/middleware-fr-boi-tva-decl-30-10-30/) +- [Italy (IT-RT)](doc/middleware-it-registratore-telematico/) + +### Technical Reference +- API Specifications +- Data Structures +- Integration Patterns +- Error Handling +- Compliance Requirements + +## Contributing + +We welcome contributions from the community! Please follow these steps: + +1. Read our [Style Guide](doc/templates/style-guide.md) +2. Fork the repository +3. Create a feature branch +4. Make your changes +5. Submit a pull request + +### Documentation Standards +- Use clear, concise language +- Include practical examples +- Provide complete code samples +- Keep content up-to-date +- Follow the style guide + +## Building the Documentation + +### Prerequisites +- Node.js 14+ +- DocFX +- PowerShell 5.1+ + +### Build Steps +1. Clone the repository + ```bash + git clone https://github.com/fiskaltrust/interface-doc.git + ``` + +2. Install dependencies + ```bash + npm install + ``` + +3. Build the documentation + ```bash + npm run build + ``` + +### Testing Links +```bash +npm run test:links +``` + +## Support and Community + +- [GitHub Issues](https://github.com/fiskaltrust/interface-doc/issues) +- [Support Portal](https://portal.fiskaltrust.cloud) +- [Community Forum](https://forum.fiskaltrust.cloud) + +## License + +This documentation is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. + +## Version History + +| Version | Release Date | Major Changes | +|---------|--------------|---------------| +| 1.3 | 2024-01-01 | Added new country support | +| 1.2 | 2023-06-01 | Enhanced API documentation | +| 1.1 | 2023-01-01 | Initial release | ## Contributions By reviewing this README file in order to understand its structure and which tools are being used, you are contributing to improving this documentation. diff --git a/doc/general/api-reference.md b/doc/general/api-reference.md new file mode 100644 index 00000000..cdcf9696 --- /dev/null +++ b/doc/general/api-reference.md @@ -0,0 +1,66 @@ +--- +slug: /api-reference +title: API Reference +--- + +# API Reference + +## Available APIs + +### [POS System API](./pos-system-api.md) +The POS System API is the central entry point to the fiskaltrust.Middleware. It provides: +- Receipt signing and fiscalization +- Journal operations +- Configuration management +- Error handling + +[Learn more about the POS System API](./pos-system-api.md) + +## API Overview + +### Authentication +All APIs require proper authentication using: +- CashBoxId +- AccessToken + +### Versioning +Our APIs follow semantic versioning: +- Major version changes (v1 -> v2) include breaking changes +- Minor version changes (v2.1 -> v2.2) are backward compatible +- Latest version is used by default +- Explicit version can be specified in URL + +### Common Headers +| Header | Required | Description | +|--------|----------|-------------| +| x-operation-id | Yes | Idempotency key | +| Authorization | Yes | Bearer token | +| Content-Type | Yes | application/json | + +### Error Handling +All APIs use standard HTTP status codes and return detailed error messages: +```json +{ + "error": "error_code", + "message": "Human readable message", + "details": { + "field": "Specific field with error", + "reason": "Detailed explanation" + } +} +``` + +## Integration Support + +### SDKs +- [.NET SDK](https://github.com/fiskaltrust/middleware-interface-dotnet) +- [Java SDK](https://github.com/fiskaltrust/middleware-interface-java) +- [Node.js SDK](https://github.com/fiskaltrust/middleware-interface-nodejs) + +### Sample Code +Find implementation examples in our [samples repository](https://github.com/fiskaltrust/middleware-demo). + +## Need Help? +- [API Documentation](https://docs.fiskaltrust.cloud) +- [Support Portal](https://portal.fiskaltrust.cloud) +- [GitHub Issues](https://github.com/fiskaltrust/interface-doc/issues) \ No newline at end of file diff --git a/doc/general/getting-started.md b/doc/general/getting-started.md new file mode 100644 index 00000000..70b20494 --- /dev/null +++ b/doc/general/getting-started.md @@ -0,0 +1,180 @@ +--- +slug: /getting-started +title: Getting Started with fiskaltrust +--- + +# Getting Started with fiskaltrust + +Welcome to fiskaltrust! This guide will help you get started with integrating our solutions into your point-of-sale system. + +## Quick Start Guide + +### 1. Prerequisites +Before you begin, ensure you have: +- A fiskaltrust account +- Your POS system requirements documented +- Development environment setup +- Required certificates (if applicable for your country) + +### 2. Choose Your Integration Path +fiskaltrust offers multiple integration options: + +#### REST API +Best for: +- Web-based POS systems +- Cross-platform applications +- Modern architecture + +#### SOAP +Best for: +- Legacy systems +- Windows-based applications +- Systems requiring WS-* standards + +#### gRPC +Best for: +- High-performance requirements +- Bi-directional streaming +- Modern microservices + +### 3. Basic Implementation Steps + +1. **Install the Middleware** + ```powershell + # Windows installation example + ./fiskaltrust-middleware-setup.exe --mode=install + ``` + +2. **Configure Your Environment** + ```json + { + "cashboxid": "your-cashbox-id", + "accesstoken": "your-access-token", + "endpoint": "your-endpoint" + } + ``` + +3. **Test Your Connection** + ```csharp + // C# example + var client = new FiskaltrustClient(configuration); + var response = await client.Echo("test"); + ``` + +### 4. First Receipt +Here's a minimal example of creating your first receipt: + +```csharp +var request = new ReceiptRequest +{ + ftCashBoxID = "your-cashbox-id", + ftPosSystemId = "your-pos-id", + cbTerminalID = "your-terminal-id", + cbReceiptReference = "receipt-001", + cbReceiptMoment = DateTime.UtcNow, + ftReceiptCase = 0x4445000000000001, + cbPayItems = new[] + { + new PayItem + { + Quantity = 1.0m, + Description = "Test Item", + Amount = 10.00m, + VATRate = 19.00m + } + } +}; + +var response = await client.Sign(request); +``` + +## Next Steps + +After completing the basic setup, explore these topics: + +1. [Detailed Configuration Guide](./configuration.md) +2. [Security Best Practices](./security.md) +3. [Testing and Certification](./testing.md) +4. [Country-Specific Requirements](./country-requirements.md) + +## Common Integration Patterns + +### Queue-based Processing +```csharp +// Example of queue-based receipt processing +public async Task ProcessReceiptQueue() +{ + while (await _queue.HasItems()) + { + var receipt = await _queue.Dequeue(); + await _client.Sign(receipt); + } +} +``` + +### Error Handling +```csharp +try +{ + var response = await client.Sign(request); +} +catch (FiskaltrustException ex) +{ + // Handle fiskaltrust-specific errors + Logger.Error($"Fiskaltrust error: {ex.Message}"); +} +catch (Exception ex) +{ + // Handle general errors + Logger.Error($"General error: {ex.Message}"); +} +``` + +## Troubleshooting + +### Common Issues +1. Connection Problems + - Check network connectivity + - Verify endpoint configuration + - Validate credentials + +2. Signing Errors + - Verify receipt format + - Check required fields + - Validate amounts and calculations + +### Getting Help +- [Documentation](https://docs.fiskaltrust.cloud) +- [Support Portal](https://support.fiskaltrust.cloud) +- [GitHub Issues](https://github.com/fiskaltrust/interface-doc/issues) + +## Best Practices + +1. **Performance** + - Implement proper queuing + - Use connection pooling + - Cache when appropriate + +2. **Security** + - Secure credential storage + - Regular updates + - Audit logging + +3. **Reliability** + - Implement retry logic + - Handle offline scenarios + - Regular backups + +## Version Compatibility + +| Middleware Version | Features | Supported Until | +|-------------------|----------|-----------------| +| 1.3.x | Basic | 2024-12-31 | +| 1.2.x | Legacy | 2023-12-31 | + +## Need Help? + +If you need assistance: +1. Check our [FAQ](./faq.md) +2. Search [existing issues](https://github.com/fiskaltrust/interface-doc/issues) +3. Contact [support](mailto:support@fiskaltrust.cloud) \ No newline at end of file diff --git a/doc/general/pos-system-api.md b/doc/general/pos-system-api.md new file mode 100644 index 00000000..4399a650 --- /dev/null +++ b/doc/general/pos-system-api.md @@ -0,0 +1,1488 @@ +--- +slug: /pos-system-api +title: POS System API Documentation v2.1 +--- + +# POS System API Documentation + +## Overview + +The POS System API (v2.1) is the central entry point to the fiskaltrust.Middleware, providing: +- Receipt fiscalization (signing) +- Payment processing +- Digital receipt handling +- Data export capabilities + +## API Design Principles + +The POS System API follows these key principles: +- **Idempotent Operations**: Each call is safe to replay using operation IDs +- **Stateful Processing**: Processes are handled as state machines +- **Frictionless Execution**: Optimized for reliable transaction processing + +## Authentication + +The API requires CashBox credentials from the fiskaltrust.Portal: +- `CashBoxId` (UUID) +- `AccessToken` + +These credentials can be found on the CashBox Configuration page in the portal. + +## Common Headers + +| Header | Required | Description | +|--------|----------|-------------| +| x-operation-id | Yes | UUID for idempotency key | +| x-operation-lifetime | No | Operation timeout in milliseconds (default: 15000) | +| x-terminal-id | No | Terminal identifier | +| x-possystem-id | No | POS system identifier | +| x-cashbox-id | Yes | CashBox identification | +| x-cashbox-accesstoken | Yes | CashBox authentication token | + +## Data Models + +### Receipt Request + +The main data structure for sending receipt data to the middleware: + +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "1234", + "cbReceiptMoment": "2024-03-29T10:15:00.000Z", + "ftReceiptCase": "0x4954200000000001", + "cbChargeItems": [ + { + "Quantity": 2.0, + "Description": "Product A", + "Amount": 122.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + } + ], + "cbPayItems": [ + { + "Quantity": 1.0, + "Description": "Cash", + "Amount": 122.00, + "ftPayItemCase": "0x495420000000001" + } + ] +} +``` + +Required fields: +- `cbReceiptReference`: Unique receipt identifier +- `cbReceiptMoment`: UTC timestamp +- `cbChargeItems`: Array of charge items +- `cbPayItems`: Array of payment items + +### Charge Item + +Represents a product or service line item: + +```json +{ + "Quantity": 1.0, + "Description": "Product description", + "Amount": 100.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301", + "ProductNumber": "SKU123", + "Unit": "pcs", + "UnitPrice": 100.00 +} +``` + +Required fields: +- `Quantity`: Number of items +- `Description`: Item description +- `Amount`: Total amount +- `VATRate`: VAT rate percentage + +### Pay Item + +Represents a payment line item: + +```json +{ + "Quantity": 1.0, + "Description": "Payment method", + "Amount": 100.00, + "ftPayItemCase": "0x495420000000001", + "MoneyNumber": "TRANS123" +} +``` + +Required fields: +- `Description`: Payment method description +- `Amount`: Payment amount + +### Receipt Response + +The middleware's response containing signature data: + +```json +{ + "ftQueueID": "UUID", + "ftQueueItemID": "UUID", + "ftCashBoxIdentification": "IT-SCU-1234567", + "ftReceiptIdentification": "ft1234567890", + "ftReceiptMoment": "2024-03-29T10:15:00.000Z", + "ftSignatures": [ + { + "ftSignatureFormat": "0x4954200000000001", + "ftSignatureType": "0x4954200000000001", + "Caption": "RT Device", + "Data": "RT-12345678" + } + ], + "ftState": "0x4954200000000000" +} +``` + +Required fields: +- `ftQueueId`: Queue identifier +- `ftQueueItemId`: Queue item identifier +- `ftCashBoxIdentification`: Cash register identifier +- `ftReceiptIdentification`: Receipt number +- `ftReceiptMoment`: Processing timestamp +- `ftSignatures`: Array of signatures +- `ftState`: Processing state + +## Endpoints + +### Sign Receipt + +```http +POST /v2/sign +Content-Type: application/json +x-operation-id: ea4279ee-8684-412f-b8eb-32b5dea52811 +``` + +Signs (fiscalizes) a receipt through the middleware. + +### Journal + +```http +GET /v2/journal/{queueId}/{type} +``` + +Retrieves journal entries by type: +- `ReceiptJournal`: Processed receipts +- `ActionJournal`: System events +- `QueueItem`: Queue items + +### Configuration + +```http +POST /v2/configuration +``` + +Manages terminal configuration and pairing. + +## Response Status Codes + +| Code | Description | +|------|-------------| +| 200 | Operation successful | +| 201 | Created successfully | +| 400 | Invalid request | +| 401 | Authentication failed | +| 422 | Duplicate operation ID | +| 500 | Server error | + +## Environments + +### Production +``` +https://possystem-api.fiskaltrust.eu/v2 +``` + +### Sandbox +``` +https://possystem-api-sandbox.fiskaltrust.eu/v2 +``` + +## Best Practices + +1. **Idempotency** + - Always include unique `x-operation-id` header + - Reuse same operation ID for retries + - Handle 422 status for duplicate operations + +2. **Performance** + - Use batch operations where possible + - Implement proper error handling + - Monitor response times + +3. **Security** + - Store credentials securely + - Use HTTPS for all requests + - Rotate access tokens periodically + +## Support + +- Technical Support: support@fiskaltrust.cloud +- API Documentation: https://docs.fiskaltrust.eu/apis/pos-system-api +- GitHub Issues: https://github.com/fiskaltrust/interface-doc/issues + +## Additional Resources + +- [API Documentation](https://docs.fiskaltrust.eu/apis/pos-system-api) +- [OpenAPI Specification](https://docs.fiskaltrust.cloud/downloads/apis/pos-system-api.yaml) +- [Support](https://support.fiskaltrust.cloud) + +## Testing + +### Sandbox Environment +``` +https://possystem-api-sandbox.fiskaltrust.eu/v2 +``` + +### Production Environment +``` +https://possystem-api.fiskaltrust.eu/v2 +``` + +### Test Scenarios +1. Basic receipt signing +2. Error handling +3. Timeout scenarios +4. Network interruptions + +## Common Use Cases + +### 1. Standard Sales Receipt +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "SALE-1234", + "cbReceiptMoment": "2024-03-29T10:15:00.000Z", + "ftReceiptCase": "0x4954200000000001", + "cbChargeItems": [ + { + "Quantity": 2.0, + "Description": "Product A", + "Amount": 122.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301", + "ProductNumber": "SKU123" + }, + { + "Quantity": 1.0, + "Description": "Service B", + "Amount": 50.00, + "VATRate": 10.00, + "ftChargeItemCase": "0x495420000000102" + } + ], + "cbPayItems": [ + { + "Quantity": 1.0, + "Description": "Cash", + "Amount": 172.00, + "ftPayItemCase": "0x495420000000001" + } + ] +} +``` + +### 2. Mixed Payment Methods +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "MIXED-1235", + "cbReceiptMoment": "2024-03-29T10:20:00.000Z", + "ftReceiptCase": "0x4954200000000001", + "cbChargeItems": [ + { + "Quantity": 1.0, + "Description": "High-value Item", + "Amount": 1000.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + } + ], + "cbPayItems": [ + { + "Description": "Cash", + "Amount": 500.00, + "ftPayItemCase": "0x495420000000001" + }, + { + "Description": "Credit Card", + "Amount": 500.00, + "ftPayItemCase": "0x495420000000005", + "ftPayItemCaseData": { + "Provider": { + "Protocol": "worldline_wpi_2", + "Action": "payment", + "ProtocolVersion": "2.0" + } + } + } + ] +} +``` + +### 3. B2B Invoice with Customer Data +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "INV-1236", + "cbReceiptMoment": "2024-03-29T10:25:00.000Z", + "ftReceiptCase": "0x4954200000201002", + "cbCustomer": { + "Name": "ACME Corp", + "Address": "Via Roma 123, 00184 Roma RM", + "VATId": "IT12345678901" + }, + "cbChargeItems": [ + { + "Quantity": 10.0, + "Description": "Enterprise License", + "Amount": 1000.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000302", + "ProductNumber": "LIC-ENT-001" + } + ], + "cbPayItems": [ + { + "Description": "Bank Transfer", + "Amount": 1000.00, + "ftPayItemCase": "0x49542000000000A" + } + ] +} +``` + +### 4. Refund Receipt +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "REF-1237", + "cbReceiptMoment": "2024-03-29T10:30:00.000Z", + "ftReceiptCase": "0x4954200000100001", + "cbPreviousReceiptReference": "SALE-1234", + "cbChargeItems": [ + { + "Quantity": -1.0, + "Description": "Product A Return", + "Amount": -61.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + } + ], + "cbPayItems": [ + { + "Description": "Cash Refund", + "Amount": -61.00, + "ftPayItemCase": "0x495420000000001" + } + ] +} +``` + +## Payment Protocols + +### Available Payment Protocols + +| Protocol | Description | Supported Actions | +|----------|-------------|------------------| +| bluecode | Mobile payment via Bluecode | payment, cancel, refund | +| hobex_zvt | Card terminal via ZVT | payment, cancel, refund, pre_authorization | +| hobex_restapi | Direct REST API integration | payment, cancel, refund, pre_authorization | +| payone_softpos_wpi | SoftPOS integration | payment, cancel, refund | +| worldline_wpi_2 | Worldline Payment Interface | payment, cancel, refund | + +### Payment Protocol Examples + +#### 1. Card Payment (hobex_zvt) +```json +{ + "Protocol": "hobex_zvt", + "Action": "payment", + "cbPayItem": { + "Description": "Card Payment", + "Amount": 100.00, + "ftPayItemCase": "0x495420000000005", + "ftPayItemCaseData": { + "Provider": { + "ProtocolRequest": { + "TerminalId": "12345678", + "PrinterFlag": 1 + } + } + } + } +} +``` + +#### 2. Mobile Payment (bluecode) +```json +{ + "Protocol": "bluecode", + "Action": "payment", + "cbPayItem": { + "Description": "Bluecode Payment", + "Amount": 50.00, + "ftPayItemCase": "0x495420000000007", + "ftPayItemCaseData": { + "Token": "BC123456789", + "Provider": { + "ProtocolRequest": { + "MerchantId": "MERCHANT123" + } + } + } + } +} +``` + +## Error Handling + +### Common Error Scenarios + +1. **Device Not Reachable** +```json +{ + "error": "device_not_reachable", + "message": "RT device is not responding", + "details": { + "deviceId": "RT-12345", + "lastContact": "2024-03-29T10:00:00Z" + } +} +``` + +2. **Invalid Receipt Format** +```json +{ + "error": "validation_error", + "message": "Receipt validation failed", + "details": { + "field": "cbChargeItems", + "reason": "Total amount mismatch with payment items" + } +} +``` + +3. **Payment Protocol Error** +```json +{ + "error": "payment_error", + "message": "Payment processing failed", + "details": { + "protocol": "hobex_zvt", + "errorCode": "CARD_DECLINED", + "terminalId": "12345678" + } +} +``` + +### Error Recovery Strategies + +1. **Device Connection Issues** + - Retry with exponential backoff + - Maximum 3 retries + - Use same operation ID for retries + - Check device status before retrying + +2. **Payment Processing Issues** + - Check payment status before retrying + - Use payment reversal if needed + - Maintain transaction log + - Implement reconciliation process + +3. **Data Validation Issues** + - Validate data before sending + - Check amount calculations + - Verify VAT rates + - Ensure unique receipt references + +## Best Practices + +### 1. Receipt Processing +- Generate unique receipt references +- Include all required fields +- Validate amounts before sending +- Handle special characters in descriptions +- Use correct VAT rates and cases + +### 2. Payment Integration +- Implement proper error handling +- Support payment reversals +- Handle timeout scenarios +- Maintain payment logs +- Implement reconciliation + +### 3. Security +- Secure credential storage +- Regular token rotation +- TLS 1.2 or higher +- IP whitelisting +- Request signing + +### 4. Performance +- Batch operations when possible +- Implement caching +- Monitor response times +- Handle rate limits +- Optimize payload size + +## Support Resources + +### Documentation +- [API Reference](https://docs.fiskaltrust.eu/apis/pos-system-api) +- [Integration Guide](https://docs.fiskaltrust.eu/docs/poscreators/getting-started) +- [Security Guidelines](https://docs.fiskaltrust.eu/docs/poscreators/security) + +### Tools +- [Postman Collection](https://docs.fiskaltrust.eu/downloads/postman) +- [Test Environment](https://sandbox.fiskaltrust.eu) +- [Middleware Configurator](https://portal.fiskaltrust.eu) + +### Support Channels +- Technical Support: support@fiskaltrust.cloud +- API Questions: api@fiskaltrust.cloud +- Security Issues: security@fiskaltrust.cloud + +## Advanced Use Cases + +### 1. Daily Closing Receipt +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "CLOSE-1238", + "cbReceiptMoment": "2024-03-29T23:59:59.000Z", + "ftReceiptCase": "0x4954200000000003", + "cbChargeItems": [ + { + "Description": "Daily Total", + "Amount": 5000.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + }, + { + "Description": "Daily Total Reduced", + "Amount": 1000.00, + "VATRate": 10.00, + "ftChargeItemCase": "0x495420000000102" + } + ], + "cbPayItems": [ + { + "Description": "Cash Total", + "Amount": 3000.00, + "ftPayItemCase": "0x495420000000001" + }, + { + "Description": "Card Total", + "Amount": 3000.00, + "ftPayItemCase": "0x495420000000005" + } + ] +} +``` + +### 2. Training Mode Receipt +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "TRAIN-1239", + "cbReceiptMoment": "2024-03-29T14:30:00.000Z", + "ftReceiptCase": "0x4954200000000010", + "cbChargeItems": [ + { + "Quantity": 1.0, + "Description": "Training Item", + "Amount": 100.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + } + ], + "cbPayItems": [ + { + "Description": "Training Payment", + "Amount": 100.00, + "ftPayItemCase": "0x495420000000001" + } + ] +} +``` + +### 3. Pre-Authorization Flow +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "AUTH-1240", + "cbReceiptMoment": "2024-03-29T15:00:00.000Z", + "ftReceiptCase": "0x4954200000000020", + "cbChargeItems": [ + { + "Description": "Hotel Stay Deposit", + "Amount": 500.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + } + ], + "cbPayItems": [ + { + "Description": "Card Pre-Authorization", + "Amount": 500.00, + "ftPayItemCase": "0x495420000000005", + "ftPayItemCaseData": { + "Provider": { + "Protocol": "hobex_zvt", + "Action": "pre_authorization", + "ProtocolVersion": "1.0" + } + } + } + ] +} +``` + +## Implementation Guidelines + +### 1. Queue Management +- Implement persistent storage for queued items +- Monitor queue length and processing time +- Handle queue overflow scenarios +- Implement retry mechanism with backoff + +### 2. Receipt Lifecycle +1. **Receipt Creation** + - Generate unique reference + - Validate business rules + - Calculate totals + +2. **Processing** + - Send to middleware + - Handle responses + - Store signatures + +3. **Archival** + - Store receipt data + - Backup signatures + - Maintain audit trail + +### 3. Error Recovery Patterns + +#### Network Issues +```javascript +async function sendReceiptWithRetry(receipt, maxRetries = 3) { + let attempt = 0; + const operationId = generateUUID(); + + while (attempt < maxRetries) { + try { + const response = await sendReceipt(receipt, operationId); + return response; + } catch (error) { + if (error.status === 422) { + // Duplicate operation, check status + const status = await checkReceiptStatus(operationId); + if (status.completed) return status; + } + + attempt++; + if (attempt < maxRetries) { + await wait(Math.pow(2, attempt) * 1000); // Exponential backoff + } + } + } + throw new Error('Max retries exceeded'); +} +``` + +#### Device Recovery +```javascript +async function handleDeviceFailure(error) { + if (error.code === 'device_not_reachable') { + // 1. Log incident + await logDeviceIssue(error); + + // 2. Check device status + const status = await checkDeviceStatus(); + + // 3. Attempt recovery + if (status.needsReboot) { + await initiateDeviceReboot(); + await waitForDeviceOnline(); + } + + // 4. Verify recovery + const health = await checkDeviceHealth(); + return health.isHealthy; + } + throw error; +} +``` + +### 4. Performance Optimization + +#### Batch Processing +```javascript +async function processBatchReceipts(receipts) { + // 1. Group by receipt type + const groups = groupReceiptsByType(receipts); + + // 2. Process in parallel with limits + const results = await Promise.all( + Object.entries(groups).map(([type, items]) => + processReceiptGroup(type, items, { + maxConcurrent: 5, + intervalMs: 100 + }) + ) + ); + + return results.flat(); +} +``` + +#### Caching Strategy +```javascript +class ReceiptCache { + constructor() { + this.cache = new Map(); + this.ttl = 3600000; // 1 hour + } + + async getReceipt(reference) { + const cached = this.cache.get(reference); + if (cached && Date.now() - cached.timestamp < this.ttl) { + return cached.data; + } + + const receipt = await fetchReceipt(reference); + this.cache.set(reference, { + data: receipt, + timestamp: Date.now() + }); + + return receipt; + } +} +``` + +## Security Guidelines + +### 1. Credential Management +```javascript +class CredentialManager { + constructor() { + this.keyStore = new SecureKeyStore(); + } + + async rotateAccessToken() { + const currentToken = await this.keyStore.getAccessToken(); + const newToken = await requestNewToken(currentToken); + await this.keyStore.setAccessToken(newToken); + return newToken; + } + + async getEncryptedCredentials() { + const credentials = await this.keyStore.getCredentials(); + return encryptCredentials(credentials); + } +} +``` + +### 2. Request Signing +```javascript +async function signRequest(request) { + const timestamp = new Date().toISOString(); + const payload = `${request.method}${request.path}${timestamp}`; + const signature = await generateHMAC(payload, getSecretKey()); + + return { + ...request, + headers: { + ...request.headers, + 'x-request-signature': signature, + 'x-request-timestamp': timestamp + } + }; +} +``` + +## Monitoring and Logging + +### 1. Health Checks +```javascript +async function performHealthCheck() { + const checks = [ + checkMiddlewareConnection(), + checkDeviceStatus(), + checkQueueHealth(), + checkDatabaseConnection() + ]; + + const results = await Promise.all(checks); + return { + healthy: results.every(r => r.status === 'healthy'), + details: results + }; +} +``` + +### 2. Audit Logging +```javascript +class AuditLogger { + async logOperation(operation) { + const entry = { + timestamp: new Date().toISOString(), + operationId: operation.id, + type: operation.type, + user: operation.user, + details: operation.details, + status: operation.status + }; + + await this.store.save(entry); + await this.notifyMonitoring(entry); + } +} +``` + +## Italian Fiscal Requirements + +### Receipt Types (ftReceiptCase) + +| Receipt Case | Value | Description | RT Signature Required | +|-------------|-------|-------------|----------------------| +| `0x4954200000000001` | POS Receipt | Standard point-of-sale receipt | Yes | +| `0x4954200000000003` | Daily Closing | End-of-day closing receipt (Chiusura giornaliera) | Yes | +| `0x4954200000000010` | Training Mode | Training/demo mode receipt | No | +| `0x4954200000100001` | Void/Refund | Void or refund receipt (Reso) | Yes | +| `0x4954200000201002` | Invoice | Electronic invoice (Fattura elettronica) | Yes | +| `0x4954200000000020` | Pre-Authorization | Payment pre-authorization | No | + +### VAT Rates and Nature Codes + +| VAT Rate | Nature Code | Description | ftChargeItemCase | +|----------|-------------|-------------|------------------| +| 22% | - | Standard rate | `0x495420000000301` | +| 10% | - | Reduced rate | `0x495420000000102` | +| 5% | - | Super-reduced rate | `0x495420000000101` | +| 4% | - | Special reduced rate | `0x495420000000100` | +| 0% | N1 | Excluded Art. 15 | `0x495420000000401` | +| 0% | N2 | Not subject | `0x495420000000402` | +| 0% | N3 | Not taxable | `0x495420000000403` | +| 0% | N4 | Exempt | `0x495420000000404` | +| 0% | N5 | Margin scheme | `0x495420000000405` | + +### Payment Methods (ftPayItemCase) + +| Code | Description | RT Requirements | +|------|-------------|-----------------| +| `0x495420000000001` | Cash | Standard reporting | +| `0x495420000000005` | Credit/Debit Card | Electronic payment | +| `0x495420000000007` | Mobile Payment | Electronic payment | +| `0x49542000000000A` | Bank Transfer | Bank transaction | +| `0x49542000000000B` | Voucher | Special handling | + +### RT Device Integration + +#### Device States +```json +{ + "ftState": { + "0x4954200000000000": "Ready", + "0x4954200000000001": "Processing", + "0x4954200000000002": "Error", + "0x4954200000000003": "Offline", + "0x4954200000000004": "Maintenance" + } +} +``` + +#### Signature Format +```json +{ + "ftSignatures": [ + { + "ftSignatureFormat": "0x4954200000000001", + "ftSignatureType": "0x4954200000000001", + "Caption": "RT Device", + "Data": { + "rtSerialNumber": "RT12345678", + "zRepNumber": "0001", + "documentNumber": "1234", + "signature": "MEUCIQDJsJ3..." + } + } + ] +} +``` + +### Italian-Specific Examples + +#### 1. Electronic Invoice Receipt +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "FT-2024-1234", + "cbReceiptMoment": "2024-03-29T10:15:00.000Z", + "ftReceiptCase": "0x4954200000201002", + "cbCustomer": { + "Name": "ACME SRL", + "Address": "Via Roma 123, 00184 Roma RM", + "VATId": "IT12345678901", + "FiscalCode": "ABCDEF12G34H567I", + "PEC": "acme@pec.it", + "SDICode": "SUBM70N" + }, + "cbChargeItems": [ + { + "Quantity": 1.0, + "Description": "Professional Services", + "Amount": 1000.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301", + "VATNature": "", + "ProductNumber": "SERV-001" + }, + { + "Quantity": 1.0, + "Description": "Exempt Service", + "Amount": 500.00, + "VATRate": 0.00, + "ftChargeItemCase": "0x495420000000404", + "VATNature": "N4", + "ProductNumber": "SERV-002" + } + ], + "cbPayItems": [ + { + "Description": "Bank Transfer", + "Amount": 1500.00, + "ftPayItemCase": "0x49542000000000A", + "PaymentReference": "BON-2024-1234" + } + ] +} +``` + +#### 2. Daily Closing with Lottery +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "CLOSE-2024-0123", + "cbReceiptMoment": "2024-03-29T23:59:59.000Z", + "ftReceiptCase": "0x4954200000000003", + "cbChargeItems": [ + { + "Description": "Daily Total Standard VAT", + "Amount": 10000.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + }, + { + "Description": "Daily Total Reduced VAT", + "Amount": 5000.00, + "VATRate": 10.00, + "ftChargeItemCase": "0x495420000000102" + }, + { + "Description": "Daily Total Exempt", + "Amount": 1000.00, + "VATRate": 0.00, + "ftChargeItemCase": "0x495420000000404" + } + ], + "cbPayItems": [ + { + "Description": "Cash Total", + "Amount": 8000.00, + "ftPayItemCase": "0x495420000000001" + }, + { + "Description": "Electronic Payments Total", + "Amount": 8000.00, + "ftPayItemCase": "0x495420000000005" + } + ], + "ftLotteryData": { + "dailyTotalTickets": 50, + "validTransmissions": 48, + "pendingTransmissions": 2 + } +} +``` + +### RT Device Error Handling + +#### Common RT Device Errors +```json +{ + "error": "rt_device_error", + "message": "RT device error occurred", + "details": { + "errorCode": "RT-001", + "description": "Paper end", + "severity": "warning", + "action": "Replace paper roll" + } +} +``` + +#### RT Connection Issues +```javascript +async function handleRTDeviceError(error) { + if (error.code === 'rt_device_error') { + // 1. Check RT status + const rtStatus = await checkRTDeviceStatus(); + + // 2. Handle specific RT errors + switch (rtStatus.errorCode) { + case 'RT-001': // Paper end + await notifyOperator('Replace paper roll'); + break; + case 'RT-002': // Communication error + await reconnectRTDevice(); + break; + case 'RT-003': // Memory almost full + await performDataTransmission(); + break; + default: + await notifyTechnicalSupport(rtStatus); + } + + // 3. Verify RT recovery + return await verifyRTDeviceStatus(); + } + throw error; +} +``` + +### Italian Compliance Guidelines + +1. **RT Device Management** + - Regular status checks + - Paper level monitoring + - Memory usage tracking + - Automatic data transmission + +2. **Receipt Requirements** + - Unique progressive numbering + - RT serial number inclusion + - Proper VAT calculation + - Correct nature codes + +3. **Daily Operations** + - End-of-day closing + - Data transmission verification + - Lottery data management + - Error log maintenance + +4. **Data Retention** + - Electronic storage requirements + - Backup procedures + - Archive management + - Access control + +## Advanced Implementation Examples + +### 1. Lottery Receipt Integration +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "LOT-2024-001", + "cbReceiptMoment": "2024-03-29T14:30:00.000Z", + "ftReceiptCase": "0x4954200000000001", + "cbChargeItems": [ + { + "Quantity": 1.0, + "Description": "Eligible Product", + "Amount": 100.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + } + ], + "cbPayItems": [ + { + "Description": "Card Payment", + "Amount": 100.00, + "ftPayItemCase": "0x495420000000005" + } + ], + "ftLotteryData": { + "customerCode": "ABCD1234EFGH5678", + "eligibleAmount": 100.00, + "transmissionState": "pending" + } +} +``` + +### 2. Split Payment with Multiple VAT Rates +```json +{ + "ftCashBoxID": "UUID", + "ftPosSystemId": "UUID", + "cbTerminalID": "T1", + "cbReceiptReference": "SPLIT-2024-001", + "cbReceiptMoment": "2024-03-29T15:45:00.000Z", + "ftReceiptCase": "0x4954200000000001", + "cbChargeItems": [ + { + "Quantity": 1.0, + "Description": "Standard Rate Item", + "Amount": 122.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + }, + { + "Quantity": 1.0, + "Description": "Reduced Rate Item", + "Amount": 110.00, + "VATRate": 10.00, + "ftChargeItemCase": "0x495420000000102" + }, + { + "Quantity": 1.0, + "Description": "Exempt Item", + "Amount": 50.00, + "VATRate": 0.00, + "ftChargeItemCase": "0x495420000000404", + "VATNature": "N4" + } + ], + "cbPayItems": [ + { + "Description": "Cash Payment", + "Amount": 150.00, + "ftPayItemCase": "0x495420000000001" + }, + { + "Description": "Card Payment", + "Amount": 132.00, + "ftPayItemCase": "0x495420000000005", + "ftPayItemCaseData": { + "Provider": { + "Protocol": "worldline_wpi_2", + "Action": "payment" + } + } + } + ] +} +``` + +### 3. Advanced Error Recovery Patterns + +#### Timeout Handling +```javascript +async function handleReceiptTimeout(receipt, operationId) { + // 1. Check operation status + const status = await checkOperationStatus(operationId); + + if (status.state === 'unknown') { + // 2. Verify RT device state + const rtStatus = await checkRTDeviceStatus(); + + if (rtStatus.lastReceipt?.reference === receipt.cbReceiptReference) { + // Receipt was processed but response was lost + return await retrieveReceiptData(receipt.cbReceiptReference); + } + + // 3. Receipt was not processed, retry with same operationId + return await sendReceipt(receipt, operationId); + } + + return status; +} +``` + +#### Queue Management with Persistence +```javascript +class PersistentQueue { + constructor() { + this.storage = new LocalStorage('receipt-queue'); + this.maxRetries = 3; + } + + async enqueue(receipt) { + const queueItem = { + id: generateUUID(), + receipt, + attempts: 0, + status: 'pending', + created: new Date().toISOString() + }; + + await this.storage.save(queueItem); + return queueItem.id; + } + + async processQueue() { + const items = await this.storage.getPending(); + + for (const item of items) { + try { + if (item.attempts >= this.maxRetries) { + await this.markFailed(item.id); + continue; + } + + const result = await sendReceipt(item.receipt, item.id); + await this.markCompleted(item.id, result); + } catch (error) { + await this.incrementAttempts(item.id, error); + } + } + } +} +``` + +### 4. RT Device State Management + +#### Device Health Monitoring +```javascript +class RTDeviceMonitor { + constructor() { + this.healthCheckInterval = 60000; // 1 minute + this.criticalErrors = new Set(['RT-002', 'RT-003']); + } + + async startMonitoring() { + setInterval(async () => { + try { + const health = await this.checkDeviceHealth(); + await this.processHealthStatus(health); + } catch (error) { + await this.handleMonitoringError(error); + } + }, this.healthCheckInterval); + } + + async processHealthStatus(health) { + if (!health.isHealthy) { + if (this.criticalErrors.has(health.errorCode)) { + await this.notifyTechnicalSupport(health); + } + + await this.logDeviceStatus({ + timestamp: new Date().toISOString(), + status: health.status, + errorCode: health.errorCode, + lastContact: health.lastContact + }); + } + } +} +``` + +#### Automatic Recovery Procedures +```javascript +class RTDeviceRecovery { + async attemptRecovery(device) { + const procedures = [ + this.checkConnection, + this.resetCommunication, + this.checkPaper, + this.checkMemory, + this.rebootDevice + ]; + + for (const procedure of procedures) { + try { + const result = await procedure(device); + if (result.success) { + await this.logRecovery(device, procedure.name); + return result; + } + } catch (error) { + await this.logRecoveryAttempt(device, procedure.name, error); + } + } + + throw new Error('Recovery failed after all attempts'); + } + + async checkMemory(device) { + const memory = await device.getMemoryStatus(); + + if (memory.usedPercentage > 80) { + await this.performDataTransmission(device); + } + + return { success: memory.usedPercentage < 90 }; + } +} +``` + +### 5. Data Transmission Management + +#### Automated Data Export +```javascript +class DataTransmissionManager { + constructor() { + this.transmissionSchedule = { + daily: '23:50', + backup: '12:00' + }; + } + + async scheduleDailyTransmission() { + const now = new Date(); + const scheduledTime = this.parseTime(this.transmissionSchedule.daily); + + if (now >= scheduledTime) { + await this.performDataTransmission(); + } + } + + async performDataTransmission() { + const data = await this.collectTransmissionData(); + + try { + const result = await this.sendToAuthority(data); + await this.logTransmission(result); + + if (result.status === 'success') { + await this.updateLastTransmission(result); + } + } catch (error) { + await this.handleTransmissionError(error); + } + } +} +``` + +#### Transmission Verification +```javascript +class TransmissionVerification { + async verifyTransmission(transmissionId) { + const verification = { + transmissionId, + timestamp: new Date().toISOString(), + checks: [] + }; + + // 1. Check local data + const localData = await this.getLocalData(transmissionId); + verification.checks.push({ + type: 'local_data', + status: localData ? 'success' : 'failed' + }); + + // 2. Check authority receipt + const authorityReceipt = await this.getAuthorityReceipt(transmissionId); + verification.checks.push({ + type: 'authority_receipt', + status: authorityReceipt ? 'success' : 'failed', + receiptNumber: authorityReceipt?.number + }); + + // 3. Compare checksums + const checksumMatch = await this.compareChecksums( + localData?.checksum, + authorityReceipt?.checksum + ); + verification.checks.push({ + type: 'checksum', + status: checksumMatch ? 'success' : 'failed' + }); + + return verification; + } +} +``` + +### 6. Security Implementation Examples + +#### Access Token Management +```javascript +class TokenManager { + constructor() { + this.tokenStorage = new SecureStorage('ft-tokens'); + this.refreshThreshold = 300000; // 5 minutes + } + + async getValidToken() { + const current = await this.tokenStorage.get(); + + if (!current || this.isExpiringSoon(current)) { + return await this.refreshToken(current); + } + + return current; + } + + async refreshToken(currentToken) { + const newToken = await this.requestNewToken(currentToken); + await this.tokenStorage.save(newToken); + return newToken; + } + + isExpiringSoon(token) { + const expiresAt = new Date(token.expiresAt).getTime(); + const now = Date.now(); + return expiresAt - now < this.refreshThreshold; + } +} +``` + +#### Request Encryption +```javascript +class RequestEncryption { + constructor(publicKey) { + this.publicKey = publicKey; + } + + async encryptSensitiveData(data) { + const sessionKey = await this.generateSessionKey(); + const encryptedData = await this.encryptWithSessionKey(data, sessionKey); + const encryptedKey = await this.encryptSessionKey(sessionKey); + + return { + data: encryptedData, + key: encryptedKey, + algorithm: 'AES-256-GCM', + iv: this.generateIV() + }; + } + + async encryptWithSessionKey(data, key) { + const encoder = new TextEncoder(); + const encoded = encoder.encode(JSON.stringify(data)); + + const encrypted = await crypto.subtle.encrypt( + { + name: 'AES-GCM', + iv: this.iv + }, + key, + encoded + ); + + return Buffer.from(encrypted).toString('base64'); + } +} \ No newline at end of file diff --git a/doc/general/troubleshooting.md b/doc/general/troubleshooting.md new file mode 100644 index 00000000..0bf20900 --- /dev/null +++ b/doc/general/troubleshooting.md @@ -0,0 +1,223 @@ +--- +slug: /troubleshooting +title: Troubleshooting Guide +--- + +# Troubleshooting Guide + +This guide helps you diagnose and resolve common issues with the fiskaltrust middleware. + +## Quick Diagnosis + +### Connection Issues + +#### Symptoms +- Timeout errors +- Connection refused errors +- Unable to reach middleware + +#### Solutions +1. **Check Network Connectivity** + ```powershell + # Test basic connectivity + Test-NetConnection -ComputerName localhost -Port 1234 + ``` + +2. **Verify Configuration** + ```json + { + "cashboxid": "check-this-matches", + "endpoint": "verify-url-and-port" + } + ``` + +3. **Check Service Status** + ```powershell + Get-Service fiskaltrust.Middleware + ``` + +### Signing Issues + +#### Symptoms +- Invalid signature errors +- Missing required fields +- Calculation errors + +#### Solutions +1. **Validate Receipt Format** + ```csharp + // Ensure all required fields are present + if (string.IsNullOrEmpty(request.ftCashBoxID)) + throw new ValidationException("CashBoxID is required"); + ``` + +2. **Check Amount Calculations** + ```csharp + // Verify totals match line items + decimal total = request.cbPayItems.Sum(x => x.Amount); + if (total != request.cbPayTotal) + throw new ValidationException("Total mismatch"); + ``` + +### Performance Issues + +#### Symptoms +- Slow response times +- High CPU usage +- Memory problems + +#### Solutions +1. **Monitor Resources** + ```powershell + # Check CPU and memory usage + Get-Counter '\Processor(_Total)\% Processor Time' + Get-Counter '\Memory\Available MBytes' + ``` + +2. **Optimize Queue Processing** + ```csharp + // Implement batch processing + public async Task ProcessBatch(IEnumerable requests) + { + foreach (var batch in requests.Chunk(100)) + { + await Task.WhenAll(batch.Select(r => _client.Sign(r))); + } + } + ``` + +## Common Error Codes + +### 1000 - General Errors +| Code | Description | Solution | +|------|-------------|----------| +| 1001 | Invalid configuration | Check configuration file | +| 1002 | Service not running | Start the service | +| 1003 | Network error | Check connectivity | + +### 2000 - Receipt Errors +| Code | Description | Solution | +|------|-------------|----------| +| 2001 | Invalid format | Validate against schema | +| 2002 | Missing field | Check required fields | +| 2003 | Invalid amount | Verify calculations | + +## Logging and Diagnostics + +### Enable Debug Logging +```json +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "Microsoft": "Warning" + } + } +} +``` + +### Collect Diagnostic Information +```powershell +# Collect logs +$logPath = "C:\ProgramData\fiskaltrust\Middleware\logs" +Compress-Archive -Path $logPath -DestinationPath "diagnostics.zip" + +# Export configuration +Get-Content "C:\ProgramData\fiskaltrust\Middleware\configuration.json" +``` + +## Recovery Procedures + +### Service Recovery +1. Stop the service + ```powershell + Stop-Service fiskaltrust.Middleware + ``` + +2. Clear temporary files + ```powershell + Remove-Item "C:\ProgramData\fiskaltrust\Middleware\temp\*" + ``` + +3. Restart the service + ```powershell + Start-Service fiskaltrust.Middleware + ``` + +### Database Recovery +1. Backup current data + ```powershell + Copy-Item "C:\ProgramData\fiskaltrust\Middleware\db" "backup" + ``` + +2. Verify backup + ```powershell + Test-Path "backup\queue.db" + ``` + +## Prevention + +### Regular Maintenance +1. Monitor disk space +2. Check log files +3. Update middleware regularly +4. Test backup procedures + +### Best Practices +1. Implement proper error handling +2. Use retry mechanisms +3. Monitor performance metrics +4. Keep documentation updated + +## Getting Support + +### Before Contacting Support +1. Collect relevant logs +2. Document the issue +3. List steps to reproduce +4. Try suggested solutions + +### Support Channels +- Email: support@fiskaltrust.cloud +- Portal: https://portal.fiskaltrust.cloud +- GitHub: https://github.com/fiskaltrust/interface-doc/issues + +## FAQ + +### Q: Why is my service not starting? +A: Check these common causes: +1. Port conflicts +2. Invalid configuration +3. Missing permissions + +### Q: How do I handle offline scenarios? +A: Implement these strategies: +1. Local queue storage +2. Automatic retry logic +3. Failover configuration + +### Q: What should I do if signatures fail? +A: Follow these steps: +1. Verify request format +2. Check TSE status +3. Validate calculations + +## Appendix + +### Useful Commands +```powershell +# Check service status +Get-Service fiskaltrust.Middleware + +# View recent logs +Get-Content "C:\ProgramData\fiskaltrust\Middleware\logs\latest.log" -Tail 100 + +# Test network +Test-NetConnection -ComputerName localhost -Port 1234 +``` + +### System Requirements +- .NET Framework 4.7.2+ +- Windows 7 SP1 or later +- 2GB RAM minimum +- 1GB free disk space \ No newline at end of file diff --git a/doc/middleware-de-kassensichv/README.md b/doc/middleware-de-kassensichv/README.md new file mode 100644 index 00000000..5fcd1d6f --- /dev/null +++ b/doc/middleware-de-kassensichv/README.md @@ -0,0 +1,292 @@ +--- +slug: /middleware-de-kassensichv +title: German KassenSichV Documentation +--- + +# German KassenSichV Documentation + +## Overview + +This documentation covers the implementation of the German KassenSichV (Kassensicherungsverordnung) requirements in the fiskaltrust.Middleware. + +### Regulatory Background + +The KassenSichV requires all electronic cash registers and POS systems in Germany to be equipped with a certified technical security device (TSE - Technische Sicherheitseinrichtung) starting January 1, 2020. + +### Key Requirements + +1. Technical Security Device (TSE) + - Certified security module + - Digital record storage + - Digital signature creation + - Export interface + +2. Digital Records + - Transaction data + - Training mode records + - System events + +3. DSFinV-K Compliance + - Standardized data format + - Export capabilities + - Audit readiness + +## Implementation Guide + +### Prerequisites + +1. Hardware Requirements + - Compatible TSE device + - Network connectivity + - Sufficient storage space + +2. Software Requirements + - .NET Framework 4.7.2+ + - Windows 7 SP1 or later + - Admin privileges for installation + +### Installation Steps + +1. Install the Middleware + ```powershell + # Download and install + ./fiskaltrust-middleware-setup.exe --mode=install + ``` + +2. Configure TSE + ```json + { + "TSE": { + "Type": "Cryptovision", + "DevicePath": "COM3", + "AdminPIN": "12345", + "TimeAdminPIN": "98765" + } + } + ``` + +3. Verify Installation + ```powershell + # Check service status + Get-Service fiskaltrust.Middleware + ``` + +## Integration Guide + +### Receipt Signing Flow + +1. Create Receipt Request + ```csharp + var request = new ReceiptRequest + { + ftCashBoxID = "DE-CASHBOX-ID", + ftPosSystemId = "DE-POS-ID", + cbTerminalID = "T1", + cbReceiptReference = "receipt-001", + ftReceiptCase = 0x4445000000000001, // German normal receipt + cbPayItems = new[] + { + new PayItem + { + Quantity = 1.0m, + Description = "Article 1", + Amount = 119.00m, + VATRate = 19.00m + } + } + }; + ``` + +2. Send to Middleware + ```csharp + var response = await client.Sign(request); + ``` + +3. Process Response + ```csharp + // Print or store TSE data + Console.WriteLine($"Signature: {response.ftSignature}"); + Console.WriteLine($"Transaction: {response.ftTransactionId}"); + ``` + +### Special Cases + +#### Training Mode +```csharp +request.ftReceiptCase = 0x4445000000000002; // German training receipt +``` + +#### Cancellation +```csharp +request.ftReceiptCase = 0x4445000000000003; // German void receipt +``` + +## Compliance + +### DSFinV-K Export + +1. Generate Export + ```csharp + var export = await client.GenerateDSFinVKExport( + new DateTime(2024, 1, 1), + new DateTime(2024, 1, 31) + ); + ``` + +2. Verify Export + ```powershell + # Validate export structure + Test-Path "export/cashpoint_closing.csv" + ``` + +### TAR Export + +1. Generate TAR File + ```csharp + var tarFile = await client.GenerateTARExport( + new DateTime(2024, 1, 1), + new DateTime(2024, 1, 31) + ); + ``` + +2. Verify Export + ```powershell + # Check TAR file + Test-Path "export.tar" + ``` + +## Error Handling + +### Common Issues + +1. TSE Connection Problems + ```csharp + try + { + await client.Sign(request); + } + catch (TSEConnectionException ex) + { + // Handle TSE issues + Logger.Error($"TSE error: {ex.Message}"); + } + ``` + +2. Invalid Configuration + ```csharp + try + { + await client.Initialize(); + } + catch (ConfigurationException ex) + { + // Handle configuration issues + Logger.Error($"Config error: {ex.Message}"); + } + ``` + +### Recovery Procedures + +1. TSE Recovery + ```csharp + await client.ResetTSE(); // Reset TSE state + await client.InitializeTSE(); // Reinitialize TSE + ``` + +2. Data Recovery + ```csharp + // Backup TSE data + await client.BackupTSEData("backup.tar"); + ``` + +## Best Practices + +### Performance + +1. Queue Implementation + ```csharp + public class ReceiptQueue + { + private readonly Queue _queue; + private readonly IFiskaltrustClient _client; + + public async Task ProcessQueue() + { + while (_queue.Any()) + { + var request = _queue.Dequeue(); + await _client.Sign(request); + } + } + } + ``` + +2. Batch Processing + ```csharp + public async Task ProcessBatch(IEnumerable requests) + { + foreach (var batch in requests.Chunk(100)) + { + await Task.WhenAll(batch.Select(r => _client.Sign(r))); + } + } + ``` + +### Security + +1. Credential Storage + ```csharp + // Use Windows Credential Manager + var credentials = new SecureString(); + // ... add characters to secure string + ``` + +2. Audit Logging + ```csharp + public class AuditLogger + { + public void LogReceiptRequest(ReceiptRequest request) + { + // Log receipt details + Logger.Info($"Receipt {request.cbReceiptReference} processed"); + } + } + ``` + +## FAQ + +### Common Questions + +1. **Q: How often should I backup TSE data?** + A: Daily backups are recommended, with weekly full exports. + +2. **Q: What happens if TSE fails?** + A: Implement fallback procedures and notify authorities within one month. + +3. **Q: How long should I keep the data?** + A: Retain all fiscal data for 10 years. + +## Support + +### Contact Information + +- Technical Support: support@fiskaltrust.de +- Compliance Questions: compliance@fiskaltrust.de +- Emergency Support: +49 xxx xxx xxx + +### Resources + +- [KassenSichV Law Text](https://www.gesetze-im-internet.de/kassensichv/) +- [BSI Technical Guidelines](https://www.bsi.bund.de/) +- [fiskaltrust Documentation](https://docs.fiskaltrust.cloud) + +## Version History + +### Current Version (2.0) +- Added DSFinV-K 2.3 support +- Improved error handling +- Enhanced backup procedures + +### Previous Versions +- 1.5: Added cloud TSE support +- 1.0: Initial KassenSichV implementation \ No newline at end of file diff --git a/doc/middleware-it-registratore-telematico/README.md b/doc/middleware-it-registratore-telematico/README.md new file mode 100644 index 00000000..e5df2606 --- /dev/null +++ b/doc/middleware-it-registratore-telematico/README.md @@ -0,0 +1,93 @@ +--- +slug: /middleware-it-registratore-telematico +title: Italian Middleware Documentation v2.0 +--- + +# Italian Middleware for Compliance-as-a-Service (v2.0) + +## Breaking Changes Notice + +Version 2.0 introduces significant breaking changes to improve the middleware's functionality and compliance with Italian fiscal regulations. Please review the changes carefully before upgrading. + +## Overview + +The fiskaltrust Middleware provides a comprehensive solution for point-of-sale systems to achieve fiscal compliance in Italy. This middleware supports: + +- Cloud native, local, and hybrid deployments +- Full fiscalization compliance +- Seamless integration with the fiskaltrust ecosystem +- Support for add-on products and subscriptions + +### Supported Fiscal Solutions + +The middleware supports three official methods for fiscal compliance: + +1. **RT-Printer (Fiscal Printer)** + - Certified device for receipt printing + - Internal storage on SD card + - Daily automated government reporting + +2. **RT-Server (Fiscal Server)** + - Certified device for multi-till environments + - Centralized signature creation + - Automated daily closures + +3. **Government WebService** + - Direct integration with government services + - Real-time receipt validation + - Limited daily transaction volume + +4. **Telematic Receipt** (Coming in 2026) + - Software-based solution + - Requires certification + - Pending legislation completion + +## Documentation Structure + +1. [Installation Guide](installation/README.md) +2. [Configuration Guide](configuration/README.md) +3. [Integration Guide](cash-register-integration/README.md) +4. [Receipt Types and Cases](receipt-case-definitions/README.md) +5. [Data Structures](data-structures/README.md) +6. [Reference Tables](reference-tables/README.md) +7. [Operation Modes](operation-modes/README.md) +8. [Communication](communication/README.md) +9. [Troubleshooting](troubleshooting/README.md) + +## Version Information + +- **Version**: 2.0.20240329 +- **Status**: Production Ready +- **Release Date**: March 29, 2024 + +## Breaking Changes in v2.0 + +1. **New Receipt Format** + - Updated signature structure + - Enhanced metadata support + - Additional fiscal information fields + +2. **Modified API Endpoints** + - Restructured request/response formats + - New endpoint versioning scheme + - Enhanced error handling + +3. **Updated Data Structures** + - New charge item cases + - Extended payment types + - Modified receipt case definitions + +4. **Security Enhancements** + - Improved signature verification + - Enhanced audit trail + - Updated encryption standards + +## Support and Resources + +- [Technical Support](https://support.fiskaltrust.cloud) +- [API Documentation](https://docs.fiskaltrust.cloud) +- [Developer Portal](https://portal.fiskaltrust.cloud) + +## Legal Notice + +This documentation is confidential and proprietary to fiskaltrust consulting gmbh. \ No newline at end of file diff --git a/doc/middleware-it-registratore-telematico/receipt-case-definitions/README.md b/doc/middleware-it-registratore-telematico/receipt-case-definitions/README.md new file mode 100644 index 00000000..feba00d1 --- /dev/null +++ b/doc/middleware-it-registratore-telematico/receipt-case-definitions/README.md @@ -0,0 +1,285 @@ +--- +slug: /middleware-it-registratore-telematico/receipt-case-definitions +title: Receipt Case Definitions and Common Use Cases v2.0 +--- + +# Receipt Case Definitions and Common Use Cases + +## Standard Sales Receipt + +### Cash Sale with Multiple VAT Rates +```json +{ + "ftCashBoxID": "IT-SCU-1234567", + "ftPosSystemId": "POS-1", + "cbTerminalID": "T1", + "cbReceiptReference": "1234", + "ftReceiptCase": "0x4954200000000001", + "cbChargeItems": [ + { + "Quantity": 2.0, + "Description": "Product A", + "Amount": 122.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + }, + { + "Quantity": 1.0, + "Description": "Product B", + "Amount": 110.00, + "VATRate": 10.00, + "ftChargeItemCase": "0x495420000000101" + } + ], + "cbPayItems": [ + { + "Quantity": 1.0, + "Description": "Cash", + "Amount": 232.00, + "ftPayItemCase": "0x495420000000001" + } + ] +} +``` + +### Mixed Payment Methods +```json +{ + "ftCashBoxID": "IT-SCU-1234567", + "ftPosSystemId": "POS-1", + "cbTerminalID": "T1", + "cbReceiptReference": "1235", + "ftReceiptCase": "0x4954200000000001", + "cbChargeItems": [ + { + "Quantity": 1.0, + "Description": "Service A", + "Amount": 244.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000302" + } + ], + "cbPayItems": [ + { + "Quantity": 1.0, + "Description": "Cash", + "Amount": 100.00, + "ftPayItemCase": "0x495420000000001" + }, + { + "Quantity": 1.0, + "Description": "Card Payment", + "Amount": 144.00, + "ftPayItemCase": "0x495420000000005" + } + ] +} +``` + +### B2B Invoice with VAT ID +```json +{ + "ftCashBoxID": "IT-SCU-1234567", + "ftPosSystemId": "POS-1", + "cbTerminalID": "T1", + "cbReceiptReference": "INV-1236", + "ftReceiptCase": "0x4954200000201002", + "cbReceiptAmount": 1220.00, + "cbUser": "John Doe", + "cbArea": "Main Store", + "cbCustomer": { + "Name": "ACME Corp", + "Address": "Via Roma 123, 00184 Roma RM", + "VATId": "IT12345678901" + }, + "cbChargeItems": [ + { + "Quantity": 10.0, + "Description": "Product A", + "Amount": 1220.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301", + "ProductNumber": "A-123", + "Unit": "pcs" + } + ], + "cbPayItems": [ + { + "Quantity": 1.0, + "Description": "Bank Transfer", + "Amount": 1220.00, + "ftPayItemCase": "0x49542000000000A" + } + ] +} +``` + +### Void Receipt with Reference +```json +{ + "ftCashBoxID": "IT-SCU-1234567", + "ftPosSystemId": "POS-1", + "cbTerminalID": "T1", + "cbReceiptReference": "VOID-1234", + "ftReceiptCase": "0x4954200000040001", + "cbPreviousReceiptReference": "1234", + "cbChargeItems": [ + { + "Quantity": -2.0, + "Description": "Product A", + "Amount": -122.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + }, + { + "Quantity": -1.0, + "Description": "Product B", + "Amount": -110.00, + "VATRate": 10.00, + "ftChargeItemCase": "0x495420000000101" + } + ], + "cbPayItems": [ + { + "Quantity": -1.0, + "Description": "Cash", + "Amount": -232.00, + "ftPayItemCase": "0x495420000000001" + } + ] +} +``` + +### Refund with Customer Data +```json +{ + "ftCashBoxID": "IT-SCU-1234567", + "ftPosSystemId": "POS-1", + "cbTerminalID": "T1", + "cbReceiptReference": "REF-1237", + "ftReceiptCase": "0x4954200000100001", + "cbCustomer": { + "Name": "Mario Rossi", + "Address": "Via Veneto 1, Roma", + "FiscalCode": "RSSMRA80A01H501U" + }, + "cbChargeItems": [ + { + "Quantity": -1.0, + "Description": "Product Return", + "Amount": -122.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + } + ], + "cbPayItems": [ + { + "Quantity": -1.0, + "Description": "Cash Refund", + "Amount": -122.00, + "ftPayItemCase": "0x495420000000001" + } + ] +} +``` + +### Daily Closing with Totals +```json +{ + "ftCashBoxID": "IT-SCU-1234567", + "ftPosSystemId": "POS-1", + "cbTerminalID": "T1", + "cbReceiptReference": "CLOSE-1", + "ftReceiptCase": "0x4954200000002011", + "cbChargeItems": [ + { + "Description": "Daily Total", + "Amount": 5000.00, + "VATRate": 22.00, + "ftChargeItemCase": "0x495420000000301" + }, + { + "Description": "Daily Total", + "Amount": 2000.00, + "VATRate": 10.00, + "ftChargeItemCase": "0x495420000000101" + } + ], + "cbPayItems": [ + { + "Description": "Cash Total", + "Amount": 3000.00, + "ftPayItemCase": "0x495420000000001" + }, + { + "Description": "Card Total", + "Amount": 4000.00, + "ftPayItemCase": "0x495420000000005" + } + ] +} +``` + +## Response Examples + +### Standard Response with RT Data +```json +{ + "ftCashBoxID": "IT-SCU-1234567", + "ftQueueID": "IT-QUEUE-1234567", + "ftQueueItemID": "1234567890", + "ftQueueRow": 1234, + "cbTerminalID": "T1", + "cbReceiptReference": "1234", + "ftCashBoxIdentification": "POS-1", + "ftReceiptIdentification": "ft1234567890", + "ftReceiptMoment": "2024-03-29T10:15:00.000Z", + "ftSignatures": [ + { + "ftSignatureFormat": "0x4954200000000001", + "ftSignatureType": "0x4954200000000001", + "Caption": "RT Device", + "Data": "RT-12345678" + }, + { + "ftSignatureFormat": "0x4954200000000003", + "ftSignatureType": "0x4954200000000010", + "Caption": "Receipt QR Code", + "Data": "https://scontrino.fiskaltrust.it/1234567890" + } + ], + "ftState": 0x4954200000000000 +} +``` + +### Error Response - Device Not Reachable +```json +{ + "ftState": "0x4954200000000001", + "ftSignatures": [ + { + "ftSignatureFormat": "0x4954200000000001", + "ftSignatureType": "0x4954200000000301", + "Caption": "Error", + "Data": "RT device not reachable" + } + ] +} +``` + +### Response with Lottery Code +```json +{ + "ftCashBoxID": "IT-SCU-1234567", + "ftQueueID": "IT-QUEUE-1234567", + "ftQueueItemID": "1234567890", + "ftSignatures": [ + { + "ftSignatureFormat": "0x4954200000000001", + "ftSignatureType": "0x4954200000000015", + "Caption": "Lottery Code", + "Data": "ABCD1234EFGH5678" + } + ], + "ftState": 0x4954200000000000 +} \ No newline at end of file diff --git a/doc/middleware-it-registratore-telematico/reference-tables/README.md b/doc/middleware-it-registratore-telematico/reference-tables/README.md new file mode 100644 index 00000000..3582e381 --- /dev/null +++ b/doc/middleware-it-registratore-telematico/reference-tables/README.md @@ -0,0 +1,189 @@ +--- +slug: /middleware-it-registratore-telematico/reference-tables +title: Reference Tables v2.0 +--- + +# Reference Tables for Italian Middleware v2.0 + +## Receipt Cases (ftReceiptCase) + +### Format +`_4954_2000_gggg_txcc` + +Where: +- `4954`: Country code for Italy (IT) +- `2000`: Version 2.0 +- `gggg`: Global flags +- `t`: Receipt type +- `xcc`: Receipt case + +### Receipt Types + +| Type | Category | Description | +|------|----------|-------------| +| 0 | Receipt | Basic POS sale receipt | +| 1 | Invoice | Invoice for deferred payment | +| 2 | Daily Operations | Required for downstream processes | +| 3 | Log | Event logging and security | +| 4 | Lifecycle | Queue state management | + +### Receipt Cases + +| Code | Description | Details | RT Requirements | +|------|-------------|---------|-----------------| +| 0001 | Point-Of-Sale receipt | Standard sales receipt | Requires RT signature | +| 0002 | Payment transfer | Cash management | Requires RT signature | +| 0003 | Non-fiscal receipt | No fiscalization required | No RT signature | +| 0004 | E-Commerce receipt | Online transaction | Requires RT signature | +| 1001 | B2C invoice | Consumer invoice | Requires RT signature | +| 1002 | B2B invoice | Business invoice | Requires RT signature | +| 2011 | Daily Closing | End of day processing | Requires RT signature | +| 3001 | Technical event | System event logging | No RT signature | +| 4001 | Queue-Start-Receipt | Initial operations | Requires RT signature | + +### Global Flags (gggg) + +| Flag | Description | +|------|-------------| +| 0001 | Late signing | +| 0002 | Training mode | +| 0004 | Void receipt | +| 0008 | Handwritten receipt | +| 0010 | Small business | +| 0020 | Business customer | +| 0040 | Known customer | +| 0100 | Return/Refund | + +## Charge Items (ftChargeItemCase) + +### Format +`_4954_2000_gggg_NNSV` + +Where: +- `4954`: Country code for Italy +- `2000`: Version 2.0 +- `gggg`: Global flags +- `NN`: Nature of VAT +- `S`: Service type +- `V`: VAT rate + +### VAT Types for Italy + +| Code | Description | Rate | Marker | +|------|-------------|------|---------| +| 3 | Normal VAT rate | 22% | A | +| 1 | Reduced VAT rate 1 | 10% | B | +| 2 | Reduced VAT rate 2 | 5% | C | +| 4 | Super reduced | 4% | D | +| 7 | Zero VAT rate | 0% | H | + +### Nature of VAT Codes + +| Code | Description | Marker | Details | +|------|-------------|---------|---------| +| 10 | Not Taxable | NI (N3) | Exports and similar transactions | +| 11 | Non-taxable - intra-community | NI (N3.1) | EU transactions | +| 12 | Non-taxable - San Marino | NI (N3.2) | San Marino transactions | +| 20 | Not Subject | NS (N2) | Out of scope | +| 21 | Not subject - other | NS (N2.2) | Other cases | +| 30 | Exempt | ES (N4) | Art. 10 DPR 633/72 | +| 40 | Margin scheme | RM (N5) | Used goods, art, antiques | +| 50 | Reverse charge | AL (N6) | Construction sector | +| 51 | Reverse charge - other | AL (N6.1) | Other sectors | + +### Service Types (S) + +| Code | Description | Requirements | +|------|-------------|--------------| +| 1 | Goods delivery | Standard VAT rules | +| 2 | Services | Standard VAT rules | +| 3 | Tip | Special handling | +| 4 | Voucher | Special rules based on type | +| 5 | Catalog service | Standard VAT rules | +| 6 | Agency business | Special documentation | +| 7 | Own consumption | Special VAT rules | + +## Payment Types (ftPayItemCase) + +### Format +`_4954_2000_gggg_xxPP` + +Where: +- `4954`: Country code for Italy +- `2000`: Version 2.0 +- `gggg`: Global flags +- `PP`: Payment type + +### Payment Types + +| Code | Description | RT Requirements | +|------|-------------|-----------------| +| 01 | Cash | Must be reported | +| 02 | Non-Cash | Must be reported | +| 04 | Debit Card | Must be reported | +| 05 | Credit Card | Must be reported | +| 06 | Voucher | Special handling | +| 07 | Online | Must be reported | +| 08 | Loyalty program | Special handling | +| 09 | Account receivable | Must be reported | +| 0C | Internal transfer | Special handling | + +## Signature Types (ftSignatureType) + +### Format +`_4954_2000_gggg_tsss` + +### Signature Cases for Italy + +| Code | Description | Format | Required | +|------|-------------|---------|----------| +| 001 | RT Fiscalization | QR Code | Yes | +| 010 | RT Serial Number | Text | Yes | +| 011 | RT Z-Number | Text | Yes | +| 012 | RT Document Number | Text | Yes | +| 013 | RT Document Moment | Text | Yes | +| 014 | RT Document Type | Text | Yes | +| 015 | RT Lottery ID | Text | Optional | +| 016 | RT Customer ID | Text | Conditional | +| 017 | RT SHA Metadata | Base64 | Yes | + +### Signature Formats + +| Format | Description | +|--------|-------------| +| 0001 | Text | +| 0002 | URL | +| 0003 | QR Code | +| 0004 | Code128 | +| 000D | Base64 | + +## Journal Types (ftJournalType) + +### Format +`_4954_2000_gggg_tjjj` + +### Journal Cases for Italy + +| Code | Description | Period | +|------|-------------|---------| +| 000 | Queue Status | On demand | +| 001 | RT Export | Daily | +| 002 | Daily Report | Daily | +| 003 | Monthly Report | Monthly | +| 004 | Annual Report | Yearly | + +## State Flags (ftState) + +### Format +`_4954_2000_gggg_gggg` + +### Local State Flags for Italy + +| Code | Description | Action Required | +|------|-------------|----------------| +| 001 | RT device not reachable | Check connection | +| 002 | Daily closing required | Perform closing | +| 004 | Network error | Check network | +| 008 | Paper low/end | Replace paper | +| 010 | Memory almost full | Perform export | +| 020 | Time drift detected | Sync time | \ No newline at end of file diff --git a/doc/templates/api-documentation-template.md b/doc/templates/api-documentation-template.md new file mode 100644 index 00000000..75ea7f68 --- /dev/null +++ b/doc/templates/api-documentation-template.md @@ -0,0 +1,270 @@ +--- +slug: /api-documentation-template +title: API Documentation Template +--- + +# API Documentation Template + +## Overview +Brief description of the API endpoint or service. + +### Authentication +Describe authentication methods and requirements. + +### Base URL +``` +https://api.fiskaltrust.cloud/v1 +``` + +## Endpoints + +### [Endpoint Name] + +#### `HTTP Method /path/to/endpoint` + +Description of what this endpoint does. + +##### Parameters + +###### Path Parameters +| Name | Type | Required | Description | +|------|------|----------|-------------| +| id | string| Yes | Resource identifier | + +###### Query Parameters +| Name | Type | Required | Description | +|------|------|----------|-------------| +| limit| integer| No | Maximum number of items to return | + +###### Request Body +```json +{ + "property1": "string", + "property2": 123, + "property3": { + "nested": "value" + } +} +``` + +##### Response + +###### Success Response (200 OK) +```json +{ + "id": "string", + "status": "success", + "data": { + "property": "value" + } +} +``` + +###### Error Responses + +**400 Bad Request** +```json +{ + "error": "validation_error", + "message": "Invalid input", + "details": [ + { + "field": "property1", + "message": "Field is required" + } + ] +} +``` + +**401 Unauthorized** +```json +{ + "error": "unauthorized", + "message": "Invalid authentication credentials" +} +``` + +**403 Forbidden** +```json +{ + "error": "forbidden", + "message": "Insufficient permissions" +} +``` + +**404 Not Found** +```json +{ + "error": "not_found", + "message": "Resource not found" +} +``` + +##### Example + +###### cURL +```bash +curl -X POST \ + 'https://api.fiskaltrust.cloud/v1/endpoint' \ + -H 'Authorization: Bearer YOUR_TOKEN' \ + -H 'Content-Type: application/json' \ + -d '{ + "property1": "value1", + "property2": 123 + }' +``` + +###### C# +```csharp +var client = new FiskaltrustClient(configuration); +var request = new RequestModel +{ + Property1 = "value1", + Property2 = 123 +}; + +try +{ + var response = await client.CallEndpointAsync(request); + Console.WriteLine($"Success: {response.Status}"); +} +catch (FiskaltrustException ex) +{ + Console.WriteLine($"Error: {ex.Message}"); +} +``` + +###### TypeScript +```typescript +const client = new FiskaltrustClient(config); +const request = { + property1: 'value1', + property2: 123 +}; + +try { + const response = await client.callEndpoint(request); + console.log('Success:', response.status); +} catch (error) { + console.error('Error:', error.message); +} +``` + +##### Rate Limiting +| Tier | Rate Limit | +|------|------------| +| Free | 100/hour | +| Pro | 1000/hour | + +##### Notes +- Important considerations +- Special cases +- Known limitations + +## Data Types + +### Common Objects + +#### RequestModel +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| property1 | string | Yes | Description of property1 | +| property2 | number | No | Description of property2 | + +#### ResponseModel +| Field | Type | Description | +|-------|------|-------------| +| id | string| Unique identifier | +| status| string| Response status | + +## Error Codes + +| Code | Description | Resolution | +|------|-------------|------------| +| 1001 | Invalid input | Check request parameters | +| 1002 | Rate limit exceeded | Wait and retry | + +## Best Practices + +### Performance +1. Use batch operations when possible +2. Implement proper caching +3. Handle rate limits appropriately + +### Security +1. Store credentials securely +2. Use HTTPS for all requests +3. Implement proper error handling + +### Reliability +1. Implement retry logic +2. Handle network errors +3. Log all API interactions + +## Testing + +### Test Environment +``` +https://api-test.fiskaltrust.cloud/v1 +``` + +### Test Credentials +```json +{ + "client_id": "test_client", + "client_secret": "test_secret" +} +``` + +### Test Cases +1. Successful request +2. Invalid input +3. Rate limit handling +4. Error scenarios + +## SDK Support + +### Official SDKs +- [.NET SDK](https://github.com/fiskaltrust/middleware-interface-dotnet) +- [Java SDK](https://github.com/fiskaltrust/middleware-interface-java) +- [Node.js SDK](https://github.com/fiskaltrust/middleware-interface-nodejs) + +### Community SDKs +- List of community-maintained SDKs +- Guidelines for SDK development + +## Migration Guide + +### Version Changes +| Version | Changes | Migration Steps | +|---------|---------|----------------| +| 2.0 | New auth| Update tokens | +| 1.5 | New endpoints| Update SDK | + +### Deprecation Schedule +| Feature | Deprecated | Removed | +|---------|------------|---------| +| Old auth | 2023-01-01| 2024-01-01| + +## Support + +### Getting Help +- Documentation resources +- Support channels +- Community forums + +### Reporting Issues +- GitHub issues +- Security vulnerabilities +- Feature requests + +## Changelog + +### Latest Version (2.0.0) +- Added new endpoints +- Improved error handling +- Updated authentication + +### Previous Versions +- 1.5.0: Added batch operations +- 1.0.0: Initial release \ No newline at end of file diff --git a/doc/templates/country-middleware-template.md b/doc/templates/country-middleware-template.md new file mode 100644 index 00000000..dab9d2a9 --- /dev/null +++ b/doc/templates/country-middleware-template.md @@ -0,0 +1,106 @@ +--- +slug: /middleware-{country-code} +title: {Country Name} Middleware Documentation +--- + +# {Country Name} Middleware Documentation + +## Overview +- Brief introduction to the country-specific requirements +- Regulatory framework +- Key features + +## Installation Guide +### Prerequisites +- System requirements +- Network requirements +- Required certificates or credentials + +### Installation Steps +1. Step-by-step installation process +2. Configuration options +3. Validation steps + +## Configuration +### Basic Configuration +- Essential settings +- Environment variables +- Configuration file structure + +### Advanced Configuration +- Performance tuning +- High availability setup +- Security configurations + +## Integration Guide +### Getting Started +- Basic integration steps +- Authentication setup +- Test environment setup + +### API Integration +- REST API endpoints +- SOAP endpoints (if applicable) +- gRPC endpoints (if applicable) + +### Code Examples +```csharp +// C# example +``` + +```java +// Java example +``` + +```typescript +// TypeScript example +``` + +## Common Use Cases +### Basic Receipt Creation +- Step-by-step guide +- Code examples +- Validation + +### Special Receipts +- Training mode +- Copy receipts +- Cancellation receipts + +## Troubleshooting +### Common Issues +- Known problems and solutions +- Error codes and meanings +- Debugging tips + +### Performance Optimization +- Best practices +- Configuration recommendations +- Common bottlenecks + +## Security +### Best Practices +- Authentication +- Authorization +- Data protection + +### Compliance +- Regulatory requirements +- Audit preparation +- Data retention + +## FAQ +- Frequently asked questions +- Common integration challenges +- Regulatory compliance questions + +## Version History +### Current Version +- Features +- Changes +- Breaking changes + +### Previous Versions +- Migration guides +- Deprecated features +- Upgrade paths \ No newline at end of file diff --git a/doc/templates/style-guide.md b/doc/templates/style-guide.md new file mode 100644 index 00000000..353cc8ba --- /dev/null +++ b/doc/templates/style-guide.md @@ -0,0 +1,147 @@ +--- +slug: /style-guide +title: Documentation Style Guide +--- + +# Documentation Style Guide + +## General Principles +- Use clear, concise language +- Write in present tense +- Use active voice +- Be consistent with terminology +- Include examples for complex concepts + +## Document Structure +### Headers +- Use Title Case for Main Headers +- Use Sentence case for subheaders +- Maximum of 4 heading levels (h1-h4) + +### Content Organization +- Start with an overview +- Include a table of contents for long documents +- Use consistent section ordering +- End with related links or next steps + +## Formatting +### Code Blocks +```markdown +Use language-specific syntax highlighting: +```csharp +public void Example() { + // C# code +} +``` +``` + +### Lists +- Use bullet points for unordered lists +- Use numbers for sequential steps +- Maintain consistent capitalization +- End each list item with appropriate punctuation + +### Tables +| Use | Tables | Sparingly | +|-----|---------|-----------| +| For | structured | data | + +### Links +- Use relative paths for internal links +- Use descriptive link text +- Include link title attributes +- Check links regularly for validity + +## Version Control +### Branch Naming +- feature/doc-{feature-name} +- fix/doc-{issue-number} +- update/doc-{section-name} + +### Commit Messages +- Start with a verb (Add, Update, Fix, Remove) +- Keep under 72 characters +- Include issue reference if applicable + +## Images and Diagrams +### File Format +- Use SVG for diagrams +- Use PNG for screenshots +- Optimize image sizes +- Include alt text + +### Naming Convention +- Use lowercase +- Separate words with hyphens +- Include meaningful descriptors +- Example: api-authentication-flow.svg + +## API Documentation +### Endpoint Documentation +```markdown +### Endpoint Name +`POST /api/v1/endpoint` + +**Description:** +Brief description of the endpoint. + +**Parameters:** +| Name | Type | Required | Description | +|------|------|----------|-------------| +| id | string| Yes | Resource ID | + +**Request Example:** +```json +{ + "key": "value" +} +``` + +**Response Example:** +```json +{ + "status": "success" +} +``` +``` + +### Error Handling +- Document all possible error codes +- Include error messages +- Provide troubleshooting steps + +## Terminology +### Glossary +- Maintain a central glossary +- Use consistent terms +- Include industry-specific terms +- Link to official references + +### Abbreviations +- Define on first use +- Include in glossary +- Use consistently + +## Localization +### Text +- Use neutral language +- Avoid idioms +- Consider cultural differences +- Support right-to-left languages + +### Date and Time +- Use ISO 8601 format +- Include timezone information +- Consider 12/24 hour formats + +## Accessibility +### Content +- Use descriptive headings +- Provide alt text for images +- Use sufficient color contrast +- Support screen readers + +### Navigation +- Provide keyboard navigation +- Include skip links +- Use ARIA labels where needed \ No newline at end of file