Skip to main content
Version: 2.0.0

Developer API

The Superfaktura plugin exposes services, an invoice provider, an order-edit UI component, and MCP tools for integration with yStore's invoicing system and external/automation clients.

Services

Access services via the plugin instance:

use Yui\Superfaktura\Plugin;

$superfaktura = Plugin::getInstance();
$api = $superfaktura->getApi();
$invoices = $superfaktura->getInvoices();
$dashboard = $superfaktura->getDashboard();
$license = $superfaktura->getLicense();

ApiService

Builds the authenticated connection to the SuperFaktura API (getConnection(?int $siteId)) using the Email, API Key, Company ID, and Market (Country) resolved for a given site (falling back to the global settings), and honors Sandbox Mode. Every response updates the plugin's persisted daily/ monthly rate-limit fields (shown read-only in the settings sidebar).

InvoiceService

Creates, updates, downloads, emails, and lists SuperFaktura documents from order data.

  • handleAutomaticDocuments(int $orderId, ?string $orderStatus) -- entry point called on CheckoutService::EVENT_AFTER_PURCHASE_SUCCESS. Queues a CreateInvoiceDocumentsJob; if the job cannot be queued, it falls back to processing synchronously via processAutomaticDocuments().
  • processAutomaticDocuments(int $orderId, ?string $orderStatus) -- attempts to create both the proforma and the regular invoice for the order based on the configured order-status/payment-method triggers.
  • processAutomaticDocumentsFromData(array $invoiceData) -- the invoice-provider entry point; builds documents from a normalized $invoiceData array (with order_id/order_status under meta) instead of loading the order directly. Used by SuperfakturaInvoiceProvider::createInvoice().
  • createInvoice(int $orderId, ?string $orderStatus, bool $manualCreate = false) / createProformaInvoice(...) -- create a regular invoice / proforma. When $manualCreate is false, creation only proceeds if $orderStatus (and, if configured, the order's payment method) matches the configured trigger. Refuses to create a duplicate document for an order that already has one, and refuses a zero-total order unless Zero Total Orders is enabled. Returns true on success, false on an unexpected failure, or an array of human-readable error messages (including B2B validation errors).
  • createCreditNote(int $orderId, ?string $orderStatus, bool $manualCreate = false) -- creates a credit note (storno) against an existing regular invoice. Fails if no regular invoice exists yet, or if a credit note already exists for the order.
  • updateInvoice(...) / updateProformaInvoice(...) -- re-send invoice/proforma data for a document that already has a recorded invoice.
  • sendInvoiceEmailByOrderId(int $orderId) / sendProformaEmailByOrderId(int $orderId) / sendCreditNoteEmailByOrderId(int $orderId) -- email the corresponding document to the customer, adding any configured Invoice email BCC recipients. Fails if the order or the target document doesn't exist, or the order has no customer email address.
  • retryInvoiceCreation(int $orderId, string $invoiceType) -- retries a previously failed document creation for regular, proforma, or cancel.
  • getFailedInvoiceTypesByOrderId(int $orderId) -- returns the pending failure(s) recorded for an order, keyed by invoice type, backing the order-edit menu's failure indicators and the RetryFailedTool MCP tool.
  • getCachedInvoicePaymentStatusesByOrderId(int $orderId) -- returns cached payment status per document type (paid / partially paid / overdue / unpaid) shown in the order-edit menu.
  • syncRemoteInvoices() -- re-fetches invoices from the SuperFaktura API and refreshes the locally cached copies (requires Store Remote Invoices in Database); backs the Superfaktúra → Invoices → Sync Invoices action.
  • getInvoices(int $page = 1, int $perPage = 10, ?string $searchTerm = null) -- paginated/searchable listing backing the Superfaktúra → Invoices CP page and its superfaktura/invoices/get-list endpoint.

Every invoice/client/item detail sent to SuperFaktura is assembled from the order (address, line items, shipping, payment, discounts, notes) and the plugin's settings (tax payer status, tax class, rounding type, invoice language, signature/payment-info/By Square toggles, and whether shipping/payment are added as line items).

CP notifications

Superfaktura registers three notification types with yui/craft-core's NotificationService on NotificationService::EVENT_REGISTER_NOTIFICATION_TYPES, so admins see and can filter them like any other CP notification source (source = superfaktura):

TypeSeverityLabelFired when
invoice.createdinfoInvoice createdA regular invoice, proforma, or credit note is created successfully (processInvoiceCreationResult()).
invoice.failedwarningInvoice creation failedDocument creation returns validation/API error messages instead of throwing (processInvoiceCreationResult()).
invoice.errorcriticalInvoice system unavailableDocument creation throws (CannotCreateInvoiceException, CannotCreateRequestException, or any other \Exception) — for example when the SuperFaktura API is unreachable.

InvoiceService::notifyInvoiceEvent() builds a title that includes the document kind (invoice/proforma/ credit note) and order number, and calls NotificationService::createNotification() with source: 'superfaktura'; any error/API message is passed as the notification body. Notification creation is best-effort: failures inside notifyInvoiceEvent() are swallowed so a notification-service problem never blocks invoice creation itself.

B2B validation and EU reverse charge

InvoiceService (both the order-based and the data-based variants) applies, when Validate B2B Details is enabled:

  • Company ID and Tax ID must be present on the order/company details, or invoice creation fails with a validation error.
  • If Require VAT ID for B2B Orders is enabled, a VAT ID must also be present.
  • Any provided VAT ID must match ^[A-Z]{2}[A-Z0-9]{8,12}$ (after stripping spaces/dashes/dots), or creation fails.
  • If EU Reverse Charge is enabled and the order's billing country is an EU country different from the configured Market (Country), a VAT ID is required; when present, the invoice is sent with zero VAT and reverse-charge metadata instead of the store's normal tax class.

DashboardService

Extends the shared yui\craftcore\services\CoreDashboardService to build the Superfaktúra → Dashboard modules: Invoices generated, In this period, and Unresolved failures KPI tiles, a Recent failures list, and a Recent invoices table (date, order, type, invoice ID).

LicenseService

Backs the Superfaktúra → License CP page (shared yui/craft-core license activation/status UI).

Invoice provider

Yui\Superfaktura\providers\SuperfakturaInvoiceProvider registers itself with handle superfaktura on yui\craft\services\sales\InvoiceService::EVENT_REGISTER_INVOICE_PROVIDERS, so it appears alongside any other invoice provider yStore has registered.

public function isEnabled(): bool
{
return Plugin::getInstance()?->getSettings()?->enabled ?? false;
}

The provider is enabled purely based on the Enabled settings toggle. createInvoice() delegates to InvoiceService::processAutomaticDocumentsFromData(), and getAttachments() returns the invoices already recorded for the order (via $invoiceData['meta']['order_id']) using InvoiceService::getInvoicesByOrderId().

Order-edit component

When Show Superfaktúra Button is on, the plugin hooks into the order-edit-extra-actions template hook and renders a Superfaktúra menu button on the order edit page (superfaktura/components/order/edit/manage-invoice.twig). Menu items are computed per order from existing invoice/proforma/credit-note records and shown only when the acting user has the matching permission:

  • Create Invoice / Create Proforma Invoice -- shown when the order has no recorded document of that type yet. Requires yui:superfaktura:create.
  • Update Invoice / Update Proforma Invoice -- shown when the order already has one. Requires yui:superfaktura:update.
  • Create Credit Note -- shown when a regular invoice exists and no credit note has been created yet. Requires yui:superfaktura:create.
  • Send Invoice/Proforma/Credit Note Email -- shown for existing documents. Requires yui:superfaktura:send.
  • Download Invoice/Proforma/Credit Note -- shown for existing documents.

These map to InvoiceController::actionCreate(), actionCreateProforma(), actionCreateCreditNote(), actionUpdate(), actionUpdateProforma(), actionDownload(), actionDownloadProforma(), actionDownloadCreditNote(), actionSendEmail(), actionSendProformaEmail(), actionSendCreditNoteEmail(), and actionSync(). The menu also surfaces cached payment statuses (paid/partially paid/overdue/unpaid) and any pending creation failures per document type.

MCP Tools

When the yui/craft-mcp plugin is installed, Superfaktura registers five MCP tools on yui\mcp\Plugin::EVENT_REGISTER_TOOLS, all extending the shared AbstractSuperfakturaTool base, which accepts an order identifier (order_id and/or increment_id).

superfaktura_get_invoices

Lists all SuperFaktura invoice documents (regular, proforma, credit note) for a given order, including pending failures.

{
"order_id": 123,
"count": 2,
"documents": [
{"type": "regular", "invoice_id": 456, "asset_id": 789},
{"type": "proforma", "invoice_id": 457, "asset_id": null}
],
"failures": []
}

superfaktura_create_invoice

Manually creates a regular invoice for an order, bypassing the order-status trigger and forcing creation. Fails if an invoice already exists for the order. Requires WRITE permission.

superfaktura_create_credit_note

Manually creates a credit note (storno) for an order. Requires a regular invoice to already exist, and fails if a credit note already exists. Requires WRITE permission.

superfaktura_send_invoice_email

Sends a document email to the customer. document_type selects which document to send (regular default, proforma, or credit_note); the document must already exist. Requires WRITE permission.

superfaktura_retry_failed

Retries failed SuperFaktura document creation for an order. Omit invoice_type to retry every pending failure type for the order; specify regular, proforma, or cancel to retry a single type. Requires WRITE permission.

{
"order_id": 123,
"retried": 1,
"results": {
"regular": {"success": true, "order_id": 123, "invoice_type": "regular"}
}
}

Settings model

Yui\Superfaktura\models\Settings (extends yui\craftcore\models\BasePluginSettingsModel) holds every field documented in Settings. Validation: invoiceName, dueDateDays, createInvoiceOnOrderStatus, and roundingType are required whenever the plugin is enabled; on a single-site install, invoiceNumberFormatted, title, email, api_key, company_id, invoiceLanguage, taxClassId, and superfakturaMarketCountry are additionally required (Settings::rules()). invoiceEmailBcc is validated as a list of email addresses. sandboxMode, api_key, email, title, company_id, superfakturaMarketCountry, and invoiceLanguage are site-overridable (siteOverridableAttributes()), so a multi-site store can use different SuperFaktura accounts/markets per site.

CP Routes

RoutePurpose
superfaktura / superfaktura/dashboardDashboard
superfaktura/invoices, /invoices/get-list, /invoices/delete, /invoices/syncInvoice list, AJAX listing, delete, manual sync
superfaktura/invoice/create(-proforma|-credit-note)/<orderId>Manual document creation from the order edit page
superfaktura/invoice/update(-proforma)/<orderId>Manual document update
superfaktura/invoice/sync/<orderId>, /retry/<orderId>/<invoiceType>Per-order sync, failure retry
superfaktura/invoice/download(-proforma|-credit-note)/<orderId>Document PDF download
superfaktura/invoice/send(-proforma|-credit-note)-email/<orderId>Document email send
superfaktura/settings, /settings/test-connection, /settings/reset-api-errorsSettings, connection test, diagnostics reset
superfaktura/licenseLicense activation/status
superfaktura/license/redeem, /revoke, /activate, /delete, /copy-tokenLicense actions

Permissions

The plugin registers five CP user permissions under the Superfaktúra heading: yui:superfaktura:create (Create invoice), yui:superfaktura:update (Update invoice), yui:superfaktura:download (Download invoice), yui:superfaktura:send (Send invoice email), and yui:superfaktura:sync (Sync invoices).

Compatibility

  • Craft CMS 5+ (craftcms/cms ^5.6.11)
  • yui/craft-core ^1
  • superfaktura/apiclient (SuperFaktura's official PHP API client)
  • Optional: yui/craft-mcp, for the MCP tools described above