# AI Integration Hub # Build With Donutwork, Faster This page is the main entry point for AI-assisted integration on Donutwork. If your team uses Codex or other AI copilots, start here to reduce implementation time, lower scope mistakes, and ship production-ready integrations faster. ## Why This Matters * Faster onboarding with a pre-packaged integration skill. * Clear endpoint-to-scope mapping for least-privilege access. * Field-level entity models for safer payload implementation. * Repeatable go-live checklist for reliable releases. ## Official AI Integration Assets * Donutwork Skill (latest): [`/downloads/donutwork-skill-latest.tar.gz`](/downloads/donutwork-skill-latest.tar.gz) * Checksum (latest): [`/downloads/donutwork-skill-latest.sha256`](/downloads/donutwork-skill-latest.sha256) * Donutwork Claude Code skill (latest): [`/downloads/donutwork-claude-code-skill-latest.skill`](/downloads/donutwork-claude-code-skill-latest.skill) * Claude Code checksum (latest): [`/downloads/donutwork-claude-code-skill-latest.sha256`](/downloads/donutwork-claude-code-skill-latest.sha256) * OpenAPI snapshot: [`/openapi.json`](/openapi.json) * AI full context bundle: [`/llms-full.txt`](/llms-full.txt) * AI quick index: [`/llms.txt`](/llms.txt) ## Install In 60 Seconds ```bash mkdir -p "${CODEX_HOME:-$HOME/.codex}/skills" tar -xzf donutwork-skill-latest.tar.gz -C "${CODEX_HOME:-$HOME/.codex}/skills" ``` Then invoke: ```text Use $donutwork to design my integration plan. ``` ## Claude Code Setup ```bash unzip -o donutwork-claude-code-skill-latest.skill -d "$HOME" ``` Optional integrity check: ```bash sha256sum -c donutwork-claude-code-skill-latest.sha256 ``` ## What You Get With `$donutwork` * Endpoint plan by feature (method, path, purpose). * Required OAuth/API scopes by endpoint. * Entity payload model guidance with required fields. * Ready-to-use request examples. * Launch checklist for staging and production. ## Recommended First Prompts 1. `Use $donutwork to map scopes for customers, charges, and webhooks.` 2. `Use $donutwork to generate payload models for customer and subscription sync.` 3. `Use $donutwork to produce a production go-live checklist for our integration.` ## Next Step Go to the full skill documentation: * [Donutwork Codex Skill](/en/docs/applications/donutwork-skill) * [Donutwork Claude Code Skill](/en/docs/applications/donutwork-claude-code-skill) # Introduction import { Card, Cards } from 'fumadocs-ui/components/card'; import { BarChart3, CreditCard, ShieldCheck, Layout, Users, Workflow } from 'lucide-react'; # Welcome to Donutwork Donutwork is a comprehensive SaaS platform designed to help you manage your business efficiently. Whether you are managing customers, partners, or recurring payments, Donutwork provides the tools you need to scale. ## What is Donutwork? Donutwork simplifies the complex operations of running a SaaS by providing a unified interface for: * **Customer Management**: Track and engage with your user base. * **Partner Programs**: Manage affiliates and revenue sharing. * **Subscription Billing**: Automate recurring payments and invoicing. * **Analytics**: Gain deep insights into your business performance. ## Platform Areas } title="Recurring Payments" href="/en/docs/recurring-payments" description="Run subscriptions, seat pricing, lifecycle changes, and renewal calculations with predictable rules." /> } title="BI & Growth" href="/en/docs/bi-growth" description="Track MRR/ARR, revenue mix, and growth dynamics to guide commercial decisions." /> } title="Sentinel Security" href="/en/docs/sentinel" description="Protect accounts with adaptive MFA, risk scoring, and identity controls." /> } title="Dynamic Content" href="/en/docs/dynamic-content-modeling" description="Model custom schemas and manage content through structured, reusable entries." /> } title="Partner Program" href="/en/docs/partner-program" description="Configure partner groups, commission logic, and payout-ready growth models." /> } title="Applications & Workflow" href="/en/docs/applications" description="Integrate third-party applications and automate business logic with workflow orchestration." /> *** ## Recommended First Path 1. Start with [Recurring Payments](/en/docs/recurring-payments) to define your monetization baseline. 2. Configure [Customer Management](/en/docs/customer) for profile, billing, and transaction operations. 3. Enable [Sentinel Security](/en/docs/sentinel) to harden authentication and risk controls. 4. Activate [Email Gateway](/en/docs/email-gateway) and [Workflow](/en/docs/workflow) for communication automation. 5. Use [BI & Growth](/en/docs/bi-growth) to validate outcomes and iterate on pricing and retention. ## Target Audience This documentation is specifically tailored for **Business Users** (Founders, Product Managers, Customer Success, and Sales) to help you get the most out of the platform without needing technical expertise. ## AI Integration Entry Point If you are integrating Donutwork with AI copilots or autonomous coding agents, start from: * [AI Integration Hub](/en/docs/ai-integration) # Authentication import { Callout } from 'fumadocs-ui/components/callout'; import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Step, Steps } from 'fumadocs-ui/components/steps'; # Authentication The Donutwork API uses API Keys to authenticate requests. You can view and manage your API keys in the Donutwork Dashboard. ## Authorization Header All API requests must include your API Key in the `Authorization` HTTP header as a Bearer token. ```http Authorization: Bearer ``` Your API keys carry significant privileges. Keep them secure and never expose them in client-side code or public repositories. ## Obtaining an API Key Donutwork is currently in a controlled rollout phase. Access is granted to partners and early adopters through the following process: ### Request Access Submit a request to the Donutwork team outlining your integration use case. ### Review & Provisioning Our team will review your requirements and provision the necessary environments. ### Environment Keys Upon approval, you will be provided with distinct keys for: * **Staging**: For development, testing, and sandbox experimentation. * **Production**: For live, customer-facing traffic. ## Connectivity and Health Checks Use these endpoints to validate your authentication credentials and monitor API availability. ### System Ping Verify the operational status of the Donutwork API environment. ### Connection Metadata Retrieve detailed information about your current connection, including client IP and protocol negotiation. # Company import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Company The Company API allows you to retrieve metadata about your own organization and lookup public data for third-party companies using VAT identifiers. *** ## Get Company Profile Retrieve the core configuration and identification attributes for your company profile. This includes your unique internal identifier and official registered name. *** ## List Active Modules Discover and monitor the status of functional modules enabled for your organization. Each module represents a specific capability (e.g., Recurring Payments, Email Gateway) along with its configuration and activation state. *** ## Company Intelligence Stats Retrieve the company intelligence snapshot used by operational dashboards. This endpoint returns KPI data, usage widgets, revenue chart aggregates, and metadata for the current company context. *** ## Lookup Registered Company (Open Data) Retrieve public business information for a company using its VAT number. This is particularly useful for automating KYC (Know Your Customer) workflows and ensuring data accuracy during customer onboarding. # Currency import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Currency The Currency API provides programmatic access to platform-supported monetary denominations and enables precision-grade currency conversion based on Donutwork's centralized exchange data. *** ## List Enabled Currencies Retrieve the full collection of ISO 4217 currency codes supported by the platform. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/currencies.json' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` ```js const currencies = await sdk.currency.list(); console.table(currencies); ``` *** ## Perform Currency Conversion Execute a real-time conversion between two supported currencies.\ The response field `amount` is the converted value, not the original request amount. ### Technical Implementation ```sh curl --location --request POST \ 'https://api.hub.donutwork.com/2026-02-01/currencies/EUR/USD.json' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer YOUR_API_KEY' \ --data '{"amount": 100}' ``` ```js const conversion = await sdk.currency.convert("EUR", "USD", 100); console.log(`Converted: ${conversion.amount} ${conversion.to} @ rate ${conversion.rate}`); ``` # Customers import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Customers The Customer API is the central hub for managing your client base. It allows you to synchronize your internal CRM data, manage billing profiles, and monitor subscription health across your organization. *** ## List All Customers Retrieve a paginated collection of customers associated with your organization. This endpoint is ideal for dashboard overviews and batch synchronization processes. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/customers.json?size=20' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` ```js const customers = await sdk.customers.list({ size: 20 }); console.table(customers.elements); ``` *** ## Create a New Customer Initialize a new customer profile. This is the prerequisite step for attaching subscriptions or processing one-time charges. High-quality data at this stage ensures accurate tax calculation and communication delivery. *** ## Retrieve Customer Details Fetch the complete profile for a specific customer. This includes organizational metadata, contact information, and summarized subscription status. *** ## Search by External Identifier Locate a customer profile using your internal system's identifier (externalId). This is essential for maintaining synchronization between Donutwork and your primary CRM/ERP. *** ## Update Customer Profile Modify an existing customer record. This endpoint supports partial updates (PATCH-style behavior); only the fields included in the request body will be modified. This is useful for updating contact information or adding organizational tags. *** ## Decommission Customer Profile Permanently remove a customer profile and all associated metadata. This action is destructive and irreversible. Ensure that all active subscriptions are terminated before choosing to decommission a profile. *** ## Customer Properties (Metadata) Extend the customer profile with custom key-value pairs. Properties are ideal for storing domain-specific data, integration identifiers, or specialized configuration flags that are not captured by standard profile fields. ### Retrieve All Properties Fetch the complete set of custom metadata associated with a customer. ### Atomic Update/Insert (Upsert) Properties Update existing property values or append new keys to the customer's property collection. This endpoint performs an "upsert" operation; keys that do not exist will be created, and existing keys will have their values overwritten. *** ## Secure Hosted Payment Link Generate a unique, short-lived URL for the Donutwork Hosted Payment Page. This secure interface allow customers to update their sensitive payment information (e.g., Credit Card, SEPA Mandate) without sensitive data passing through your servers. *** ## Subscription Management Manage recurring billing cycles and plan associations for your customers. Subscriptions automate the generation of invoices and payment processing based on predefined logic. ### List Active and Historical Subscriptions Retrieve a collection of all subscription entities associated with a customer, including active, canceled, and past-due states. ### Attach New Subscription Provision a new subscription for a customer. This endpoint allows for runtime overrides of plan defaults, such as custom discounts and initial addon quantities. ### Detach Subscription Detach a subscription from the customer profile. ### Retrieve Subscription Status Read the operational status of a specific customer subscription. ### Modify Subscription Status Manually transition a subscription between operational states. This is typically used for administrative overrides or manual churn management. *** ### Advanced Subscription Lifecycle (Additive) These endpoints extend subscription lifecycle management without replacing existing legacy routes. Use them when you need pause/resume, plan amendments, scheduled changes, and proration-aware updates. #### Read Extended Lifecycle State #### Pause, Resume, Cancel-at-Period-End Use the same payload model with: * `.../lifecycle/resume.json` * `.../lifecycle/cancel-at-period-end.json` * `.../lifecycle/undo-cancel-at-period-end.json` Pause/resume billing behavior: * No retroactive automatic billing is created when resuming after a long pause. * If resumed two months later (for example pause on **May 1, 2026** and resume on **July 1, 2026**), renewal is re-anchored to the resume date (or future `resume_at` if provided). Undo-cancel behavior: * If a subscription is `cancel_pending`, you can revert it to `active` before renewal boundary. * Plan/addons remain the current ones on the subscription; cancellation flag is removed. #### Change Plan or Addons with Immediate/Scheduled Application #### Proration Preview (No Mutation) #### Amendment History ### Backward Compatibility Lifecycle endpoints are **additive and opt-in**. Existing integrations can keep using current routes unchanged. | Area | Legacy Contract | Lifecycle Extension | | :----------------------- | :--------------------- | :----------------------------------------------- | | Attach/Detach | Unchanged | Still valid | | Status route | Unchanged payload keys | Additional lifecycle visibility | | Addons route | Unchanged | Optional proration-aware lifecycle change-addons | | Usage/metering | Unchanged | Unchanged | | Existing panel/API flows | Unchanged | New actions available when explicitly called | *** ### Subscription Addons Manage the quantity of modular features (addons) attached to a specific subscription. Addons allow for flexible, feature-based pricing. #### Audit Addon Quantities Retrieve a list of all addons currently active on a subscription along with their provisioned quantities. #### Reconcile Addon Quantities Update the provisioned quantities for one or more addons. This operation is additive or disruptive based on the provided quantity values. *** ### Simulation Interface (Sandbox Only) Accelerate development cycles by simulating subscription lifecycle events in non-production environments. #### Simulate Success Event Force a successful renewal or provisioning event for a subscription. #### Simulate Failure Event Force a failed renewal or payment rejection event. *** ## Metered Usage Tracking For subscriptions with `metering: true`, consumption must be reported via these endpoints. Usage is aggregated and billed at the end of the current billing cycle. ### Report Usage Event Record a new consumption event (e.g., API requests, data processed, seats occupied). Each record requires a unique `externalId` to prevent idempotent replay errors. ### Audit Usage History Retrieve a paginated history of all usage events reported for a specific subscription. *** ## Ad-hoc Charges Charges represent immediate, non-recurring billable events created independently of a subscription's billing cycle (e.g., setup fees, professional services). ### Create One-Time Charge Generate an ad-hoc charge. If the `capture` flag is set to `true`, the system will immediately attempt to authorize and capture the funds using the customer's primary payment method. ### List Organizational Charges Retrieve all charges (including pending and failed attempts) associated with a specific customer profile. ### Charge Details and Reconciliation Retrieve detailed metadata for a specific charge, including its internal lifecycle state and tax calculations. ### External Invoice Synchronization Manage links to external accounting systems (e.g., Fatture in Cloud) for each charge. #### Retrieve Invoice Metadata #### Persist Invoice Metadata *** ### Global Charge Resolution Resolve charge details using only the global unique identifier. This is optimized for callback handlers and webhook reconciliation modules. # Directory Monitor import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Directory Monitor The Directory Monitor API enables real-time synchronization and event orchestration for local filesystem changes. It is designed for deep integration with local agents to monitor project directories, capture file events, and trigger remote workflows. *** ## Initialize Monitor (Startup) Signal the start of a monitoring session for a specific project. This initialization step validates the project configuration and prepares the environment for ingress events. *** ## Synchronize Event (Ingress) Report a filesystem event (creation, modification, deletion) to the centralized monitor. This endpoint processes file metadata and executes any associated workflow triggers. *** ## Audit Monitor Events Retrieve a paginated history of synchronized filesystem events for a specific project. This is used for auditing changes and verifying synchronization state. # DNS # DNS API Use DNS endpoints for diagnostic and propagation checks across public resolvers. ## DNS Capabilities ## DNS Lookup (GET) ## DNS Lookup (POST) # Content Box import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Content Box API The Content Box system provides a schematized storage layer for unstructured or custom-structured data. It allows organizations to define complex data models (Types) and instantiate them as managed content entities (Contents), suitable for blogs, product catalogs, and internal metadata repositories. *** ## Content Entity Management Manage the lifecycle of data entries within your defined content structures. ### List Content Entities Retrieve a paginated collection of content entities. Results can be filtered by state, content type, or via a full-text search query. ### Create Content Entity Provision a new content entry. The `data` payload must adhere to the requirements of the associated `type_id`. ### Update Content Entity Modify an existing content entry. This endpoint supports partial updates; only the fields provided in the `content` object will be modified. ### Retrieve Content Entity Fetch the full payload for a single content entry. ### Decommission Content Entity Permanently delete a content entry. This action is irreversible. *** ## Content Type Modeling (Schema Definition) Define and manage the structural blueprints that govern how content is stored and validated. ### List Content Types Retrieve the catalog of all defined content schemas for your organization. ### Create Content Type Define a new organizational schema. Specify the attributes and UI input types for each field in the model. {label, type})." } ]} responses={[ { status: "201 Created", description: "Content type definition created.", content: { "id": "6751...", "title": "E-Commerce Product" } } ]} /> ### Retrieve Type Definition Fetch the precise structural definition for a specific content type. ### Update Type Definition Update metadata or fields for a specific content schema. When `fields` is provided, each field must include both `label` and `type` and use allowed input types. # Email Gateway # Email Gateway API The Email Gateway API manages template files and transactional sends. *** ## List Templates ## Create Template Hello FIRST_NAME" } }} properties={[ { name: "template.id", type: "string", required: true, description: "Template filename identifier." }, { name: "template.content", type: "string", required: false, description: "Optional initial template content." } ]} responses={[ { status: "201 Created", description: "Template created.", content: { "id": "welcome.html" } }, { status: "409 Conflict", description: "Template already exists.", content: { "error": "Template already exists" } } ]} /> ## Get Template Hello FIRST_NAME" } }, { status: "404 Not Found", description: "Template not found.", content: { "error": "Template not found" } } ]} /> ## Update Template Hello FIRST_NAME

Updated

" } }} properties={[ { name: "template.content", type: "string", required: true, description: "Template content to persist." } ]} responses={[ { status: "200 OK", description: "Template updated.", content: { "id": "welcome.html", "updated": true } } ]} /> ## Delete Template ## Preview Template Hello Alex" } } ]} /> ## Dispatch Transactional Email # General import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # General API The General API provides a set of infrastructure-level endpoints designed for environmental diagnostics and the retrieval of global static datasets. These tools are essential for verifying network reachability, inspecting client-server connection properties, and populating standardized geographic data across your application. *** ## Infrastructure Health (Ping) A high-performance heartbeat endpoint used to verify that the DonutWork API gateway is operational and to measure basic network round-trip time (RTT). ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/ping.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js const heartbeat = await sdk.utils.ping(); console.log(`System Status: ${heartbeat.status} (${heartbeat.RRT})`); ``` *** ## Connection Diagnostics Retrieve a detailed diagnostic profile of your current API session. This endpoint is instrumental for debugging network protocols, verifying IP whitelisting, and ensuring the correct API version is being targeted. *** ## Global Metadata (Countries) Retrieve a comprehensive, standardized list of countries and their associated ISO 3166-1 alpha-2 codes. This dataset ensures data integrity when capturing geographic information in user profiles or billing addresses. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/countries/countries.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js const countryList = await sdk.utils.listCountries(); const italy = countryList.find(c => c.code === 'IT'); console.log(`Country Name: ${italy.name}`); ``` # GeoIP (Location Services) import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # GeoIP API The GeoIP API enables the resolution of IPv4 addresses into rich geographical and jurisdictional datasets. Beyond simple location coordinates, this service provides essential metadata—including currency systems, telecommunication prefixes, and linguistic profiles—enabling automated tax compliance (VAT/GST), regional content personalization, and fraud detection through threat-level auditing. *** ## Intelligence Resolution (Geo-Location) Retrieve the full intelligence profile for a specific IPv4 address. This includes Autonomous System (AS) data, high-level geolocation, and localized jurisdictional metadata. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/geoip/ip.json?ip=8.8.8.8' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js const ipAddress = "8.8.8.8"; try { const data = await sdk.geolocation.resolve(ipAddress); console.dir(data, { depth: null }); } catch (error) { console.error(`Resolution Failed: ${error.message}`); } ``` **Business Context:** Use this data to automate tax profile selection for checkout flows or to enforce regional compliance for regulated digital services. # Identity Provider (IDP) & MFA import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Identity Provider (IDP) API The Identity Provider (IDP) service centralizes user identity management and provides robust secondary authentication layers. It allows organizations to link external user identifiers to a secure, managed identity capable of Multi-Factor Authentication (MFA) via Time-based One-Time Passwords (TOTP) and advanced risk assessment (Sentinel). *** ## Identity Management ### Provision External User Provision a new managed identity within the IDP ecosystem. This creates a security context linked to your platform's internal `external_id`. ### Retrieve Identity Profile Fetch the security profile for a specific user. This includes authentication capabilities (MFA status), operational status (locked/active), and audit metadata. *** ## Multi-Factor Authentication (MFA) ### Configuration of TOTP Secret Generate a new TOTP secret and QR code payload to enable secondary authentication. Scanning this payload into an authenticator application (e.g., Microsoft/Google Authenticator) completes the setup. ### Verify Authentication Code Validate a 6-digit TOTP code (or a one-time backup code) to finalize the authentication process. ### Provision Backup Codes Generate a collection of single-use backup codes. These allow users to regain access if the primary MFA device is unavailable. *** ## Sentinel Risk Assessment Sentinel provides a sophisticated analytical layer for evaluating authentication risk in real-time. ### Analyze Session Integrity (Discover) Submit session metadata to Sentinel to perform a risk assessment based on behavioral patterns, network reputation, and environmental context. # API Reference import { ShieldCheck, Key, Mail, MapPin, Link, Percent, Share2, Box, Layers, Zap } from 'lucide-react'; Initialize your integration with our unified headless architecture. Designed to handle millions of requests with enterprise-grade latency and deterministic execution. *** ## Core Infrastructure
### Identity Provider (IDP) Manage user identities with native MFA and TOTP support. [Explore IDP →](/en/docs/api/idp)
### Key Management Service (KMS) Store and reveal sensitive credentials with strict IP whitelisting. [Explore KMS →](/en/docs/api/kms)
### Email Gateway **Transactional Intelligence.** Trigger localized templates with dynamic variable injection. Scale communications via high-deliverability routes. [Explore Email →](/en/docs/api/email-gateway)
### GeoIP & Metadata **Localized Intelligence.** Resolve IPv4 to precise geographic data and rich country metadata for automated compliance and tax logic. [Explore GeoIP →](/en/docs/api/geo-ip)
*** ## Growth & Operations
#### Share Secrets One-time encrypted payload sharing with automatic purge.
#### Shortlinks URL redirection with traffic attribution.
#### Taxes VAT and sales tax logic for billing compliance.
#### DNS Multi-resolver DNS diagnostics and propagation checks.
#### Mobile Push Register and revoke iOS push tokens for mobile clients.
*** ## Enterprise Orchestration
### Content Box Model custom data structures and serve them via a unified JSON API. [Explore Content Box →](/en/docs/api/dynamic-content)
### Workflow Automate business logic with stage-based auditing and dynamic payload injection. [Explore Workflow →](/en/docs/api/workflow)
*** ### Integration Architecture | Metric | Specification | | :------------------ | :-------------------------- | | **Uptime SLA** | 99.99% Enterprise Tier | | **Auth Protocol** | Bearer Token (Stateless) | | **Default Version** | `2026-02-01` | | **Execution** | Deterministic / Low Latency | # Integrations & Capabilities import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Integrations & Capabilities API The Integrations API provides a unified abstraction layer for extending the DonutWork core platform with third-party application functionalites. By declaring "capabilities," applications can expose their own endpoints as managed actions within the DonutWork ecosystem, allowing for seamless cross-platform orchestration, automated authorization handling (app-to-app), and centralized audit logging. *** ## Lifecycle Management ### Audit Active Integrations Retrieve a paginated directory of all integrations currently authorized for your organization. This includes high-level connectivity status and identification handlers for each service. ### Declare Functional Capabilities Register or update the specific actions (capabilities) that your application exposes. This declaration defines the input requirements and contract for each action, enabling DonutWork to proxy requests to your service securely. *** ## Resource Discovery ### Retrieve Specific Integration Fetch the full configuration, permission sets, and connectivity health for a specific integration. *** ## Execution (Capability Proxy) ### Dispatch Delegated Action Execute a capability on a remote integration. DonutWork acts as a secure proxy, handling authorization headers and validating input schemas before relaying the request to the target service. The request payload for action dispatch is dynamic. Required body fields are validated at runtime using the integration capability declaration (`capabilities[].inputs[]` with `required: true`). ### Read Delegated Action ### Update Delegated Action ### Delete Delegated Action ### Emit Integration Event Emit an application-scoped event so workflows and event listeners can react to integration activity. .` format.", location: "path" } ]} body={{ "metadata": { "message_id": "msg_001", "status": "sent" }, "entity_id": "SLACK_ENT" }} properties={[ { name: "metadata", type: "object", required: false, description: "Event payload metadata object." }, { name: "entity_id", type: "string", required: false, description: "Entity identifier. If omitted, the app handler is used." } ]} responses={[ { status: "200 OK", description: "Event accepted and dispatched.", content: { "success": true, "app_handler": "SLACK", "event": "Slack.MESSAGE_SENT", "queued_workflows": 1 } } ]} /> ### Technical Implementation ```sh curl --location --request POST \ 'https://api.hub.donutwork.com/2026-02-01/integrations/SLACK/SEND_MSG.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' \ --header 'Content-Type: application/json' \ --data-raw '{"message": "Automated Deployment Completed"}' ``` ```js const payload = { message: "System Alert: Resource threshold reached." }; try { const result = await sdk.integrations.dispatch("SLACK", "SEND_MSG", payload); console.log(`Action Result: ${result.success} (Status: ${result.external_status})`); } catch (error) { console.error(`Dispatch Failed: ${error.message}`); } ``` # Job Runner # Job Runner API ## List Jobs ## Create Job ## Run Job ## Delete Job # Key Management Service (KMS) import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # Key Management Service (KMS) API The Key Management Service (KMS) provides a hardened environment for the storage and lifecycle management of sensitive credentials, such as third-party API keys, service accounts, and cryptographic tokens. By using KMS, organizations can eliminate the risk of hardcoded secrets within source code, instead retrieving them dynamically via secure, audited endpoints protected by strict IP-based whitelisting. *** ## Secret Management ### Audit KMS Inventory Retrieve a paginated directory of all KMS secret handlers associated with your organization. This endpoint provides administrative metadata and is used for secret discovery; it does **not** expose the underlying secret values. ### Retrieve Secret Configuration Fetch the detailed metadata and operational configuration for a unique KMS handler. This includes the registered IP whitelist and custom properties defined for the secret. *** ## Secret Consumption ### Decrypt & Reveal Secret Securely decrypt and reveal the underlying secret content. Access to this endpoint is strictly enforced via IP-based whitelisting and results in an immediate audit entry. Use this endpoint only within backend environments to dynamically inject credentials. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/kms/reveal/aws-s3-prod-credentials.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js const handler = "aws-s3-prod-credentials"; try { const secret = await sdk.kms.reveal(handler); console.log(`Resource Access Granted. Payload: ${secret.content}`); } catch (error) { console.error(`Vault Access Denied: ${error.message}`); } ``` **Security Audit:** Every call to the `reveal` endpoint is logged with the requesting IP, User-Agent, and timestamp. Ensure your infrastructure IPs are properly whitelisted in the KMS configuration to avoid 403 authorization failures. # Media Library # Media Library API ## Strategy For large files, use presigned direct upload: 1. Request upload link from API. 2. Upload file directly to storage with `PUT`. 3. Use media list or download-link APIs for retrieval flow. ## List Files ## Create Upload Link ## Upload File (Fallback) ## Create Download Link # Mobile Push Tokens # Mobile Push Tokens API These endpoints are available only when using a mobile-scoped API key. ## Save Device Push Token ## Delete Device Push Token # Newsletter Campaigns # Newsletter API The Newsletter API exposes campaign lifecycle, recipient synchronization, dispatch queue controls, analytics, and suppression list management. *** ## List Newsletter Campaigns ## Create Newsletter Campaign ## Retrieve Campaign Details ## Update Campaign Metadata ## Delete Campaign ## Get Campaign Recipients Snapshot ## Set Campaign Recipients ## Queue Campaign Dispatch ## Send Test Email ## Get Campaign Stats *** ## Suppression List ### List Unsubscribes ### Add Unsubscribe ### Resubscribe Email # Partner Groups import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # Partner Groups API Partner Groups provide an automated logic layer for categorizing partners and enforcing organization-wide distribution policies. These groups define rules that govern revenue sharing percentages, time-based commission tiers, and performance-driven upgrades based on total Lifetime Value (LTV) or charge volume. *** ## Group Inventory ### List Partner Groups Retrieve a paginated directory of all defined Partner Groups. This directory contains the high-level metadata and administrative identifiers for each group. ### Retrieve Group Configuration & Rules Fetch the comprehensive configuration for a specific governance group, including the active rules engine parameters that define commission logic. *** ## Group Lifecycle Management ### Create Partner Group ### Update Partner Group ### Delete Partner Group ### Simulate Rules *** ## The Rules Engine Partner groups are powered by a deterministic rules engine that evaluates transactions in real-time. The following rule types are supported: ### Rule Type Definitions | Rule Type | Description | Key Parameters | | :----------------------- | :------------------------------------------------------------------------------------------------ | :------------------------------------ | | `new_customer_time_tier` | Applies a specific commission for the initial months of a customer's lifecycle. | `max_months`, `percentage` | | `recurring` | The baseline commission applied to all transactions when no other specific rule applies. | `percentage` | | `partner_ltv_upgrade` | Triggers a commission percentage increase once a partner's total managed LTV exceeds a threshold. | `min_ltv_total`, `upgrade_percentage` | | `charge_threshold_bonus` | Provides a one-time bonus for transactions exceeding a specific amount. | `min_charge_total`, `bonus` | **Evaluation Hierarchy:** Rules are evaluated based on the customer's acquisition date and the partner's historical performance. A `recurring` rule is required for all groups as a fallback mechanism. # Partners import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Partners API The Partners API enables organizations to build and scale distribution networks through agencies, resellers, and affiliates. It provides a framework for managing partner identities, commission calculations (fees), and financial settlements (payouts), while maintaining clear attribution for every customer acquired through the channel. *** ## Channel Management ### List Partners Retrieve a paginated directory of all registered partners. This list includes high-level identification data and current status for each collaborative entity. ### Provision New Partner Onboard a new partner into the ecosystem. This initializes their profile and associates them with a governance group (Partner Group) to define their commission rules. ### Retrieve Partner Profile Fetch the comprehensive profile of a specific partner, including their fee structure, whitelist configuration, and association metadata. *** ## Attribution & Performance ### Audit Attributed Customers Retrieve a paginated list of all customers currently attributed to a specific partner. This is used to verify channel performance and revenue attribution. ### Performance Analytics Retrieve high-level performance metrics for a partner, including total attributed revenue and cumulative commissions earned. *** ## Financial Settlement (Payouts) ### Audit Commission Ledger (Fees) Retrieve individual commission entries (fees) generated by attributed customer transactions. These entries serve as the basis for payout generation. ### Generate Payout Request Consolidate multiple 'pending' commission fees into a single Payout request. This initiates the financial settlement cycle and generates a draft settlement record. ### Retrieve Payout Documentation (PDF) Retrieve a base64-encoded PDF report (Account Statement) for a specific payout. This document serves as the official settlement record for the partner. ### Technical Implementation (Payout Flow) ```js const payoutData = { payout: { partner_id: "PARTNER_6621", transactions: ["FEE_001", "FEE_002"], invoice: { number: "REF-9921", date: "2026-03-03" }, vat_settings: { tax_id: "VAT_22_IT" } } }; try { const settlement = await sdk.partners.createPayout(payoutData); console.log(`Settlement Processed. ID: ${settlement.id}, Total: ${settlement.total}`); } catch (error) { console.error(`Settlement Failed: ${error.message}`); } ``` *** ## Additional Partner Operations ### Search Partner by External ID or Email ### Update Partner Profile ### Delete Partner ### Get Partner Fee by ID ### List Global Payouts ### List Payouts for One Partner ### Get Payout by Partner and ID ### Get Payout by ID ### Update Payout Status ### Stream Payout PDF # Recurring Payments import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Recurring Payments API The Recurring Payments API provides the operational infrastructure for managing subscription-based revenue models. It allows organizations to define sophisticated billing cycle parameters, configure automated dunning (retry) policies for failed transactions, and monitor the real-time status of all active subscriptions across the platform. *** ## Operational Configuration ### Audit Recurring Settings Retrieve the global operational parameters governing recurring billing. This includes the current retry logic for failed payments and the timing offsets for subsequent billing cycles. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/recurring-payments/settings.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js try { const config = await sdk.recurringPayments.getSettings(); console.log(`Billing Policy: ${config.settings.retry_policy} (Max Retries: ${config.settings.max_retries})`); } catch (error) { console.error(`Fetch Failed: ${error.message}`); } ``` *** ## Subscription Lifecycle Monitoring ### Audit Active Subscriptions Retrieve a comprehensive inventory of all subscriptions currently managed by the recurring payment engine. This endpoint provides crucial visibility into renewal dates, customer associations, and current billing health. ### Implementation ```js const filters = { page: 1, size: 50 }; try { const activeSubs = await sdk.recurringPayments.listSubscriptions(filters); activeSubs.elements.forEach(sub => { console.log(`Subscription ${sub.id}: Renewal due on ${sub.next_renewal_date}`); }); } catch (error) { console.error(`Telemetry Error: ${error.message}`); } ``` # Scheduler # Scheduler API ## List Events ## Create Event ## Update Event ## Delete Event # Share Secrets import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # Share Secrets API The Share Secrets API provides a secure mechanism for transmitting sensitive information (such as passwords, private keys, or PII) without leaving a persistent digital footprint. Secrets are encrypted and associated with a unique, short-lived URL. To ensure maximum security, content is **purged immediately after the first successful access**, rendering the link permanently invalid. *** ## Secret Management ### Audit Secret Inventory Retrieve a paginated directory of all active (unread) or recently expired share secret entries. This allows for administrative tracking of shared links and their current consumption status. ### Provision Secure Secret Link Generate a new ephemeral secret link. The `content` provided is encrypted at rest and will be revealed only once. You can optionally trigger an automated email notification to the recipient. ### Technical Implementation ```js const secretPayload = { shareSecret: { name: "Inter-Service Auth Key", content: "PRIVATE_KEY_CONTENT_HERE", sendTo: { email: "security-ops@acme.com", message: "Key Rotation: 2026-Q1" } } }; try { const response = await sdk.tools.createShareSecret(secretPayload); console.log(`Secret Link Generated: ${response.url}`); } catch (error) { console.error(`Provisioning Failed: ${error.message}`); } ``` *** ## Access & Revocation ### Audit Access Metadata Retrieve the access status and reader telemetry for a specific secret link. This endpoint provides audit trails (IP, User-Agent, Timestamp) once the secret has been consumed. ### Revoke Secret Link Manually revoke a secret link before it is consumed, or purge the audit record of an already read secret. **Security Policy:** Content retrieval is handled via the specific `url` field returned during provisioning. Once the `readed` flag is set to `true`, the content is physically deleted from the database and cannot be recovered. # Shortlinks import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Shortlinks API The Shortlinks API enables organizations to transform complex destination URLs into concise links. Beyond simple redirection, the system provides integrated telemetry for traffic attribution, enabling teams to monitor engagement performance in real time across distribution channels. *** ## Link Lifecycle Management ### Audit Shortlink Directory Retrieve a paginated directory of all shortlinks associated with your organization. This inventory includes current operational status and destination metadata. ### Provision New Shortlink Generate a new shortlink for a target destination.\ You can optionally provide a custom `fragment` (bitly-style suffix). The platform always prepends an auto-generated prefix to reduce collision risk. ### Retrieve Link Configuration Fetch the detailed configuration and operational status for a specific shortlink. *** ## Operational Controls ### Update Link Parameters Modify the destination URL, custom fragment, or operational status of an existing shortlink. Link updates are propagated across the redirection edge in near real-time.\ When updating `fragment`, the existing auto-generated prefix is preserved. ### Revoke Shortlink Permanently revoke a shortlink and decommission its redirection service. *** ## Analytics & Telemetry ### Retrieve Interaction Metrics Access real-time engagement telemetry for a specific shortlink. This include visit counts, unique interactions, and longitudinal performance data. ### Technical Implementation ```js const shortlinkId = "675d9fea..."; try { const stats = await sdk.dw2.getStats(shortlinkId); console.log(`Campaign Performance: ${stats.metrics.summary.total} total interactions.`); } catch (error) { console.error(`Telemetry Error: ${error.message}`); } ``` # Taxes import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # Taxes API The Taxes API provides a centralized layer for managing tax profiles and regional tax logic. By defining tax profiles (such as VAT, GST, or Sales Tax), organizations can automate tax calculation during invoicing and subscription renewals, ensuring consistent compliance with local regulations. *** ## Tax Profiles ### List Tax Profiles Retrieve a comprehensive directory of all tax profiles configured for your organization. These profiles act as the authoritative source for tax percentage calculations and must be referenced when provisiong new customers or products. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/taxes.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js try { const taxProfiles = await sdk.taxes.list(); console.log(`Active Tax Profiles: ${taxProfiles.count}`); } catch (error) { console.error(`Compliance Check Failed: ${error.message}`); } ``` **Integration Note:** When orchestrating customer provisioning (via the CRM/Customer API), ensure the `tax_id` from these profiles is correctly mapped. This association is critical for accurate automated invoicing and financial reporting. *** ## Tax Profile Lifecycle ### Create Tax Profile = 0." }, { name: "tax.description", type: "string", required: false, description: "Optional internal description." }, { name: "tax.default", type: "boolean", required: false, description: "Marks the profile as default when true." } ]} responses={[ { status: "201 Created", description: "Tax profile created.", content: { "status": "success", "tax": { "id": "tax_001", "name": "Standard EU VAT (22%)", "percentage": 22.0 } } } ]} /> ### Update Tax Profile = 0." }, { name: "tax.default", type: "boolean", required: false, description: "Update default profile flag." } ]} responses={[ { status: "200 OK", description: "Tax profile updated.", content: { "status": "success", "tax": { "id": "tax_001", "name": "EU VAT 2026", "percentage": 23.0 } } } ]} /> ### Delete Tax Profile # Webhook API # Webhook API Use webhooks to receive asynchronous notifications for supported platform events. *** ## List Webhooks ## Create Webhook ## List Supported Webhook Types ## Get Webhook ## Delete Webhook # Workflow import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # Workflow API The Workflow API provides an engine for orchestrating complex, multi-stage business processes. By defining structured workflows, organizations can automate repetitive operational tasks, ensuring deterministic execution and full auditability. The engine supports dynamic payload injection for contextualized automation across the platform. *** ## Workflow Management ### List Workflows Retrieve a comprehensive directory of all registered business workflows for your organization. This inventory includes the operational status, task count, and administrative metadata for each automation. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/workflow.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js try { const inventory = await sdk.workflow.list(); console.log(`Active Automations: ${inventory.count}`); } catch (error) { console.error(`Workflow Audit Failed: ${error.message}`); } ``` *** ## Workflow Execution ### Dispatch Workflow Execution Trigger the execution of a specific business workflow. This endpoint accepts a dynamic `data` payload that is injected into the execution context, allowing tasks to operate on real-time request data. ### Technical Implementation (Execution Flow) ```js const context = { data: { userId: "USR-001", action: "PROVISION_RESOURCE", quota: 100 } }; try { const result = await sdk.workflow.execute("ONBOARD_WF_01", context); if (result.success) { console.log(`Automation Finished: ${result.execution_id}`); } } catch (error) { console.error(`Execution Halted: ${error.message}`); } ``` **Auditability:** Every workflow execution generates a unique `execution_id` and provides detailed telemetry for each stage (node) within the sequence, including input/output data and operational latency. *** ## Workflow Tracing ### List Workflow Traces Retrieve paginated execution traces for a workflow. ### Get Workflow Trace Load full trace payload for one workflow run. # Authentication & Iframe Governance import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Step, Steps } from 'fumadocs-ui/components/steps'; import { Callout } from 'fumadocs-ui/components/callout'; # Authentication & Embedding DonutWork uses a robust security model to ensure that third-party applications can securely access data while providing a unified user experience. This guide covers the Dual-Auth workflow and the requirements for enterprise-grade Iframe embedding. *** ## 1. The OAuth 2.0 Workflow Applications use a standard OAuth 2.0 Authorization Code flow to obtain scoped access to a company's data. ### Step 1: Authorization Request Redirect the user to the DonutWork authorization server. This occurs when a user first installs or accesses your app. **Endpoint**: `GET /i3/oauth/authorize` **Parameters**: * `client_id`: Your unique application identifier. * `redirect_uri`: The endpoint where the code will be sent. * `response_type`: Always `code`. * `scope`: Space- or comma-separated list of permissions in canonical format `resource:action` (e.g., `customers:read charges:write`). * `scope` minimum requirement: include at least `company:read` to complete a valid OAuth connection flow for app integrations. * `state`: A unique string to prevent CSRF attacks. ### Step 2: Token Exchange Once the user approves the request, DonutWork redirects them to your `redirect_uri` with a `code`. Exchange this code for an access token immediately. **Endpoint**: `POST /i3/oauth/token` (Form-Encoded) **Body**: * `client_id`: Your application identifier. * `client_secret`: Your secure application secret. * `code`: The authorization code received in the redirect. * `redirect_uri`: Must match the URI used in Step 1. ### Step 3: Persistence Store the returned `access_token` and `refresh_token` securely. These tokens allow your app to make direct API calls to DonutWork (e.g., to `/2026-02-01/customers.json`). *** ## 2. Iframe Context & Security When an application is rendered inside the DonutWork dashboard, it is embedded via an Iframe. Every request to your application's entry point includes a security signature. ### Request Parameters DonutWork appends the following query parameters to your application URL: * `company`: The unique identifier of the active company. * `hmac`: A cryptographic signature of the request. * `timestamp`: The Unix timestamp of the request. ### Signature Verification (HMAC-SHA256) To verify that the request is authentic and originated from DonutWork, you must validate the `hmac` parameter using your `client_secret`. **Verification Procedure**: 1. Remove the `hmac` parameter from the key-value pairs. 2. Sort the remaining parameters alphabetically by key. 3. Concatenate the sorted keys and values into a query string (e.g., `company=C123×tamp=1740000000`). 4. Calculate the HMAC-SHA256 of this string using your `client_secret` as the key. 5. Compare the result with the provided `hmac`. ```js const crypto = require('crypto'); function verifyHmac(queryParams, clientSecret) { const { hmac, ...params } = queryParams; const message = Object.keys(params) .sort() .map(key => `${key}=${params[key]}`) .join('&'); const expectedHmac = crypto .createHmac('sha256', clientSecret) .update(message) .digest('hex'); return hmac === expectedHmac; } ``` ```text 1. ARGS = QueryString.Remove("hmac") 2. SORTED_MSG = ARGS.SortByKey().Join("&") 3. SIGNATURE = HMAC_SHA256(SORTED_MSG, APP_CLIENT_SECRET) 4. VALIDATE(SIGNATURE == QueryString["hmac"]) ``` *** ## 3. UI Integration Requirements Because the application runs in a cross-site Iframe, standard browser security policies apply. ### Session Management Modern browsers block third-party cookies by default. To maintain a session within the Iframe, your session cookies **must** use the following attributes: * `SameSite=None`: Allows the cookie to be sent in a cross-site context. * `Secure=true`: Required when `SameSite=None` is used. If your cookies do not have `SameSite=None; Secure`, users will be logged out immediately after redirection or when navigating within the app. ### Content Security Policy (CSP) Ensure your server headers allow DonutWork to embed your application: ```http Content-Security-Policy: frame-ancestors 'self' https://hub.donutwork.com; X-Frame-Options: ALLOW-FROM https://hub.donutwork.com ``` *** ## 4. Capability Discovery As the final step of the authentication flow, your application should declare its "capabilities" to the platform. This allows DonutWork to proxy requests to your app (Actions). **Action**: `PUT /2026-02-01/integrations.json` This declaration should include your `app_token` (used by DonutWork to call you) and a manifest of supported endpoints. Refer to the [Application Discovery Guide](/en/docs/applications/how-to-build#2-capability-discovery-the-manifest) for details. For uninstall flow details (`DELETE uninstall_url` with `company_id` + HMAC `verify`), refer to [How to Build](/en/docs/applications/how-to-build). # Donutwork Claude Code Skill import { Callout } from 'fumadocs-ui/components/callout'; # Donutwork Claude Code Skill The official Claude Code bundle is designed for teams that use Claude Code as their implementation copilot for Donutwork integrations. It provides ready-to-use context so your team can move from API discovery to production launch with less rework. *** ## Why Teams Adopt It * Speed up integration delivery with a structured `SKILL.md`. * Reduce scope mistakes with endpoint and ACL references. * Build payloads with higher confidence using field-level entity models. * Standardize AI-assisted implementation across teams. *** ## What Is Included * `.claude/skills/donutwork/SKILL.md`: Claude Code skill instructions and operating workflow. * `references/api-endpoint-map.json`: method/path/scope inventory. * `references/entity-models.json`: field-level entity model catalog. * `references/openapi.public.json`: OpenAPI snapshot for tooling. * `references/integration-playbook.md`: implementation and launch blueprint. *** ## Download * Latest package (`.skill`): [`/downloads/donutwork-claude-code-skill-latest.skill`](/downloads/donutwork-claude-code-skill-latest.skill) * Latest checksum: [`/downloads/donutwork-claude-code-skill-latest.sha256`](/downloads/donutwork-claude-code-skill-latest.sha256) * Versioned package (`v1.1.0`): [`/downloads/donutwork-claude-code-skill-v1.1.0.skill`](/downloads/donutwork-claude-code-skill-v1.1.0.skill) * Versioned checksum (`v1.1.0`): [`/downloads/donutwork-claude-code-skill-v1.1.0.sha256`](/downloads/donutwork-claude-code-skill-v1.1.0.sha256) *** ## Install In 60 Seconds ```bash unzip -o donutwork-claude-code-skill-latest.skill -d "$HOME" ``` Optional integrity check: ```bash sha256sum -c donutwork-claude-code-skill-latest.sha256 ``` This package installs `.claude/skills/donutwork/SKILL.md` and references under your home directory, so Claude Code can auto-discover the skill. *** ## Quickstart Prompts 1. `Map required scopes for customers, charges, and webhooks in our Donutwork integration.` 2. `Generate payload contracts for customer and subscription synchronization.` 3. `Prepare a production readiness checklist for our Donutwork API launch.` *** ## Next Steps * Start from the [AI Integration Hub](/en/docs/ai-integration) for the full AI-first path. * If your team uses Codex, see [Donutwork Codex Skill](/en/docs/applications/donutwork-skill). * Use [API Authentication](/en/docs/api/authentication) to validate key and OAuth setup. # Donutwork Codex Skill import { Callout } from 'fumadocs-ui/components/callout'; # Donutwork Codex Skill The official `donutwork` Codex skill is a ready-to-use integration accelerator for partner and product teams. It turns API docs into implementation-ready guidance with scope mapping, entity payload models, and go-live checklists. *** ## Why Teams Adopt It * Reduce API onboarding time from days to hours. * Build safer integrations with least-privilege scope guidance. * Standardize payload contracts across engineering teams. * Improve go-live confidence with repeatable validation checklists. *** ## What Is Included * `SKILL.md`: operating workflow and response contract. * `references/api-endpoint-map.json`: method/path/scope inventory. * `references/entity-models.json`: field-level entity model catalog. * `references/openapi.public.json`: OpenAPI snapshot for tooling. * `references/integration-playbook.md`: implementation and launch blueprint. *** ## Download * Latest package: [`/downloads/donutwork-skill-latest.tar.gz`](/downloads/donutwork-skill-latest.tar.gz) * Latest checksum: [`/downloads/donutwork-skill-latest.sha256`](/downloads/donutwork-skill-latest.sha256) * Versioned package (`v1.0.0`): [`/downloads/donutwork-skill-v1.0.0.tar.gz`](/downloads/donutwork-skill-v1.0.0.tar.gz) * Versioned checksum (`v1.0.0`): [`/downloads/donutwork-skill-v1.0.0.sha256`](/downloads/donutwork-skill-v1.0.0.sha256) *** ## Install In 60 Seconds ```bash mkdir -p "${CODEX_HOME:-$HOME/.codex}/skills" tar -xzf donutwork-skill-latest.tar.gz -C "${CODEX_HOME:-$HOME/.codex}/skills" ``` Optional integrity check: ```bash sha256sum -c donutwork-skill-latest.sha256 ``` The extracted folder name is `donutwork`, so you can invoke it directly with `$donutwork`. *** ## Quickstart Prompts 1. `Use $donutwork to design an integration plan for syncing customers and subscriptions.` 2. `Use $donutwork to map required scopes for customer, charge, and webhook endpoints.` 3. `Use $donutwork to generate request payload models and a production go-live checklist.` *** ## Next Steps * Start from the [AI Integration Hub](/en/docs/ai-integration) for a complete AI-first integration path. * If your team uses Claude Code, see [Donutwork Claude Code Skill](/en/docs/applications/donutwork-claude-code-skill). * Use [API Authentication](/en/docs/api/authentication) to validate API key and OAuth setup. * Use [API Reference](/en/docs/api) to expand your endpoint coverage after the first release. # How to Build a DonutWork App import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Building for DonutWork This guide provides a conceptual and technical blueprint for developing third-party applications. The DonutWork framework is explicitly **programming language agnostic**, relying on standard HTTP/REST protocols and secure UI embedding to facilitate cross-system orchestration. *** ## 1. Application Registration Before you begin development, you must register your application to obtain the necessary credentials for identity and platform access. * **Client ID**: Your application's public identifier. * **Client Secret**: A secure credential used to authorize your app to act on behalf of a company. * **Redirect URI**: The URL where DonutWork will send authorization codes. Refer to the [Detailed OAuth Guide](/en/docs/applications/auth-and-embedding) for the technical authentication handshake. *** ## 2. Capability Discovery (The Manifest) DonutWork uses a **Discovery Pattern** to understand what your application is capable of. Instead of DonutWork calling your app blindly, your app must "declare" its capabilities (Actions). ### Declaring Capabilities Your application should send a `PUT` request to the `/integrations.json` endpoint. This manifest tells DonutWork which endpoints to call when a specific action is triggered (e.g., via a Workflow or the UI). * **app\_token**: DonutWork will include this Bearer token in every `Authorization` header when it calls your application. This allows your app to verify that the request is coming from DonutWork. * **capabilities**: An array of allowed actions, each with a defined `endpoint`, `method`, and expected `inputs`. *** ## 3. Communication Pattern (The Action Logic) When a user or a generic workflow triggers an action, DonutWork acts as a **Secure Proxy**. 1. **Trigger**: DonutWork identifies the target `Action` (e.g., `provision_resource`). 2. **Identification**: DonutWork retrieves the `endpoint` and `app_token` from your saved manifest. 3. **Execution**: DonutWork sends an HTTP request to your endpoint, including the `app_token` in the header and the required data in the body. 4. **Response**: Your application processes the request and returns a standard JSON response. *** ## 4. UI Framework (The Iframe) DonutWork embeds your application's frontend inside its own dashboard via an **Iframe**. To ensure a smooth user experience and maintain security, you must adhere to the following policies: ### Cookie Security (`SameSite=None`) Because your application is running in an Iframe context (cross-site), traditional session cookies may be blocked by modern browsers. You must configure your session cookies with: * `SameSite=None` * `Secure=true` ### Security Headers DonutWork allows Iframe embedding from registered applications. On your end, you should ensure your headers allow the platform to display your content. For a deep dive into signature verification, see [Iframe Context & Security](/en/docs/applications/auth-and-embedding#2-iframe-context--security). ```http Content-Security-Policy: frame-ancestors 'self' https://hub.donutwork.com; X-Frame-Options: ALLOW-FROM https://hub.donutwork.com ``` *** ## 5. Event Synchronization (Webhooks) To react to platform events in real-time (e.g., when a user pays a bill), you should register a Webhook. 1. **Endpoint**: Your application should provide a dedicated HTTPS URL to receive POST payloads. 2. **Key Rotation**: During registration, you will receive a `token`. Use this key to verify the `X-SIGNATURE` header on every incoming request. *** ## 6. Uninstall Callback (Company Data Cleanup) When a company uninstalls your app from DonutWork, the platform sends a server-to-server callback to your configured `uninstall_url`. * **Method**: `DELETE` * **Content-Type**: `application/x-www-form-urlencoded` * **Body**: * `company_id`: Company identifier to delete. * `verify`: HMAC signature computed as `HMAC_SHA256(company_id, client_secret)`. Example payload: ```http DELETE /uninstall HTTP/1.1 Content-Type: application/x-www-form-urlencoded company_id=699ecb44790ac4eea20e9cd3&verify=7c72b2... ``` Verification rule on your side: ```php $expected = hash_hmac('sha256', $companyId, $clientSecret); $isValid = hash_equals($expected, $verify); ``` Implementation requirements: * Validate `company_id` and `verify` before deleting anything. * Delete only tenant-scoped data for that `company_id`. * Make the endpoint idempotent (repeated calls must not fail). * Return a `2xx` response only when cleanup is completed (or already completed). If your endpoint returns non-2xx, DonutWork will treat the uninstall callback as failed and local uninstall will be blocked. *** ## Summary Checklist * [ ] Register App and obtain Client ID/Secret. * [ ] Implement OAuth 2.0 to obtain Platform Access Tokens. * [ ] Use `PUT /integrations.json` to declare your app's endpoints. * [ ] Implement your API endpoints to handle requests from the DonutWork proxy. * [ ] Configure `SameSite=None` and `Secure` cookies for your Iframe UI. * [ ] Register Webhooks for real-time event processing. * [ ] Implement `DELETE uninstall_url` with `company_id` + HMAC `verify` and tenant-safe cleanup. # Application Framework import { Puzzle, Settings, Zap, Shield, Package } from 'lucide-react'; import { Step, Steps } from 'fumadocs-ui/components/steps'; import { Callout } from 'fumadocs-ui/components/callout'; The DonutWork Application Framework allows developers to extend the platform's core capabilities with specialized third-party services. Whether you are building a financial connector, a marketing automation tool, or a custom CRM integration, our framework provides the necessary hooks for seamless orchestration. *** ## Integration Architecture DonutWork applications operate on a hybrid model that combines secure UI embedding with robust API-driven capability discovery.
### Capability Discovery **Autonomous Registration.** Applications declare their available "Actions" via a standard JSON manifest. DonutWork then makes these actions available to the core engine and workflows. [How to build →](/en/docs/applications/how-to-build)
### Iframe Embedding **Unified UI Experience.** Apps are embedded directly into the DonutWork dashboard. This ensures a consistent user experience while maintaining the app's independent execution context.
### Event-Driven Hooks **Real-Time Synchronization.** Use Webhooks to react to platform lifecycle events (charges, renewals, identity changes) and maintain data integrity across systems.
### Zero-Trust Security **Managed Authorization.** DonutWork acts as a secure proxy, handling authorization between the platform and your application with signed requests and scoped tokens.
### Codex Integration Skill **Faster Implementation.** Download the official `donutwork` skill package to get endpoint maps, entity models, and launch checklists for your integration team. [Get the skill →](/en/docs/applications/donutwork-skill)
*** ## Developer Roadmap Building an application for DonutWork involves the following key phases: ### Registration & Authentication Provision your application in the Developer Portal to obtain a unique `Client ID` and `Client Secret`. Use these to implement the standard [OAuth 2.0 flow](/en/docs/applications/auth-and-embedding). ### Capability Declaration Call the `/integrations.json` endpoint to tell DonutWork what your app can do. This manifest defines your endpoints, the methods they support, and the required input data. ### Lifecycle & UI Implementation Build your application frontend, ensuring compatibility with our [Iframe-based embedding system](/en/docs/applications/auth-and-embedding#2-iframe-context--security) and security policies (such as `SameSite` cookie requirements). ### Production Readiness Configure your webhook security tokens and deploy your service to a production environment. # Business Intelligence & Growth import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { TrendingUp, PieChart, Activity, Zap } from 'lucide-react'; # Business Intelligence & Growth The Donutwork BI & Growth section is designed to give you a crystal-clear view of your project's financial health. No more cross-referencing spreadsheets: everything is calculated automatically in real time. ## Key Metrics Tracked Donutwork aggregates data from the billing engine and user interactions to provide you with precise KPIs: } title="MRR & ARR" description="View monthly and annual recurring revenue with historical growth projections." /> } title="Revenue Mix" description="Detailed analysis of recurring revenue (subscriptions) and one-time revenue (add-ons, setup fees)." /> } title="Growth Rate" description="Month-over-Month (MoM) growth tracking to validate your marketing strategy." /> *** ## Revenue Analysis Donutwork intelligently separates the different revenue sources to allow you to understand what's truly driving your growth. ### Real-time Analytics As soon as you access the dashboard, you'll have a quick overview of: * **Recent Transactions:** Real-time history of every purchase or renewal. * **Customer Lifetime Value (LTV):** Automatic calculation of the average value of a customer over time. *** ## Growth Strategies Use the data collected to fuel your growth processes: * **Identify Power Users:** Discover which customers are most consistent and/or growing and propose upgrades to higher plans. * **Churn Prevention:** Monitor sudden drops in subscription activity to intervene before the user cancels their subscription. * **Partner Performance:** Cross-reference BI data with the [Partner Program](/en/docs/partner-program) to see which affiliates bring in the highest LTV customers. *** ## Operating Rhythm Turn BI into action with a recurring cadence: 1. Weekly: review failed renewals and churn signals. 2. Bi-weekly: compare cohort retention by acquisition source. 3. Monthly: adjust pricing, partner incentives, or plan packaging based on margin and LTV. For best results, review BI dashboards together with Customer, Recurring Payments, and Partner Program owners before shipping pricing or lifecycle changes. ## Related Areas * [Recurring Payments](/en/docs/recurring-payments) * [Customer Management](/en/docs/customer) * [Partner Program](/en/docs/partner-program) # Customer Management & Financial Hub import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Users, Fingerprint, CreditCard, Tags, TrendingUp, ShieldAlert, Receipt, Layers } from 'lucide-react'; # Customer Management & Financial Hub The **Customer** module in Donutwork is more than just a contact database; it is a financial control center for every individual client. It allows you to monitor business health through predictive metrics and manage the entire payment lifecycle. ## Customer Financial Scorecard (Beta) For every customer with at least one transaction, Donutwork automatically generates a **financial scorecard** to help evaluate stability and growth: } title="MRR & YRR" description="Instant calculation of Monthly Recurring Revenue and annual projections based on active subscriptions." /> } title="Risk Assessment" description="Analysis of volatility and history duration to assign a specific risk class to the customer." /> *** ## Subscription & Add-ons Management Donutwork allows for granular management of recurring revenue directly from the customer profile: * **Plan Association:** Quickly link existing subscription plans to the profile. * **Add-on Modification:** Dynamic management of quantities and pricing for additional subscription components. * **Tax & Discounts:** Apply global discounts (percentage or fixed) and manage multiple VAT rates per service line. * **Metering:** Monitor usage for consumption-based plans (Metered Billing). *** ## Payments & Transactions The interface organizes financial activities into three main sections using a persistent tab system: ### 1. Payment Methods Manage associated credit cards (via Stripe). The system supports: * **Secure Payment Links:** Generate protected links to allow customers to enter their payment details autonomously. * **CVC/3DS Validation:** Real-time security status checks for payment methods. ### 2. Transactions (Charges) A complete history of every charge attempt or successful payment: * **Manual Creation:** Create "One-time charges" (e.g., setup fees or consulting) directly from the panel. * **Receipts & Logs:** Immediate access to PDF receipts and status monitoring (Pending, Succeeded, Failed). ### 3. Subscriptions A dedicated tab to control active plans, renewal dates, and provisioning status. *** ## Dynamic Properties (Custom Fields) Beyond financial data, you can extend the customer profile using **Customer Properties**. These metadata fields are essential for: * Configuring custom API limits per customer. * Saving specific workflow preferences. * Mapping External IDs for third-party system integrations. # Directory Monitor & Event Automation import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { FolderSearch, ShieldCheck, Activity, Workflow, FileSearch, Timer, Fingerprint, Zap } from 'lucide-react'; # Directory Monitor The Donutwork Directory Monitor is a native **security + automation module** that tracks file activity in watched paths and converts those events into actionable automations. It is designed for teams that need: 1. Reliable filesystem event capture 2. Centralized event visibility 3. Deterministic workflow triggering *** ## System Architecture The module is built on four connected layers: 1. **Local Agent (Rust):** Watches directories and emits normalized events (`Create`, `Delete`, `WriteFinished`). 2. **Secure Ingress API:** Accepts monitor payloads, validates auth, and deduplicates by `eventId`. 3. **Event Store:** Persists monitor events with indexed search for operational and forensic review. 4. **Workflow Dispatcher:** Publishes both generic and typed triggers to run matching workflows. Existing generic triggers remain supported: DirectoryMonitor.\{projectId}.notify. You can progressively adopt typed triggers such as DirectoryMonitor.\{projectId}.WriteFinished.notify. *** ## Event Pipeline When a file changes, the following happens: 1. The monitor emits a payload with event metadata (`filename`, `event`, `filesize`, optional `sha256`, `uid`, `pid`, `timestampUtc`, `eventId`). 2. Ingress validates: * API key (`Authorization: Bearer ...`) * Project token (`X-Directory-Monitor-Token`) 3. Event is saved in the monitor event collection. 4. Two notifications are dispatched: * Generic: `DirectoryMonitor.{projectId}.notify` * Typed: `DirectoryMonitor.{projectId}.{event}.notify` 5. Matching workflows are queued and executed through the existing workflow async pipeline. *** ## Logs & Observability Directory Monitor includes a dedicated **Logs View** per project with: 1. Event filtering by: * Event type * Path contains * Status * Date range 2. Paginated event list with: * Timestamp * Event type * File path * File size * Workflow status badges (`queued`, `workflow_triggered`, `workflow_failed`) 3. Direct links to related workflow traces. Events are stored with TTL indexing (default 90 days). *** ## Workflow Triggering Model For high-precision automation, prefer typed triggers: | Trigger | Purpose | Example | | :-------------------------------------------------- | :-------------------------------------- | :------------------------------------------ | | `DirectoryMonitor.{projectId}.WriteFinished.notify` | Run only after file write stabilization | Launch malware scan after upload completion | | `DirectoryMonitor.{projectId}.Create.notify` | React on object creation | Tag and classify newly dropped files | | `DirectoryMonitor.{projectId}.Delete.notify` | Detect deletions | Alert on unexpected file removal | | `DirectoryMonitor.{projectId}.notify` | Legacy generic trigger | Backward compatible workflows | *** ## Security Controls The monitor ingress path is protected with layered controls: 1. **Company API key authentication** 2. **Project-level secret token validation** 3. **Payload validation for required fields** 4. **Idempotent dedupe through unique `eventId`** This model allows multi-project isolation while preserving your current API gateway behavior. *** ## Real World Automation Patterns } title="File Compliance Checks" description="On WriteFinished, run validation workflows (hash policy, naming convention, extension checks)." /> } title="Security Response" description="Trigger scan, quarantine, and alert actions when suspicious files appear in watched paths." /> } title="Business Automation" description="Automatically launch ingestion pipelines, enrichment jobs, and webhook notifications from file events." /> *** ## Feature Snapshot } title="Recursive Monitoring" description="Observe complete directory trees and capture create, modify, and delete behavior." /> } title="Write Stability Handling" description="`WriteFinished` is emitted after stabilization windows to avoid partial-file processing." /> } title="Heartbeat & Startup Signals" description="Monitors report startup and active status, enabling operational visibility per project." /> } title="Rich Event Metadata" description="Attach `sha256`, `uid`, and `pid` (when available) for stronger audit and investigation context." /> } title="Event-Driven Workflows" description="Bridge file system events directly into the existing Donutwork workflow engine." /> # Dynamic Content Modeling import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Layout, Database, FileJson, Eye, Settings, FormInput } from 'lucide-react'; # Dynamic Content Modeling (Content Box) The **Content Box** system is designed to eliminate the rigidity of traditional databases. It allows you to create "Models" (Types) that define the schema of your data, and then manage that content through automatically generated, user-friendly interfaces. ## The Core Concept: Types vs. Contents To master content modeling in Donutwork, it is important to distinguish between these two levels: 1. **Types (The Schema):** You define the structure. Example: "A *Team Member* type has a name, a photo, a bio, and a role." 2. **Contents (The Data):** You create the actual entries based on that schema. Example: "John Doe, CEO, photo.jpg..." *** ## Supported Field Types The **Fields Manager** offers a wide variety of inputs to cover any data-entry requirement, from simple strings to complex logic: | Category | Input Type | Typical Use Case | | :---------------- | :------------------- | :----------------------------------------------------- | | **Textual** | Standard Text | Titles, short names, labels. | | | Long Text (Textarea) | Descriptions, bios, rich content. | | | Password / Secure | API Keys, secrets, or sensitive data (masked). | | | URL Address | External links, social media profiles. | | **Logic & Lists** | Dropdown Select | Single choice from a predefined list (e.g., Category). | | | Multiple Selection | Tags, skills, or multi-category assignments. | | | Toggle / Checkbox | Boolean states (Yes/No, Active/Inactive). | *** ## Structure Examples (Use Cases) Here are common ways to configure your **Types** for different business scenarios: ### 1. FAQ Section * **Question:** Standard Text (Required) * **Answer:** Long Text * **Category:** Dropdown Select (Options: *Billing, Technical, Account*) * **Featured:** Toggle ### 2. Product Datasheet (SaaS) * **Product Name:** Standard Text * **Stripe Price ID:** Masked Input (to protect sensitive billing IDs) * **Feature List:** Multiple Selection * **Documentation:** URL Address * **Maturity:** Dropdown Select (*Beta, Stable, Deprecated*) ### 3. Customer Testimonials * **Client Name:** Standard Text * **Company:** Standard Text * **Quote:** Long Text * **Rating:** Dropdown Select (*1, 2, 3, 4, 5 stars*) *** ## Visibility States Every **Content Box** entry can be set to one of the following states: * 🟡 **Draft:** The content is saved but not accessible via public APIs or the frontend. * 🟢 **Public:** The content is live and ready to be displayed. * 🔴 **Private:** Only visible within the Donutwork Admin area—perfect for internal configuration data. *** ## Advanced Features } title="Auto-Generated UI" description="No need to build forms manually. As soon as you update a Type's schema, the entry form updates instantly." /> } title="Drag & Drop Ordering" description="Reorder fields within your schema to prioritize the most important information for your team." /> } title="Headless-Ready" description="All saved data is delivered as clean JSON via REST API, perfect for React, Vue, or Mobile Apps." /> Every field has an **Internal Key (DB)**. Use clear, `snake_case` names (e.g., `hero_image_url`) because this key will be used as the property name in the JSON returned by the Donutwork API. # Email Gateway import { Card, Cards } from 'fumadocs-ui/components/card'; import { Palette, Settings, ShieldCheck } from 'lucide-react'; # Email Gateway The Donutwork **Email Gateway** is the complete infrastructure for managing your SaaS communications. It handles the entire lifecycle of an email: from DNS record configuration to visual template design. } title="Template Design" href="/en/docs/email-gateway/template" description="Create professional emails using the Drag & Drop editor or write your own custom HTML code." /> } title="SMTP Configuration" href="/en/docs/email-gateway/settings" description="Set up your own sending servers (Custom SMTP) or use Donutwork's shared infrastructure." /> } title="Deliverability" href="/en/docs/email-gateway/settings" description="Protect your sender reputation by correctly configuring SPF and DKIM records." /> *** ## Key Features ### 1. Visual & Code Editor Choose how you work. The visual **Mail Designer** (powered by GrapesJS) allows anyone to create responsive layouts. For developers, the integrated **Ace Editor** provides total control over the source code with real-time previews. ### 2. Multi-Sender Management Define **Alternative Senders** to send communications from different departments (e.g., `support@`, `billing@`, `info@`) without needing to configure multiple SMTP servers. ### 3. Native Integration Templates saved in the Gateway are instantly available across the platform: * **Workflows:** Send automated emails by dragging a simple node. * **API:** Call templates via REST endpoints while passing dynamic variables. *** ## Quick Navigation The Email Gateway is divided into two main areas: ### [Template Management & Design](/en/docs/email-gateway/template) Learn how to create new files, organize your template library, and use the designer to make your emails look perfect on any device. ### [Settings & Deliverability](/en/docs/email-gateway/settings) Learn how to configure your custom SMTP server, validate connections with the test tool, and set up the DNS records required to stay out of the SPAM folder. ## Suggested Go-Live Sequence 1. Configure SMTP and DNS authentication first. 2. Create one transactional template and one operational alert template. 3. Run delivery tests from staging addresses. 4. Connect template sends to [Workflow](/en/docs/workflow) and API flows. # Settings & Deliverability import { Callout } from 'fumadocs-ui/components/callout'; # Email Settings & Deliverability To ensure your emails reach the inbox and not the spam folder, Donutwork provides advanced tools for mail server configuration and domain authentication. ## SMTP Configuration Donutwork allows you to choose between two sending modes: 1. **System SMTP:** Use Donutwork’s default infrastructure for immediate setup. 2. **Custom SMTP:** Configure your own providers (e.g., SendGrid, Mailgun, Amazon SES) by entering Host, Port, Username, and Password. *** ## Domain Authentication (SPF & DKIM) Security is key to email delivery. Use the following settings to authorize Donutwork to send mail on your behalf. ### SPF Record Add this value to your domain's SPF record in your DNS settings: `include:_spf_hosted.donutwork.com` ### Enforce DKIM DKIM adds a digital signature to your emails. To enable it: 1. Toggle the **Enforce DKIM** option in settings. 2. Add a **CNAME** record to your DNS: * **Host:** `donutwork._domainkey.YOUR_DOMAIN` * **Target:** `smtp._domainkey.donutwork.com` *** ## Alternative Senders You are not limited to a single "From" address. You can define multiple senders for different purposes: * `support@yourbrand.com` for help desk replies. * `billing@yourbrand.com` for automated invoices. * `news@yourbrand.com` for marketing updates. Each sender can have a unique **Display Name** to increase user trust. *** ## Email Tester Before going live, use the integrated **Email Tester**. 1. Enter your personal email address. 2. Click **Send Test Email**. 3. Instantly verify if your SMTP settings are correct and if the email arrives with the correct formatting. Use the **Test Connection** button after entering your SMTP credentials for immediate feedback on server reachability before saving. # Templates import { Card, Cards } from 'fumadocs-ui/components/card'; import { Palette, Code, Eye } from 'lucide-react'; # Managing Email Templates Donutwork decouples email design from your application logic. By using templates, your marketing team can update content and layouts without touching a single line of backend code. ## Two Editing Modes Donutwork offers total flexibility in template creation by supporting two distinct approaches: } title="Visual Mail Designer" description="A drag-and-drop editor based on GrapesJS for creating responsive layouts without coding." /> } title="Advanced Code Editor" description="A professional environment (Ace Editor) with syntax highlighting for developers needing custom HTML/CSS." /> *** ## Working with Templates From the main dashboard, you can: * **Create New Templates:** Define clear filenames (e.g., `welcome-kit` or `payment-failed`). Naming follows the `[a-z0-9-]` pattern. * **Visual Designer:** Click the **Palette** icon to enter the visual editor. It includes pre-built blocks like buttons, images, and columns. * **Code Editor:** Click the **Pencil** icon to edit raw HTML. * **Live Preview:** Use the **Eye** icon within the editor to see how your email renders on mobile and desktop devices. *** ## Workflow Integration Once a template is saved, it is immediately available in the **Workflow** module. Simply drag a **Send Email** node into your flow and select the desired template from the dropdown menu. *** ## Next Steps # Charge Entity import { Steps, Step } from 'fumadocs-ui/components/steps'; # Charge Entity A **Charge** (also referred to as a Transaction) represents a specific financial balance associated with a **Customer**. It can be generated automatically by a subscription renewal or created manually for one-off services. ## Usage The Charge entity is used to: * Process ad-hoc payments for setup fees, consulting, or hardware. * Store the history of recurring billing events. * Manage association with legal documents (invoices and receipts). * Track the real-time payment status (Pending, Paid, Refunded). ## Expected Operational Flow Lifecycle of a financial transaction: ### Charge Generation Create a charge object via `POST /customers/{id}/charges.json`. You can define multiple service lines, each with its own specific tax profile for granular accounting. ### Execution & Capture If `capture: true` is set, DonutWork immediately attempts to process the transaction using the customer's primary payment method. Otherwise, the charge remains `awaiting_response`. ### Status Synchronization Monitor the real-time status of the charge. Upon successful payment, the system triggers a `Charge.Paid` webhook to your application. ### Invoicing & Compliance Once paid, synchronize the transaction with your accounting software and use the `PUT /.../invoice.json` endpoint to attach the legal document details to the record. *** ## Data Schema The fields defining a Charge object: | Field | Type | Description | | :------------ | :------- | :------------------------------------------------------ | | `id` | `eid` | Unique extended identifier. | | `customer_id` | `string` | The owner of the transaction. | | `total` | `number` | Net total of the transaction (including tax lines). | | `status` | `string` | Current state: `pending`, `paid`, `refunded`, `failed`. | | `services` | `array` | List of items being billed with their tax profiles. | | `invoice` | `object` | Metadata for accounting (number, date, external link). | | `date` | `object` | Precise timestamp of the creation event. | *** ## Relationship Call Graph How Charges interact with external payment gateways: # Customer Entity import { Steps, Step } from 'fumadocs-ui/components/steps'; import { Card, Cards } from 'fumadocs-ui/components/card'; import { User, Key, CreditCard, Play } from 'lucide-react'; # Customer Entity The **Customer** is the central node of the DonutWork ecosystem. It represents the legal entity or individual that consumes your services and generates revenue. ## Usage The Customer entity is used to: * Track contact and billing information. * Associate recurring subscriptions and one-time charges. * Store custom metadata via dynamic properties for deep integration with your own platform. * Monitor financial risk and health (MRR/YRR). ## Expected Implementation Flow To successfully onboard and bill a customer, follow this standard logical flow: ### Customer Lifecycle Initialization Create the identity using the `POST /customers.json` endpoint. Assign a unique `externalId` from your internal database to maintain perfect synchronization. ### Context & Property Enrichment (Optional) Use `PUT /customers/{id}/properties.json` to store platform-specific data like billing tiers, preferred language, or API quotas. ### Secure Payment Onboarding Call `GET /customers/{id}/payment_link.json`. This generates a one-time use URL. Redirect your user to this page—DonutWork handles the PCI-compliant credit card entry via Stripe. ### Activation & Billing Once the payment method is attached (confirmed via Webhook), trigger a billing event. You can either attach a `Subscription` for recurring revenue or create a `Charge` for one-time fees. *** ## Data Schema The following table defines the core structure of a Customer object: | Field | Type | Description | | :------------- | :------- | :--------------------------------------------------- | | `id` | `eid` | Unique extended identifier generated by DonutWork. | | `external_id` | `string` | Your internal system identifier. | | `email` | `string` | Primary contact and billing email. | | `company_name` | `string` | Legal name used for invoicing. | | `address` | `object` | Geographic data (country is required for tax logic). | | `properties` | `array` | Key-value pairs for custom integration data. | | `status` | `string` | `active`, `suspended`, or `deleted`. | *** ## Relationship Call Graph This graph illustrates how the Customer entity interacts with other core system components during its lifecycle. # Email Delivery Entity import { Steps, Step } from 'fumadocs-ui/components/steps'; # Email Delivery Entity The **Email Delivery** (or Email Job) represents a single transactional communication event. It bridges your application logic with the professional SMTP infrastructure of DonutWork. ## Usage The Email Delivery entity is used to: * Send transactional emails (receipts, password resets) using pre-defined templates. * Inject dynamic data into responsive layouts via variables. * Distribute legal or technical documents as secure attachments. * Orchestrate multi-sender communication (Support, Billing, Sales). ## Expected Delivery Flow Sending a secure email with attachments follows this operational path: ### Template Selection Identify the logical `templateId` in your Email Gateway. This defines the visual layout and the placeholders available for injection. ### Variable Mapping & Context Prepare the `vars` object containing the dynamic data (e.g., customer name, order number) that will replace the placeholders in the designer. ### Attachment Encoding Convert your files (PDF, CSV, Images) into **Base64** strings. DonutWork processes these strings to recreate valid SMTP attachments safely. ### Dispatch & Transmission Submit a `POST` request to the delivery endpoint. DonutWork validates the sender identity, resolves the variables, attaches the files, and transmits via the configured SMTP. *** ## Data Schema (JSON Body) The payload for an email delivery job: | Field | Type | Description | | :------------ | :------- | :------------------------------------------------------ | | `to` | `string` | **Required**. Primary recipient email address. | | `subject` | `string` | **Required**. The title of the email. | | `from` | `string` | Optional. Must match one of your "Alternative Senders". | | `vars` | `object` | Key-value pairs matching placeholders in the template. | | `attachments` | `array` | List of attachment objects (see below). | | `cc` / `bcc` | `mixed` | String or array of additional recipients. | ### Attachment Object | Field | Type | Description | | :------------ | :------- | :-------------------------------------------------- | | `filename` | `string` | The display name of the file (e.g., `invoice.pdf`). | | `type` | `string` | MIME type (e.g., `application/pdf`). | | `content` | `string` | The file content encoded in **Base64**. | | `disposition` | `string` | `attachment` (default) or `inline`. | *** ## Relationship Call Graph How your app interacts with the Gateway to send a document: # Partner Entity import { Steps, Step } from 'fumadocs-ui/components/steps'; # Partner Entity A **Partner** represents an external agency, reseller, or affiliate that manages its own pool of customers. Partners are categorized into **Groups** for tiered commission management and service segmentation. ## Usage The Partner entity is used to: * Segment your customer base by agency or reseller. * Manage commission structures and payout history. * Distribute reporting and management capabilities to third parties. ## Expected Lifecycle Flow Follow this logical flow to establish a partner-based reseller model: ### Define Tiers & Groups Use `POST /partners/groups.json` to categorize partners. This allows you to apply different commission rules or API access levels to different types of resellers. ### Partner Onboarding Initialize the partner identity via `POST /partners.json`. Associate them with a `group_id` and provide their legal and tax information. ### Customer Attribution When onboarding a new customer through your platform, include the `partner.id` in the creation payload. DonutWork will automatically attribute future revenue to this partner. ### Performance & Payouts Monitor real-time performance via `GET /partners/{id}/stats.json` and manage revenue sharing through the `payouts.json` endpoints. *** ## Data Schema The core fields defining a Partner object: | Field | Type | Description | | :------------ | :------- | :---------------------------------------------------------------- | | `id` | `eid` | Unique extended identifier. | | `name` | `string` | Legal company name of the partner. | | `email` | `string` | Main contact and billing address. | | `group_id` | `string` | The ID of the assigned classification group. | | `external_id` | `string` | Your internal system reference. | | `tags` | `array` | Arbitrary labels for custom filtering (e.g., 'gold', 'reseller'). | *** ## Relationship Call Graph How Partners interact with the customer onboarding flow: # Subscription Entity import { Steps, Step } from 'fumadocs-ui/components/steps'; # Subscription Entity The **Subscription** object represents a recurring commercial agreement attached to a **Customer**. It combines plan pricing, addon quantities, billing cadence, and lifecycle state. ## Usage Use the Subscription entity to: * Attach a pricing plan to a customer. * Manage seat-based pricing through addon quantity. * Apply global and addon-level discounts. * Track metered usage when enabled. * Execute lifecycle transitions (pause, resume, change, cancel-at-period-end). * Keep amendment history for audits. ## Seat-Based Pricing Model In Donutwork, seat-based pricing is handled through **addons**. * Configure the per-seat value in the addon price. * Set the number of seats in `addons[].quantity`. * Renewal totals automatically include seat addons. Example: * Addon `workspace_seat` price: `12.00` * Quantity: `25` * Seat subtotal contribution: `300.00` (before taxes/discounts) ## Expected Subscription Flow ### Plan Association Attach a plan with `POST /customers/{id}/subscriptions.json`. ### Runtime Configuration Adjust addon quantities (including seats), discounts, and usage inputs as needed. ### Lifecycle Transitions Optionally apply lifecycle operations (`pause`, `resume`, `change-plan`, `change-addons`, `cancel-at-period-end`). ### Renewal Boundary Processing At `next_renew`, scheduled changes are applied and recurring billing is executed. *** ## Lifecycle States and Transitions | Lifecycle State | Meaning | Typical Entry | | :---------------------- | :---------------------------------------- | :------------------------------------- | | `active` | Subscription is billable and renewable | Attach, resume, successful change | | `paused` | Billing is temporarily suspended | Pause action | | `cancel_pending` | Marked to stop at period boundary | Cancel-at-period-end | | `cancelled` | No longer active | Post-boundary stop/legacy cancellation | | `trialing` / `past_due` | Optional advanced states for integrations | External lifecycle orchestration | ### State Definitions with Practical Examples * `active`: customer is billed normally at each renewal date. Example: a monthly plan renews on May 1, 2026 and remains active. * `paused`: billing is temporarily halted. Example: customer asks to freeze service for 30 days; no renewal charge is attempted while paused. * `cancel_pending`: subscription will stop at period boundary. Example: customer cancels on April 15, 2026; access remains until the next renewal boundary. * `cancel_pending` can be reversed before boundary. Example: customer cancels, then changes mind after 3 days; use undo-cancel-at-period-end to return to `active`. * `cancelled`: subscription is fully closed. Example: boundary reached and cancellation finalized. * `trialing`: customer is in free trial before first paid cycle. Example: plan includes 14-day trial after initial attach. * `past_due`: payment issue detected and recovery flow is required. Example: renewal attempt failed and account is awaiting payment method update. ### Pause and Resume Billing Semantics When a subscription is paused, Donutwork stops renewal execution and clears `next_renew` while storing the previous renewal date in `pause_state.previous_next_renew`. When resumed: * If `resume_at` is provided and is in the future, that date becomes the new `next_renew`. * If `resume_at` is missing, Donutwork uses the stored `previous_next_renew`. * If the stored date is already in the past, Donutwork sets `next_renew` to the resume day (today), not retroactively. Practical timeline example: * Subscription paused on **May 1, 2026**. * Resumed on **July 1, 2026** (after 2 months). * Result: no automatic back-billing for May/June; `next_renew` is re-anchored to July 1, 2026 (or a future `resume_at` if provided). ### Lifecycle Graph ## Proration Rules * **Positive delta** (upgrade): immediate debit charge. * **Negative delta** (downgrade): credit stored in `carryover_credit`. * Carryover credit is consumed in future renewals before charging new amount. ## Scheduled Changes For `change-plan` and `change-addons`, you can set `when: period_end`. The request is stored in `scheduled_change` and applied automatically at renewal boundary. ## Amendment History Every lifecycle change is written to an immutable amendment stream. This supports support/debug/audit use cases with before/after snapshots and proration metadata. *** ## Data Schema | Field | Type | Description | | :--------------------- | :--------------- | :------------------------------------------------------------- | | `id` | `eid` | Unique customer-subscription identifier. | | `subscription_id` | `string` | Plan identifier currently applied. | | `status` | `string` | Legacy status (`active`, `dismiss`, `dismissed`, ...). | | `next_renew` | `date \| null` | Next billing boundary. | | `addons` | `array` | Addon entries with price and `quantity` (seat count included). | | `global_discount` | `object` | Plan-level discount descriptor. | | `lifecycle` | `object` | Advanced lifecycle state metadata. | | `pricing_snapshot` | `object` | Captured pricing context for lifecycle operations. | | `scheduled_change` | `object \| null` | Deferred mutation to apply at renewal. | | `pause_state` | `object \| null` | Pause/resume metadata. | | `carryover_credit` | `number` | Credit wallet generated by negative prorations. | | `cancel_at_period_end` | `boolean` | Explicit cancellation intent at renewal boundary. | *** ## Backward Compatibility No legacy route or payload shape is removed. ### Legacy vs New lifecycle behavior | Area | Legacy Behavior | New Lifecycle Behavior | | :-------------- | :---------------------------- | :----------------------------------------------------------- | | Attach/Detach | Existing routes remain valid | Unchanged, plus additive lifecycle metadata | | Addons update | Existing addon mutation works | Optional lifecycle change-addons with proration/scheduling | | Status endpoint | Legacy `status` continues | Adds lifecycle visibility without removing legacy keys | | Seat pricing | Addons with quantity | Same model, now explicitly documented as official seat model | | Cancellation | `dismiss` based flow | `cancel_at_period_end` maps to compatible legacy status | *** ## Relationship Call Graph # Media Library import { Card, Cards } from 'fumadocs-ui/components/card'; import { UploadCloud, HardDrive, FileSearch, Download } from 'lucide-react'; # Media Library The **Media Library** serves as a centralized repository for all files within your workspace. It leverages a scalable remote storage infrastructure to ensure your assets are always available, secure, and ready to be served via CDN. ## Core Features } title="Fast Upload" description="Multi-file upload system with Drag & Drop support." /> } title="Remote Storage" description="Native integration with isolated company buckets, ensuring maximum data security." /> } title="Format Recognition" description="Automatic identification of file types (Images, PDFs, Documents) with dedicated iconography." /> *** ## File Management The gallery interface provides immediate control over your uploaded assets: ### 1. Upload & Ingestion Drag multiple files simultaneously into the upload area. The system automatically manages the queue and notifies you when the process is complete. ### 2. Gallery & Navigation Files are displayed in a responsive grid showing: * **Filename:** The original asset name (Key). * **Size:** Automatic calculation of file weight (KB, MB, GB). * **Identifier (ETag):** The unique file hash for cache and versioning management. ### 3. Intelligent Pagination For workspaces with thousands of files, the Media Library uses **Continuation Token-based pagination**, optimizing load times and reducing bandwidth consumption. *** ## Common Use Cases * **Dynamic Content:** Upload product images or partner logos to be referenced in your [Dynamic Content](/en/docs/dynamic-content-modeling). * **Email Gateway:** Host graphical assets for your transactional email templates. * **User Documents:** Store PDFs or guides for your customers in a secure environment. # Partner Program & Revenue Sharing import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Calculator, Fingerprint, TrendingUp, Zap } from 'lucide-react'; # Partner Program Donutwork helps you run a partner channel like a product, not a spreadsheet. Create structured partner groups, define powerful commission rules, and validate outcomes before you publish. ## What You Can Do 1. Group partners by commercial model (agencies, resellers, strategic channels). 2. Apply layered commission logic to each group. 3. Enforce quality gates (X paying customers in N months). 4. Simulate outcomes instantly and avoid guesswork. 5. Keep payouts transparent and explainable. *** ## Configure In 7 Steps 1. Open a partner group. 2. Set your base logic with `Time-Based Tier` or `Recurring (Fallback)`. 3. Add optional growth levers: * `Charge Amount` * `LTV Bonus` 4. Add a `Customer Volume Gate` if you want minimum performance requirements. 5. Test realistic scenarios in `Commission Simulator`. 6. Review the breakdown and confirm expected behavior. 7. Save and apply to the group. Start with base commission, then add upgrades/adjustments, and only then add eligibility gates. This gives the clearest and most controllable result. *** ## Rule Catalog (How Each Rule Behaves) ### Time-Based Tier Use it for onboarding acceleration. * Goal: reward early lifecycle months more aggressively. * Key fields: * `Max Months (e.g., 12)` * `Percentage (%)` * `Bonus (€ - Optional)` * Behavior: applies when customer age is within the configured month limit. * Typical use: “12% for first 12 months + optional one-time bonus.” ### Recurring (Fallback) Use it as your long-term baseline. * Goal: define steady commission after no time tier matches. * Key field: * `Recurring Percentage (%)` * Behavior: used as default base commission. * Typical use: “6% lifetime after introductory tiers.” ### Charge Amount Use it to adapt margins by transaction size. * Goal: adjust commission when charge value crosses a threshold. * Key fields: * `Min Charge Total (€)` * `Deduction % (e.g., 1.0)` * Behavior: when threshold is met, adjustment is applied to the fee at that point. * Typical use: “Apply a deduction on high-ticket deals to preserve margin.” ### LTV Bonus Use it to reward long-term partner contribution. * Goal: unlock extra commission when cumulative partner revenue reaches milestones. * Key fields: * `Min LTV Total (€)` * `Upgrade Bonus %` * Behavior: highest qualified LTV bonus is applied. * Typical use: “+3% after €20k generated.” ### Customer Volume Gate Use it to protect quality and consistency. * Goal: require minimum paying-customer volume. * Key fields: * `Required Customers (X)` * `Lookback Months (N)` * `Window Mode` * `Anchor Source` * `Below-threshold Action` * `Reduction Mode` * Behavior: * checks whether partner reaches X paying customers in the selected window. * if below threshold, applies your configured policy (reduce, defer, forfeit). *** ## Calculation Logic You Can Trust ### Monetary base Commission percentages and thresholds are evaluated on the charge net taxable amount (before taxes), for consistent financial behavior. ### Deterministic order Rules are applied in this order: 1. Base: `Time-Based Tier` or `Recurring (Fallback)` 2. `Charge Amount` 3. `LTV Bonus` 4. `Customer Volume Gate` ### No retroactive surprises When rules change, historical approved calculations stay untouched. *** ## Customer Volume Gate: Rolling vs Anchored ### Rolling window Best for continuous performance monitoring. * evaluates the last N months from each charge date. ### Anchored window Best for lifecycle-based partner programs. * evaluates N months from a chosen anchor point. ### First paid customer bootstrap If anchored mode uses first paid customer and there is no historical paid event yet, the first paid transaction starts the window automatically. The rule is still evaluated normally. *** ## Commission Simulator Use the simulator before publishing any rule update. * Input realistic values in: * `Simulated Charge Amount (€)` * `Months Since Customer Creation` * `Simulated Partner LTV (€)` * `Qualified Customers (X window)` * `First Paid Customer (bootstrap)` * Run `Simulate Commission` and review `Commission Simulation Breakdown`. This is the fastest way to align finance, sales, and operations before go-live. *** ## Ready-to-Use Playbooks 1. Startup acquisition push: * strong first-year tier * lower recurring fallback * moderate volume gate 2. Agency channel: * stable recurring * LTV milestones for upsell behavior * rolling gate to maintain consistency 3. Enterprise referrals: * high-ticket charge adjustment * selective LTV upgrades * anchored gate for program-cycle governance *** ## Why Donutwork Stands Out } title="Explainable" description="Every payout can be justified with a clear rule sequence and simulation breakdown." /> } title="Configurable" description="Mix lifecycle, value, LTV, and performance gates without custom development." /> } title="Scalable" description="Move from simple affiliate payouts to sophisticated partner economics as you grow." /> } title="Fast to Operate" description="Design, test, and publish changes quickly with confidence." /> # Recurring Payments import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Repeat, Zap, Gift, Settings2, Calculator, GitBranchPlus, ShieldCheck } from 'lucide-react'; # Recurring Payments & Subscriptions Donutwork lets you run subscription billing with a predictable model: * create plan catalog rules, * attach subscriptions to customers, * scale seat-based pricing through addons, * change contracts over time with lifecycle controls, * keep compatibility with existing legacy integrations. This page explains how the system behaves in production, with practical examples. ## What A Subscription Includes } title="Renewal Cadence" description="Day-based or month-based cycles (`renewal_days` / `renewal_months`) with a next renewal date (`next_renew`)." /> } title="Trial Handling" description="Optional trial before first paid cycle." /> } title="Seat + Addon Pricing" description="Seat-based pricing uses addon quantity (`addons[].quantity`) and unit price (`addons[].price`)." /> } title="Discounts & Taxes" description="Addon discounts, global discount, carryover credit, and tax profile are applied in deterministic order." /> *** ## Renewal Amount Calculation (Order Matters) At each renewal boundary, Donutwork computes the due amount in this order: 1. Base plan amount. 2. Addon charges (`price * quantity`) for active addon quantities. 3. Addon-level discount if configured and still active (`discount_until`). 4. Global discount (`fixed` or `percentage`, if still active). 5. Carryover credit (`carryover_credit`) from previous downgrade/proration. 6. Taxes from subscription tax profile. ### Formula (simplified) ```text net_subtotal = base + addons_after_addon_discounts net_after_global_discount = net_subtotal - global_discount net_due = max(0, net_after_global_discount - carryover_credit_applied) vat_due = net_due * tax_rate gross_due = net_due + vat_due ``` ### Example * Base plan: `99.00` * Seat addon: `12.00` x `8` seats = `96.00` * Addon discount 10% active => addon effective `86.40` * Net subtotal = `185.40` * Global discount 15% => `-27.81` * Carryover credit used: `20.00` * Net due = `137.59` * VAT 22% = `30.27` * Gross due = `167.86` *** ## Seat-Based Pricing Model Seat pricing does **not** use a separate seat schema. It is intentionally modeled through addons: * per-seat value: `addons[].price` * seats count: `addons[].quantity` * final seat amount: included automatically in subscription renewal This model is stable and backward compatible with existing panel/API flows. *** ## Lifecycle States (Billing Meaning) | State | Billable | Meaning | | :--------------- | :----------- | :--------------------------------------------------------------- | | `active` | Yes | Normal recurring billing. | | `trialing` | Usually no | Trial phase before first paid renewal. | | `past_due` | Conditional | Payment recovery state after failed attempt. | | `paused` | No | Billing paused. Renewals are not charged while paused. | | `cancel_pending` | No new cycle | Scheduled to stop at period end (can be undone before boundary). | | `cancelled` | No | Closed subscription. | Pausing does not create retroactive debt. If a subscription is resumed after 2 months, the system does not auto-charge the paused months. The next renewal is re-anchored to resume date logic. ### Lifecycle Graph *** ## Supported Lifecycle Operations All lifecycle features are additive (no legacy route removal): | Operation | Immediate | Period End | Proration | Notes | | :------------------------ | :--------- | :-------------------- | :-------- | :--------------------------------------- | | Pause | Yes | No | No | Stops renewal attempts while paused. | | Resume | Yes | No | No | `resume_at` can define next boundary. | | Change Plan | Yes | Yes | Optional | Upgrade/downgrade supported. | | Change Addons | Yes | Yes | Optional | Seat quantity updates included. | | Cancel At Period End | Yes (flag) | Effective at boundary | No | Legacy-compatible cancellation behavior. | | Undo Cancel At Period End | Yes | No | No | Restores active plan before boundary. | | Next Renewal Preview | Read-only | N/A | N/A | Shows expected next charge breakdown. | | Amendment History | N/A | N/A | N/A | Full audit trail for lifecycle changes. | *** ## API Examples ### Schedule Seat Change At Period End ```json { "subscription": { "action": "change_addons", "when": "period_end", "proration": false, "addons": [ { "name": "workspace_seat", "quantity": 25, "price": 12 } ] } } ``` ### Preview Next Renewal (response excerpt) ```json { "status": "success", "data": { "subscription_id": "sub_abc123", "next_renewal": "2026-07-01", "billable": true, "pricing": { "items": [ { "service": "Subscription Base: Pro", "net": 99, "tax_rate": 22, "tax": 21.78, "total": 120.78 }, { "service": "Addon: workspace_seat (Qty: 25)", "net": 300, "tax_rate": 22, "tax": 66, "total": 366 } ], "net_due": 399, "vat_due": 87.78, "gross_due": 486.78 } } } ``` *** ## API FAQ (Common Combinations) The combinations below refer to Customer API routes documented in `/en/docs/api/customer#subscription-management`. ### How can I upgrade a plan? Use `change-plan` with immediate application. ```json { "lifecycle": { "plan_id": "PLAN_ENTERPRISE_V3", "when": "immediate", "proration": true } } ``` * Endpoint: `PUT /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/change-plan.json` * If proration delta is positive, an immediate adjustment charge is attempted. * If that immediate charge fails, the lifecycle change is not applied. ### How can I downgrade a plan? Use `change-plan` and target a lower-priced plan. ```json { "lifecycle": { "plan_id": "PLAN_STARTER_V1", "when": "immediate", "proration": true } } ``` * Endpoint: `PUT /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/change-plan.json` * With a negative delta, the platform stores credit in `carryover_credit`. * That credit is consumed on future renewals before new debit. ### How can I schedule plan changes for next renewal? ```json { "lifecycle": { "plan_id": "PLAN_PRO_V2", "when": "period_end", "proration": false } } ``` * Endpoint: `PUT /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/change-plan.json` * No immediate charge is attempted; change is applied at renewal boundary. ### How can I change addon quantities (including seats)? ```json { "lifecycle": { "addons": [ { "element": "workspace_seat", "quantity": 25 } ], "when": "immediate", "proration": true } } ``` * Endpoint: `PUT /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/change-addons.json` * In seat-based setups, seat count is `addons[].quantity`. ### How can I schedule addon quantity changes at period end? ```json { "lifecycle": { "addons": [ { "element": "workspace_seat", "quantity": 40 } ], "when": "period_end", "proration": false } } ``` * Endpoint: `PUT /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/change-addons.json` * Useful for commercial changes that should start next cycle. ### What happens if I pause and resume after two months? * Pause: `PUT .../lifecycle/pause.json` * Resume: `PUT .../lifecycle/resume.json` (optional `resume_at`) Concrete timeline: * pause on **May 1, 2026** * resume on **July 1, 2026** * no retroactive billing for May/June; renewal restarts from resume logic. ### Can I undo a cancellation already set for period end? Yes: * set cancellation: `PUT .../lifecycle/cancel-at-period-end.json` * undo cancellation: `PUT .../lifecycle/undo-cancel-at-period-end.json` If undone before renewal boundary, subscription returns to `active`. ### How can I preview financial impact before applying changes? Use lifecycle preview (no mutation): ```json { "lifecycle": { "action": "change_addons", "addons": [ { "element": "workspace_seat", "quantity": 30 } ] } } ``` * Endpoint: `POST /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/preview.json` * Response includes `old_due`, `new_due`, `delta`, `direction`. ### How should I handle safe retries in integrations? Use `lifecycle.idempotency_key` on mutating operations. On retries, this prevents duplicate application of the same change. ### Where can I fetch full lifecycle change history? Use amendment history: * Endpoint: `GET /customers/{customerId}/subscriptions/{subscriptionId}/amendments.json` * Includes action, timing (`immediate`/`period_end`), before/after, and proration metadata. ### Quick combination matrix | Goal | Endpoint | `when` | `proration` | | :-------------------------- | :----------------------------------- | :----------- | :---------- | | Upgrade plan now | `.../change-plan.json` | `immediate` | `true` | | Downgrade plan now | `.../change-plan.json` | `immediate` | `true` | | Change plan next cycle | `.../change-plan.json` | `period_end` | `false` | | Increase/decrease seats now | `.../change-addons.json` | `immediate` | `true` | | Change seats next cycle | `.../change-addons.json` | `period_end` | `false` | | Pause service | `.../pause.json` | N/A | N/A | | Resume service | `.../resume.json` | N/A | N/A | | Cancel at period end | `.../cancel-at-period-end.json` | boundary | N/A | | Undo cancellation | `.../undo-cancel-at-period-end.json` | immediate | N/A | | Simulate impact | `.../preview.json` | N/A | N/A | | Audit changes | `.../amendments.json` | N/A | N/A | *** ## Practical Scenarios ### 1) Pause For 2 Months, Then Resume * Pause on **May 1, 2026** * Resume on **July 1, 2026** * Result: no back-charge for May/June, renewal continues from resumed schedule. ### 2) Mid-Cycle Upgrade * Customer increases seats from 10 to 20 with immediate change. * Positive proration delta => immediate debit adjustment. ### 3) Mid-Cycle Downgrade * Customer reduces seats mid-cycle. * Negative delta => credit is stored in `carryover_credit`. * Next renewal consumes this credit before any new debit. ### 4) Cancel Pending Then Undo * Customer requests cancellation at period end. * State moves to `cancel_pending`. * If customer changes mind before boundary, undo operation restores normal lifecycle. *** ## Backward Compatibility (No Break Changes) Legacy panel and API flows stay valid. New lifecycle capabilities are opt-in. | Area | Legacy Behavior | Current Behavior | | :------------------------- | :-------------- | :-------------------------------- | | Attach/detach subscription | Supported | Still supported | | Legacy addon update route | Supported | Still supported | | Legacy status field | Supported | Still present | | Seat modeling | Addon quantity | Same official model | | Existing integrations | Stable | Can adopt lifecycle incrementally | If you already use legacy routes, you can keep them unchanged and adopt lifecycle endpoints gradually for pause/resume, proration, and amendment tracking. *** ## Recommended Setup Checklist } title="Model Seats Via Addons" description="Set per-seat price on addon and update quantity for seat count." /> } title="Use Scheduled Changes" description="Prefer `period_end` for commercial changes that should start from next cycle." /> } title="Enable Audit Visibility" description="Use amendment history and renewal preview to improve support and billing transparency." /> *** ## Related Docs # Sentinel Dashboard import { Callout } from 'fumadocs-ui/components/callout'; # Security Command Center The Sentinel Dashboard is the operational heart of your security infrastructure. It provides an immediate, high-impact visual overview of your authentication ecosystem's health. ## Real-Time Metrics The dashboard monitors four critical KPIs: * **Threats Detected:** Number of threats actively blocked by the system. * **Failed Logins:** Unsuccessful access attempts (potential brute-force or credential stuffing). * **Active Sessions:** Number of users currently authenticated globally. * **Avg Response:** Average response time of the security engine (in milliseconds). ## Global Login Activity Powered by **MapLibre GL**, Sentinel visualizes login density on a global map. * **Blue points** indicate regular activity. * **Red points** signal high-density attempts, helping you quickly identify geographically targeted attacks. ## Security Alerts & Decisions This section lists recent anomalies. For every alert, Sentinel displays: 1. **Severity:** From *Low* to *Critical*. 2. **Decision Taken:** - `Allow`: Access granted. * `Challenge MFA`: Two-factor authentication required. * `Deny`: Access blocked immediately. * `Monitor`: Suspicious activity recorded but below the intervention threshold. 3. **Triggers:** Specific reasons that raised the risk (e.g., *New User Agent*, *TOR/VPN Flag*). You can click on any IP or User ID within the alerts to view the full activity history for that specific profile. # Sentinel Security Platform import { Card, Cards } from 'fumadocs-ui/components/card'; import { ShieldCheck, Lock, Eye, Zap } from 'lucide-react'; # Sentinel Security Platform **Sentinel** is Donutwork's intelligent security module designed to protect your business and users from modern threats. Unlike static security systems, Sentinel analyzes every login attempt in real-time, assigning a dynamic **Risk Score** based on dozens of behavioral and environmental signals. ## Core Pillars of Sentinel } title="Adaptive MFA" description="Requires two-factor authentication only when the detected risk exceeds a predefined threshold." /> } title="IP Intelligence" description="Automatic analysis of malicious IPs, TOR nodes, VPNs, and suspicious geographic locations." /> } title="Identity Provider (IDP)" description="Centralized management of external users with support for T-OTP and backup recovery codes." /> } title="Risk-Based Decisions" description="Automates security decisions (Allow, Challenge MFA, Deny) in milliseconds." /> *** ## How the Risk Engine Works Every time a user interacts with the authentication system, Sentinel evaluates the following factors: 1. **IP Reputation:** Does the address come from a network known for botnets or attacks? 2. **Device Novelty:** Is the user using a browser or OS never seen before for this account? 3. **Geolocation:** Is the access attempt coming from an unusual country for this user? 4. **Session Continuity:** If the user is already logged in and the session is stable, the risk score is reduced. The result is a score from **0.00** to **1.00**. Based on this value and your configurations, Sentinel decides the next step. *** ## Sentinel Sections * **[Dashboard](/en/docs/sentinel/dashboard):** Real-time monitoring of global threats. * **[User Management](/en/docs/sentinel/users):** Granular control over user access and security status. * **[Risk Settings](/en/docs/sentinel/settings):** Fine-tuning of risk weights and decision thresholds. ## Recommended Setup Order 1. Define your baseline thresholds in [Risk Settings](/en/docs/sentinel/settings). 2. Validate high-risk scenarios from the [Dashboard](/en/docs/sentinel/dashboard). 3. Operationalize controls in [User Management](/en/docs/sentinel/users) for exceptions and manual overrides. # Sentinel Risk Configuration import { Callout } from 'fumadocs-ui/components/callout'; # Sentinel Configuration Sentinel allows you to "train" the risk engine based on your specific security needs. You can decide how much weight to assign to various security events. ## Score Adjustments (Weights) Every suspicious event adds a value to the total **Risk Score** (from 0.0 to 1.0). You can adjust the following parameters: * **Malware/Threat IP Flag:** High risk score for IPs found in global blacklists. * **TOR/VPN Flag:** Risk associated with anonymizing networks. * **Unknown IP / Country:** Extra risk added when a user logs in from a location or IP never seen before. * **New User Agent:** Risk for using a new browser or hardware. ### Risk Reduction * **Session Continuity Reduction:** This negative value reduces the risk score if the user maintains a stable, known session. This is vital for avoiding "false positives" during normal app usage. *** ## Decision Thresholds Define the limits at which Sentinel must intervene: | Threshold | Description | | :-------------------------- | :-------------------------------------------------------------------------------------------------------------------- | | **Challenge MFA Threshold** | If the score is `>=` this value, the user will be prompted for T-OTP, even if not strictly required by their profile. | | **Deny Threshold** | If the score is `>=` this value, access is denied immediately, regardless of correct credentials. | Setting a *Deny* threshold too low (e.g., 0.40) might block legitimate users who are traveling or using new devices. It is recommended to start with conservative thresholds (MFA at 0.50 and Deny at 0.85). *** ## T-OTP Integration Sentinel allows you to globally enable or disable the **Time-Based One-Time Password** service. When enabled, you can offer 2FA via apps like Google Authenticator or Authy using Donutwork's native APIs. # User Management (IDP) # Sentinel User Management Sentinel acts as a native **Identity Provider (IDP)** for your SaaS applications. In this section, you can monitor and manage the security profile of every registered user. ## User Security Status For every user, the table provides: * **CustomerID:** The external identifier linked to your user. * **Status:** Account state (Active or Suspended). * **OTP (One-Time Password):** Indicates if the user has correctly configured 2FA (T-OTP). * **Backup Codes:** Shows whether emergency recovery codes have been generated. ## Administrative Actions As an administrator, you have total control over user sessions: 1. **Suspend Access:** If you detect compromised activity, you can instantly suspend the user. This invalidates all active sessions. 2. **Restore Access:** Allows you to reactivate a previously suspended user once the threat is resolved. 3. **Delete:** Permanently removes the user from the Sentinel system. > **Note:** Suspending a user in Sentinel blocks authentication at the IDP level, preventing access to all services connected to the platform. # Directory Monitor import { Card, Cards } from 'fumadocs-ui/components/card'; import { FolderOpen, Terminal, Bell, Cpu } from 'lucide-react'; # Directory Monitor The **Directory Monitor** is a file system surveillance engine designed for automation. It allows you to monitor specific folders—locally or on remote servers—and trigger notifications or workflows whenever a file is created, modified, or deleted. ## The Monitoring Agent To enable monitoring on your own infrastructure, Donutwork provides a **Linux Binary** agent. This lightweight agent runs on your server and communicates securely with the platform, providing low-latency event tracking without exposing your file system to the public internet. } title="Linux Binary" description="Download the pre-compiled .tar package and run it as a service on your server." /> } title="Real-time Alerts" description="Receive instant notifications via Webhook or Email when critical files are accessed or changed." /> ## Common Use Cases 1. **Automated Data Ingestion:** Drop a CSV into a monitored folder to automatically trigger a Donutwork [Workflow](/en/docs/workflow) for data processing. 2. **Security Auditing:** Monitor sensitive directories (like `/etc/` or `/bin/`) and get alerted if unauthorized changes occur. 3. **Backup Verification:** Trigger post-processing tasks as soon as a database dump file is completed in a specific directory. ## Project Structure * **Project ID:** A unique identifier used by the monitoring agent to sync with the Donutwork dashboard. * **Startup Status:** Indicates if the monitoring process has successfully initialized and is actively listening for events. # Systems & Monitoring import { Card, Cards } from 'fumadocs-ui/components/card'; import { ShieldCheck, FolderTree, Code2, Key } from 'lucide-react'; # Systems & Monitoring The **Systems & Monitoring** section is the operational command center of Donutwork. It provides the essential tools to ensure your SaaS infrastructure remains secure, high-performing, and constantly monitored. From SSL certificate validation to secret management via KMS, Donutwork offers total visibility into your system's operational health. ## Monitoring & Infrastructure Modules Explore the dedicated sections to configure and manage the different layers of your infrastructure: } title="TLS Monitor" href="/en/docs/system-and-monitoring/tls-monitor" description="Monitor SSL/TLS certificate validity and expiration to prevent service downtime." /> } title="Directory Monitor" href="/en/docs/system-and-monitoring/directory-monitor" description="Automate processes and notifications by monitoring changes in critical directories." /> } title="Sources" href="/en/docs/system-and-monitoring/sources" description="Manage SFTP/FTP remote connections for automated file exchanges." /> } title="KMS Keys" href="/en/docs/system-and-monitoring/kms" description="Key Management Service (KMS) for encrypting sensitive data and managing master keys." /> *** ## Why Monitoring is Crucial? In a modern SaaS environment, stability and data flow integrity are non-negotiable. Donutwork automates routine checks to prevent issues before they impact the end user: 1. **Proactive Security:** Detect expiring TLS certificates or unauthorized system file modifications before they cause an outage. 2. **Data Governance:** Centrally manage cryptographic keys via the **KMS** module, ensuring compliance with global security standards. 3. **Automation & Traceability:** Streamline operations by triggering notifications and workflows as soon as changes are detected in remote or local directories. ## First 15 Minutes Setup 1. Start with [TLS Monitor](/en/docs/system-and-monitoring/tls-monitor) for certificate visibility. 2. Configure [KMS](/en/docs/system-and-monitoring/kms) before onboarding secrets into automations. 3. Connect [Sources](/en/docs/system-and-monitoring/sources) if your flows pull files from SFTP/FTP endpoints. 4. Use [Directory Monitor](/en/docs/system-and-monitoring/directory-monitor) to convert filesystem events into workflow triggers. # Key Management System (KMS) import { Callout } from 'fumadocs-ui/components/callout'; # Key Management System (KMS) The Donutwork **KMS** is your SaaS's cryptographic vault. It provides a centralized system for storing sensitive credentials, application secrets, and master keys that should never be hard-coded or stored in plain text. ## Key Structure Each KMS entry is designed for programmatic access and high security: * **Handler:** A unique alias used by your APIs or scripts to retrieve the key without exposing its actual content. * **Content:** The secret value (e.g., Stripe Secret Key, AWS Access Key, or a private certificate). * **Whitelist (Network Isolation):** Restrict key usage to specific IP addresses or CIDR ranges. If a request comes from an unauthorized IP, the KMS will block access even with valid credentials. ## Security Auditing Traceability is built into the core of the KMS. Every time a key is read or modified, an **Audit Log** is generated. ### Audit Log Details: * **Requester Identity:** Who accessed the key. * **Timestamp:** Exactly when the access occurred. * **Source IP:** The network origin of the request. * **Outcome:** Whether the request was successful or blocked by the whitelist policy. Use the **Handler** in your application code to keep your repositories clean of secrets. This allows you to rotate keys in the Donutwork dashboard without re-deploying your application. # External Connections (Sources) import { Card, Cards } from 'fumadocs-ui/components/card'; import { Link, Shield, Server, FileCode } from 'lucide-react'; # Sources & External Connections The **Sources** module manages the secure communication gateways between Donutwork and your external infrastructure. It allows you to configure and store credentials for remote servers, enabling automated file transfers and data synchronization. ## Supported Protocols Donutwork supports the most common industry-standard protocols for secure file exchange: * **SFTP (SSH File Transfer Protocol):** The most secure method, utilizing SSH for data transit. * **FTPS (FTP over SSL/TLS):** A secure version of FTP that encrypts both commands and payload. * **FTP:** Supported for legacy system compatibility (not recommended for sensitive data). ## Security & Advanced Settings * **SSL/TLS Encryption:** Force encrypted connections to ensure credentials and files are never transmitted in plain text. * **Passive Mode:** Essential for FTP/S connections to bypass firewall or NAT restrictions on the server side. * **Credential Masking:** For security compliance, passwords are never displayed in the UI after the initial setup. ## Technical Configuration When creating a connection, you will need: * **Hostname & Port:** The address of the remote server (e.g., `sftp.partner.com`). * **Authentication:** Username and Password (securely stored and encrypted). * **Security Toggles:** Enable SSL/TLS and Passive Mode depending on your server's requirements. # TLS Monitor import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { ShieldCheck, Clock, Globe, Lock } from 'lucide-react'; # TLS Monitor The **TLS Monitor** is a dedicated security tool designed to track the health of your HTTPS endpoints. Unlike basic uptime monitors, it performs deep cryptographic scans to ensure your SSL/TLS certificates are valid, up-to-date, and compliant with modern security standards. ## Key Features * **Expiration Tracking:** Get real-time visibility into certificate expiry dates to prevent service downtime. * **Protocol Version Verification:** Ensures your servers are using secure versions (TLS 1.2, 1.3) and flags deprecated protocols (SSLv3, TLS 1.0/1.1). * **Compliance Warnings:** Automatically identifies non-compliant configurations based on GDPR and industry best practices. * **Multi-Host Management:** Centralized dashboard to manage and monitor dozens of domains simultaneously. ## Dashboard Overview The TLS Monitor table provides a comprehensive snapshot of your monitored hosts: | Field | Description | | :-------------- | :----------------------------------------------------------------- | | **Hostname** | The full URL being monitored (e.g., `https://api.yourdomain.com`). | | **Status** | The result of the last automated check (Success/Failed). | | **TLS Version** | The specific protocol version currently served by the host. | | **Expire Date** | The exact date when the current certificate will stop being valid. | The system will generate a "Warning" badge if the scan detects insecure cipher suites or upcoming expirations, allowing your team to rotate certificates before users are affected. ## Configuration To add a new monitor, simply provide a descriptive name and the full hostname. You can also assign **Tags** to organize monitors by environment (e.g., `Production`, `Staging`) or project. # Automation & Workflows import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Zap, Code2, Cpu, Workflow, MessageSquare, Bot } from 'lucide-react'; # Workflow Automation The Donutwork **Workflow** module is the operational "brain" of the platform. It is a **No-Code/Low-Code** visual automation engine that allows you to connect events (triggers), decision logic, and external actions via an intuitive node-based interface. Built on an **event-driven** architecture, you can trigger sequences of actions whenever a specific event occurs in your SaaS (e.g., customer creation, payment updates, or partner onboarding). ## How It Works Every Workflow consists of three fundamental building blocks: 1. **Trigger (The Start):** The event that initiates the flow (e.g., `Customer.create`). 2. **Logic Nodes:** Blocks that process data, apply filters, or make decisions (IF/Else, Switch). 3. **Actions (The Output):** Concrete operations such as sending emails, triggering Webhooks, or updating database records. *** ## Node Catalog The editor provides an extensive library of ready-to-use blocks categorized by function: | Category | Key Nodes | Function | | :---------- | :-------------------- | :---------------------------------------------------------------------- | | **Control** | Trigger, End | Handle the entry and exit points of the flow. | | **Logic** | IF, Switch, Filter | Create conditional paths and route data based on specific criteria. | | **Data** | Math, Merge, Text | Perform calculations, merge JSON objects, or format dynamic strings. | | **CRM** | Get Customer, Partner | Retrieve real-time entity data directly from your database. | | **Actions** | Webhook, Email | Communicate with external tools (e.g., Slack, Zapier, or your own API). | *** ## AI-Powered Automation Donutwork takes automation to the next level by integrating AI tools directly into the workflow canvas: } title="AI Build (Copilot)" description="Describe your logic in plain English (e.g., 'If a new customer is created, send a webhook') and the AI will architect the flow for you." /> } title="AI Explain" description="Analyze any existing workflow to get a clear, step-by-step textual explanation of the implemented logic." /> *** ## Advanced Capabilities ### Loops and Variables Use the **Set Variable** node to store temporary data during execution or the **For Each** node to iterate over arrays (e.g., processing all pending payouts for a partner). ### Error Prevention & Safety The editor includes a built-in **Cycle Detection** system that prevents infinite loops, ensuring the stability of your system and protecting your external API rate limits. ### Custom Blocks Developers can register **Custom Blocks** to extend the platform. These nodes appear in the sidebar with specific icons and badges, allowing non-technical team members to use proprietary business functions (e.g., `CRM Notifier`) safely. Before saving, the system ensures that the workflow contains at least one **Initial Trigger**, one **End** node, and that all placed nodes are properly connected. *** ## Use Case Example: Onboarding Flow 1. **Trigger:** `Customer.create` 2. **Logic:** `IF` node to check if the customer provided a VAT number. 3. **Action (True):** Send a "Business Welcome Kit" email. 4. **Action (False):** Send a "Prosumer Welcome Kit" email. 5. **End:** Close the execution. # AI Integration Hub # Integra Donutwork Più Velocemente Questa e' la pagina principale per l'integrazione AI-assisted su Donutwork. Se il tuo team usa Codex o altri copiloti AI, parti da qui per ridurre i tempi di implementazione, limitare errori sugli scope e pubblicare integrazioni piu' solide. ## Perche' E' Importante * Onboarding rapido con skill di integrazione pronta all'uso. * Mappa endpoint-to-scope chiara per privilegio minimo. * Modelli entita' a livello campo per payload piu' sicuri. * Checklist go-live ripetibile per rilasci affidabili. ## Asset Ufficiali Per Integrazione AI * Skill Donutwork (latest): [`/downloads/donutwork-skill-latest.tar.gz`](/downloads/donutwork-skill-latest.tar.gz) * Checksum (latest): [`/downloads/donutwork-skill-latest.sha256`](/downloads/donutwork-skill-latest.sha256) * Skill Donutwork per Claude Code (latest): [`/downloads/donutwork-claude-code-skill-latest.skill`](/downloads/donutwork-claude-code-skill-latest.skill) * Checksum Claude Code (latest): [`/downloads/donutwork-claude-code-skill-latest.sha256`](/downloads/donutwork-claude-code-skill-latest.sha256) * Snapshot OpenAPI: [`/openapi.json`](/openapi.json) * Bundle AI completo: [`/llms-full.txt`](/llms-full.txt) * Indice AI rapido: [`/llms.txt`](/llms.txt) ## Installazione In 60 Secondi ```bash mkdir -p "${CODEX_HOME:-$HOME/.codex}/skills" tar -xzf donutwork-skill-latest.tar.gz -C "${CODEX_HOME:-$HOME/.codex}/skills" ``` Poi invoca: ```text Use $donutwork to design my integration plan. ``` ## Setup Claude Code ```bash unzip -o donutwork-claude-code-skill-latest.skill -d "$HOME" ``` Verifica integrita' (opzionale): ```bash sha256sum -c donutwork-claude-code-skill-latest.sha256 ``` ## Cosa Ottieni Con `$donutwork` * Piano endpoint per feature (metodo, path, scopo). * Scope OAuth/API richiesti per endpoint. * Guida modelli payload con campi richiesti. * Esempi request pronti da usare. * Checklist di rilascio per staging e produzione. ## Prompt Consigliati 1. `Use $donutwork to map scopes for customers, charges, and webhooks.` 2. `Use $donutwork to generate payload models for customer and subscription sync.` 3. `Use $donutwork to produce a production go-live checklist for our integration.` ## Prossimo Step Apri la documentazione completa della skill: * [Skill Codex Donutwork](/it/docs/applications/donutwork-skill) * [Donutwork Claude Code Skill](/it/docs/applications/donutwork-claude-code-skill) # Benvenuto in Donutwork import { Card, Cards } from 'fumadocs-ui/components/card'; import { BarChart3, CreditCard, ShieldCheck, Cpu, Layout, Users } from 'lucide-react'; # Accelerare il tuo Business con Donutwork Donutwork è il cuore pulsante del tuo SaaS. Abbiamo creato un ecosistema di strumenti pronti all’uso che eliminano la necessità di reinventare la ruota ogni volta che lanci un nuovo progetto. Dalla gestione dei pagamenti al monitoraggio dell’infrastruttura, Donutwork gestisce la complessità, così puoi concentrarti sul tuo core business. ## Esplora i Pilastri della Piattaforma Scegli l’area che desideri esplorare per configurare i tuoi sistemi. } title="Business Intelligence" href="/it/docs/bi-growth" description="Monitora MRR, KPI e crescita dei ricavi in tempo reale con dashboard avanzate." /> } title="Fatturazione & Monetizzazione" href="/it/docs/recurring-payments" description="Gestisci abbonamenti, componenti aggiuntivi dinamici e regole di reward." /> } title="Sicurezza Sentinel" href="/it/docs/sentinel" description="Proteggi i tuoi utenti con MFA adattivo, analisi comportamentale e policy di sicurezza enterprise." /> } title="Piattaforma per Sviluppatori" href="/it/docs/applications" description="Webhook, gestione chiavi API, Job Runner e Scheduler per il controllo totale." /> } title="Contenuti Dinamici" href="/it/docs/dynamic-content-modeling" description="Sistema headless-ready e Media Library per contenuti dinamici." /> } title="Partner & Revenue" href="/it/docs/partner-program" description="Crea programmi partner, gestisci commissioni e calcola automaticamente i pagamenti." /> *** ## Strumenti Utility Integrati Donutwork include una suite di microservizi pronti per le tue API, risparmiando ore di sviluppo personalizzato: * **Utility Finanziarie:** validazione Partita IVA, conversione valuta. * **Networking:** IP Intelligence, geolocalizzazione e monitoraggio certificati TLS. * **Produttività per Sviluppatori:** generatore di short link, strumenti di screenshot e bot Telegram integrato. * **Comunicazione:** gateway email integrato con template transazionali. *** ## Approccio Enterprise-Ready Ogni componente di Donutwork è progettato per scalare. Gestisci **Multi-company**, ambienti separati **Staging** e **Production**, e mantieni il controllo completo tramite il **Key Management Service (KMS)**. > **Hai bisogno di supporto tecnico?** > Se stai integrando Donutwork nel tuo stack tecnologico, consulta la nostra Documentazione API ([https://api.hub.donutwork.com/docs](https://api.hub.donutwork.com/docs)) o contatta il nostro team di supporto dedicato all’architettura dei sistemi. ## Percorso Consigliato Per Partire 1. Definisci il modello commerciale da [Pagamenti Ricorrenti](/it/docs/recurring-payments). 2. Configura i flussi operativi nel modulo [Customer](/it/docs/customer). 3. Attiva [Sentinel](/it/docs/sentinel) per controlli rischio e autenticazione adattiva. 4. Imposta [Email Gateway](/it/docs/email-gateway) e [Workflow](/it/docs/workflow) per automazioni end-to-end. 5. Misura impatto e trend in [Business Intelligence & Growth](/it/docs/bi-growth). ## Punto di Accesso AI Se stai integrando Donutwork con copiloti AI o agent coding autonomi, parti da: * [AI Integration Hub](/it/docs/ai-integration) # Authentication import { Callout } from 'fumadocs-ui/components/callout'; import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Step, Steps } from 'fumadocs-ui/components/steps'; # Authentication The Donutwork API uses API Keys to authenticate requests. You can view and manage your API keys in the Donutwork Dashboard. ## Authorization Header All API requests must include your API Key in the `Authorization` HTTP header as a Bearer token. ```http Authorization: Bearer ``` Your API keys carry significant privileges. Keep them secure and never expose them in client-side code or public repositories. ## Obtaining an API Key Donutwork is currently in a controlled rollout phase. Access is granted to partners and early adopters through the following process: ### Request Access Submit a request to the Donutwork team outlining your integration use case. ### Review & Provisioning Our team will review your requirements and provision the necessary environments. ### Environment Keys Upon approval, you will be provided with distinct keys for: * **Staging**: For development, testing, and sandbox experimentation. * **Production**: For live, customer-facing traffic. ## Connectivity and Health Checks Use these endpoints to validate your authentication credentials and monitor API availability. ### System Ping Verify the operational status of the Donutwork API environment. ### Connection Metadata Retrieve detailed information about your current connection, including client IP and protocol negotiation. # Company import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Company The Company API allows you to retrieve metadata about your own organization and lookup public data for third-party companies using VAT identifiers. *** ## Get Company Profile Retrieve the core configuration and identification attributes for your company profile. This includes your unique internal identifier and official registered name. *** ## List Active Modules Discover and monitor the status of functional modules enabled for your organization. Each module represents a specific capability (e.g., Recurring Payments, Email Gateway) along with its configuration and activation state. *** ## Company Intelligence Stats Retrieve the company intelligence snapshot used by operational dashboards. This endpoint returns KPI data, usage widgets, revenue chart aggregates, and metadata for the current company context. *** ## Lookup Registered Company (Open Data) Retrieve public business information for a company using its VAT number. This is particularly useful for automating KYC (Know Your Customer) workflows and ensuring data accuracy during customer onboarding. # Currency import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Currency The Currency API provides programmatic access to platform-supported monetary denominations and enables precision-grade currency conversion based on Donutwork's centralized exchange data. *** ## List Enabled Currencies Retrieve the full collection of ISO 4217 currency codes supported by the platform. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/currencies.json' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` ```js const currencies = await sdk.currency.list(); console.table(currencies); ``` *** ## Perform Currency Conversion Execute a real-time conversion between two supported currencies.\ The response field `amount` is the converted value, not the original request amount. ### Technical Implementation ```sh curl --location --request POST \ 'https://api.hub.donutwork.com/2026-02-01/currencies/EUR/USD.json' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer YOUR_API_KEY' \ --data '{"amount": 100}' ``` ```js const conversion = await sdk.currency.convert("EUR", "USD", 100); console.log(`Converted: ${conversion.amount} ${conversion.to} @ rate ${conversion.rate}`); ``` # Customers import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Customers The Customer API is the central hub for managing your client base. It allows you to synchronize your internal CRM data, manage billing profiles, and monitor subscription health across your organization. *** ## List All Customers Retrieve a paginated collection of customers associated with your organization. This endpoint is ideal for dashboard overviews and batch synchronization processes. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/customers.json?size=20' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` ```js const customers = await sdk.customers.list({ size: 20 }); console.table(customers.elements); ``` *** ## Create a New Customer Initialize a new customer profile. This is the prerequisite step for attaching subscriptions or processing one-time charges. High-quality data at this stage ensures accurate tax calculation and communication delivery. *** ## Retrieve Customer Details Fetch the complete profile for a specific customer. This includes organizational metadata, contact information, and summarized subscription status. *** ## Search by External Identifier Locate a customer profile using your internal system's identifier (externalId). This is essential for maintaining synchronization between Donutwork and your primary CRM/ERP. *** ## Update Customer Profile Modify an existing customer record. This endpoint supports partial updates (PATCH-style behavior); only the fields included in the request body will be modified. This is useful for updating contact information or adding organizational tags. *** ## Decommission Customer Profile Permanently remove a customer profile and all associated metadata. This action is destructive and irreversible. Ensure that all active subscriptions are terminated before choosing to decommission a profile. *** ## Customer Properties (Metadata) Extend the customer profile with custom key-value pairs. Properties are ideal for storing domain-specific data, integration identifiers, or specialized configuration flags that are not captured by standard profile fields. ### Retrieve All Properties Fetch the complete set of custom metadata associated with a customer. ### Atomic Update/Insert (Upsert) Properties Update existing property values or append new keys to the customer's property collection. This endpoint performs an "upsert" operation; keys that do not exist will be created, and existing keys will have their values overwritten. *** ## Secure Hosted Payment Link Generate a unique, short-lived URL for the Donutwork Hosted Payment Page. This secure interface allow customers to update their sensitive payment information (e.g., Credit Card, SEPA Mandate) without sensitive data passing through your servers. *** ## Subscription Management Manage recurring billing cycles and plan associations for your customers. Subscriptions automate the generation of invoices and payment processing based on predefined logic. ### List Active and Historical Subscriptions Retrieve a collection of all subscription entities associated with a customer, including active, canceled, and past-due states. ### Attach New Subscription Provision a new subscription for a customer. This endpoint allows for runtime overrides of plan defaults, such as custom discounts and initial addon quantities. ### Detach Subscription Detach a subscription from the customer profile. ### Retrieve Subscription Status Read the operational status of a specific customer subscription. ### Modify Subscription Status Manually transition a subscription between operational states. This is typically used for administrative overrides or manual churn management. *** ### Advanced Subscription Lifecycle (Additive) These endpoints extend subscription lifecycle management without replacing existing legacy routes. Use them when you need pause/resume, plan amendments, scheduled changes, and proration-aware updates. #### Read Extended Lifecycle State #### Pause, Resume, Cancel-at-Period-End Use the same payload model with: * `.../lifecycle/resume.json` * `.../lifecycle/cancel-at-period-end.json` * `.../lifecycle/undo-cancel-at-period-end.json` Pause/resume billing behavior: * No retroactive automatic billing is created when resuming after a long pause. * If resumed two months later (for example pause on **May 1, 2026** and resume on **July 1, 2026**), renewal is re-anchored to the resume date (or future `resume_at` if provided). Undo-cancel behavior: * If a subscription is `cancel_pending`, you can revert it to `active` before renewal boundary. * Plan/addons remain the current ones on the subscription; cancellation flag is removed. #### Change Plan or Addons with Immediate/Scheduled Application #### Proration Preview (No Mutation) #### Amendment History ### Backward Compatibility Lifecycle endpoints are **additive and opt-in**. Existing integrations can keep using current routes unchanged. | Area | Legacy Contract | Lifecycle Extension | | :----------------------- | :--------------------- | :----------------------------------------------- | | Attach/Detach | Unchanged | Still valid | | Status route | Unchanged payload keys | Additional lifecycle visibility | | Addons route | Unchanged | Optional proration-aware lifecycle change-addons | | Usage/metering | Unchanged | Unchanged | | Existing panel/API flows | Unchanged | New actions available when explicitly called | *** ### Subscription Addons Manage the quantity of modular features (addons) attached to a specific subscription. Addons allow for flexible, feature-based pricing. #### Audit Addon Quantities Retrieve a list of all addons currently active on a subscription along with their provisioned quantities. #### Reconcile Addon Quantities Update the provisioned quantities for one or more addons. This operation is additive or disruptive based on the provided quantity values. *** ### Simulation Interface (Sandbox Only) Accelerate development cycles by simulating subscription lifecycle events in non-production environments. #### Simulate Success Event Force a successful renewal or provisioning event for a subscription. #### Simulate Failure Event Force a failed renewal or payment rejection event. *** ## Metered Usage Tracking For subscriptions with `metering: true`, consumption must be reported via these endpoints. Usage is aggregated and billed at the end of the current billing cycle. ### Report Usage Event Record a new consumption event (e.g., API requests, data processed, seats occupied). Each record requires a unique `externalId` to prevent idempotent replay errors. ### Audit Usage History Retrieve a paginated history of all usage events reported for a specific subscription. *** ## Ad-hoc Charges Charges represent immediate, non-recurring billable events created independently of a subscription's billing cycle (e.g., setup fees, professional services). ### Create One-Time Charge Generate an ad-hoc charge. If the `capture` flag is set to `true`, the system will immediately attempt to authorize and capture the funds using the customer's primary payment method. ### List Organizational Charges Retrieve all charges (including pending and failed attempts) associated with a specific customer profile. ### Charge Details and Reconciliation Retrieve detailed metadata for a specific charge, including its internal lifecycle state and tax calculations. ### External Invoice Synchronization Manage links to external accounting systems (e.g., Fatture in Cloud) for each charge. #### Retrieve Invoice Metadata #### Persist Invoice Metadata *** ### Global Charge Resolution Resolve charge details using only the global unique identifier. This is optimized for callback handlers and webhook reconciliation modules. # Directory Monitor import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Directory Monitor The Directory Monitor API enables real-time synchronization and event orchestration for local filesystem changes. It is designed for deep integration with local agents to monitor project directories, capture file events, and trigger remote workflows. *** ## Initialize Monitor (Startup) Signal the start of a monitoring session for a specific project. This initialization step validates the project configuration and prepares the environment for ingress events. *** ## Synchronize Event (Ingress) Report a filesystem event (creation, modification, deletion) to the centralized monitor. This endpoint processes file metadata and executes any associated workflow triggers. *** ## Audit Monitor Events Retrieve a paginated history of synchronized filesystem events for a specific project. This is used for auditing changes and verifying synchronization state. # DNS # DNS API Use DNS endpoints for diagnostic and propagation checks across public resolvers. ## DNS Capabilities ## DNS Lookup (GET) ## DNS Lookup (POST) # Content Box import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Content Box API The Content Box system provides a schematized storage layer for unstructured or custom-structured data. It allows organizations to define complex data models (Types) and instantiate them as managed content entities (Contents), suitable for blogs, product catalogs, and internal metadata repositories. *** ## Content Entity Management Manage the lifecycle of data entries within your defined content structures. ### List Content Entities Retrieve a paginated collection of content entities. Results can be filtered by state, content type, or via a full-text search query. ### Create Content Entity Provision a new content entry. The `data` payload must adhere to the requirements of the associated `type_id`. ### Update Content Entity Modify an existing content entry. This endpoint supports partial updates; only the fields provided in the `content` object will be modified. ### Retrieve Content Entity Fetch the full payload for a single content entry. ### Decommission Content Entity Permanently delete a content entry. This action is irreversible. *** ## Content Type Modeling (Schema Definition) Define and manage the structural blueprints that govern how content is stored and validated. ### List Content Types Retrieve the catalog of all defined content schemas for your organization. ### Create Content Type Define a new organizational schema. Specify the attributes and UI input types for each field in the model. {label, type})." } ]} responses={[ { status: "201 Created", description: "Content type definition created.", content: { "id": "6751...", "title": "E-Commerce Product" } } ]} /> ### Retrieve Type Definition Fetch the precise structural definition for a specific content type. ### Update Type Definition Update metadata or fields for a specific content schema. When `fields` is provided, each field must include both `label` and `type` and use allowed input types. # Email Gateway # Email Gateway API The Email Gateway API manages template files and transactional sends. *** ## List Templates ## Create Template Hello FIRST_NAME" } }} properties={[ { name: "template.id", type: "string", required: true, description: "Template filename identifier." }, { name: "template.content", type: "string", required: false, description: "Optional initial template content." } ]} responses={[ { status: "201 Created", description: "Template created.", content: { "id": "welcome.html" } }, { status: "409 Conflict", description: "Template already exists.", content: { "error": "Template already exists" } } ]} /> ## Get Template Hello FIRST_NAME" } }, { status: "404 Not Found", description: "Template not found.", content: { "error": "Template not found" } } ]} /> ## Update Template Hello FIRST_NAME

Updated

" } }} properties={[ { name: "template.content", type: "string", required: true, description: "Template content to persist." } ]} responses={[ { status: "200 OK", description: "Template updated.", content: { "id": "welcome.html", "updated": true } } ]} /> ## Delete Template ## Preview Template Hello Alex" } } ]} /> ## Dispatch Transactional Email # General import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # General API The General API provides a set of infrastructure-level endpoints designed for environmental diagnostics and the retrieval of global static datasets. These tools are essential for verifying network reachability, inspecting client-server connection properties, and populating standardized geographic data across your application. *** ## Infrastructure Health (Ping) A high-performance heartbeat endpoint used to verify that the DonutWork API gateway is operational and to measure basic network round-trip time (RTT). ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/ping.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js const heartbeat = await sdk.utils.ping(); console.log(`System Status: ${heartbeat.status} (${heartbeat.RRT})`); ``` *** ## Connection Diagnostics Retrieve a detailed diagnostic profile of your current API session. This endpoint is instrumental for debugging network protocols, verifying IP whitelisting, and ensuring the correct API version is being targeted. *** ## Global Metadata (Countries) Retrieve a comprehensive, standardized list of countries and their associated ISO 3166-1 alpha-2 codes. This dataset ensures data integrity when capturing geographic information in user profiles or billing addresses. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/countries/countries.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js const countryList = await sdk.utils.listCountries(); const italy = countryList.find(c => c.code === 'IT'); console.log(`Country Name: ${italy.name}`); ``` # GeoIP (Location Services) import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # GeoIP API The GeoIP API enables the resolution of IPv4 addresses into rich geographical and jurisdictional datasets. Beyond simple location coordinates, this service provides essential metadata—including currency systems, telecommunication prefixes, and linguistic profiles—enabling automated tax compliance (VAT/GST), regional content personalization, and fraud detection through threat-level auditing. *** ## Intelligence Resolution (Geo-Location) Retrieve the full intelligence profile for a specific IPv4 address. This includes Autonomous System (AS) data, high-level geolocation, and localized jurisdictional metadata. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/geoip/ip.json?ip=8.8.8.8' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js const ipAddress = "8.8.8.8"; try { const data = await sdk.geolocation.resolve(ipAddress); console.dir(data, { depth: null }); } catch (error) { console.error(`Resolution Failed: ${error.message}`); } ``` **Business Context:** Use this data to automate tax profile selection for checkout flows or to enforce regional compliance for regulated digital services. # Identity Provider (IDP) & MFA import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Identity Provider (IDP) API The Identity Provider (IDP) service centralizes user identity management and provides robust secondary authentication layers. It allows organizations to link external user identifiers to a secure, managed identity capable of Multi-Factor Authentication (MFA) via Time-based One-Time Passwords (TOTP) and advanced risk assessment (Sentinel). *** ## Identity Management ### Provision External User Provision a new managed identity within the IDP ecosystem. This creates a security context linked to your platform's internal `external_id`. ### Retrieve Identity Profile Fetch the security profile for a specific user. This includes authentication capabilities (MFA status), operational status (locked/active), and audit metadata. *** ## Multi-Factor Authentication (MFA) ### Configuration of TOTP Secret Generate a new TOTP secret and QR code payload to enable secondary authentication. Scanning this payload into an authenticator application (e.g., Microsoft/Google Authenticator) completes the setup. ### Verify Authentication Code Validate a 6-digit TOTP code (or a one-time backup code) to finalize the authentication process. ### Provision Backup Codes Generate a collection of single-use backup codes. These allow users to regain access if the primary MFA device is unavailable. *** ## Sentinel Risk Assessment Sentinel provides a sophisticated analytical layer for evaluating authentication risk in real-time. ### Analyze Session Integrity (Discover) Submit session metadata to Sentinel to perform a risk assessment based on behavioral patterns, network reputation, and environmental context. # API Reference import { ShieldCheck, Key, Mail, MapPin, Link, Percent, Share2, Box, Layers, Zap } from 'lucide-react'; Initialize your integration with our unified headless architecture. Designed to handle millions of requests with enterprise-grade latency and deterministic execution. *** ## Core Infrastructure
### Identity Provider (IDP) Manage user identities with native MFA and TOTP support. [Explore IDP →](/en/docs/api/idp)
### Key Management Service (KMS) Store and reveal sensitive credentials with strict IP whitelisting. [Explore KMS →](/en/docs/api/kms)
### Email Gateway **Transactional Intelligence.** Trigger localized templates with dynamic variable injection. Scale communications via high-deliverability routes. [Explore Email →](/en/docs/api/email-gateway)
### GeoIP & Metadata **Localized Intelligence.** Resolve IPv4 to precise geographic data and rich country metadata for automated compliance and tax logic. [Explore GeoIP →](/en/docs/api/geo-ip)
*** ## Growth & Operations
#### Share Secrets One-time encrypted payload sharing with automatic purge.
#### Shortlinks URL redirection with traffic attribution.
#### Taxes VAT and sales tax logic for billing compliance.
#### DNS Multi-resolver DNS diagnostics and propagation checks.
#### Mobile Push Register and revoke iOS push tokens for mobile clients.
*** ## Enterprise Orchestration
### Content Box Model custom data structures and serve them via a unified JSON API. [Explore Content Box →](/en/docs/api/dynamic-content)
### Workflow Automate business logic with stage-based auditing and dynamic payload injection. [Explore Workflow →](/en/docs/api/workflow)
*** ### Integration Architecture | Metric | Specification | | :------------------ | :-------------------------- | | **Uptime SLA** | 99.99% Enterprise Tier | | **Auth Protocol** | Bearer Token (Stateless) | | **Default Version** | `2026-02-01` | | **Execution** | Deterministic / Low Latency | # Integrations & Capabilities import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Integrations & Capabilities API The Integrations API provides a unified abstraction layer for extending the DonutWork core platform with third-party application functionalites. By declaring "capabilities," applications can expose their own endpoints as managed actions within the DonutWork ecosystem, allowing for seamless cross-platform orchestration, automated authorization handling (app-to-app), and centralized audit logging. *** ## Lifecycle Management ### Audit Active Integrations Retrieve a paginated directory of all integrations currently authorized for your organization. This includes high-level connectivity status and identification handlers for each service. ### Declare Functional Capabilities Register or update the specific actions (capabilities) that your application exposes. This declaration defines the input requirements and contract for each action, enabling DonutWork to proxy requests to your service securely. *** ## Resource Discovery ### Retrieve Specific Integration Fetch the full configuration, permission sets, and connectivity health for a specific integration. *** ## Execution (Capability Proxy) ### Dispatch Delegated Action Execute a capability on a remote integration. DonutWork acts as a secure proxy, handling authorization headers and validating input schemas before relaying the request to the target service. The request payload for action dispatch is dynamic. Required body fields are validated at runtime using the integration capability declaration (`capabilities[].inputs[]` with `required: true`). ### Read Delegated Action ### Update Delegated Action ### Delete Delegated Action ### Emit Integration Event Emit an application-scoped event so workflows and event listeners can react to integration activity. .` format.", location: "path" } ]} body={{ "metadata": { "message_id": "msg_001", "status": "sent" }, "entity_id": "SLACK_ENT" }} properties={[ { name: "metadata", type: "object", required: false, description: "Event payload metadata object." }, { name: "entity_id", type: "string", required: false, description: "Entity identifier. If omitted, the app handler is used." } ]} responses={[ { status: "200 OK", description: "Event accepted and dispatched.", content: { "success": true, "app_handler": "SLACK", "event": "Slack.MESSAGE_SENT", "queued_workflows": 1 } } ]} /> ### Technical Implementation ```sh curl --location --request POST \ 'https://api.hub.donutwork.com/2026-02-01/integrations/SLACK/SEND_MSG.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' \ --header 'Content-Type: application/json' \ --data-raw '{"message": "Automated Deployment Completed"}' ``` ```js const payload = { message: "System Alert: Resource threshold reached." }; try { const result = await sdk.integrations.dispatch("SLACK", "SEND_MSG", payload); console.log(`Action Result: ${result.success} (Status: ${result.external_status})`); } catch (error) { console.error(`Dispatch Failed: ${error.message}`); } ``` # Job Runner # Job Runner API ## List Jobs ## Create Job ## Run Job ## Delete Job # Key Management Service (KMS) import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # Key Management Service (KMS) API The Key Management Service (KMS) provides a hardened environment for the storage and lifecycle management of sensitive credentials, such as third-party API keys, service accounts, and cryptographic tokens. By using KMS, organizations can eliminate the risk of hardcoded secrets within source code, instead retrieving them dynamically via secure, audited endpoints protected by strict IP-based whitelisting. *** ## Secret Management ### Audit KMS Inventory Retrieve a paginated directory of all KMS secret handlers associated with your organization. This endpoint provides administrative metadata and is used for secret discovery; it does **not** expose the underlying secret values. ### Retrieve Secret Configuration Fetch the detailed metadata and operational configuration for a unique KMS handler. This includes the registered IP whitelist and custom properties defined for the secret. *** ## Secret Consumption ### Decrypt & Reveal Secret Securely decrypt and reveal the underlying secret content. Access to this endpoint is strictly enforced via IP-based whitelisting and results in an immediate audit entry. Use this endpoint only within backend environments to dynamically inject credentials. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/kms/reveal/aws-s3-prod-credentials.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js const handler = "aws-s3-prod-credentials"; try { const secret = await sdk.kms.reveal(handler); console.log(`Resource Access Granted. Payload: ${secret.content}`); } catch (error) { console.error(`Vault Access Denied: ${error.message}`); } ``` **Security Audit:** Every call to the `reveal` endpoint is logged with the requesting IP, User-Agent, and timestamp. Ensure your infrastructure IPs are properly whitelisted in the KMS configuration to avoid 403 authorization failures. # Media Library # Media Library API ## Strategy For large files, use presigned direct upload: 1. Request upload link from API. 2. Upload file directly to storage with `PUT`. 3. Use media list or download-link APIs for retrieval flow. ## List Files ## Create Upload Link ## Upload File (Fallback) ## Create Download Link # Mobile Push Tokens # Mobile Push Tokens API These endpoints are available only when using a mobile-scoped API key. ## Save Device Push Token ## Delete Device Push Token # Newsletter Campaigns # Newsletter API The Newsletter API exposes campaign lifecycle, recipient synchronization, dispatch queue controls, analytics, and suppression list management. *** ## List Newsletter Campaigns ## Create Newsletter Campaign ## Retrieve Campaign Details ## Update Campaign Metadata ## Delete Campaign ## Get Campaign Recipients Snapshot ## Set Campaign Recipients ## Queue Campaign Dispatch ## Send Test Email ## Get Campaign Stats *** ## Suppression List ### List Unsubscribes ### Add Unsubscribe ### Resubscribe Email # Partner Groups import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # Partner Groups API Partner Groups provide an automated logic layer for categorizing partners and enforcing organization-wide distribution policies. These groups define rules that govern revenue sharing percentages, time-based commission tiers, and performance-driven upgrades based on total Lifetime Value (LTV) or charge volume. *** ## Group Inventory ### List Partner Groups Retrieve a paginated directory of all defined Partner Groups. This directory contains the high-level metadata and administrative identifiers for each group. ### Retrieve Group Configuration & Rules Fetch the comprehensive configuration for a specific governance group, including the active rules engine parameters that define commission logic. *** ## Group Lifecycle Management ### Create Partner Group ### Update Partner Group ### Delete Partner Group ### Simulate Rules *** ## The Rules Engine Partner groups are powered by a deterministic rules engine that evaluates transactions in real-time. The following rule types are supported: ### Rule Type Definitions | Rule Type | Description | Key Parameters | | :----------------------- | :------------------------------------------------------------------------------------------------ | :------------------------------------ | | `new_customer_time_tier` | Applies a specific commission for the initial months of a customer's lifecycle. | `max_months`, `percentage` | | `recurring` | The baseline commission applied to all transactions when no other specific rule applies. | `percentage` | | `partner_ltv_upgrade` | Triggers a commission percentage increase once a partner's total managed LTV exceeds a threshold. | `min_ltv_total`, `upgrade_percentage` | | `charge_threshold_bonus` | Provides a one-time bonus for transactions exceeding a specific amount. | `min_charge_total`, `bonus` | **Evaluation Hierarchy:** Rules are evaluated based on the customer's acquisition date and the partner's historical performance. A `recurring` rule is required for all groups as a fallback mechanism. # Partners import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Partners API The Partners API enables organizations to build and scale distribution networks through agencies, resellers, and affiliates. It provides a framework for managing partner identities, commission calculations (fees), and financial settlements (payouts), while maintaining clear attribution for every customer acquired through the channel. *** ## Channel Management ### List Partners Retrieve a paginated directory of all registered partners. This list includes high-level identification data and current status for each collaborative entity. ### Provision New Partner Onboard a new partner into the ecosystem. This initializes their profile and associates them with a governance group (Partner Group) to define their commission rules. ### Retrieve Partner Profile Fetch the comprehensive profile of a specific partner, including their fee structure, whitelist configuration, and association metadata. *** ## Attribution & Performance ### Audit Attributed Customers Retrieve a paginated list of all customers currently attributed to a specific partner. This is used to verify channel performance and revenue attribution. ### Performance Analytics Retrieve high-level performance metrics for a partner, including total attributed revenue and cumulative commissions earned. *** ## Financial Settlement (Payouts) ### Audit Commission Ledger (Fees) Retrieve individual commission entries (fees) generated by attributed customer transactions. These entries serve as the basis for payout generation. ### Generate Payout Request Consolidate multiple 'pending' commission fees into a single Payout request. This initiates the financial settlement cycle and generates a draft settlement record. ### Retrieve Payout Documentation (PDF) Retrieve a base64-encoded PDF report (Account Statement) for a specific payout. This document serves as the official settlement record for the partner. ### Technical Implementation (Payout Flow) ```js const payoutData = { payout: { partner_id: "PARTNER_6621", transactions: ["FEE_001", "FEE_002"], invoice: { number: "REF-9921", date: "2026-03-03" }, vat_settings: { tax_id: "VAT_22_IT" } } }; try { const settlement = await sdk.partners.createPayout(payoutData); console.log(`Settlement Processed. ID: ${settlement.id}, Total: ${settlement.total}`); } catch (error) { console.error(`Settlement Failed: ${error.message}`); } ``` *** ## Additional Partner Operations ### Search Partner by External ID or Email ### Update Partner Profile ### Delete Partner ### Get Partner Fee by ID ### List Global Payouts ### List Payouts for One Partner ### Get Payout by Partner and ID ### Get Payout by ID ### Update Payout Status ### Stream Payout PDF # Recurring Payments import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Recurring Payments API The Recurring Payments API provides the operational infrastructure for managing subscription-based revenue models. It allows organizations to define sophisticated billing cycle parameters, configure automated dunning (retry) policies for failed transactions, and monitor the real-time status of all active subscriptions across the platform. *** ## Operational Configuration ### Audit Recurring Settings Retrieve the global operational parameters governing recurring billing. This includes the current retry logic for failed payments and the timing offsets for subsequent billing cycles. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/recurring-payments/settings.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js try { const config = await sdk.recurringPayments.getSettings(); console.log(`Billing Policy: ${config.settings.retry_policy} (Max Retries: ${config.settings.max_retries})`); } catch (error) { console.error(`Fetch Failed: ${error.message}`); } ``` *** ## Subscription Lifecycle Monitoring ### Audit Active Subscriptions Retrieve a comprehensive inventory of all subscriptions currently managed by the recurring payment engine. This endpoint provides crucial visibility into renewal dates, customer associations, and current billing health. ### Implementation ```js const filters = { page: 1, size: 50 }; try { const activeSubs = await sdk.recurringPayments.listSubscriptions(filters); activeSubs.elements.forEach(sub => { console.log(`Subscription ${sub.id}: Renewal due on ${sub.next_renewal_date}`); }); } catch (error) { console.error(`Telemetry Error: ${error.message}`); } ``` # Scheduler # Scheduler API ## List Events ## Create Event ## Update Event ## Delete Event # Share Secrets import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # Share Secrets API The Share Secrets API provides a secure mechanism for transmitting sensitive information (such as passwords, private keys, or PII) without leaving a persistent digital footprint. Secrets are encrypted and associated with a unique, short-lived URL. To ensure maximum security, content is **purged immediately after the first successful access**, rendering the link permanently invalid. *** ## Secret Management ### Audit Secret Inventory Retrieve a paginated directory of all active (unread) or recently expired share secret entries. This allows for administrative tracking of shared links and their current consumption status. ### Provision Secure Secret Link Generate a new ephemeral secret link. The `content` provided is encrypted at rest and will be revealed only once. You can optionally trigger an automated email notification to the recipient. ### Technical Implementation ```js const secretPayload = { shareSecret: { name: "Inter-Service Auth Key", content: "PRIVATE_KEY_CONTENT_HERE", sendTo: { email: "security-ops@acme.com", message: "Key Rotation: 2026-Q1" } } }; try { const response = await sdk.tools.createShareSecret(secretPayload); console.log(`Secret Link Generated: ${response.url}`); } catch (error) { console.error(`Provisioning Failed: ${error.message}`); } ``` *** ## Access & Revocation ### Audit Access Metadata Retrieve the access status and reader telemetry for a specific secret link. This endpoint provides audit trails (IP, User-Agent, Timestamp) once the secret has been consumed. ### Revoke Secret Link Manually revoke a secret link before it is consumed, or purge the audit record of an already read secret. **Security Policy:** Content retrieval is handled via the specific `url` field returned during provisioning. Once the `readed` flag is set to `true`, the content is physically deleted from the database and cannot be recovered. # Shortlinks import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Shortlinks API The Shortlinks API enables organizations to transform complex destination URLs into concise links. Beyond simple redirection, the system provides integrated telemetry for traffic attribution, enabling teams to monitor engagement performance in real time across distribution channels. *** ## Link Lifecycle Management ### Audit Shortlink Directory Retrieve a paginated directory of all shortlinks associated with your organization. This inventory includes current operational status and destination metadata. ### Provision New Shortlink Generate a new shortlink for a target destination.\ You can optionally provide a custom `fragment` (bitly-style suffix). The platform always prepends an auto-generated prefix to reduce collision risk. ### Retrieve Link Configuration Fetch the detailed configuration and operational status for a specific shortlink. *** ## Operational Controls ### Update Link Parameters Modify the destination URL, custom fragment, or operational status of an existing shortlink. Link updates are propagated across the redirection edge in near real-time.\ When updating `fragment`, the existing auto-generated prefix is preserved. ### Revoke Shortlink Permanently revoke a shortlink and decommission its redirection service. *** ## Analytics & Telemetry ### Retrieve Interaction Metrics Access real-time engagement telemetry for a specific shortlink. This include visit counts, unique interactions, and longitudinal performance data. ### Technical Implementation ```js const shortlinkId = "675d9fea..."; try { const stats = await sdk.dw2.getStats(shortlinkId); console.log(`Campaign Performance: ${stats.metrics.summary.total} total interactions.`); } catch (error) { console.error(`Telemetry Error: ${error.message}`); } ``` # Taxes import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # Taxes API The Taxes API provides a centralized layer for managing tax profiles and regional tax logic. By defining tax profiles (such as VAT, GST, or Sales Tax), organizations can automate tax calculation during invoicing and subscription renewals, ensuring consistent compliance with local regulations. *** ## Tax Profiles ### List Tax Profiles Retrieve a comprehensive directory of all tax profiles configured for your organization. These profiles act as the authoritative source for tax percentage calculations and must be referenced when provisiong new customers or products. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/taxes.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js try { const taxProfiles = await sdk.taxes.list(); console.log(`Active Tax Profiles: ${taxProfiles.count}`); } catch (error) { console.error(`Compliance Check Failed: ${error.message}`); } ``` **Integration Note:** When orchestrating customer provisioning (via the CRM/Customer API), ensure the `tax_id` from these profiles is correctly mapped. This association is critical for accurate automated invoicing and financial reporting. *** ## Tax Profile Lifecycle ### Create Tax Profile = 0." }, { name: "tax.description", type: "string", required: false, description: "Optional internal description." }, { name: "tax.default", type: "boolean", required: false, description: "Marks the profile as default when true." } ]} responses={[ { status: "201 Created", description: "Tax profile created.", content: { "status": "success", "tax": { "id": "tax_001", "name": "Standard EU VAT (22%)", "percentage": 22.0 } } } ]} /> ### Update Tax Profile = 0." }, { name: "tax.default", type: "boolean", required: false, description: "Update default profile flag." } ]} responses={[ { status: "200 OK", description: "Tax profile updated.", content: { "status": "success", "tax": { "id": "tax_001", "name": "EU VAT 2026", "percentage": 23.0 } } } ]} /> ### Delete Tax Profile # Webhook API # Webhook API Use webhooks to receive asynchronous notifications for supported platform events. *** ## List Webhooks ## Create Webhook ## List Supported Webhook Types ## Get Webhook ## Delete Webhook # Workflow import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; # Workflow API The Workflow API provides an engine for orchestrating complex, multi-stage business processes. By defining structured workflows, organizations can automate repetitive operational tasks, ensuring deterministic execution and full auditability. The engine supports dynamic payload injection for contextualized automation across the platform. *** ## Workflow Management ### List Workflows Retrieve a comprehensive directory of all registered business workflows for your organization. This inventory includes the operational status, task count, and administrative metadata for each automation. ### Technical Implementation ```sh curl --location --request GET \ 'https://api.hub.donutwork.com/2026-02-01/workflow.json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' ``` ```js try { const inventory = await sdk.workflow.list(); console.log(`Active Automations: ${inventory.count}`); } catch (error) { console.error(`Workflow Audit Failed: ${error.message}`); } ``` *** ## Workflow Execution ### Dispatch Workflow Execution Trigger the execution of a specific business workflow. This endpoint accepts a dynamic `data` payload that is injected into the execution context, allowing tasks to operate on real-time request data. ### Technical Implementation (Execution Flow) ```js const context = { data: { userId: "USR-001", action: "PROVISION_RESOURCE", quota: 100 } }; try { const result = await sdk.workflow.execute("ONBOARD_WF_01", context); if (result.success) { console.log(`Automation Finished: ${result.execution_id}`); } } catch (error) { console.error(`Execution Halted: ${error.message}`); } ``` **Auditability:** Every workflow execution generates a unique `execution_id` and provides detailed telemetry for each stage (node) within the sequence, including input/output data and operational latency. *** ## Workflow Tracing ### List Workflow Traces Retrieve paginated execution traces for a workflow. ### Get Workflow Trace Load full trace payload for one workflow run. # Autenticazione e Governance Iframe import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Step, Steps } from 'fumadocs-ui/components/steps'; import { Callout } from 'fumadocs-ui/components/callout'; # Autenticazione e Incorporamento DonutWork utilizza un solido modello di sicurezza per garantire che le applicazioni di terze parti possano accedere ai dati in modo sicuro fornendo un'esperienza utente unificata. Questa guida copre il flusso di lavoro di Dual-Auth e i requisiti per l'incorporamento di Iframe di livello enterprise. *** ## 1. Il Flusso di Lavoro OAuth 2.0 Le applicazioni utilizzano un flusso standard OAuth 2.0 Authorization Code per ottenere l'accesso autorizzato ai dati di un'azienda. ### Step 1: Richiesta di Autorizzazione Rindirizza l'utente al server di autorizzazione di DonutWork. Ciò avviene quando un utente installa o accede alla tua app per la prima volta. **Endpoint**: `GET /i3/oauth/authorize` **Parametri**: * `client_id`: Il tuo identificativo univoco dell'applicazione. * `redirect_uri`: L'endpoint dove verrà inviato il codice. * `response_type`: Sempre `code`. * `scope`: Elenco (spazio o virgola) dei permessi nel formato canonico `resource:action` (es. `customers:read charges:write`). * requisito minimo `scope`: includere almeno `company:read` per completare correttamente il flusso di connessione OAuth delle app. * `state`: Una stringa univoca per prevenire attacchi CSRF. ### Step 2: Scambio del Token Una volta che l'utente approva la richiesta, DonutWork lo reindirizza al tuo `redirect_uri` con un `code`. Scambia immediatamente questo codice con un token di accesso. **Endpoint**: `POST /i3/oauth/token` (Form-Encoded) **Corpo**: * `client_id`: Il tuo identificativo dell'applicazione. * `client_secret`: Il tuo segreto protetto dell'applicazione. * `code`: Il codice di autorizzazione ricevuto nel reindirizzamento. * `redirect_uri`: Deve corrispondere all'URI utilizzato nello Step 1. ### Step 3: Persistenza Memorizza in modo sicuro i valori `access_token` e `refresh_token` restituiti. Questi token consentono alla tua app di effettuare chiamate API dirette a DonutWork (es. a `/2026-02-01/customers.json`). *** ## 2. Contesto Iframe e Sicurezza Quando un'applicazione viene renderizzata all'interno della dashboard di DonutWork, viene incorporata tramite un Iframe. Ogni richiesta al punto di ingresso della tua applicazione include una firma di sicurezza. ### Parametri della Richiesta DonutWork aggiunge i seguenti parametri di query all'URL della tua applicazione: * `company`: L'identificativo univoco dell'azienda attiva. * `hmac`: Una firma crittografica della richiesta. * `timestamp`: Il timestamp Unix della richiesta. ### Verifica della Firma (HMAC-SHA256) Per verificare che la richiesta sia autentica e provenga da DonutWork, è necessario convalidare il parametro `hmac` utilizzando il tuo `client_secret`. **Procedura di Verifica**: 1. Rimuovi il parametro `hmac` dalle coppie chiave-valore. 2. Ordina alfabeticamente i parametri rimanenti per chiave. 3. Concatena le chiavi e i valori ordinati in una stringa di query (es. `company=C123×tamp=1740000000`). 4. Calcola l'HMAC-SHA256 di questa stringa utilizzando il tuo `client_secret` come chiave. 5. Confronta il risultato con l' `hmac` fornito. ```js const crypto = require('crypto'); function verifyHmac(queryParams, clientSecret) { const { hmac, ...params } = queryParams; const message = Object.keys(params) .sort() .map(key => `${key}=${params[key]}`) .join('&'); const expectedHmac = crypto .createHmac('sha256', clientSecret) .update(message) .digest('hex'); return hmac === expectedHmac; } ``` ```text 1. ARGS = QueryString.Remove("hmac") 2. SORTED_MSG = ARGS.SortByKey().Join("&") 3. SIGNATURE = HMAC_SHA256(SORTED_MSG, APP_CLIENT_SECRET) 4. VALIDATE(SIGNATURE == QueryString["hmac"]) ``` *** ## 3. Requisiti di Integrazione UI Poiché l'applicazione viene eseguita in un Iframe cross-site, si applicano le policy standard di sicurezza del browser. ### Gestione della Sessione I browser moderni bloccano i cookie di terze parti per impostazione predefinita. Per mantenere una sessione all'interno dell'Iframe, i cookie di sessione **devono** utilizzare i seguenti attributi: * `SameSite=None`: Consente l'invio del cookie in un contesto cross-site. * `Secure=true`: Richiesto quando viene utilizzato `SameSite=None`. Se i tuoi cookie non hanno `SameSite=None; Secure`, gli utenti verranno disconnessi immediatamente dopo il reindirizzamento o durante la navigazione all'interno dell'app. ### Content Security Policy (CSP) Assicurati che gli header del tuo server consentano a DonutWork di incorporare la tua applicazione: ```http Content-Security-Policy: frame-ancestors 'self' https://hub.donutwork.com; X-Frame-Options: ALLOW-FROM https://hub.donutwork.com ``` *** ## 4. Scoperta delle Funzionalità Come fase finale del flusso di autenticazione, la tua applicazione dovrebbe dichiarare le sue "capability" alla piattaforma. Ciò consente a DonutWork di effettuare il proxy delle richieste alla tua app (Azioni). **Azione**: `PUT /2026-02-01/integrations.json` Questa dichiarazione dovrebbe includere il tuo `app_token` (utilizzato da DonutWork per chiamarti) e un manifesto degli endpoint supportati. Fai riferimento alla [Guida alla Scoperta delle Applicazioni](/it/docs/applications/how-to-build#2-scoperta-delle-funzionalità-il-manifesto) per i dettagli. Per i dettagli del flusso di disinstallazione (`DELETE uninstall_url` con `company_id` + HMAC `verify`), vedi [Come costruire](/it/docs/applications/how-to-build). # Donutwork Claude Code Skill import { Callout } from 'fumadocs-ui/components/callout'; # Donutwork Claude Code Skill Il bundle ufficiale per Claude Code e' pensato per i team che usano Claude Code come copilota implementativo nelle integrazioni Donutwork. Fornisce contesto operativo pronto all'uso per passare dalla discovery API al rilascio in produzione con meno rework. *** ## Perche' i Team la Adottano * Accelera la delivery con uno `SKILL.md` strutturato. * Riduce errori sugli scope grazie a mappe endpoint e ACL. * Migliora la qualita' dei payload con modelli entita' a livello campo. * Standardizza l'implementazione AI-assisted tra team diversi. *** ## Cosa Include * `.claude/skills/donutwork/SKILL.md`: istruzioni della skill Claude Code e workflow operativo. * `references/api-endpoint-map.json`: inventario metodo/percorso/scope. * `references/entity-models.json`: catalogo modelli entita' a livello campo. * `references/openapi.public.json`: snapshot OpenAPI per tooling. * `references/integration-playbook.md`: blueprint implementativo e lancio. *** ## Download * Pacchetto latest (`.skill`): [`/downloads/donutwork-claude-code-skill-latest.skill`](/downloads/donutwork-claude-code-skill-latest.skill) * Checksum latest: [`/downloads/donutwork-claude-code-skill-latest.sha256`](/downloads/donutwork-claude-code-skill-latest.sha256) * Pacchetto versionato (`v1.1.0`): [`/downloads/donutwork-claude-code-skill-v1.1.0.skill`](/downloads/donutwork-claude-code-skill-v1.1.0.skill) * Checksum versionato (`v1.1.0`): [`/downloads/donutwork-claude-code-skill-v1.1.0.sha256`](/downloads/donutwork-claude-code-skill-v1.1.0.sha256) *** ## Installazione In 60 Secondi ```bash unzip -o donutwork-claude-code-skill-latest.skill -d "$HOME" ``` Verifica integrita' (opzionale): ```bash sha256sum -c donutwork-claude-code-skill-latest.sha256 ``` Questo pacchetto installa `.claude/skills/donutwork/SKILL.md` e i riferimenti sotto home, cosi Claude Code puo' auto-scoprire la skill. *** ## Prompt Rapidi 1. `Map required scopes for customers, charges, and webhooks in our Donutwork integration.` 2. `Generate payload contracts for customer and subscription synchronization.` 3. `Prepare a production readiness checklist for our Donutwork API launch.` *** ## Prossimi Passi * Parti da [AI Integration Hub](/it/docs/ai-integration) per il percorso completo AI-first. * Se il tuo team usa Codex, vedi [Donutwork Codex Skill](/it/docs/applications/donutwork-skill). * Usa [API Authentication](/it/docs/api/authentication) per validare setup key e OAuth. # Skill Codex Donutwork import { Callout } from 'fumadocs-ui/components/callout'; # Skill Codex Donutwork La skill ufficiale `donutwork` per Codex e' un acceleratore pronto all'uso per team di prodotto e integrazione. Trasforma la documentazione API in output implementabili: mappatura scope, modelli payload e checklist di rilascio. *** ## Perche' i Team la Adottano * Riduce il tempo di onboarding API da giorni a ore. * Migliora la sicurezza con guidance sugli scope a privilegio minimo. * Standardizza i contratti payload tra team tecnici. * Aumenta la confidenza al go-live con checklist ripetibili. *** ## Cosa Include * `SKILL.md`: workflow operativo e formato risposta. * `references/api-endpoint-map.json`: inventario metodo/percorso/scope. * `references/entity-models.json`: catalogo modelli entita' a livello campo. * `references/openapi.public.json`: snapshot OpenAPI per tooling. * `references/integration-playbook.md`: blueprint implementativo e lancio. *** ## Download * Pacchetto latest: [`/downloads/donutwork-skill-latest.tar.gz`](/downloads/donutwork-skill-latest.tar.gz) * Checksum latest: [`/downloads/donutwork-skill-latest.sha256`](/downloads/donutwork-skill-latest.sha256) * Pacchetto versionato (`v1.0.0`): [`/downloads/donutwork-skill-v1.0.0.tar.gz`](/downloads/donutwork-skill-v1.0.0.tar.gz) * Checksum versionato (`v1.0.0`): [`/downloads/donutwork-skill-v1.0.0.sha256`](/downloads/donutwork-skill-v1.0.0.sha256) *** ## Installazione In 60 Secondi ```bash mkdir -p "${CODEX_HOME:-$HOME/.codex}/skills" tar -xzf donutwork-skill-latest.tar.gz -C "${CODEX_HOME:-$HOME/.codex}/skills" ``` Verifica integrita' (opzionale): ```bash sha256sum -c donutwork-skill-latest.sha256 ``` La cartella estratta si chiama `donutwork`, quindi puoi invocarla direttamente con `$donutwork`. *** ## Prompt Rapidi 1. `Use $donutwork to design an integration plan for syncing customers and subscriptions.` 2. `Use $donutwork to map required scopes for customer, charge, and webhook endpoints.` 3. `Use $donutwork to generate request payload models and a production go-live checklist.` *** ## Prossimi Passi * Parti da [AI Integration Hub](/it/docs/ai-integration) per un percorso completo AI-first. * Se il tuo team usa Claude Code, vedi [Donutwork Claude Code Skill](/it/docs/applications/donutwork-claude-code-skill). * Usa [API Authentication](/it/docs/api/authentication) per validare API key e setup OAuth. * Usa [API Reference](/it/docs/api) per estendere la copertura endpoint dopo il primo rilascio. # Come Costruire un'App DonutWork import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; # Costruire per DonutWork Questa guida fornisce un blueprint concettuale e tecnico per lo sviluppo di applicazioni di terze parti. Il framework DonutWork è esplicitamente **agnostico rispetto al linguaggio di programmazione**, basandosi su protocolli standard HTTP/REST e sull'incorporamento sicuro della UI per facilitare l'orchestrazione tra sistemi. *** ## 1. Registrazione dell'Applicazione Prima di iniziare lo sviluppo, è necessario registrare l'applicazione per ottenere le credenziali necessarie per l'identità e l'accesso alla piattaforma. * **Client ID**: L'identificativo pubblico della tua applicazione. * **Client Secret**: Una credenziale sicura utilizzata per autorizzare la tua app ad agire per conto di un'azienda. * **Redirect URI**: L'URL dove DonutWork invierà i codici di autorizzazione. Consulta la [Guida Dettagliata OAuth](/it/docs/applications/auth-and-embedding) per l'handshake tecnico di autenticazione. *** ## 2. Scoperta delle Funzionalità (Il Manifesto) DonutWork utilizza un **Discovery Pattern** per comprendere le capacità della tua applicazione. Invece di chiamare la tua app alla cieca, la tua app deve "dichiarare" le sue funzionalità (Azioni). ### Dichiarazione delle Funzionalità La tua applicazione deve inviare una richiesta `PUT` all'endpoint `/integrations.json`. Questo manifesto comunica a DonutWork quali endpoint chiamare quando viene attivata un'azione specifica (ad esempio, tramite un Workflow o la UI). * **app\_token**: DonutWork includerà questo Bearer token in ogni header `Authorization` quando chiamerà la tua applicazione. Ciò consente alla tua app di verificare che la richiesta provenga da DonutWork. * **capabilities**: Un array di azioni consentite, ciascuna con un `endpoint`, un `method` e gli `inputs` attesi. *** ## 3. Modello di Comunicazione (La Logica dell'Azione) Quando un utente o un workflow generico attiva un'azione, DonutWork agisce come un **Proxy Sicuro**. 1. **Trigger**: DonutWork identifica l'azione di destinazione (es. `provision_resource`). 2. **Identificazione**: DonutWork recupera l' `endpoint` e l' `app_token` dal manifesto salvato. 3. **Esecuzione**: DonutWork invia una richiesta HTTP al tuo endpoint, includendo l' `app_token` nell'intestazione e i dati richiesti nel corpo. 4. **Risposta**: La tua applicazione elabora la richiesta e restituisce una risposta JSON standard. *** ## 4. Framework UI (L'Iframe) DonutWork incorpora il frontend della tua applicazione all'interno della propria dashboard tramite un **Iframe**. Per garantire un'esperienza utente fluida e mantenere la sicurezza, è necessario rispettare le seguenti policy: ### Sicurezza dei Cookie (`SameSite=None`) Poiché la tua applicazione è in esecuzione in un contesto Iframe (cross-site), i cookie di sessione tradizionali potrebbero essere bloccati dai browser moderni. È necessario configurare i cookie di sessione con: * `SameSite=None` * `Secure=true` ### Header di Sicurezza DonutWork consente l'incorporamento di Iframe da applicazioni registrate. Da parte tua, dovresti assicurarti che i tuoi header consentano alla piattaforma di visualizzare i tuoi contenuti. Per approfondire la verifica della firma, vedi [Contesto Iframe e Sicurezza](/it/docs/applications/auth-and-embedding#2-iframe-context--security). ```http Content-Security-Policy: frame-ancestors 'self' https://hub.donutwork.com; X-Frame-Options: ALLOW-FROM https://hub.donutwork.com ``` *** ## 5. Sincronizzazione degli Eventi (Webhook) Per reagire agli eventi della piattaforma in tempo reale (ad esempio, quando un utente paga una fattura), dovresti registrare un Webhook. 1. **Endpoint**: La tua applicazione dovrebbe fornire un URL HTTPS dedicato per ricevere i payload POST. 2. **Rotazione delle Chiavi**: Durante la registrazione, riceverai un `token`. Usa questa chiave per verificare l'intestazione `X-SIGNATURE` su ogni richiesta in arrivo. *** ## 6. Callback di Disinstallazione (Pulizia Dati Company) Quando una company disinstalla la tua app da DonutWork, la piattaforma invia una callback server-to-server verso l'`uninstall_url` configurata. * **Metodo**: `DELETE` * **Content-Type**: `application/x-www-form-urlencoded` * **Body**: * `company_id`: identificativo della company da eliminare. * `verify`: firma HMAC calcolata come `HMAC_SHA256(company_id, client_secret)`. Esempio payload: ```http DELETE /uninstall HTTP/1.1 Content-Type: application/x-www-form-urlencoded company_id=699ecb44790ac4eea20e9cd3&verify=7c72b2... ``` Regola di verifica lato app: ```php $expected = hash_hmac('sha256', $companyId, $clientSecret); $isValid = hash_equals($expected, $verify); ``` Requisiti implementativi: * Valida `company_id` e `verify` prima di qualsiasi cancellazione. * Elimina solo i dati tenant-scoped della `company_id` ricevuta. * Rendi l'endpoint idempotente (chiamate ripetute non devono fallire). * Restituisci `2xx` solo quando la pulizia e' completata (o gia' completata). Se il tuo endpoint restituisce status non-2xx, DonutWork considera fallita la callback di uninstall e blocca la disinstallazione locale. *** ## Elenco di Controllo Riassuntivo * [ ] Registra l'App e ottieni Client ID/Secret. * [ ] Implementa OAuth 2.0 per ottenere i Platform Access Tokens. * [ ] Usa `PUT /integrations.json` per dichiarare gli endpoint della tua app. * [ ] Implementa i tuoi endpoint API per gestire le richieste dal proxy DonutWork. * [ ] Configura i cookie `SameSite=None` e `Secure` per la tua UI in Iframe. * [ ] Registra i Webhook per l'elaborazione degli eventi in tempo reale. * [ ] Implementa `DELETE uninstall_url` con `company_id` + HMAC `verify` e cleanup tenant-safe. # Framework Applicazioni import { Puzzle, Settings, Zap, Shield, Package } from 'lucide-react'; import { Step, Steps } from 'fumadocs-ui/components/steps'; import { Callout } from 'fumadocs-ui/components/callout'; Il Framework Applicazioni di DonutWork consente agli sviluppatori di estendere le funzionalità principali della piattaforma con servizi specializzati di terze parti. Che tu stia costruendo un connettore finanziario, uno strumento di automazione del marketing o un'integrazione CRM personalizzata, il nostro framework fornisce gli hook necessari per un'orchestrazione senza interruzioni. *** ## Architettura di Integrazione Le applicazioni DonutWork operano su un modello ibrido che combina l'incorporamento sicuro dell'interfaccia utente (UI) con una solida scoperta delle funzionalità guidata dalle API.
### Scoperta delle Funzionalità **Registrazione Autonoma.** Le applicazioni dichiarano le loro "Azioni" disponibili tramite un manifesto JSON standard. DonutWork rende quindi queste azioni disponibili al motore principale e ai workflow. [Come costruire →](/it/docs/applications/how-to-build)
### Incorporamento Iframe **Esperienza UI Unificata.** Le app sono incorporate direttamente nella dashboard di DonutWork. Ciò garantisce un'esperienza utente coerente mantenendo il contesto di esecuzione indipendente dell'app.
### Hook Orientati agli Eventi **Sincronizzazione in Tempo Reale.** Usa i Webhook per reagire agli eventi del ciclo di vita della piattaforma (addebiti, rinnovi, cambi di identità) e mantenere l'integrità dei dati tra i sistemi.
### Sicurezza Zero-Trust **Autorizzazione Gestita.** DonutWork agisce come un proxy sicuro, gestendo l'autorizzazione tra la piattaforma e la tua applicazione con richieste firmate e token con ambito limitato.
### Skill Codex per Integrazioni **Implementazione Più Veloce.** Scarica il pacchetto ufficiale della skill `donutwork` con mappa endpoint, modelli entita' e checklist di rilascio. [Scarica la skill →](/it/docs/applications/donutwork-skill)
*** ## Roadmap per gli Sviluppatori La creazione di un'applicazione per DonutWork prevede le seguenti fasi chiave: ### Registrazione e Autenticazione Fornisci la tua applicazione nel Portale Sviluppatori per ottenere un `Client ID` e un `Client Secret` univoci. Usali per implementare il flusso standard [OAuth 2.0 flow](/it/docs/applications/auth-and-embedding). ### Dichiarazione delle Funzionalità Chiama l'endpoint `/integrations.json` per comunicare a DonutWork cosa può fare la tua app. Questo manifesto definisce i tuoi endpoint, i metodi supportati e i dati di input richiesti. ### Implementazione del Ciclo di Vita e dell'Interfaccia Utente Costruisci il frontend della tua applicazione, garantendo la compatibilità con il nostro [sistema di incorporamento basato su Iframe](/it/docs/applications/auth-and-embedding#2-iframe-context--security) e le policy di sicurezza (come i requisiti dei cookie `SameSite`). ### Prontezza per la Produzione Configura i token di sicurezza dei tuoi webhook e distribuisci il tuo servizio in un ambiente di produzione. # Business Intelligence & Growth import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { TrendingUp, PieChart, Activity, Zap } from 'lucide-react'; # Business Intelligence & Growth La sezione BI & Growth di Donutwork è progettata per darti una visione cristallina della salute economica del tuo progetto. Non dovrai più incrociare fogli di calcolo: tutto è calcolato automaticamente in tempo reale. ## Metriche Chiave Monitorate Donutwork aggrega i dati provenienti dal motore di billing e dalle interazioni utenti per offrirti KPI precisi: } title="MRR & ARR" description="Visualizza i ricavi ricorrenti mensili e annuali con proiezioni di crescita basate sullo storico." /> } title="Revenue Mix" description="Analisi dettagliata tra ricavi ricorrenti (abbonamenti) e ricavi one-time (add-on, setup fee)." /> } title="Growth Rate" description="Monitoraggio della crescita MoM (Month-over-Month) per validare la tua strategia di marketing." /> *** ## Analisi dei Ricavi Donutwork separa intelligentemente le diverse fonti di entrata per permetterti di capire cosa sta guidando davvero la tua crescita. ### Analytics Real-time Appena accedi alla dashboard, avrai un colpo d'occhio su: * **Transazioni Recenti:** Storico in tempo reale di ogni acquisto o rinnovo. * **Customer Lifetime Value (LTV):** Calcolo automatico di quanto vale mediamente un cliente nel tempo. *** ## Strategie di Growth Utilizza i dati raccolti per alimentare i tuoi processi di crescita: * **Identifica i Power Users:** Scopri quali clienti sono più costanti e/o in crescita e proponi upgrade a piani superiori. * **Prevenzione Churn:** Monitora i cali di attività repentini nei tassi di subscription per intervenire prima che l'utente disdica l'abbonamento. * **Partner Performance:** Incrocia i dati della BI con il [Programma Partner](/it/docs/partner-program) per vedere quali affiliati portano i clienti con il LTV più alto. *** ## Ritmo Operativo Consigliato Trasforma la BI in decisioni con una cadenza fissa: 1. Ogni settimana: controlla rinnovi falliti e segnali di churn. 2. Ogni due settimane: confronta la retention per coorte e canale acquisizione. 3. Ogni mese: aggiorna pricing, incentivi partner e packaging dei piani in base a margine e LTV. Per ottenere il massimo, leggi i report BI insieme ai referenti di Customer, Pagamenti Ricorrenti e Programma Partner prima di rilasciare modifiche commerciali. ## Aree Correlate * [Pagamenti Ricorrenti](/it/docs/recurring-payments) * [Customer Management](/it/docs/customer) * [Programma Partner](/it/docs/partner-program) # Customer Management & Hub Finanziario import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Users, Fingerprint, CreditCard, Tags, TrendingUp, ShieldAlert, Receipt, Layers } from 'lucide-react'; # Gestione Clienti e Hub Finanziario Il modulo **Customer** di Donutwork non è solo un database di contatti, ma un centro di controllo finanziario per ogni singolo cliente. Permette di monitorare la salute del business attraverso metriche predittive e di gestire l'intero ciclo di vita dei pagamenti. ## Customer Financial Scorecard (Beta) Per ogni cliente con almeno una transazione, Donutwork genera automaticamente uno **scorecard finanziario** che aiuta a valutare la stabilità e la crescita: } title="MRR & YRR" description="Calcolo istantaneo del Monthly Recurring Revenue e proiezione annuale basata sugli abbonamenti attivi." /> } title="Risk Assessment" description="Analisi della volatilità e durata dello storico per assegnare una classe di rischio al cliente." /> *** ## Gestione Abbonamenti e Add-ons Donutwork permette una gestione granulare delle ricorrenze direttamente dal profilo cliente: * **Associazione Piani:** Collega rapidamente nuovi piani di abbonamento esistenti al profilo. * **Modifica Add-ons:** Gestione dinamica delle quantità e dei prezzi per i componenti aggiuntivi di una sottoscrizione. * **Agevolazioni Fiscali:** Applicazione di sconti globali (percentuali o fissi) e gestione di diverse aliquote IVA per riga di servizio. * **Metering:** Monitoraggio dei consumi per i piani basati sull'utilizzo (Metered Billing). *** ## Pagamenti e Transazioni L'interfaccia divide le attività finanziarie in tre sezioni principali tramite un sistema a tab persistenti: ### 1. Metodi di Pagamento Gestione delle carte di credito associate (via Stripe). Il sistema supporta: * **Secure Payment Links:** Generazione di link protetti per permettere al cliente di inserire i propri dati di pagamento in autonomia. * **Validazione CVC/3DS:** Verifica in tempo reale dello stato di sicurezza del metodo di pagamento. ### 2. Transazioni (Charges) Storico completo di ogni addebito effettuato o tentato: * **Creazione Manuale:** Possibilità di creare "One-time charges" (es. costi di setup o consulenza) direttamente dal pannello. * **Ricevute e Log:** Accesso immediato ai PDF delle ricevute e monitoraggio dello stato (Pending, Succeeded, Failed). ### 3. Sottoscrizioni Tab dedicato per il controllo dei piani attivi, date di rinnovo e stato del provisioning. *** ## Proprietà Dinamiche (Custom Fields) Oltre ai dati finanziari, puoi estendere l'anagrafica tramite le **Customer Properties**. Questi metadati sono fondamentali per: * Configurare limiti API personalizzati per singolo cliente. * Salvare preferenze specifiche del workflow. * Mappare ID esterni per integrazioni con sistemi di terze parti. # Directory Monitor & Automazione Eventi import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { FolderSearch, ShieldCheck, Activity, Workflow, FileSearch, Timer, Fingerprint, Zap } from 'lucide-react'; # Directory Monitor Il Directory Monitor di Donutwork è un modulo nativo di **sicurezza + automazione** che traccia le attività sui file nelle cartelle osservate e trasforma questi eventi in azioni automatiche. È pensato per team che hanno bisogno di: 1. Raccolta affidabile degli eventi filesystem 2. Visibilità centralizzata degli eventi 3. Trigger deterministici dei workflow *** ## Architettura del Sistema Il modulo è composto da quattro livelli connessi: 1. **Agente Locale (Rust):** osserva le directory ed emette eventi normalizzati (`Create`, `Delete`, `WriteFinished`). 2. **API di Ingress Sicura:** riceve i payload del monitor, valida l'autenticazione e deduplica tramite `eventId`. 3. **Event Store:** persiste gli eventi con indici per ricerca operativa e forense. 4. **Workflow Dispatcher:** pubblica trigger sia generici sia tipizzati per eseguire i workflow compatibili. I trigger generici restano supportati: DirectoryMonitor.\{projectId}.notify. Puoi adottare gradualmente i trigger tipizzati come DirectoryMonitor.\{projectId}.WriteFinished.notify. *** ## Pipeline Eventi Quando un file cambia, accade quanto segue: 1. Il monitor invia un payload con metadati evento (`filename`, `event`, `filesize`, opzionali `sha256`, `uid`, `pid`, `timestampUtc`, `eventId`). 2. L'ingress valida: * API key (`Authorization: Bearer ...`) * Token di progetto (`X-Directory-Monitor-Token`) 3. L'evento viene salvato nella collection eventi del monitor. 4. Vengono pubblicate due notifiche: * Generica: `DirectoryMonitor.{projectId}.notify` * Tipizzata: `DirectoryMonitor.{projectId}.{event}.notify` 5. I workflow corrispondenti vengono messi in coda ed eseguiti tramite la pipeline async esistente. *** ## Log e Osservabilità Il Directory Monitor include una **vista Log** dedicata per progetto con: 1. Filtri per: * Tipo evento * Path contiene * Stato * Intervallo date 2. Lista paginata con: * Timestamp * Tipo evento * Percorso file * Dimensione file * Badge stato workflow (`queued`, `workflow_triggered`, `workflow_failed`) 3. Link diretti alle trace dei workflow correlati. Gli eventi sono salvati con indice TTL (default 90 giorni). *** ## Modello di Trigger Workflow Per automazioni ad alta precisione, usa i trigger tipizzati: | Trigger | Scopo | Esempio | | :-------------------------------------------------- | :-------------------------------------------------- | :------------------------------------------- | | `DirectoryMonitor.{projectId}.WriteFinished.notify` | Esegue solo dopo la stabilizzazione della scrittura | Avvio scansione malware a upload completato | | `DirectoryMonitor.{projectId}.Create.notify` | Reagisce alla creazione di oggetti | Tag/classificazione automatica di nuovi file | | `DirectoryMonitor.{projectId}.Delete.notify` | Rileva cancellazioni | Alert su rimozioni inattese | | `DirectoryMonitor.{projectId}.notify` | Trigger generico legacy | Compatibilità con workflow esistenti | *** ## Controlli di Sicurezza L'ingress del monitor è protetto da controlli a più livelli: 1. **Autenticazione API key aziendale** 2. **Validazione token segreto a livello progetto** 3. **Validazione payload sui campi obbligatori** 4. **Deduplica idempotente tramite `eventId` univoco** Questo approccio garantisce isolamento tra progetti mantenendo il comportamento attuale del gateway API. *** ## Pattern di Automazione Reali } title="Controlli di Compliance File" description="Su WriteFinished esegui workflow di validazione (policy hash, naming convention, controlli estensione)." /> } title="Risposta di Sicurezza" description="Attiva scansione, quarantena e alert quando compaiono file sospetti nelle cartelle monitorate." /> } title="Automazione Business" description="Lancia pipeline di ingestione, enrichment e webhook automatici a partire da eventi filesystem." /> *** ## Panoramica Funzionalità } title="Monitoraggio Ricorsivo" description="Osserva interi alberi directory e cattura comportamenti di create, modify e delete." /> } title="Gestione Stabilità Scrittura" description="`WriteFinished` viene emesso dopo la finestra di stabilizzazione per evitare file parziali." /> } title="Heartbeat e Startup" description="I monitor inviano segnali di avvio e attività, utili per visibilità operativa per progetto." /> } title="Metadata Evento Ricchi" description="Allega `sha256`, `uid` e `pid` (quando disponibili) per audit e investigazioni più solide." /> } title="Workflow Event-Driven" description="Collega direttamente gli eventi filesystem al motore workflow già presente in Donutwork." /> # Dynamic Content Modeling import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Layout, Database, FileJson, Eye, Settings, FormInput } from 'lucide-react'; # Dynamic Content Modeling (Content Box) Il sistema **Content Box** è progettato per eliminare la rigidità dei database tradizionali. Ti permette di creare dei "Modelli" (Types) che definiscono quali campi deve avere un contenuto, e successivamente di compilare tali contenuti tramite interfacce generate automaticamente. ## Il Concetto: Types vs Contents Per comprendere il funzionamento, bisogna distinguere due livelli: 1. **Types (Lo Schema):** Definisci la struttura. Esempio: "Il tipo *Membro del Team* ha un nome, una foto, una bio e un ruolo." 2. **Contents (I Dati):** Crei le istanze basate sullo schema. Esempio: "Mario Rossi, Foto.jpg, CTO..." *** ## Tipi di Campi Supportati Il **Fields Manager** di Donutwork offre una vasta gamma di input per coprire ogni esigenza di data-entry: | Categoria | Tipo di Input | Utilizzo Tipico | | :----------- | :------------------- | :---------------------------------------------------- | | **Testuale** | Standard Text | Titoli, nomi brevi, etichette. | | | Long Text (Textarea) | Descrizioni, biografie, contenuti ricchi. | | | Password / Secure | Chiavi API, segreti o dati sensibili (mascherati). | | | URL | Link esterni, riferimenti a social media. | | **Logica** | Dropdown Select | Scelta singola da una lista definita (es. Categoria). | | | Multi-select | Tag, competenze, selezioni multiple. | | | Toggle / Checkbox | Stati booleani (Sì/No, Attivo/Inattivo). | *** ## Esempi di Strutture (Use Cases) Ecco come puoi configurare i tuoi **Types** per diversi scenari comuni: ### 1. Sezione FAQ * **Domanda:** Standard Text (Obbligatorio) * **Risposta:** Long Text * **Categoria:** Dropdown Select (Opzioni: *Billing, Tecnico, Account*) * **In evidenza:** Toggle ### 2. Scheda Prodotto (SaaS) * **Nome Prodotto:** Standard Text * **Prezzo Mensile:** Standard Text (o Masked se è un ID di Stripe) * **Feature List:** Multi-select * **Documentazione URL:** URL Address * **Stato:** Dropdown Select (*Beta, Stabile, Deprecato*) ### 3. Testimonial Clienti * **Nome Cliente:** Standard Text * **Azienda:** Standard Text * **Citazione:** Long Text * **Rating:** Dropdown Select (*1, 2, 3, 4, 5 stelle*) *** ## Gestione della Visibilità Ogni **Content Box** può trovarsi in uno dei seguenti stati: * 🟡 **Draft (Bozza):** Il contenuto è salvato ma non è accessibile dalle API pubbliche o dal frontend. * 🟢 **Public (Pubblico):** Il contenuto è live e pronto per essere visualizzato. * 🔴 **Private (Privato):** Visibile solo all'interno dell'area amministrativa di Donutwork, ideale per dati di configurazione interna. *** ## Funzionalità Avanzate } title="Generazione Automatica UI" description="Non devi creare i form. Appena modifichi lo schema di un Type, l'interfaccia di inserimento dati si aggiorna istantaneamente." /> } title="Ordinamento Drag & Drop" description="Puoi riordinare i campi nello schema per dare priorità visiva alle informazioni più importanti per il tuo team." /> } title="Headless-Ready" description="Tutti i dati salvati sono pronti per essere consumati tramite API in formato JSON, perfetti per React, Vue o Mobile App." /> Ogni campo ha una **Internal Key (DB)**. Usa nomi chiari e in `snake_case` (es. `hero_image_url`) perché sarà la chiave che troverai nel JSON restituito dalle API di Donutwork. # Email Gateway import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Palette, Settings, ShieldCheck } from 'lucide-react'; # Email Gateway Il modulo **Email Gateway** di Donutwork è l'infrastruttura completa per la gestione delle email del tuo SaaS. Non si occupa solo dell'invio, ma copre l'intero ciclo di vita di una comunicazione: dalla configurazione dei record DNS alla progettazione visuale dei template. } title="Template Design" href="/it/docs/email-gateway/template" description="Crea email professionali con l'editor Drag & Drop o scrivi il tuo codice HTML personalizzato." /> } title="Configurazione SMTP" href="/it/docs/email-gateway/settings" description="Configura i tuoi server di invio (Custom SMTP) o utilizza l'infrastruttura condivisa di Donutwork." /> } title="Deliverability" href="/it/docs/email-gateway/settings" description="Proteggi la tua reputazione mittente configurando correttamente SPF e DKIM." /> *** ## Funzionalità Chiave ### 1. Visual & Code Editor Scegli come lavorare. Il **Mail Designer** visuale (basato su GrapesJS) permette a chiunque di creare layout responsivi. Per gli sviluppatori, l'**Ace Editor** integrato offre il controllo totale sul codice sorgente, con anteprima in tempo reale. ### 2. Gestione Multi-Mittente Definisci **Alternative Senders** per inviare comunicazioni da dipartimenti diversi (es. `supporto@`, `amministrazione@`, `info@`) senza dover configurare server SMTP multipli. ### 3. Integrazione Nativa I template salvati nel Gateway sono immediatamente disponibili in tutta la piattaforma: * **Workflow:** Invia email automatiche trascinando un semplice nodo. * **API:** Richiama i template tramite endpoint REST passando variabili dinamiche. *** ## Guide Rapide L'Email Gateway è diviso in due aree principali: ### [Gestione Template & Design](/it/docs/email-gateway/template) Scopri come creare nuovi file, organizzare la libreria dei template e utilizzare il designer per rendere le tue email perfette su ogni dispositivo. ### [Impostazioni & Consegna](/it/docs/email-gateway/settings) Impara a configurare il tuo server SMTP personalizzato, a validare la connessione con lo strumento di test e a impostare i record DNS necessari per evitare che le tue email finiscano in SPAM. ## Sequenza Consigliata Di Go-Live 1. Configura SMTP e autenticazione DNS. 2. Crea almeno un template transazionale e uno operativo. 3. Esegui test di recapito da ambienti di staging. 4. Collega gli invii ai flussi di [Workflow](/it/docs/workflow) e alle chiamate API. *** Usa sempre la funzione **Test Email** dopo aver modificato le impostazioni SMTP o i record DNS per assicurarti che la configurazione sia valida prima di inviare comunicazioni ai tuoi clienti. # Settings & Deliverability import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; # Configurazione Email e Deliverability Per garantire che le tue email non finiscano nella cartella spam, Donutwork offre strumenti avanzati per la configurazione dei server di invio e l'autenticazione del dominio. ## Impostazioni SMTP Donutwork ti permette di scegliere tra due modalità di invio: 1. **System SMTP:** Utilizza l'infrastruttura predefinita di Donutwork per un setup immediato. 2. **Custom SMTP:** Configura i tuoi server (es. SendGrid, Mailgun, Amazon SES) inserendo Host, Porta, Username e Password. *** ## Autenticazione del Dominio (SPF & DKIM) La sicurezza è fondamentale per la consegna delle email. Sentinel e il Gateway Email lavorano insieme per proteggere il tuo dominio. ### Record SPF Per autorizzare Donutwork a inviare email a tuo nome, aggiungi il seguente valore al tuo record SPF nel DNS: `include:_spf_hosted.donutwork.com` ### Enforce DKIM Il DKIM aggiunge una firma digitale alle tue email. Per abilitarlo: 1. Attiva l'opzione **Enforce DKIM** nelle impostazioni. 2. Aggiungi un record **CNAME** nel tuo DNS: * **Host:** `donutwork._domainkey.TUO_DOMINIO` * **Target:** `smtp._domainkey.donutwork.com` *** ## Mittenti Alternativi (Alternative Senders) Non sei limitato a un unico indirizzo di invio. Puoi configurare diversi mittenti per scopi differenti: * `support@yourbrand.com` per l'assistenza. * `billing@yourbrand.com` per le fatture. * `newsletter@yourbrand.com` per il marketing. Ogni mittente può avere un **Nome Visualizzato** personalizzato per aumentare la fiducia dell'utente finale. *** ## Email Tester Prima di andare in produzione, utilizza il modulo **Email Tester** integrato. Inserisci il tuo indirizzo email e invia un messaggio di prova per verificare istantaneamente se la configurazione SMTP e i record DNS sono corretti. Usa il pulsante **Test Connection** dopo aver inserito i dati SMTP per ricevere un feedback immediato sulla raggiungibilità del server prima di salvare le impostazioni. *** ## Prossimi Passi # Gateway & Templates import { Card, Cards } from 'fumadocs-ui/components/card'; import { Palette, Code } from 'lucide-react'; # Email Gateway Donutwork centralizza la comunicazione via email del tuo SaaS. Grazie al sistema di template, puoi separare la logica di invio (nel tuo codice o nei [Workflow](/it/docs/workflow)) dal design grafico, permettendo al team marketing di aggiornare i contenuti senza l'intervento degli sviluppatori. ## Due Modalità di Editing Donutwork offre flessibilità totale nella creazione dei template, supportando due diversi approcci: } title="Visual Mail Designer" description="Editor drag-and-drop basato su GrapesJS per creare layout responsivi senza toccare una riga di codice." /> } title="Advanced Code Editor" description="Editor professionale (Ace Editor) con evidenziazione del codice per sviluppatori che necessitano di HTML/CSS personalizzato." /> *** ## Gestione dei Template Dalla dashboard principale puoi: * **Creare Nuovi Template:** Definisci nomi file chiari (es. `welcome-email` o `invoice-receipt`). * **Visual Designer:** Accedi tramite l'icona della tavolozza per un editing visuale con anteprima in tempo reale. * **Modifica Codice:** Accedi tramite l'icona della matita per scrivere codice HTML puro. * **Preview Rapida:** Visualizza come apparirà l'email sui diversi dispositivi prima di salvarla. *** ## Utilizzo nei Workflow Una volta creato un template, puoi richiamarlo istantaneamente all'interno del modulo **Workflow**. Basta trascinare il nodo **Send Email** e selezionare il file desiderato dalla lista a discesa. > **Regola dei Nomi:** I file devono seguire il pattern `[a-z0-9-]`. Esempio corretto: `newsletter-gennaio-2024`. *** ## Prossimi Passi # Entità Addebito (Charge) # Entità Addebito (Charge) Un **Charge** (chiamato anche Transazione) rappresenta un saldo finanziario specifico associato a un **Customer**. Può essere generato automaticamente dal rinnovo di un abbonamento o creato manualmente per servizi una tantum. ## Utilizzo L'entità Charge viene utilizzata per: * Processare pagamenti ad-hoc per costi di setup, consulenza o hardware. * Archiviare lo storico degli eventi di fatturazione ricorrente. * Gestire l'associazione con documenti legali (fatture e ricevute). * Tracciare in tempo reale lo stato del pagamento (Pending, Paid, Refunded). ## Flusso Atteso Ciclo di vita di una transazione finanziaria manuale: 1. **Generazione**: Crea l'oggetto charge con una o più righe di servizio. 2. **Esecuzione**: Se il `capture` è abilitato, il sistema utilizza il metodo di pagamento predefinito del cliente. 3. **Adempimento**: Dopo il successo, i dettagli formali della fattura vengono allegati per la sincronizzazione contabile. *** ## Schema Dati I campi che definiscono un oggetto Charge: | Campo | Tipo | Descrizione | | :------------ | :------- | :------------------------------------------------------------- | | `id` | `eid` | Identificativo univoco esteso. | | `customer_id` | `string` | Il proprietario della transazione. | | `total` | `number` | Totale netto della transazione (comprensivo di tasse). | | `status` | `string` | Stato corrente: `pending`, `paid`, `refunded`, `failed`. | | `services` | `array` | Elenco degli articoli addebitati con relativi profili fiscali. | | `invoice` | `object` | Metadati per la contabilità (numero, data, link esterno). | | `date` | `object` | Timestamp preciso dell'evento di creazione. | *** ## Grafo delle Chiamate (Relationship) Come i Charge interagiscono con i gateway di pagamento esterni: # Entità Cliente import { Steps, Step } from 'fumadocs-ui/components/steps'; import { Card, Cards } from 'fumadocs-ui/components/card'; import { User, Key, CreditCard, Play } from 'lucide-react'; # Entità Cliente Il **Customer** è il nodo centrale dell'ecosistema DonutWork. Rappresenta l'entità legale o l'individuo che consuma i tuoi servizi e genera fatturato. ## Utilizzo L'entità Customer viene utilizzata per: * Tracciare le informazioni di contatto e di fatturazione. * Associare abbonamenti ricorrenti e addebiti una tantum. * Memorizzare metadati personalizzati tramite proprietà dinamiche per un'integrazione profonda con la tua piattaforma. * Monitorare il rischio finanziario e la salute del business (MRR/YRR). ## Flusso Operativo Atteso Per gestire correttamente l'onboarding e la fatturazione di un cliente, segui questo flusso logico: ### Inizializzazione Identità Crea l'entità tramite l'endpoint `POST /customers.json`. Assegna un `externalId` univoco dal tuo database interno per mantenere una sincronizzazione perfetta tra i sistemi. ### Arricchimento del Contesto (Opzionale) Usa `PUT /customers/{id}/properties.json` per salvare dati specifici come tier di fatturazione, lingua preferita o quote API personalizzate. ### Onboarding Pagamento Sicuro Richiama `GET /customers/{id}/payment_link.json`. Questo genera un URL temporaneo: reindirizza l'utente a questa pagina per permettergli di inserire la carta di credito in modo sicuro e conforme PCI via Stripe. ### Attivazione e Billing Una volta che il metodo di pagamento è collegato (confermato via Webhook), attiva i servizi. Puoi associare una `Subscription` per ricavi ricorrenti o creare un `Charge` per costi una tantum. *** ## Schema Dati La seguente tabella definisce la struttura principale dell'oggetto Customer: | Campo | Tipo | Descrizione | | :------------- | :------- | :----------------------------------------------------------------- | | `id` | `eid` | Identificativo univoco esteso generato da DonutWork. | | `external_id` | `string` | Il tuo identificativo di sistema interno. | | `email` | `string` | Email primaria di contatto e fatturazione. | | `company_name` | `string` | Ragione sociale utilizzata per la fatturazione. | | `address` | `object` | Dati geografici (la nazione è obbligatoria per la logica fiscale). | | `properties` | `array` | Coppie chiave-valore per dati di integrazione personalizzati. | | `status` | `string` | `active`, `suspended`, o `deleted`. | *** ## Grafo delle Chiamate (Relationship) Questo grafo illustra come l'entità Customer interagisce con gli altri componenti del sistema durante il suo ciclo di vita. # Entità Consegna Email import { Steps, Step } from 'fumadocs-ui/components/steps'; # Entità Consegna Email L'**Email Delivery** (o Email Job) rappresenta un singolo evento di comunicazione transazionale. Collega la logica della tua applicazione con l'infrastruttura SMTP professionale di DonutWork. ## Utilizzo L'entità Email Delivery viene utilizzata per: * Inviare email transazionali (ricevute, reset password) utilizzando template predefiniti. * Iniettare dati dinamici in layout responsive tramite variabili. * Distribuire documenti legali o tecnici come allegati sicuri. * Orchestrare comunicazioni da mittenti multipli (Supporto, Billing, Sales). ## Flusso Operativo Atteso L'invio di un'email sicura con allegati segue questo percorso operativo: ### Selezione del Template Identifica il `templateId` nel tuo Email Gateway. Questo definisce il layout visivo e i segnaposto (placeholder) disponibili per l'iniezione dei dati. ### Mapping Variabili e Contesto Prepara l'oggetto `vars` contenente i dati dinamici (es. nome cliente, numero ordine) che sostituiranno i segnaposto nel designer. ### Codifica Allegati Converti i tuoi file (PDF, CSV, Immagini) in stringhe **Base64**. DonutWork elabora queste stringhe per ricreare in modo sicuro gli allegati SMTP. ### Invio e Trasmissione Invia una richiesta `POST` all'endpoint di consegna. DonutWork valida l'identità del mittente, risolve le variabili, allega i file e trasmette tramite l'SMTP configurato. *** ## Schema Dati (Body JSON) Il payload per un job di consegna email: | Campo | Tipo | Descrizione | | :------------ | :------- | :------------------------------------------------------------------ | | `to` | `string` | **Obbligatorio**. Indirizzo email del destinatario principale. | | `subject` | `string` | **Obbligatorio**. L'oggetto dell'email. | | `from` | `string` | Opzionale. Deve corrispondere a uno dei tuoi "Alternative Senders". | | `vars` | `object` | Coppie chiave-valore per i placeholder nel template. | | `attachments` | `array` | Elenco di oggetti allegato (vedi sotto). | | `cc` / `bcc` | `mixed` | Stringa o array di destinatari aggiuntivi. | ### Oggetto Allegato | Campo | Tipo | Descrizione | | :------------ | :------- | :------------------------------------------------- | | `filename` | `string` | Il nome visualizzato del file (es. `fattura.pdf`). | | `type` | `string` | Tipo MIME (es. `application/pdf`). | | `content` | `string` | Il contenuto del file codificato in **Base64**. | | `disposition` | `string` | `attachment` (default) o `inline`. | *** ## Grafo delle Chiamate (Relationship) Come la tua app interagisce con il Gateway per inviare un documento: # Entità Partner # Entità Partner Un **Partner** rappresenta un'agenzia esterna, un rivenditore o un affiliato che gestisce il proprio bacino di clienti. I Partner sono classificati in **Gruppi** (Groups) per gestire commissioni a scaglioni e segmentazione dei servizi. ## Utilizzo L'entità Partner viene utilizzata per: * Segmentare la base clienti per agenzia o rivenditore. * Gestire le strutture di commissione e lo storico dei pagamenti (payouts). * Distribuire report e capacità di gestione a terze parti. ## Flusso Atteso Segui questo flusso logico per stabilire un modello di rivendita basato sui partner: 1. **Categorizzazione**: Usa i Partner Groups per definire livelli di servizio o scaglioni di sconto. 2. **Setup**: Crea l'identità del Partner con i propri dettagli legali di fatturazione. 3. **Attribuzione**: Quando crei un nuovo cliente, includi il `partner.id` per collegarlo formalmente. 4. **Monitoraggio**: Traccia le performance e la condivisione dei ricavi tramite il modulo statistiche. *** ## Schema Dati I campi principali che definiscono un oggetto Partner: | Campo | Tipo | Descrizione | | :------------ | :------- | :--------------------------------------------------------------- | | `id` | `eid` | Identificativo univoco esteso. | | `name` | `string` | Ragione sociale del partner. | | `email` | `string` | Indirizzo email principale per contatti e fatturazione. | | `group_id` | `string` | ID del gruppo di classificazione assegnato. | | `external_id` | `string` | Identificativo di riferimento del tuo sistema interno. | | `tags` | `array` | Etichette arbitrarie per filtri custom (es. 'gold', 'reseller'). | *** ## Grafo delle Chiamate (Relationship) Come i Partner interagiscono con il flusso di onboarding dei clienti: # Entita Sottoscrizione (Subscription) import { Steps, Step } from 'fumadocs-ui/components/steps'; # Entita Sottoscrizione L'oggetto **Subscription** rappresenta un accordo ricorrente collegato a un **Customer**. Combina piano, addon, cadenza di rinnovo e stato lifecycle. ## Utilizzo Usa la Subscription per: * Associare un piano al cliente. * Gestire pricing a seat tramite quantita addon. * Applicare sconti globali e per addon. * Tracciare usage metered quando presente. * Eseguire transizioni lifecycle (`pause`, `resume`, `change`, `cancel-at-period-end`). * Conservare storico amendments per audit. ## Modello Seat-Based Nel modello attuale Donutwork i seat sono gestiti tramite **addons**. * Il costo per seat e il prezzo unitario addon. * Il numero seat e `addons[].quantity`. * Il rinnovo include automaticamente la componente seat. Esempio: * Addon `workspace_seat`: `12.00` * Quantita: `25` * Totale seat: `300.00` (prima di tasse/sconti) ## Flusso Atteso ### Associazione Piano Associa il piano con `POST /customers/{id}/subscriptions.json`. ### Configurazione Runtime Aggiorna quantita addon (inclusi seat), sconti e usage. ### Transizioni Lifecycle Applica opzionalmente operazioni lifecycle (`pause`, `resume`, `change-plan`, `change-addons`, `cancel-at-period-end`). ### Boundary di Rinnovo Alla data `next_renew`, eventuali modifiche schedulate vengono applicate e parte l'addebito ricorrente. *** ## Stati Lifecycle e Transizioni | Stato Lifecycle | Significato | Ingresso Tipico | | :---------------------- | :--------------------------------------- | :------------------------------------- | | `active` | Subscription rinnovabile e addebitabile | Attach, resume, change riuscita | | `paused` | Billing sospeso temporaneamente | Azione pause | | `cancel_pending` | Cancellazione programmata a fine periodo | Cancel-at-period-end | | `cancelled` | Contratto non piu attivo | Stop a boundary / cancellazione legacy | | `trialing` / `past_due` | Stati avanzati opzionali | Orchestrazioni esterne | ### Definizione Stati con Esempi Pratici * `active`: il cliente viene addebitato regolarmente al rinnovo. Esempio: piano mensile con rinnovo al 1 maggio 2026. * `paused`: fatturazione temporaneamente sospesa. Esempio: sospensione richiesta dal cliente per 30 giorni. * `cancel_pending`: abbonamento impostato per la chiusura a fine periodo. Esempio: cancellazione richiesta il 15 aprile 2026, servizio attivo fino al boundary. * `cancel_pending` puo essere annullato prima del boundary. Esempio: il cliente annulla e poi cambia idea dopo 3 giorni; con undo-cancel-at-period-end ritorna in `active`. * `cancelled`: abbonamento chiuso definitivamente. Esempio: boundary raggiunto e chiusura completata. * `trialing`: periodo prova prima del primo addebito. Esempio: trial gratuito di 14 giorni all'associazione del piano. * `past_due`: problema di pagamento in corso. Esempio: rinnovo fallito in attesa di aggiornamento metodo pagamento. ### Semantica Pausa e Ripresa Fatturazione Quando una subscription viene messa in pausa, Donutwork interrompe i rinnovi e azzera `next_renew`, salvando la data precedente in `pause_state.previous_next_renew`. Alla ripresa: * Se `resume_at` e presente e futura, quella data diventa il nuovo `next_renew`. * Se `resume_at` non e presente, Donutwork prova a riusare `previous_next_renew`. * Se la data salvata e gia nel passato, `next_renew` viene impostata al giorno di ripresa (oggi), senza recupero retroattivo automatico. Esempio timeline: * Pausa il **1 maggio 2026**. * Riattiva il **1 luglio 2026** (dopo 2 mesi). * Risultato: nessun addebito automatico arretrato per maggio/giugno; `next_renew` viene riallineata al 1 luglio 2026 (o a `resume_at` se impostata nel futuro). ### Grafico Lifecycle ## Regole Proration * **Delta positivo** (upgrade): addebito immediato. * **Delta negativo** (downgrade): credito in `carryover_credit`. * Il credito viene consumato ai rinnovi successivi prima di nuovi addebiti. ## Scheduled Changes Per `change-plan` e `change-addons` puoi usare `when: period_end`. La modifica viene salvata in `scheduled_change` e applicata al prossimo boundary. ## Amendment History Ogni modifica lifecycle genera un amendment immutabile con before/after e metadati proration. *** ## Schema Dati | Campo | Tipo | Descrizione | | :--------------------- | :--------------- | :---------------------------------------------------- | | `id` | `eid` | Identificativo customer-subscription. | | `subscription_id` | `string` | Piano attualmente applicato. | | `status` | `string` | Stato legacy (`active`, `dismiss`, `dismissed`, ...). | | `next_renew` | `date \| null` | Prossimo boundary di billing. | | `addons` | `array` | Addon con prezzo e `quantity` (inclusi seat). | | `global_discount` | `object` | Sconto a livello piano. | | `lifecycle` | `object` | Metadati stato lifecycle avanzato. | | `pricing_snapshot` | `object` | Snapshot pricing usato nelle transizioni. | | `scheduled_change` | `object \| null` | Mutazione differita a fine periodo. | | `pause_state` | `object \| null` | Metadati pausa/ripresa. | | `carryover_credit` | `number` | Credito accumulato da proration negativo. | | `cancel_at_period_end` | `boolean` | Intenzione esplicita di stop a fine periodo. | *** ## Backward Compatibility Nessuna route o shape legacy viene rimossa. ### Legacy vs New lifecycle behavior | Area | Comportamento Legacy | Nuovo Comportamento Lifecycle | | :-------------- | :------------------------------- | :----------------------------------------------------- | | Attach/Detach | Route esistenti valide | Invariato, con metadati lifecycle additivi | | Update addons | Mutazione addon legacy invariata | Opzionale `change-addons` con proration/scheduling | | Status endpoint | `status` legacy mantenuto | Visibilita lifecycle aggiuntiva senza rimuovere chiavi | | Seat pricing | Addon con quantity | Stesso modello, ora documentato esplicitamente | | Cancellazione | Flow basato su `dismiss` | `cancel_at_period_end` mappato in compatibilita legacy | *** ## Call Graph # Media Library import { Card, Cards } from 'fumadocs-ui/components/card'; import { UploadCloud, HardDrive, FileSearch, Download } from 'lucide-react'; # Media Library La **Media Library** funge da repository centralizzato per tutti i file del tuo workspace. Sfrutta un'infrastruttura di storage remoto scalabile per garantire che i tuoi asset siano sempre disponibili, sicuri e pronti per essere serviti tramite CDN. ## Caratteristiche Principali } title="Caricamento Rapido" description="Sistema di upload multi-file con supporto Drag & Drop" /> } title="Remote Storage" description="Integrazione nativa con bucket isolati per azienda, garantendo la massima sicurezza dei dati." /> } title="Riconoscimento Formati" description="Identificazione automatica del tipo di file (Immagini, PDF, Documenti) con icone dedicate." /> *** ## Gestione dei File L'interfaccia della galleria permette un controllo immediato sugli asset caricati: ### 1. Upload e Ingestione Puoi trascinare più file contemporaneamente nell'area di upload. Il sistema gestisce automaticamente la coda e ti avvisa al termine del caricamento. ### 2. Galleria e Navigazione I file sono visualizzati in una griglia responsive che mostra: * **Nome File:** Il nome originale dell'asset (Key). * **Dimensione:** Calcolo automatico del peso del file (KB, MB, GB). * **Identificativo (ETag):** L'hash univoco del file per la gestione della cache e del versionamento. ### 3. Paginazione Intelligente Per workspace con migliaia di file, la Media Library utilizza una paginazione basata su **Continuation Tokens**, ottimizzando i tempi di caricamento e riducendo il consumo di banda. *** ## Casi d'uso Comuni * **Dynamic Content:** Carica le immagini dei prodotti o i loghi dei partner da richiamare nei tuoi [Dynamic Content](/it/docs/dynamic-content-modeling). * **Email Gateway:** Ospita gli asset grafici per i tuoi template email transazionali. * **Documenti Utente:** Archivia PDF o guide per i tuoi clienti in un ambiente sicuro. # Programma Partner e Condivisione Ricavi import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Calculator, Fingerprint, TrendingUp, Zap } from 'lucide-react'; # Programma Partner Donutwork ti permette di gestire un canale partner come un prodotto, non come un foglio Excel. Crei gruppi partner strutturati, definisci regole commissioni evolute e validi i risultati prima di pubblicare. ## Cosa puoi fare 1. Segmentare i partner per modello commerciale (agenzie, reseller, canali strategici). 2. Applicare logiche commissioni multilivello per ogni gruppo. 3. Impostare soglie qualità (X clienti paganti in N mesi). 4. Simulare gli esiti prima del rilascio. 5. Gestire payout con piena trasparenza. *** ## Configurazione in 7 passaggi 1. Apri un gruppo partner. 2. Imposta la base con `Scaglione temporale` o `Ricorrente (base)`. 3. Aggiungi leve di crescita opzionali: * `Importo transazione` * `Bonus LTV` 4. Aggiungi `Soglia volume clienti` se vuoi imporre requisiti minimi. 5. Prova scenari realistici nel `Simulatore Commissioni`. 6. Controlla il dettaglio calcolo e verifica il comportamento atteso. 7. Salva e applica al gruppo. Parti sempre dalla commissione base, poi aggiungi upgrade/rettifiche e solo alla fine le soglie di eleggibilità. Ottieni una configurazione più chiara e più controllabile. *** ## Catalogo Regole (Come si comportano) ### Scaglione temporale Ideale per spingere l’acquisizione nei primi mesi. * Obiettivo: premiare maggiormente la fase iniziale del cliente. * Campi chiave: * `Mesi massimi (es. 12)` * `Percentuale (%)` * `Bonus (€ - opzionale)` * Comportamento: si applica se l’età cliente rientra nel limite mesi. * Esempio tipico: “12% per i primi 12 mesi + bonus iniziale opzionale”. ### Ricorrente (base) È la base stabile di lungo periodo. * Obiettivo: definire la commissione standard quando non entra nessuno scaglione temporale. * Campo chiave: * `Percentuale ricorrente (%)` * Comportamento: usata come commissione base predefinita. * Esempio tipico: “6% continuativo dopo la fase iniziale”. ### Importo transazione Permette di adattare i margini in base al valore addebito. * Obiettivo: modificare la commissione quando l’importo supera una soglia. * Campi chiave: * `Importo minimo transazione (€)` * `Detrazione % (es. 1,0)` * Comportamento: al superamento soglia, la rettifica si applica sulla fee in quel punto del flusso. * Esempio tipico: “su ticket elevati, applica una detrazione per proteggere margine”. ### Bonus LTV Premia la crescita reale del partner nel tempo. * Obiettivo: sbloccare extra commissione al raggiungimento di milestone LTV. * Campi chiave: * `LTV minimo totale (€)` * `Bonus incremento %` * Comportamento: se sono valide più soglie, si applica il bonus più alto. * Esempio tipico: “+3% dopo 20.000€ generati”. ### Soglia volume clienti Garantisce qualità e continuità. * Obiettivo: richiedere un minimo clienti paganti. * Campi chiave: * `Clienti richiesti (X)` * `Mesi finestra (N)` * `Modalità finestra` * `Fonte ancoraggio` * `Azione sotto soglia` * `Modalità riduzione` * Comportamento: * verifica se il partner raggiunge X clienti paganti nella finestra selezionata. * se sotto soglia, applica la policy configurata (riduci, posticipa, annulla). *** ## Logica di Calcolo Affidabile ### Base monetaria Percentuali e soglie vengono valutate sull’importo imponibile della transazione (al netto imposte), per mantenere coerenza finanziaria. ### Ordine deterministico Le regole sono applicate in questo ordine: 1. Base: `Scaglione temporale` o `Ricorrente (base)` 2. `Importo transazione` 3. `Bonus LTV` 4. `Soglia volume clienti` ### Nessuna retroattività inattesa Quando aggiorni le regole, i calcoli storici già approvati restano invariati. *** ## Soglia Volume Clienti: Finestra mobile vs ancorata ### Finestra mobile Ideale per controllare performance continue. * valuta gli ultimi N mesi a partire da ogni data addebito. ### Finestra ancorata Ideale per programmi partner con cicli definiti. * valuta N mesi a partire da un punto di ancoraggio. ### Avvio ancoraggio sul primo pagante Se la finestra ancorata usa il primo cliente pagante ma non esiste ancora storico pagante, la prima transazione pagata avvia automaticamente la finestra. La regola viene comunque valutata normalmente. *** ## Simulatore Commissioni Usa il simulatore prima di pubblicare ogni modifica regole. * Inserisci valori realistici in: * `Importo Addebito Simulato (€)` * `Mesi dalla creazione del cliente` * `LTV Partner Simulato (€)` * `Clienti qualificati (finestra X)` * `Primo cliente pagante (avvio finestra)` * Esegui `Simula Commissione` e analizza `Dettaglio Simulazione Commissioni`. È il modo più rapido per allineare finance, commerciale e operations prima del rilascio. *** ## Configurazioni pronte all’uso 1. Spinta acquisizione startup: * scaglione forte nel primo anno * base ricorrente più bassa * soglia volume moderata 2. Canale agenzie: * base ricorrente stabile * milestone LTV per incentivare upsell * finestra mobile per continuità 3. Referral enterprise: * rettifica su ticket elevati * bonus LTV selettivi * finestra ancorata per governo del ciclo programma *** ## Perché Donutwork fa la differenza } title="Spiegabile" description="Ogni payout è giustificabile con sequenza regole e dettaglio simulazione." /> } title="Configurabile" description="Combini ciclo vita, valore transazione, LTV e soglie performance senza sviluppo custom." /> } title="Scalabile" description="Passi da affiliazione base a economia partner avanzata man mano che cresci." /> } title="Operativo subito" description="Progetti, testi e pubblichi rapidamente con controllo pieno." /> # Pagamenti Ricorrenti import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Repeat, Zap, Gift, Settings2, Calculator, GitBranchPlus, ShieldCheck } from 'lucide-react'; # Pagamenti Ricorrenti e Subscription Donutwork ti permette di gestire abbonamenti ricorrenti con un modello prevedibile: * definisci il catalogo piani, * associ il piano al cliente, * gestisci il pricing a seat con gli addon, * aggiorni il contratto nel tempo con operazioni lifecycle, * mantieni la compatibilita con i flussi legacy gia in uso. Questa pagina spiega il comportamento reale del sistema, con esempi pratici. ## Cosa Contiene Una Subscription } title="Cadenza Rinnovo" description="Cicli a giorni o mesi (`renewal_days` / `renewal_months`) con data prossimo rinnovo (`next_renew`)." /> } title="Gestione Trial" description="Periodo di prova opzionale prima del primo ciclo a pagamento." /> } title="Prezzi Seat + Addon" description="Il seat-based usa `addons[].quantity` (numero seat) e `addons[].price` (costo unitario seat)." /> } title="Sconti e Imposte" description="Sconti addon, sconto globale, carryover credit e tasse sono applicati in ordine deterministico." /> *** ## Come Viene Calcolato Il Prossimo Rinnovo A ogni rinnovo, Donutwork calcola l'importo in questo ordine: 1. Prezzo base del piano. 2. Importi addon (`price * quantity`) per addon con quantita attiva. 3. Sconto addon se configurato e non scaduto (`discount_until`). 4. Sconto globale (`fixed` o `percentage`, se attivo). 5. Credito carryover (`carryover_credit`) da downgrade/proration precedenti. 6. Imposte del profilo fiscale associato. ### Formula (semplificata) ```text net_subtotal = base + addons_dopo_sconti_addon net_post_sconto_globale = net_subtotal - sconto_globale net_due = max(0, net_post_sconto_globale - carryover_credit_usato) vat_due = net_due * aliquota_iva gross_due = net_due + vat_due ``` ### Esempio * Piano base: `99.00` * Addon seat: `12.00` x `8` seat = `96.00` * Sconto addon 10% attivo => addon effettivo `86.40` * Subtotale netto = `185.40` * Sconto globale 15% => `-27.81` * Credito carryover applicato: `20.00` * Netto dovuto = `137.59` * IVA 22% = `30.27` * Totale lordo = `167.86` *** ## Modello Seat-Based (Importante) Il pricing a seat non usa uno schema separato. Nel modello attuale i seat sono addon: * costo seat: `addons[].price` * numero seat: `addons[].quantity` * importo seat: incluso automaticamente nel rinnovo Questo approccio e stabile e retrocompatibile con i flussi esistenti. *** ## Stati Lifecycle (Significato Billing) | Stato | Addebitabile | Significato | | :--------------- | :----------------- | :-------------------------------------------------------------------- | | `active` | Si | Fatturazione ricorrente normale. | | `trialing` | In genere no | Fase trial prima del primo rinnovo pagato. | | `past_due` | Condizionale | Stato di recupero dopo pagamento fallito. | | `paused` | No | Billing in pausa. Nessun addebito durante la pausa. | | `cancel_pending` | Nessun nuovo ciclo | Chiusura programmata a fine periodo (annullabile prima del boundary). | | `cancelled` | No | Subscription chiusa. | La pausa non genera arretrati automatici. Se un abbonamento viene riattivato dopo 2 mesi, i mesi in pausa non vengono addebitati retroattivamente. Il ciclo riparte dalla logica di resume. ### Grafico Lifecycle *** ## Operazioni Lifecycle Supportate Tutte additive (nessuna rimozione route legacy): | Operazione | Immediata | Fine Periodo | Proration | Note | | :------------------------ | :-------- | :----------------- | :-------- | :---------------------------------------------------- | | Pause | Si | No | No | Sospende i rinnovi durante la pausa. | | Resume | Si | No | No | `resume_at` opzionale per definire il nuovo boundary. | | Change Plan | Si | Si | Opzionale | Supporta upgrade e downgrade. | | Change Addons | Si | Si | Opzionale | Include aggiornamento quantita seat. | | Cancel At Period End | Si (flag) | Effetto a boundary | No | Comportamento compatibile con legacy. | | Undo Cancel At Period End | Si | No | No | Ripristina il piano attivo prima del boundary. | | Next Renewal Preview | Read-only | N/A | N/A | Mostra breakdown completo del prossimo addebito. | | Amendment History | N/A | N/A | N/A | Storico completo modifiche lifecycle. | *** ## Esempi API ### Pianificare Cambio Seat A Fine Periodo ```json { "subscription": { "action": "change_addons", "when": "period_end", "proration": false, "addons": [ { "name": "workspace_seat", "quantity": 25, "price": 12 } ] } } ``` ### Anteprima Prossimo Rinnovo (estratto risposta) ```json { "status": "success", "data": { "subscription_id": "sub_abc123", "next_renewal": "2026-07-01", "billable": true, "pricing": { "items": [ { "service": "Subscription Base: Pro", "net": 99, "tax_rate": 22, "tax": 21.78, "total": 120.78 }, { "service": "Addon: workspace_seat (Qty: 25)", "net": 300, "tax_rate": 22, "tax": 66, "total": 366 } ], "net_due": 399, "vat_due": 87.78, "gross_due": 486.78 } } } ``` *** ## FAQ API (Combinazioni Comuni) Le combinazioni sotto fanno riferimento alle route Customer API documentate in `/it/docs/api/customer#subscription-management`. ### Come posso fare l'upgrade di un piano? Usa `change-plan` con applicazione immediata. ```json { "lifecycle": { "plan_id": "PLAN_ENTERPRISE_V3", "when": "immediate", "proration": true } } ``` * Endpoint: `PUT /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/change-plan.json` * Se il delta proration e positivo, viene tentato un addebito immediato. * Se l'addebito immediato fallisce, la modifica non viene applicata. ### Come posso fare il downgrade di un piano? Usa sempre `change-plan`, puntando a un piano con prezzo inferiore. ```json { "lifecycle": { "plan_id": "PLAN_STARTER_V1", "when": "immediate", "proration": true } } ``` * Endpoint: `PUT /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/change-plan.json` * Con delta negativo, il sistema genera credito in `carryover_credit`. * Il credito viene scalato sui rinnovi successivi prima di nuovi addebiti. ### Come posso pianificare upgrade o downgrade dal prossimo rinnovo? ```json { "lifecycle": { "plan_id": "PLAN_PRO_V2", "when": "period_end", "proration": false } } ``` * Endpoint: `PUT /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/change-plan.json` * Nessun addebito immediato: la modifica si applica al boundary di rinnovo. ### Come posso modificare la quantità degli addon (seat inclusi)? ```json { "lifecycle": { "addons": [ { "element": "workspace_seat", "quantity": 25 } ], "when": "immediate", "proration": true } } ``` * Endpoint: `PUT /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/change-addons.json` * Nel modello seat-based, il numero seat e `addons[].quantity`. ### Come posso pianificare una modifica addon a fine periodo? ```json { "lifecycle": { "addons": [ { "element": "workspace_seat", "quantity": 40 } ], "when": "period_end", "proration": false } } ``` * Endpoint: `PUT /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/change-addons.json` * Utile per cambi commerciali con decorrenza dal prossimo ciclo. ### Come funziona pausa e ripresa dopo mesi? * Metti in pausa: `PUT .../lifecycle/pause.json` * Riprendi: `PUT .../lifecycle/resume.json` (opzionale `resume_at`) Esempio reale: * pausa il **1 maggio 2026** * riprendi il **1 luglio 2026** * non vengono addebitati retroattivamente maggio/giugno; il ciclo riparte dalla logica di resume. ### Posso annullare una cancellazione gia impostata a fine periodo? Sì: * imposta cancellazione: `PUT .../lifecycle/cancel-at-period-end.json` * annulla cancellazione: `PUT .../lifecycle/undo-cancel-at-period-end.json` Se annulli prima del boundary, la subscription torna operativa in stato `active`. ### Come posso vedere prima l'impatto economico senza applicare modifiche? Usa la preview lifecycle (no mutation): ```json { "lifecycle": { "action": "change_addons", "addons": [ { "element": "workspace_seat", "quantity": 30 } ] } } ``` * Endpoint: `POST /customers/{customerId}/subscriptions/{subscriptionId}/lifecycle/preview.json` * Risposta con `old_due`, `new_due`, `delta`, `direction`. ### Come gestisco retry sicuri lato integrazione? Usa `lifecycle.idempotency_key` nelle chiamate mutative. In caso di retry, eviti doppie applicazioni della stessa operazione. ### Dove trovo lo storico completo delle modifiche? Usa amendment history: * Endpoint: `GET /customers/{customerId}/subscriptions/{subscriptionId}/amendments.json` * Include azione, quando (`immediate`/`period_end`), before/after, metadati proration. ### Tabella rapida combinazioni | Obiettivo | Endpoint | `when` | `proration` | | :------------------------------ | :----------------------------------- | :----------- | :---------- | | Upgrade piano subito | `.../change-plan.json` | `immediate` | `true` | | Downgrade piano subito | `.../change-plan.json` | `immediate` | `true` | | Cambio piano da prossimo ciclo | `.../change-plan.json` | `period_end` | `false` | | Aumento/diminuzione seat subito | `.../change-addons.json` | `immediate` | `true` | | Cambio seat da prossimo ciclo | `.../change-addons.json` | `period_end` | `false` | | Pausa servizio | `.../pause.json` | N/A | N/A | | Ripresa servizio | `.../resume.json` | N/A | N/A | | Cancella a fine periodo | `.../cancel-at-period-end.json` | boundary | N/A | | Annulla cancellazione | `.../undo-cancel-at-period-end.json` | immediate | N/A | | Simulazione impatto | `.../preview.json` | N/A | N/A | | Storico modifiche | `.../amendments.json` | N/A | N/A | *** ## Scenari Pratici ### 1) Pausa 2 Mesi, Poi Ripresa * Pausa il **1 maggio 2026** * Riprendi il **1 luglio 2026** * Risultato: nessun addebito arretrato per maggio/giugno, rinnovo riallineato alla ripresa. ### 2) Upgrade Mid-Cycle * Il cliente passa da 10 a 20 seat con modifica immediata. * Delta proration positivo => addebito immediato di conguaglio. ### 3) Downgrade Mid-Cycle * Il cliente riduce seat durante il periodo. * Delta negativo => credito salvato in `carryover_credit`. * Il credito viene consumato ai rinnovi successivi prima di nuovi addebiti. ### 4) Cancellazione In Attesa + Ripristino * Cliente richiede cancellazione a fine periodo. * Stato passa a `cancel_pending`. * Se cambia idea prima del boundary, `undo` riporta la subscription in stato attivo. *** ## Backward Compatibility (No Break Changes) I flussi panel/API legacy restano validi. Le nuove capability lifecycle sono opt-in. | Area | Comportamento Legacy | Comportamento Attuale | | :------------------------- | :------------------- | :----------------------------- | | Attach/detach subscription | Supportato | Ancora supportato | | Route legacy update addon | Supportata | Ancora supportata | | Campo status legacy | Presente | Ancora presente | | Modello seat | Addon quantity | Stesso modello ufficiale | | Integrazioni esistenti | Stabili | Adozione lifecycle progressiva | Se sei gia integrato con le route legacy, puoi lasciarle invariate e attivare gradualmente le route lifecycle dove ti servono pausa/resume, proration e storico amendment. *** ## Checklist Consigliata } title="Modella I Seat Con Addon" description="Configura costo unitario seat sull'addon e aggiorna quantity per il numero seat." /> } title="Usa Scheduled Change" description="Per variazioni commerciali future, preferisci `period_end`." /> } title="Aumenta Trasparenza" description="Usa renewal preview e amendment history per supporto e audit." /> *** ## Documentazione Correlata # Sentinel Dashboard import { Callout } from 'fumadocs-ui/components/callout'; # Security Command Center La Dashboard di Sentinel è il cuore operativo della sicurezza. Fornisce una visione immediata e ad alto impatto visivo dello stato di salute del tuo ecosistema di autenticazione. ## Metriche in Tempo Reale La dashboard monitora quattro KPI critici: * **Threats Detected:** Numero di minacce bloccate attivamente dal sistema. * **Failed Logins:** Tentativi di accesso non riusciti (potenziali attacchi brute-force). * **Active Sessions:** Numero di utenti attualmente autenticati globalmente. * **Avg Response:** Tempo medio di risposta del motore di sicurezza (espresso in millisecondi). ## Global Login Activity Grazie all'integrazione con **MapLibre GL**, Sentinel visualizza la densità degli accessi su una mappa globale. * I punti blu indicano attività regolare. * I punti rossi segnalano aree ad alta densità di tentativi, permettendo di identificare rapidamente attacchi geograficamente mirati. ## Security Alerts & Decisions In questa sezione vengono elencate le anomalie recenti. Per ogni alert, Sentinel mostra: 1. **Severità:** Da *Low* a *Critical*. 2. **Decisione Presa:** - `Allow`: Accesso consentito. * `Challenge MFA`: Richiesta di secondo fattore obbligatoria. * `Deny`: Accesso bloccato. * `Monitor`: Attività sospetta ma sotto la soglia di blocco. 3. **Trigger:** I motivi specifici che hanno alzato il rischio (es. *New User Agent*, *TOR/VPN Flag*). Puoi cliccare su ogni IP o User ID negli alert per approfondire lo storico delle attività di quel profilo. # Sentinel Security Platform import { Card, Cards } from 'fumadocs-ui/components/card'; import { ShieldCheck, Lock, Eye, Zap } from 'lucide-react'; # Sentinel Security Platform **Sentinel** è il modulo di sicurezza intelligente di Donutwork progettato per proteggere il tuo business e i tuoi utenti dalle minacce moderne. A differenza dei sistemi di sicurezza statici, Sentinel analizza ogni tentativo di accesso in tempo reale, assegnando un **Risk Score** dinamico basato su decine di segnali comportamentali e ambientali. ## Pilastri di Sentinel } title="Adaptive MFA" description="Richiede l'autenticazione a due fattori solo quando il rischio rilevato supera una soglia predefinita." /> } title="IP Intelligence" description="Analisi automatica di IP malevoli, nodi TOR, VPN e geolocalizzazioni sospette." /> } title="Identity Provider (IDP)" description="Gestione centralizzata delle utenze esterne con supporto a T-OTP e codici di backup." /> } title="Risk-Based Decisions" description="Prende decisioni automatiche (Allow, Challenge MFA, Deny) in millisecondi." /> *** ## Come funziona il Risk Engine? Ogni volta che un utente interagisce con il sistema di autenticazione, Sentinel valuta i seguenti fattori: 1. **Reputazione IP:** L'indirizzo proviene da una rete nota per attacchi o bot? 2. **Novità del Dispositivo:** L'utente sta usando un browser o un sistema operativo mai visto prima? 3. **Geolocalizzazione:** L'accesso proviene da un paese insolito per quell'utente? 4. **Continuità della Sessione:** Se l'utente è già loggato e la sessione è stabile, il rischio viene ridotto. Il risultato è uno score da **0.00** a **1.00**. In base a questo valore e alle tue configurazioni, Sentinel decide come procedere. *** ## Sezioni di Sentinel * **[Dashboard](/it/docs/sentinel/dashboard):** Monitoraggio in tempo reale delle minacce globali. * **[Gestione Utenti](/it/docs/sentinel/users):** Controllo granulare sugli accessi e sullo stato della sicurezza degli utenti. * **[Configurazione](/it/docs/sentinel/settings):** Calibrazione fine delle soglie di rischio e dei trigger. ## Ordine Di Setup Consigliato 1. Imposta le soglie base in [Configurazione](/it/docs/sentinel/settings). 2. Verifica gli scenari ad alto rischio dalla vista [Dashboard](/it/docs/sentinel/dashboard). 3. Gestisci eccezioni e override da [Gestione Utenti](/it/docs/sentinel/users). # Sentinel Risk Configuration import { Callout } from 'fumadocs-ui/components/callout'; # Configurazione Sentinel Sentinel ti permette di "addestrare" il motore di rischio in base alle tue specifiche necessità. Puoi decidere quanto peso dare a ogni singolo evento di sicurezza. ## Score Adjustments (Pesi) Ogni evento sospetto aggiunge un valore al **Risk Score** totale (da 0.0 a 1.0). Puoi regolare i seguenti parametri: * **Malware/Threat IP Flag:** Il punteggio massimo per IP presenti in blacklist globali. * **TOR/VPN Flag:** Rischio associato all'uso di reti anonimizzanti. * **Unknown IP / Country:** Rischio aggiunto quando un utente accede da una posizione o un IP mai usato prima. * **New User Agent:** Rischio per l'uso di un nuovo browser o dispositivo. ### Riduzione del Rischio * **Session Continuity Reduction:** Questo valore (negativo) riduce il rischio se l'utente mantiene una sessione stabile e conosciuta. È fondamentale per evitare "falsi positivi" durante l'uso normale dell'app. *** ## Soglie di Decisione (Thresholds) Definisci i limiti oltre i quali Sentinel deve intervenire: | Soglia | Descrizione | | :-------------------------- | :--------------------------------------------------------------------------------------------------------------------- | | **Challenge MFA Threshold** | Se lo score è `>=` a questo valore, all'utente verrà richiesto il T-OTP, anche se non obbligatorio per il suo profilo. | | **Deny Threshold** | Se lo score è `>=` a questo valore, l'accesso viene negato immediatamente a prescindere dalle credenziali. | Impostare una soglia di *Deny* troppo bassa (es. 0.40) potrebbe bloccare utenti legittimi che viaggiano o usano nuovi dispositivi. Si consiglia di iniziare con soglie conservative (MFA a 0.50 e Deny a 0.85). *** ## Integrazione T-OTP Sentinel permette di abilitare o disabilitare globalmente il servizio di **Time-Based One-Time Password**. Quando abilitato, potrai offrire ai tuoi utenti l'autenticazione tramite app come Google Authenticator o Authy tramite le API di Donutwork. # User Management (IDP) # Gestione Utenti Sentinel Sentinel agisce come un **Identity Provider (IDP)** per le tue applicazioni SaaS. In questa sezione puoi monitorare e gestire la sicurezza di ogni singolo utente registrato. ## Stato della Sicurezza Utente Per ogni utente, la tabella mostra: * **CustomerID:** L'identificativo esterno del tuo utente. * **Status:** Stato dell'account (Attivo o Sospeso). * **OTP (One-Time Password):** Indica se l'utente ha configurato correttamente l'autenticazione a due fattori (T-OTP). * **Backup Codes:** Mostra se sono stati generati i codici di emergenza per il recupero dell'account. ## Azioni Amministrative Come amministratore, hai il controllo totale sulle sessioni: 1. **Sospensione Accesso:** Se rilevi attività compromesse, puoi sospendere istantaneamente l'utente. Questo invaliderà tutte le sessioni attive. 2. **Ripristino Accesso:** Permette di riattivare un utente precedentemente sospeso. 3. **Eliminazione:** Rimuove permanentemente l'utente dal sistema Sentinel. > **Nota:** La sospensione in Sentinel blocca l'autenticazione a livello di IDP, impedendo l'accesso a tutti i servizi collegati alla piattaforma. # Directory Monitor import { Card, Cards } from 'fumadocs-ui/components/card'; import { FolderOpen, Terminal, Bell, Cpu } from 'lucide-react'; # Directory Monitor Il **Directory Monitor** è un motore di sorveglianza del file system progettato per l'automazione. Ti permette di monitorare cartelle specifiche — sia locali che su server remoti — e di attivare notifiche o flussi di lavoro ogni volta che un file viene creato, modificato o eliminato. ## L'Agente di Monitoraggio Per abilitare il monitoraggio sulla tua infrastruttura, Donutwork fornisce un **Binary Linux**. Questo agente leggero viene eseguito sul tuo server e comunica in modo sicuro con la piattaforma, garantendo un tracciamento degli eventi a bassa latenza senza esporre il tuo file system a internet. } title="Binary Linux" description="Scarica il pacchetto .tar pre-compilato ed eseguilo come servizio sul tuo server." /> } title="Alert in Tempo Reale" description="Ricevi notifiche istantanee via Webhook o Email quando file critici vengono modificati." /> ## Casi d'Uso Comuni 1. **Ingestione Dati Automatica:** Carica un CSV in una cartella monitorata per avviare automaticamente un [Workflow](/it/docs/workflow) di elaborazione dati. 2. **Audit di Sicurezza:** Monitora directory sensibili (come `/etc/` o `/bin/`) e ricevi avvisi se avvengono cambiamenti non autorizzati. 3. **Verifica Backup:** Attiva task di post-elaborazione non appena un file di dump del database viene completato in una directory specifica. ## Struttura del Progetto * **Project ID:** Un identificativo univoco utilizzato dall'agente per sincronizzarsi con la dashboard di Donutwork. * **Startup Status:** Indica se il processo di monitoraggio è stato inizializzato correttamente ed è in ascolto attivo di eventi. # Systems & Monitoring import { Card, Cards } from 'fumadocs-ui/components/card'; import { ShieldCheck, FolderTree, Code2, Key } from 'lucide-react'; # Systems & Monitoring La sezione **Systems & Monitoring** è il centro di controllo operativo di Donutwork. Fornisce gli strumenti necessari per garantire che l'infrastruttura del tuo SaaS sia sicura, performante e costantemente monitorata. Dalla validazione dei certificati SSL alla gestione dei segreti tramite KMS, Donutwork ti offre una visibilità totale sullo stato dei tuoi sistemi. ## Moduli di Monitoraggio Esplora le sezioni dedicate per configurare e gestire i vari aspetti della tua infrastruttura: } title="TLS Monitor" href="/it/docs/system-and-monitoring/tls-monitor" description="Monitora la validità e la scadenza dei certificati SSL/TLS per evitare interruzioni di servizio." /> } title="Directory Monitor" href="/it/docs/system-and-monitoring/directory-monitor" description="Automatizza i processi e le notifica monitorando i cambiamenti nelle directory critiche." /> } title="Sources" href="/it/docs/system-and-monitoring/sources" description="Connessioni a SFTP/FTP remoti per lo scambio di files." /> } title="KMS Keys" href="/it/docs/system-and-monitoring/kms" description="Sistema di gestione delle chiavi (Key Management Service) per la cifratura dei dati sensibili." /> *** ## Perché il Monitoraggio è Cruciale? In un ambiente SaaS moderno, la stabilità non è un optional. Donutwork automatizza i controlli di routine per prevenire i problemi prima che impattino l'utente finale: 1. **Sicurezza Proattiva:** Rileva certificati TLS in scadenza o file di sistema modificati in modo anomalo. 2. **Governance dei Dati:** Gestisci le chiavi crittografiche in modo centralizzato tramite il modulo **KMS**, garantendo la conformità agli standard di sicurezza. 3. **Tracciabilità:** Automatizza i processi e le notifica monitorando i cambiamenti nelle directory critiche. ## Setup Nei Primi 15 Minuti 1. Parti da [TLS Monitor](/it/docs/system-and-monitoring/tls-monitor) per avere visibilità immediata sui certificati. 2. Configura [KMS](/it/docs/system-and-monitoring/kms) prima di caricare segreti nei flussi operativi. 3. Collega [Sources](/it/docs/system-and-monitoring/sources) se importi file da endpoint SFTP/FTP. 4. Attiva [Directory Monitor](/it/docs/system-and-monitoring/directory-monitor) per convertire eventi filesystem in trigger workflow. # Key Management System (KMS) import { Callout } from 'fumadocs-ui/components/callout'; # Key Management System (KMS) Il **KMS** di Donutwork è la cassaforte crittografica del tuo SaaS. Fornisce un sistema centralizzato per l'archiviazione di credenziali sensibili, segreti applicativi e chiavi master che non dovrebbero mai essere scritte nel codice o salvate in testo semplice. ## Struttura delle Chiavi Ogni voce del KMS è progettata per l'accesso programmatico e un'alta sicurezza: * **Handler:** Un alias univoco utilizzato dalle tue API o script per recuperare la chiave senza esporne il contenuto reale. * **Content:** Il valore segreto effettivo (es. Stripe Secret Key, AWS Access Key o un certificato privato). * **Whitelist (Isolamento di Rete):** Limita l'uso di una chiave a specifici indirizzi IP o range CIDR. Se una richiesta arriva da un IP non autorizzato, il KMS bloccherà l'accesso anche con credenziali valide. ## Audit di Sicurezza La tracciabilità è integrata nel cuore del KMS. Ogni volta che una chiave viene letta o modificata, viene generato un **Audit Log**. ### Dettagli dell'Audit Log: * **Identità del Richiedente:** Chi ha effettuato l'accesso alla chiave. * **Timestamp:** Esattamente quando è avvenuto l'accesso. * **IP di Origine:** L'origine di rete della richiesta. * **Esito:** Se la richiesta è andata a buon fine o è stata bloccata dalla policy di whitelist. Usa l'**Handler** nel codice della tua applicazione per mantenere i tuoi repository puliti dai segreti. Questo ti permette di ruotare le chiavi nella dashboard di Donutwork senza dover rieseguire il deploy della tua applicazione. # Connessioni Esterne (Sources) import { Card, Cards } from 'fumadocs-ui/components/card'; import { Link, Shield, Server, FileCode } from 'lucide-react'; # Sources & Connessioni Esterne Il modulo **Sources** gestisce i gateway di comunicazione sicura tra Donutwork e la tua infrastruttura esterna. Ti permette di configurare e memorizzare le credenziali per server remoti, abilitando trasferimenti di file automatizzati e sincronizzazione dei dati. ## Protocolli Supportati Donutwork supporta i protocolli standard di settore per lo scambio sicuro di file: * **SFTP (SSH File Transfer Protocol):** Il metodo più sicuro, che utilizza SSH per il transito dei dati. * **FTPS (FTP over SSL/TLS):** Una versione sicura di FTP che cripta sia i comandi che il contenuto. * **FTP:** Supportato per compatibilità con sistemi legacy (non raccomandato per dati sensibili). ## Sicurezza e Impostazioni Avanzate * **Cifratura SSL/TLS:** Forza connessioni criptate per assicurare che credenziali e file non siano mai trasmessi in chiaro. * **Modalità Passiva:** Essenziale per le connessioni FTP/S per superare restrizioni di firewall o NAT lato server. * **Mascheramento Credenziali:** Per conformità di sicurezza, le password non vengono mai mostrate nell'interfaccia dopo la configurazione iniziale. ## Configurazione Tecnica Per creare una connessione, avrai bisogno di: * **Hostname & Porta:** L'indirizzo del server remoto (es. `sftp.partner.com`). * **Autenticazione:** Username e Password (archiviati in modo sicuro e criptato). * **Toggle di Sicurezza:** Abilita SSL/TLS e Modalità Passiva a seconda dei requisiti del server. # TLS Monitor import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { ShieldCheck, Clock, Globe, Lock } from 'lucide-react'; # TLS Monitor Il **TLS Monitor** è uno strumento di sicurezza dedicato al monitoraggio costante dei tuoi endpoint HTTPS. A differenza dei normali sistemi di uptime, esegue scansioni approfondite della configurazione crittografica per assicurare che i certificati SSL/TLS siano validi, aggiornati e conformi agli standard moderni. ## Funzionalità Chiave * **Tracciamento Scadenze:** Visualizzazione in tempo reale delle date di scadenza per prevenire interruzioni di servizio impreviste. * **Verifica Protocolli:** Assicura che i server utilizzino versioni sicure (TLS 1.2, 1.3) e segnala protocolli obsoleti o vulnerabili (SSLv3, TLS 1.0/1.1). * **Avvisi di Conformità:** Identifica automaticamente configurazioni non a norma basandosi sul GDPR e sulle best practice di settore. * **Gestione Multi-Host:** Un'unica dashboard per gestire e monitorare decine di domini simultaneamente. ## Panoramica della Dashboard La tabella del TLS Monitor fornisce un'istantanea completa dei tuoi host: | Campo | Descrizione | | :-------------- | :------------------------------------------------------------------ | | **Hostname** | L'URL completo monitorato (es. `https://api.tuodominio.it`). | | **Status** | Il risultato dell'ultimo controllo automatizzato (Success/Failed). | | **TLS Version** | La versione specifica del protocollo attualmente servita dall'host. | | **Expire Date** | La data esatta in cui il certificato smetterà di essere valido. | Il sistema genererà un badge di "Warning" se la scansione rileva suite di cifratura insicure o scadenze imminenti, permettendo al tuo team di rinnovare i certificati prima che gli utenti ne risentano. ## Configurazione Per aggiungere un nuovo monitor, è sufficiente fornire un nome descrittivo e l'hostname completo. Puoi anche assegnare dei **Tag** per organizzare i monitor per ambiente (es. `Production`, `Staging`) o per progetto. # Automazioni & Workflow import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; import { Zap, Code2, Cpu, Workflow, MessageSquare, Bot } from 'lucide-react'; # Workflow Automation Donutwork integra un potente editor visivo basato su nodi che permette di automatizzare processi complessi senza scrivere codice. Grazie all'architettura **event-driven**, puoi attivare sequenze di azioni ogni volta che accade qualcosa nel tuo SaaS (es. la creazione di un cliente o un aggiornamento di pagamento). ## Come Funziona Ogni Workflow è composto da tre elementi fondamentali: 1. **Trigger (L'Inizio):** L'evento che scatena il flusso (es. `Customer.create`). 2. **Nodi Logici:** Blocchi che elaborano dati, applicano filtri o prendono decisioni (IF/Else). 3. **Azioni (L'Output):** Operazioni concrete come invio email, chiamate Webhook o aggiornamenti di database. *** ## Catalogo dei Nodi Disponibili L'editor mette a disposizione una vasta libreria di blocchi pronti all'uso, divisi per categoria: | Categoria | Nodi Chiave | Funzione | | :------------ | :-------------------- | :------------------------------------------------------------------- | | **Controllo** | Trigger, Fine | Gestiscono l'ingresso e l'uscita del flusso. | | **Logica** | IF, Switch, Filter | Permettono di creare percorsi condizionali e instradare i dati. | | **Dati** | Math, Merge, Text | Eseguono calcoli, uniscono oggetti JSON o formattano stringhe. | | **CRM** | Get Customer, Partner | Recuperano in tempo reale i dati completi delle entità dal database. | | **Azioni** | Webhook, Email | Comunicano con il mondo esterno (es. Slack, CRM, Email Gateway). | *** ## Automazione con Intelligenza Artificiale Donutwork porta l'automazione al livello successivo integrando strumenti di AI direttamente nell'editor: } title="AI Build (Copilot)" description="Descrivi il flusso a parole (es: 'Se un cliente non ha un partner, invia una email') e l'AI costruirà il diagramma per te." /> } title="AI Explain" description="Analizza un workflow esistente per ottenere una spiegazione testuale chiara della logica implementata." /> *** ## Funzionalità Avanzate ### Cicli e Variabili Puoi utilizzare il nodo **Set Variable** per salvare dati temporanei durante l'esecuzione o il nodo **For Each** per iterare su liste di oggetti (es. processare tutti i payout di un partner). ### Prevenzione degli Errori L'editor include un sistema di **Cycle Detection** che impedisce la creazione di loop infiniti, proteggendo la stabilità del sistema e delle tue API. ### Custom Blocks Donutwork permette agli sviluppatori di registrare blocchi personalizzati (`Custom Blocks`). Questi nodi appaiono nell'interfaccia con icone e badge specifici, permettendo al team non-tech di utilizzare funzioni aziendali proprietarie (es. `Sync CRM Notifier`) in totale sicurezza. Prima di poter salvare un Workflow, il sistema verifica che sia presente un nodo iniziale (Trigger) e un nodo finale (End), e che tutti i nodi posizionati siano effettivamente collegati tra loro. *** ## Esempio di Utilizzo: Welcome Kit 1. **Trigger:** `Customer.create` 2. **Logic:** Nodo `IF` per verificare se il cliente ha una Partita IVA. 3. **Action (True):** Invio email con istruzioni per account Business. 4. **Action (False):** Invio email con istruzioni per account Private. 5. **End:** Chiusura del flusso.