Skip to content

Technical - Backend

Overview

This page documents the backend architecture, APIs, decorators, endpoints, handlers, and background tasks that power the Billecta Integration.

Key Components

The package is organized into these main components:

  • endpoints/ - REST API endpoints for UI and webhooks
  • handlers/ - Handlers for lifecycle logic and integrations
  • tasks/ - Background jobs and batch processing
  • config/ - Configuration schemas and field mappings
  • decorators/ - Custom workflows that can be added to your customer solution's custom for a smoother experience (highly recommended)
  • billecta/ - Billecta API client and communication
  • validations/ - Data validation and business rules
  • translations/ - Multi-language support for UI text

Quick Navigation


Billecta API

API Configuration & Base Class

The limepkg integrates with the Billecta API using the BillectaApi class.

Configuration

The BillectaApi class reads the following settings from application config:

Setting Required Description
authentication Yes Base64-encoded API key or SecureToken for Billecta
base_url Yes Base URL for Billecta API endpoint (e.g., https://api.billecta.com)

Validation: Missing configuration values raise InvalidBillectaApiConfig exception during initialization.

Request Headers

{
    "Authorization": "<Authorization header value>",
    "Content-Type": "application/json"
}

Authentication Methods

Two formats are supported for the Authorization header value:

Option 1: Basic Authentication

Basic <Base64-encoded username:password>

Option 2: SecureToken Authentication

SecureToken <Base64-encoded SecureToken>

⚠️ Important: Include the correct prefix (Basic or SecureToken) and a space before the encoded value.

Main Method

handle_api_request(method: str, url_extension: str, payload: dict = None) -> dict

Parameters: - method: HTTP method (GET, POST, PUT, DELETE) - url_extension: API endpoint path (appended to base_url) - payload: Optional request body (dict)

Returns: Parsed API response as dictionary

Behavior: - Validates required arguments - Constructs full URL from base_url + extension - Sends HTTP request with proper headers - Handles response status codes and errors - Accepts empty 200 OK responses

Error Handling

Exception Cause Detail
InvalidBillectaApiConfig Missing configuration Required setting not provided
BillectaApiRequestException General request failure Network error or unexpected response
BillectaApiBadRequestException Invalid request 400 Bad Request from Billecta

All exceptions include detailed messages for debugging.

Usage Example

from limepkg_billecta_integration.billecta.billecta_api import BillectaApi

api = BillectaApi(app)
response = api.handle_api_request(
    method="POST",
    url_extension="/debtors",
    payload={"name": "Acme Corp", "orgNo": "123456789"}
)

Decorators

Decorators are available custom workflows that can be added to your customer solution's custom limeobjects, which are run when those objects are created or modified.

@billecta_person Decorator

Target: person limetype
Purpose: Sync person data related to debtors (anonymization support)

Installation

from lime_type.limeobjects import LimeObject
from limepkg_billecta_integration.decorators.person_decorator import billecta_person

@billecta_person()
class Person(LimeObject):
    pass

def register_limeobject_classes(register_class):
    register_class("person", Person)

Behavior

  • Triggers when person records are anonymized
  • Updates related debtor anonymization in Billecta
  • Propagates changes to all related debtors

@billecta_debtor Decorator

Target: debtor limetype
Purpose: Synchronize customer information to Billecta

Installation

from lime_type.limeobjects import LimeObject
from limepkg_billecta_integration.decorators.debtor_decorator import billecta_debtor

@billecta_debtor()
class Debtor(LimeObject):
    pass

def register_limeobject_classes(register_class):
    register_class("debtor", Debtor)

Behavior

  • Triggers on creation and updates
  • Detects changes to mapped fields via is_dirty()
  • Sends upsert request to Billecta for each creditor relation
  • Updates debtorpublicid on related creditordebtor objects
  • Logs errors to billecta_error_message field

Configuration

  • Requires debtor field mappings to be configured in Lime Admin
  • Ensure creditor relations exist before enabling

@billecta_creditordebtor Decorator

Target: creditordebtor limetype
Purpose: Sync customer-specific creditor configuration

Installation

from lime_type.limeobjects import LimeObject
from limepkg_billecta_integration.decorators.creditordebtor_decorator import billecta_creditordebtor

@billecta_creditordebtor()
class CreditorDebtor(LimeObject):
    pass

def register_limeobject_classes(register_class):
    register_class("creditordebtor", CreditorDebtor)

Behavior

  • Triggers when creditor-debtor relationships change
  • Updates debtor configuration specific to each creditor
  • Syncs custom fields and settings per creditor

@billecta_article Decorator

Target: article limetype
Purpose: Synchronize product/article information to Billecta

Installation

from lime_type.limeobjects import LimeObject
from limepkg_billecta_integration.decorators.article_decorator import billecta_article

@billecta_article()
class Article(LimeObject):
    pass

def register_limeobject_classes(register_class):
    register_class("article", Article)

Behavior

  • Triggers on creation and updates
  • Detects changes to mapped fields
  • For each creditor relation, sends upsert to Billecta
  • Updates articlepublicid on related creditorarticle objects
  • Logs errors to billecta_error_message field

Configuration

  • Requires article field mappings in Lime Admin
  • Works with standard and package article types

@billecta_creditorarticle Decorator

Target: creditorarticle limetype
Purpose: Sync article configuration specific to creditors

Installation

from lime_type.limeobjects import LimeObject
from limepkg_billecta_integration.decorators.creditorarticle_decorator import billecta_creditorarticle

@billecta_creditorarticle()
class CreditorArticle(LimeObject):
    pass

def register_limeobject_classes(register_class):
    register_class("creditorarticle", CreditorArticle)

Behavior

  • Triggers on creditor-article relationship changes
  • Updates article pricing and configuration per creditor
  • Syncs creditor-specific product settings

@billecta_order Decorator

Target: order limetype
Purpose: Automatically create orders in Billecta

Installation

from lime_type.limeobjects import LimeObject
from limepkg_billecta_integration.decorators.order_decorator import billecta_order

@billecta_order()
class Order(LimeObject):
    pass

def register_limeobject_classes(register_class):
    register_class("order", Order)

Behavior

  • Triggers when new orders are created
  • Creates corresponding order in Billecta immediately
  • Validates debtor and article relationships exist
  • Links orders via actionpublicid
  • Processes order rows (standard, package, message types)

Validation

  • Requires debtor with Billecta ID
  • Requires creditor relation
  • Validates all articles exist in Billecta

@billecta_orderrow Decorator

Target: orderrow limetype
Purpose: Automatically sync order changes to Billecta when order rows are modified or deleted

Installation

from lime_type.limeobjects import LimeObject
from limepkg_billecta_integration.decorators.orderrow_decorator import billecta_orderrow

@billecta_orderrow()
class OrderRow(LimeObject):
    pass

def register_limeobject_classes(register_class):
    register_class("orderrow", OrderRow)

Behavior

  • before_delete: Prevents deletion of order rows belonging to orders with status processing, attested, credited, or cancelled
  • after_update: When an order row is created, modified, or moved to a different order, triggers an upsert/attest task for the affected order(s)
  • Only triggers for orders with status created, errorupsert, or errorattest
  • Handles order row reassignment by updating both the previous and current order

Endpoints

Article Endpoints

Upsert Articles in Billecta

Endpoint: POST /limepkg-billecta-integration/task/upsert-articles-in-billecta

Starts a background task to create or update articles in Billecta.

Request:

{
    "integration_monitor_batch_title": "Upsert articles in Billecta",
    "query_filter": {
        "key": "_id",
        "op": "IN",
        "exp": [1001, 1002, 1003]
    }
}

Triggered by: Frontend command "Upsert Articles in Billecta"

Processing: - Creates one task per article - For each creditor relation on the article, sends API request to Billecta - Updates articlepublicid on creditorarticle objects - Tracks progress in integration monitor


Delete Articles in Billecta

Endpoint: POST /limepkg-billecta-integration/task/delete-articles-in-billecta

Starts a background task to remove articles from Billecta.

Request:

{
    "integration_monitor_batch_title": "Delete articles in Billecta",
    "query_filter": {
        "key": "_id",
        "op": "IN",
        "exp": [1001, 1002, 1003]
    }
}

Triggered by: Frontend command "Delete Articles in Billecta"

Processing: - Creates one task per article - For each creditor relation, sends delete request to Billecta - Clears articlepublicid on creditorarticle objects - Tracks progress in integration monitor


Creditor Endpoints

Update Creditor in Billecta

Endpoint: POST /limepkg-billecta-integration/task/update-creditor-in-billecta

Starts a background task to update a creditor in Billecta.

Request:

{
    "integration_monitor_batch_title": "Update creditor in Billecta",
    "creditor_id": 1001
}

Triggered by: Frontend command "Update Creditor in Billecta"

Processing: - Validates creditor exists in Billecta - Fetches current Billecta creditor settings - Maps configured fields from Lime to Billecta - Makes two API requests: one for creditor data, one for default configuration - Updates creditor in Lime with fetched Billecta data


Debtor Endpoints

Upsert Debtors in Billecta

Endpoint: POST /limepkg-billecta-integration/task/upsert-debtors-in-billecta

Starts a background task to create or update debtors in Billecta.

Request:

{
    "integration_monitor_batch_title": "Upsert debtors in Billecta",
    "query_filter": {
        "key": "_id",
        "op": "IN",
        "exp": [1001, 1002, 1003]
    }
}

Triggered by: Frontend command "Upsert Debtors in Billecta"

Processing: - Fetches debtors matching the query filter - For each creditor relation on each debtor, sends API request - Updates debtorpublicid on creditordebtor objects - Tracks progress in integration monitor


Anonymize Debtors in Billecta

Endpoint: POST /limepkg-billecta-integration/task/anonymize-debtors-in-billecta

Starts a background task to remove PII from debtors in Billecta (GDPR compliance).

Request:

{
    "integration_monitor_batch_title": "Anonymize debtors in Billecta",
    "query_filter": {
        "key": "_id",
        "op": "IN",
        "exp": [1001, 1002, 1003]
    }
}

Triggered by: Frontend command "Anonymize Debtors in Billecta"

Processing: - Only anonymizes debtors that have been synced (debtorpublicid exists) - For each creditor relation, sends anonymization request - Removes sensitive debtor information from Billecta - Tracks progress in integration monitor


Invoice Endpoints

Register Manual Payments

Endpoint: POST /limepkg-billecta-integration/billecta/register-manual-payment

Register a manual payment that occurred outside Billecta.

Request:

{
    "invoice_id": 1001,
    "payment_amount": 1000.0,
    "payment_currencycode": "SEK",
    "payment_date": "2025-09-10",
    "payment_mean_code": "BG"
}

Success Response (HTTP 200):

{
    "status_code": 200
}

Error Response (HTTP 500):

{
    "status_code": 500,
    "error_message": "Description of error"
}


Register Write-Off Payments

Endpoint: POST /limepkg-billecta-integration/billecta/register-writeoff-payment

Record a write-off (bad debt or uncollectible amount) on an invoice.

Request:

{
    "invoiceid": 1001,
    "amount": 1000.0,
    "vat": "25",
    "paymentdate": "2025-09-10",
    "comment": "Uncollectible per legal review"
}

Success Response (HTTP 200):

{
    "status_code": 200
}

Error Response (HTTP 500):

{
    "status_code": 500,
    "message": "Description of error"
}


Credit Invoices in Billecta

Endpoint: POST /limepkg-billecta-integration/task/credit-invoices-in-billecta

Starts a background task to create credit notes for invoices.

Request:

{
    "integration_monitor_batch_title": "Credit invoices in Billecta",
    "query_filter": {
        "key": "_id",
        "op": "IN",
        "exp": [1001, 1002, 1003]
    }
}

Processing: - Creates one task per invoice - Sends credit note creation request to Billecta - Links credit invoice to original invoice - Tracks progress in integration monitor


Fetch Invoice PDF

Endpoint: GET /limepkg-billecta-integration/fetch-invoice-pdf/<invoice_id>/

Download an invoice PDF document from Billecta without saving to Lime.

Parameters: - invoice_id (path): Lime invoice ID

Response: Base64-encoded PDF content

Use Case: Third-party integrations that need to fetch invoices without storing in Lime


Fetch & Save Invoice PDF

Endpoint: POST /limepkg-billecta-integration/fetch-and-save-invoice-pdf/

Download invoice PDF from Billecta and attach to invoice object in Lime.

Request:

{
    "invoice_id": 1001
}

Triggered by: Frontend command "Fetch & Save Invoice PDF"

Processing: - Downloads PDF from Billecta API - Creates Lime File object - Attaches to invoice's invoice_pdf field - Updates file timestamp


Use Credit on Invoice

Endpoint: POST /limepkg-billecta-integration/billecta/use-credit-on-invoice

Apply credit from one invoice to settle balance on another.

Request:

{
    "creditinvoiceid": 1001,
    "invoicetocreditid": 1002,
    "paymentmeancode": "BG"
}

Success Response (HTTP 200): (empty body)

Error Response (HTTP 404 or 500):

{
    "message": "Error description"
}


Dispute Invoice

Endpoint: PUT /limepkg-billecta-integration/billecta/dispute-invoice

Mark an invoice as disputed in Billecta. Use this when a debtor contests or disputes an invoice.

Request:

{
    "invoice_id": 1001
}

Success Response (HTTP 200): (empty body)

Error Response (HTTP 404 or 500):

{
    "error_message": "Invoice not found or missing Billecta invoice ID"
}

Prerequisites: - Invoice must exist in Lime - Invoice must have actionpublicid (Billecta invoice ID)

Processing: - Validates invoice exists and has Billecta ID - Sends dispute request to Billecta API - Billecta updates invoice status to disputed

Use Case: Debtor contacts you to dispute an invoice; mark it as disputed in Billecta to prevent further collection attempts


Cancel Dispute Invoice

Endpoint: PUT /limepkg-billecta-integration/billecta/cancel-disputed-invoice

Cancel a dispute on an invoice in Billecta. Use this when a disputed invoice is resolved and collection should resume.

Request:

{
    "invoice_id": 1001
}

Success Response (HTTP 200): (empty body)

Error Response (HTTP 404 or 500):

{
    "error_message": "Invoice not found or missing Billecta invoice ID"
}

Prerequisites: - Invoice must exist in Lime - Invoice must have actionpublicid (Billecta invoice ID) - Invoice must have an active dispute

Processing: - Validates invoice exists and has Billecta ID - Sends cancel dispute request to Billecta API - Billecta removes disputed status from invoice

Use Case: Dispute has been resolved with the debtor; resume normal collection


Pause Invoice

Endpoint: PUT /limepkg-billecta-integration/billecta/pause-invoice

Pause an invoice in Billecta to temporarily stop collection activities.

Request:

{
    "invoice_id": 1001
}

Success Response (HTTP 200): (empty body)

Error Response (HTTP 404 or 500):

{
    "error_message": "Invoice not found or missing Billecta invoice ID"
}

Prerequisites: - Invoice must exist in Lime - Invoice must have actionpublicid (Billecta invoice ID)

Processing: - Validates invoice exists and has Billecta ID - Sends pause request to Billecta API - Billecta places invoice on hold (no reminders or escalation)

Use Case: Debtor is in payment negotiation or on a payment plan; pause reminders temporarily


Resume Paused Invoice

Endpoint: PUT /limepkg-billecta-integration/billecta/resume-paused-invoice

Resume collection on a paused invoice in Billecta.

Request:

{
    "invoice_id": 1001
}

Success Response (HTTP 200): (empty body)

Error Response (HTTP 404 or 500):

{
    "error_message": "Invoice not found or missing Billecta invoice ID"
}

Prerequisites: - Invoice must exist in Lime - Invoice must have actionpublicid (Billecta invoice ID) - Invoice must be in paused state

Processing: - Validates invoice exists and has Billecta ID - Sends resume request to Billecta API - Billecta resumes normal collection activities

Use Case: Payment negotiation concluded without settlement; resume collection


Create Reminder Invoice

Endpoint: POST /limepkg-billecta-integration/billecta/create-reminder-invoice

Create and send a reminder invoice in Billecta with customizable fee and payment terms.

Request:

{
    "invoice_action_public_id": "xxxx-xxx-xxxx",
    "delivery_method": "email",
    "reminder_fee": 150.00,
    "currency_code": "SEK",
    "payment_terms_in_days": 14
}

Success Response (HTTP 200):

{}
(Returns empty response body on success from Billecta API)

Error Response (HTTP 500):

{
    "error_message": "Invoice missing ActionPublicId"
}

Parameters: - invoice_action_public_id (required): Billecta invoice ID - delivery_method (required): Delivery method (e.g., email, post) - reminder_fee (required): Late fee amount to add - currency_code (required): Currency code (e.g., SEK) - payment_terms_in_days (required): Payment deadline in days

Prerequisites: - Invoice must exist in Billecta - Invoice must have actionpublicid (Billecta ID) - Creditor must have reminder configuration

Processing: - Validates invoice has Billecta ID - Maps delivery method option key to Billecta format - Constructs reminder invoice payload with fee and terms - Sends API request to Billecta to create and send reminder - Returns Billecta API response

Use Case: Send payment reminder to debtor with late fees and new payment deadline


Send to Debt Collection

Endpoint: POST /limepkg-billecta-integration/billecta/send-to-debt-collection

Escalate an unpaid invoice to debt collection in Billecta.

Request:

{
    "invoice_id": 1001,
    "delivery_method": "email",
    "our_reference": "COLL-001",
    "reason_description": "Invoice overdue 60 days, collection initiated",
    "reason_for_higher_interest": "Dunning process completed"
}

Success Response (HTTP 200): (empty body)

Error Response (HTTP 500):

{
    "error_message": "Invoice not found or missing Billecta invoice ID"
}

Triggered by: Frontend command "Send to Debt Collection"

Prerequisites: - Invoice must exist in Lime - Invoice must have actionpublicid (Billecta invoice ID) - Creditor must be configured in Billecta - Invoice must not already be in debt collection

Processing: - Validates invoice exists and has Billecta ID - Fetches creditor and validates it exists - Maps delivery method from option key to Billecta format - Builds debt collection payload with references and reasons - Sends API request to Billecta to initiate debt collection - Updates invoice with empty error message if successful - Fetches latest invoice data from Billecta to update status - Logs any errors to invoice's billecta_error_message field

Use Case: Invoice collection has failed; escalate to debt collection agency for continued collection efforts


Get Invoice Next Event

Endpoint: GET /limepkg-billecta-integration/billecta/get-invoice-next-event/<invoice_id>

Retrieve the date of the next scheduled event for an invoice.

Response:

{
    "next_event_date": "2025-10-15"
}

Error Response (HTTP 404):

{
    "error_message": "Invoice not found or missing Billecta invoice ID"
}

Prerequisites: - Invoice must exist in Lime - Invoice must have actionpublicid (Billecta invoice ID)

Processing: - Validates invoice has Billecta ID - Fetches invoice details from Billecta - Extracts next event date from Billecta response - Formats date as YYYY-MM-DD - Returns next event date or null if no events scheduled

Use Case: Display when the next collection action will occur for an invoice


Postpone Invoice Next Event

Endpoint: PUT /limepkg-billecta-integration/billecta/invoice-postpone-next-event/

Postpone the next scheduled event for an invoice in Billecta.

Request:

{
    "invoice_id": 1001,
    "postpone_days": 7
}

Response:

{}

Error Response (HTTP 400):

{
    "error_message": "postpone_days must be a positive integer"
}

Prerequisites: - Invoice must exist in Lime - Invoice must have actionpublicid (Billecta invoice ID) - postpone_days must be a positive integer

Processing: - Validates invoice has Billecta ID - Validates postpone_days is positive integer - Requests Billecta to postpone next event - Billecta delays next event by specified number of days

Use Case: Delay collection actions for invoices pending customer payment arrangements


Order Endpoints

Upsert Orders in Billecta

Endpoint: POST /limepkg-billecta-integration/task/upsert-orders-in-billecta

Starts a background task to create or update orders in Billecta.

Request:

{
    "integration_monitor_batch_title": "Upsert orders in Billecta",
    "query_filter": {
        "key": "_id",
        "op": "IN",
        "exp": [1001, 1002, 1003]
    }
}

Processing: - Creates one task per order - Validates debtor, creditor, and article relationships - Processes order rows with their types (standard, package, message) - Links via actionpublicid


Attest Orders in Billecta

Endpoint: POST /limepkg-billecta-integration/task/attest-orders-in-billecta

Starts a background task to officially attest (finalize) orders.

Request:

{
    "integration_monitor_batch_title": "Attest orders in Billecta",
    "query_filter": {
        "key": "_id",
        "op": "IN",
        "exp": [1001, 1002, 1003]
    }
}

Processing: - Creates one task per order - Sends attestation request to Billecta - Orders must be in correct state for attestation - Tracks progress in integration monitor


Upsert & Attest Orders in Billecta

Endpoint: POST /limepkg-billecta-integration/task/upsert-attest-orders-in-billecta

Starts a background task to create/update AND attest orders in one operation.

Request:

{
    "integration_monitor_batch_title": "Upsert & attest orders in Billecta",
    "query_filter": {
        "key": "_id",
        "op": "IN",
        "exp": [1001, 1002, 1003]
    }
}

Processing: - Creates one task per order - Upserts order data first - Immediately attests the order - Ensures debtor exists (creates if needed) - Ensures all articles exist (creates if needed)


Order Row Endpoints

Add Message to Orderrow

Endpoint: POST /limepkg-billecta-integration/add-message-to-orderrow/

Add a message row (note) to an existing order row.

Request:

{
    "orderrow_id": 1001,
    "orderrow_description": "Special handling required"
}

Success Response (HTTP 200): (empty body)

Error Response: Error details with HTTP status code

Processing: - Creates new orderrow of type "Message" - Positions message immediately after target orderrow - Re-sorts all subsequent orderrows - Updates position values


Payment Endpoints

Match Payments

Endpoint: POST /limepkg-billecta-integration/billecta/match-payment/

Link an unmatched payment to its corresponding invoice.

Request:

{
    "payment_billecta_id": "xxxx-xxx-xxxx",
    "invoice_id": 1001
}

Success Response (HTTP 200):

{
    "status_code": 200,
    "status": "The match was successful"
}


Delete Unhandled Payment

Endpoint: POST /limepkg-billecta-integration/billecta/delete-unhandled-payment/

Remove an unhandled payment from Billecta.

Request:

{
    "_id": 1001,
    "bookkeepingaccount": "1501",
    "transactiondate": "2025-09-10"
}

Success Response (HTTP 200):

{
    "status_code": 200
}

Error Response (HTTP 500):

{
    "status_code": 500,
    "error_message": "Error description"
}


Webhook Endpoints

Billecta Webhook Receiver

Endpoint: POST /limepkg-billecta-integration/billecta-webhook-receiver

Receives all webhook events from Billecta.

Behavior: - Validates webhook event type - Routes to appropriate event handler - Returns error if event type not supported - Raises UnsupportedWebhookEvent for unknown events

Webhook Flow: 1. Billecta sends event to endpoint 2. Endpoint validates event signature and format 3. Handler processes the event (creates/updates Lime objects) 4. Returns success (200) or error response 5. If error, Billecta retries up to 5 times over 24 hours


Debt Collection Endpoints

Get Debt Collection Next Event

Endpoint: GET /limepkg-billecta-integration/billecta/get-debtcollection-next-event/<debtcollection_id>

Retrieve the date of the next scheduled event for a debt collection case in Billecta.

Response:

{
    "next_event_date": "2025-10-15"
}

Error Response (HTTP 404):

{
    "error_message": "Debt collection not found in Billecta or missing Billecta ID"
}

Prerequisites: - Debt collection case must exist in Lime - Debt collection case must have actionpublicid (Billecta case ID)

Processing: - Validates debt collection has Billecta ID - Fetches debt collection details from Billecta - Extracts next event date from Billecta response - Formats date as YYYY-MM-DD - Returns next event date or null if no events scheduled

Use Case: Check when the next collection action will occur for a debt collection case


Postpone Debt Collection Next Event

Endpoint: PUT /limepkg-billecta-integration/billecta/postpone-debtcollection-next-event/

Delay the next collection event for a debt collection case in Billecta.

Request:

{
    "debtcollection_id": 1001,
    "postpone_days": 30
}

Success Response (HTTP 200): (empty body)

Error Response (HTTP 400 or 500):

{
    "error_message": "Invalid input or collection case not found"
}

Validation: - postpone_days must be a positive integer > 0 - Debt collection case must exist in Billecta

Processing: - Validates debt collection case exists - Validates postponement duration is valid - Sends postponement request to Billecta API - Billecta delays next event by specified number of days

Use Case: Debtor is in negotiations; postpone next collection action to allow more time


Cancel Debt Collection

Endpoint: PUT /limepkg-billecta-integration/billecta/cancel-debtcollection

Cancel a debt collection case in Billecta.

Request:

{
    "debtcollection_id": 1001
}

Success Response (HTTP 200): (empty body)

Error Response (HTTP 404 or 500):

{
    "error_message": "Error description"
}

Validation: - Debt collection case must exist in Lime CRM - Debt collection case must have a valid actionpublicid in Billecta

Processing: - Validates debt collection case exists - Validates debt collection has actionpublicid - Sends cancellation request to Billecta API via PUT method - Clears error message on success - Updates error message field on failure

Use Case: Debt collection should no longer proceed; cancel the active collection case


Send Debt Collection to Long-term Surveillance

Endpoint: PUT /limepkg-billecta-integration/billecta/send-to-long-term-surveillance

Send a debt collection case to long-term surveillance in Billecta.

Request:

{
    "debtcollection_id": 1001
}

Success Response (HTTP 200): (empty body)

Error Response (HTTP 404 or 500):

{
    "error_message": "Error description"
}

Validation: - Debt collection case must exist in Lime CRM - Debt collection case must have a valid actionpublicid in Billecta

Processing: - Validates debt collection case exists - Validates debt collection has actionpublicid - Sends request to Billecta API via PUT method to /debtcollection/SendToLongTermSurveillance/{actionpublicid} - Clears error message on success - Updates error message field on failure

Use Case: Standard collection procedures exhausted; transition to extended monitoring and occasional collection attempts


Send Debt Collection to Bailiff

Endpoint: PUT /limepkg-billecta-integration/billecta/send-to-bailiff

Send a debt collection case to bailiff (court enforcement) in Billecta. User selects between standard bailiff or combined eviction/bailiff proceedings.

Request:

{
    "debtcollection_id": 1001,
    "bailiff_option": "bailiff"
}

Bailiff Options: - "bailiff" - Standard bailiff enforcement proceedings - "assistance-with-bailiff" - Combined eviction and bailiff proceedings

Success Response (HTTP 200): (empty body)

Error Response (HTTP 400, 404, or 500):

{
    "error_message": "Error description"
}

Validation: - bailiff_option must be either "bailiff" or "assistance-with-bailiff" - Debt collection case must exist in Lime CRM - Debt collection case must have a valid actionpublicid in Billecta

Processing: - Validates bailiff option is valid - Validates debt collection case exists - Validates debt collection has actionpublicid - Routes to appropriate Billecta endpoint based on option: - bailiff/debtcollection/SendToBailiff/{actionpublicid} - assistance-with-bailiff/debtcollection/SendToAssistanceWithBailiff/{actionpublicid} - Sends request via PUT method - Clears error message on success - Updates error message field on failure

Use Case: Legal enforcement required; escalate to court bailiff (Kronofogdemyndigheten) for enforcement or eviction proceedings


Swish Endpoints

Create Swish Payment Request

Endpoint: POST /limepkg-billecta-integration/billecta/swish-request/<actionpublicid>?phone=<phone>&message=<message>

Create a Swish payment request for an invoice in Billecta.

Parameters: - actionpublicid (path): Billecta invoice ID - phone (query): Debtor's phone number (e.g., +46701234567) - message (query): Payment message/description

Success Response (HTTP 201):

{
    "requestid": "f4c2v3d4"
}

Error Response (HTTP 400 or 500):

{
    "error": "INVALID_PHONE_NUMBER",
    "message": "Phone number format invalid"
}

Prerequisites: - Invoice must have valid actionpublicid - Debtor must have valid Swedish phone number - Creditor must have Swish configuration in Billecta

Processing: - Validates invoice ID format - Validates phone number format - Validates message length - Sends Swish request to Billecta - Billecta sends payment request to debtor's phone - Returns Swish request ID for tracking

Use Case: Send immediate payment request via Swish to debtor's mobile phone


Get Swish Request Status

Endpoint: GET /limepkg-billecta-integration/billecta/swish-request/status/<requestid>

Check the status of a previously created Swish payment request.

Response:

{
    "requeststatus": "PAID"
}

Parameters: - requestid (path): Swish request ID returned from Create Swish endpoint

Processing: - Fetches Swish request status from Billecta - Returns the status from Billecta (e.g., CREATED, OPENED, PAID, FAILED) - Returns error message as status if request failed

Use Case: Check whether a Swish payment request has been paid by the debtor


Report Endpoints

Report Creator

Endpoint: POST /limepkg-billecta-integration/billecta/report-creator

Generate a custom report combining data from Lime and Billecta.

Request:

{
    "config_key": "accounts_receivable",
    "limetype": "creditor",
    "idlimeobject": 1001,
    "file_format": "xlsx",
    "date_from": "2025-01-01",
    "date_to": "2025-09-30"
}

Success Response (HTTP 200):

{
    "iddocument": 5042
}

Parameters: - config_key (required): Report configuration key defined in Lime Admin - limetype (required): Lime object type (creditor, etc.) - idlimeobject (required): ID of the object to report on - file_format (optional): pdf or xlsx (default: xlsx) - Additional fields: Custom parameters specific to report configuration

Processing: - Validates report configuration exists - Fetches data from Lime and Billecta - Applies any filters or transformations - Generates report file in requested format - Stores as Lime Document object - Returns document ID

Use Case: Generate custom billing reports for analysis and export


Account Receivables Report

Endpoint: POST /limepkg-billecta-integration/billecta/account-receivables-report

Generate an account receivables (Kundreskontra) report for a creditor.

Request:

{
    "idcreditor": 1001,
    "date": "2025-09-30",
    "exclude_invoices_with_period_outside_date": false,
    "is_period_specific": false,
    "file_format": "xlsx"
}

Success Response (HTTP 200):

{
    "iddocument": 5043
}

Parameters: - idcreditor (required): Creditor ID - date (required): Report date (YYYY-MM-DD format) - exclude_invoices_with_period_outside_date (optional): Exclude invoices with periods outside the report date - is_period_specific (optional): Generate period-specific report - file_format (optional): pdf or xlsx (default: xlsx)

Processing: - Fetches all invoices for creditor up to specified date - Calculates receivables, payments, and balances - Generates report with invoice details and aging summary - Stores as Lime Document - Returns document ID

Use Case: Generate accounts receivable aging report for creditor analysis


Account Reconciliation Report

Endpoint: POST /limepkg-billecta-integration/billecta/account-reconciliation-report

Generate an account reconciliation report comparing Lime and Billecta data for a date range.

Request:

{
    "idcreditor": 1001,
    "from_date": "2025-01-01",
    "to_date": "2025-09-30",
    "account": "1920",
    "date_selection_type": "invoice_date",
    "opening_balance": 10000.50,
    "file_format": "xlsx"
}

Success Response (HTTP 200):

{
    "iddocument": 5044
}

Parameters: - idcreditor (required): Creditor ID - from_date (required): Start date for reconciliation (YYYY-MM-DD format) - to_date (required): End date for reconciliation (YYYY-MM-DD format) - account (required): General ledger account number to reconcile - date_selection_type (required): Date field to filter on (e.g., invoice_date, payment_date) - opening_balance (optional): Opening balance for the period - file_format (optional): pdf or xlsx (default: xlsx)

Processing: - Fetches invoice and payment data from both Lime and Billecta for date range - Compares balances on specified account - Identifies discrepancies and matched records - Generates reconciliation report with variance analysis - Stores as Lime Document - Returns document ID

Use Case: Verify data consistency between Lime and Billecta systems for a specific account and period


Event Log Endpoints

Get Billecta Event Log

Endpoint: GET /limepkg-billecta-integration/billecta/event-log/<limetype>/<id>

Retrieve the integration event log for a specific object from Billecta.

Path Parameters: - limetype: Lime object type (currently supports invoice, debtcollection) - id: Object ID

Response (HTTP 200):

[
    {
        "eventdate": "2025-09-25 14:15:00",
        "title": "Payment Received",
        "content": "Payment received from debtor"
    },
    {
        "eventdate": "2025-09-20 10:30:00",
        "title": "Invoice Attested",
        "content": "Invoice was attested successfully"
    }
]

Error Response (HTTP 404):

{
    "error_message": "Object not found or missing Billecta ID"
}

Prerequisites: - Object must exist in Lime (supported limetypes: invoice, debtcollection) - Object must have actionpublicid (Billecta ID)

Processing: - Fetches event log from Billecta for the object - Formats timestamps as "YYYY-MM-DD HH:MM:SS" - Extracts event title and content from Billecta response - Returns events sorted by date (most recent first)

Use Case: Display event history and audit trail for an invoice or debt collection case

Error Response (HTTP 404):

{
    "error_message": "Object not found in Billecta"
}

Error Response (HTTP 400):

{
    "error_message": "Invalid limetype or ID"
}

Processing: - Validates object exists in Lime - Validates object has Billecta ID (actionpublicid) - Requests event log from Billecta API - Parses and formats event data - Returns full event history with timestamps and details

Use Case: Audit trail of all actions taken on an object in Billecta for troubleshooting or compliance


Webhook Management Endpoints

Retrigger Failed Webhook Events

Endpoint: POST /limepkg-billecta-integration/task/billecta-retrigger-failed-webhooks

Start a background task to retrigger all failed webhook events from Billecta.

Request:

{}

Success Response (HTTP 200):

{
    "task_id": "abc123def456",
    "status": "success"
}

Error Response (HTTP 500):

{
    "error_message": "Error starting retrigger task"
}

Processing: - Sends background task to retrigger failed webhook events - Returns task ID for tracking - Task processes all failed webhooks asynchronously

Use Case: Recover from missed webhook deliveries; manually trigger retry of failed events

Note: Used for development and testing purposes; typically runs on a schedule (nightly)


Handlers

Base Handler

Class: BaseHandler

Purpose: Base class inherited by all other handlers

Initialization: - Creates a Unit of Work for persistence operations - Instantiates BillectaApi for API communication - Sets up logging and error tracking

Common Methods: - Error logging to integration monitor - Object creation and updates - Billecta API request wrapping


Article Handlers

Upsert Articles Handler

Class: UpsertArticlesHandler

Synchronizes articles to Billecta, creating new items or updating existing ones.

Main Methods:

def _upsert_articles_in_billecta(self)
- Get article IDs from query filter - Create integration monitor batch - Spawn one task per article

def upsert_article_in_billecta(self, article_id: int, integration_monitor_log_id: int | None)
- Fetch creditorarticle relations - For each relation, build and send API request - Save Billecta response data (articlepublicid) to creditorarticle - Update integration monitor log status


Delete Articles Handler

Class: DeleteArticlesHandler

Removes articles from Billecta.

Main Methods:

def _delete_articles_in_billecta(self)
- Get article IDs from query filter - Create integration monitor batch - Spawn one task per article

def delete_article_in_billecta(self, article_id: int, integration_monitor_log_id: int | None)
- Fetch creditorarticle relations - For each relation, send delete request to Billecta - Clear articlepublicid from creditorarticle - Update integration monitor log status


Creditor Handlers

Update Creditor Handler

Class: UpdateCreditorHandler

Updates a single creditor in Billecta.

Main Method:

def _update_creditor_in_billecta(self)
- Validate creditor exists in Billecta - Fetch Billecta creditor data (non-Lime-owned fields) - Update Lime creditor object with Billecta data - Build payload from Lime creditor - Send two API requests: creditor update + default config update - Log any errors to creditor's billecta_error_message field


Debtor Handlers

Upsert Debtors Handler

Class: UpsertDebtorsHandler

Synchronizes debtors to Billecta.

Main Methods:

def _upsert_debtors_in_billecta(self)
- Get debtor IDs from query filter - Create integration monitor batch - Spawn one task per debtor

def upsert_debtor_in_billecta(self, debtor_id: int, integration_monitor_log_id: int | None)
- Fetch creditordebtor relations - For each relation, validate creditor exists - Validate debtor has both person and company set - Build payload and send API request - Save debtorpublicid to creditordebtor - Update integration monitor log status


Anonymize Debtors Handler

Class: AnonymizeDebtorsHandler

Removes PII from debtors in Billecta (GDPR compliance).

Main Methods:

def _anonymize_debtors_in_billecta(self)
- Get debtor IDs from query filter - Create integration monitor batch - Spawn one task per debtor

def anonymize_debtor_in_billecta(self, debtor_id: int, integration_monitor_log_id: int | None)
- Fetch creditordebtor relations where debtorpublicid is set - For each relation, send anonymization request - Update integration monitor log status - GDPR-safe deletion of sensitive data


Invoice Handlers

Register Manual Payment Handler

Class: RegisterManualPaymentHandler

Records manual payments in Billecta.

Main Method:

def register_payment(self) -> dict
- Validate invoice exists in Billecta - Build payment payload from request data - Send API request to Billecta - Return response (success or error)


Register Write-Off Payment Handler

Class: RegisterWriteOffPaymentHandler

Records write-off amounts in Billecta.

Main Method:

def register_writeoff_payment(self) -> dict
- Validate invoice exists in Billecta - Build write-off payload - Send API request to Billecta - Return response (success or error)


Credit Invoices Handler

Class: CreditInvoicesHandler

Creates credit notes for invoices in Billecta.

Main Methods:

def _credit_invoices_in_billecta(self)
- Get invoice IDs from query filter - Create integration monitor batch - Spawn one task per invoice

def credit_invoice_in_billecta(self, invoice_id: int, integration_monitor_log_id: int | None)
- Build credit note payload - Send API request to Billecta - Update integration monitor log status


Expired Invoices Handler

Class: ExpiredInvoicesHandler

Sets invoices as expired (scheduled task).

Main Method:

def _set_invoices_as_expired(self)
- Fetch invoices where invoice_expires < today AND invoicestatus IN ("sent", "subpaid") - Batch update invoicestatus to "expired" (batches of 100) - Commit after each batch - Track success/failure counters


Invoice PDF Handler

Class: InvoicePDFHandler

Downloads and manages invoice documents.

Main Methods:

def fetch_invoice_pdf_from_billecta(self) -> bytes
- Validate invoice has Billecta ID (actionpublicid) - Request PDF from Billecta API - Return binary file content

def save_invoice_pdf(self, file_content: bytes)
- Create Lime File object from content - Attach to invoice's invoice_pdf field - Update file metadata


Update Invoice Handler

Class: UpdateInvoiceWithBillectaDataHandler

Fetches latest invoice data from Billecta and updates Lime.

Main Method:

def update_invoice_in_lime(self)
- Validate invoice has Billecta ID - Fetch latest invoice data from Billecta API - Update invoice object with Billecta data (status, amounts, dates) - Commit changes


Use Credit on Invoice Handler

Class: UseCreditOnInvoiceHandler

Applies credit from one invoice to another.

Main Method:

def use_credit_on_invoice(self) -> dict
- Validate both invoices exist in Billecta - Build payload with both invoice IDs - Send API request to Billecta - Return response (success or error)


Invoice Dispute Handler

Class: InvoiceDisputeHandler

Manages invoice dispute status in Billecta.

Main Methods:

def dispute_invoice_in_billecta(self)
- Validates invoice has Billecta ID (actionpublicid) - Sends dispute request to Billecta API - Updates invoice with empty error message if successful - Fetches and updates invoice data from Billecta - Logs errors to invoice's billecta_error_message field

def cancel_dispute_in_billecta(self)
- Validates invoice has Billecta ID - Sends cancel dispute request to Billecta API - Updates invoice status to remove dispute - Fetches latest invoice data from Billecta - Logs errors to billecta_error_message field

Use Case: Mark invoices as disputed when debtor contests, or cancel dispute when resolved


Invoice Pause Handler

Class: InvoicePauseHandler

Manages invoice pause status in Billecta.

Main Methods:

def pause_invoice_in_billecta(self)
- Validates invoice has Billecta ID - Sends pause request to Billecta API - Pauses all collection activities - Updates invoice with empty error message if successful - Logs errors to billecta_error_message field

def resume_paused_invoice_in_billecta(self)
- Validates invoice has Billecta ID - Sends resume request to Billecta API - Resumes normal collection workflow - Fetches latest invoice data from Billecta - Logs errors to billecta_error_message field

Use Case: Temporarily pause collection during negotiations, then resume when settled


Invoice Next Event Handler

Class: InvoiceNextEventHandler

Retrieves the next scheduled event date for an invoice.

Main Method:

def get_next_event_date(self) -> dict
- Validates invoice has Billecta ID (actionpublicid) - Requests invoice details from Billecta API - Extracts next event date from Billecta response - Formats date as YYYY-MM-DD - Returns {"next_event_date": "YYYY-MM-DD"} or None if no events scheduled - Handles errors gracefully

Use Case: Display when the next collection action will occur


Invoice Postpone Handler

Class: InvoicePostponeHandler

Delays the next collection event for an invoice.

Main Method:

def postpone_next_event_in_billecta(self, postpone_days: int)
- Validates invoice has Billecta ID - Validates postponement duration is positive - Sends postponement request to Billecta API - Updates invoice with empty error message if successful - Logs errors to billecta_error_message field

Use Case: Give debtor additional time; postpone reminders and escalations


Create Reminder Invoice Handler

Class: CreateReminderInvoiceHandler

Creates reminder invoices in Billecta.

Main Method:

def create_reminder_invoice(self) -> dict
- Validates invoice has Billecta ID (actionpublicid) - Validates reminder fee and payment terms are provided - Maps delivery method from option key to Billecta format - Builds payload with fee, currency, and payment terms - Sends API request to Billecta to create and send reminder - Returns response from Billecta API - Logs errors and raises exceptions on failure

Use Case: Send payment reminder with late fees and extended payment terms


Expired Invoices Handler

Class: ExpiredInvoicesHandler

Sets invoices as expired when they pass their due date.

Main Method:

def _set_invoices_as_expired(self)
- Fetches invoices where: - invoice_expires < today - invoicestatus IN ("sent", "subpaid") - Batch updates invoicestatus to "expired" (100 items per batch) - Commits after each batch - Tracks success and failure counters - Logs summary of expired invoices

Schedule: Daily (typically at night)
Purpose: Automatically mark overdue unpaid invoices as expired


Update Invoice With Billecta Data Handler

Class: UpdateInvoiceWithBillectaDataHandler

Syncs latest invoice data from Billecta to Lime.

Main Method:

def update_invoice_in_lime(self)
- Validates invoice has Billecta ID (actionpublicid) - Requests latest invoice data from Billecta API - Updates Lime invoice object with Billecta data: - Invoice status - Payment amounts and balances - Payment dates - Dispute status - Other status fields - Commits changes to database - Logs any errors

Use Case: Triggered by webhooks to keep Lime invoices synchronized with Billecta state


Send to Debt Collection Handler

Class: SendToDebtCollectionHandler

Escalates invoices to debt collection in Billecta.

Main Method:

def send_invoice_to_debt_collection(self)
- Validates invoice exists and has Billecta ID (actionpublicid) - Validates creditor exists and is valid - Fetches creditor object - Builds debt collection payload: - Source invoice ID - Delivery method (email, SMS, etc.) - Custom reference - Reason description - Interest rate reason - Other collection parameters - Sends API request to Billecta - Updates invoice with empty error message if successful - Fetches latest invoice data from Billecta - Logs errors to invoice's billecta_error_message field

Use Case: Escalate unpaid invoices to debt collection agency for continued collection


Debt Collection Handlers

Debt Collection Postpone Handler

Class: DebtCollectionPostponeHandler

Delays the next collection event for a debt collection case.

Main Method:

def postpone_next_event_in_billecta(self)
- Validates debt collection has Billecta ID (actionpublicid) - Validates postponement duration is a positive integer - Sends postponement request to Billecta API - Updates debt collection with empty error message if successful - Logs errors to billecta_error_message field

Use Case: Debtor is negotiating payment; postpone collection actions to allow more time


Cancel Debt Collection Handler

Class: CancelDebtCollectionHandler

Cancels an active debt collection case in Billecta.

Main Method:

def cancel_debtcollection_in_billecta(self)
- Validates debt collection has Billecta ID (actionpublicid) - Sends cancellation request to Billecta API via PUT method to /debtcollection/cancel/{actionpublicid} - Updates debt collection with empty error message if successful - Logs errors to billecta_error_message field

Use Case: Debt collection should no longer proceed; terminate active collection case


Debt Collection Next Event Handler

Class: DebtCollectionNextEventHandler

Retrieves the next scheduled event date for a debt collection case.

Main Method:

def get_next_event_date(self) -> dict
- Validates debt collection has Billecta ID (actionpublicid) - Requests debt collection details from Billecta API - Extracts next event date from Billecta response - Formats date as YYYY-MM-DD - Returns {"next_event_date": "YYYY-MM-DD"} or None if no events scheduled - Handles errors gracefully

Use Case: Display when the next collection action will occur for a debt collection case


Send to Long-term Surveillance Handler

Class: SendToLongTermSurveillanceHandler

Transitions a debt collection case to long-term surveillance in Billecta.

Main Method:

def send_to_long_term_surveillance_in_billecta(self)
- Validates debt collection has Billecta ID (actionpublicid) - Sends request to Billecta API via PUT method to /debtcollection/SendToLongTermSurveillance/{actionpublicid} - Updates debt collection with empty error message if successful - Logs errors to billecta_error_message field

Use Case: Standard collection procedures exhausted; transition to extended monitoring with occasional collection attempts


Send to Bailiff Handler

Class: SendToBailiffHandler

Escalates a debt collection case to court bailiff (Kronofogdemyndigheten) in Billecta.

Main Method:

def send_to_bailiff_in_billecta(self)
- Validates debt collection has Billecta ID (actionpublicid) - Routes to appropriate Billecta endpoint based on bailiff_option parameter: - "bailiff"/debtcollection/SendToBailiff/{actionpublicid} - "assistance-with-bailiff"/debtcollection/SendToAssistanceWithBailiff/{actionpublicid} - Sends request to Billecta API via PUT method - Updates debt collection with empty error message if successful - Logs errors to billecta_error_message field

Parameters: - bailiff_option (str): Either "bailiff" or "assistance-with-bailiff" - "bailiff" - Standard court enforcement proceedings - "assistance-with-bailiff" - Combined eviction and court enforcement

Use Case: Legal enforcement required; escalate to court bailiff for enforcement or eviction proceedings


Order Handlers

Attest Orders Handler

Class: AttestOrdersHandler

Officially attests (finalizes) orders in Billecta.

Main Methods:

def _attest_orders_in_billecta(self)
- Get order IDs from query filter - Create integration monitor batch - Spawn one task per order

def attest_order_in_billecta(self, order_id: int, integration_monitor_log_id: int | None)
- Build attestation payload - Send API request to Billecta - Update integration monitor log status


Upsert & Attest Orders Handler

Class: UpsertAttestOrdersHandler

Creates/updates orders and optionally attests them.

Main Methods:

def _upsert_attest_orders_in_billecta(self)
- Get order IDs from query filter - Create integration monitor batch - Spawn one task per order

def upsert_attest_order_in_billecta(self, order_id: int, integration_monitor_log_id: int | None)
- Validate order has debtor and creditor - Validate debtor exists in Billecta (create if needed) - Validate articles exist in Billecta (create if needed) - Build order payload with all order rows - Send API request to Billecta - If attest=True, also send attestation request - Update integration monitor log status


Delete Orders Handler

Class: DeleteOrdersHandler

Removes orders from Billecta.

Main Method:

def delete_order_in_billecta(self, order_id: int, integration_monitor_log_id: int | None)
- Fetches order object - Validates order has Billecta ID (actionpublicid) - Sends delete request to Billecta API - Clears actionpublicid from order object - Updates integration monitor log status - Logs any errors

Note: Delete is typically not recommended for orders already sent to Billecta; cancellation may be more appropriate.


Verification Handler

Class: VerificationHandler

Verifies order data consistency and integrity (internal use).

Main Method:

def verify_order_data(self, order_id: int)
- Validates order structure and required fields - Verifies order rows are properly configured - Checks debtor and article relationships - Validates amounts and calculations - Returns verification status and any errors

Note: This handler is primarily used internally for data validation and quality assurance.


Order Row Handlers

Add Message to Orderrow Handler

Class: AddMessageToOrderrowHandler

Adds message rows to orders.

Main Method:

def add_message_to_orderrow(self) -> tuple[dict, int] | None
- Create new orderrow with type "Message" - Set position to right after target orderrow - Update position for all subsequent orderrows - Return success response with new orderrow ID


Payment Handlers

Delete Unhandled Payment Handler

Class: DeleteUnhandledPaymentHandler

Removes unhandled payments from Billecta.

Main Method:

def delete_payment(self) -> dict
- Validates that payment has a paymentreferenceid - Sends DELETE request to Billecta API with payment ID, bookkeeping account, and transaction date - Updates payment status to "Deleted" on success - Returns response with status code (HTTP 200 on success, HTTP 500 on error)

Requirements: - Payment object must exist in Lime CRM - Payment must have a valid paymentreferenceid (Billecta payment ID)

Error Handling: - Raises PaymentMissingPaymentReferenceId if payment lacks paymentreferenceid - Returns HTTP 500 with error message if API call fails - Logs exceptions for debugging


Match Payment Handler

Class: MatchPaymentHandler

Links unmatched payments to invoices.

Main Method:

def match_payment(self, payment_billecta_id: str, invoice_billecta_id: str, creditor_billecta_id: str) -> dict
- Build payload with payment and invoice IDs - Send match request to Billecta API - Return response (success or error)


Webhook Event Handlers

Autogiro Webhook Event Handler

Class: AutogiroWebhookEventHandler

Processes autogiro-related webhook events.

Supported Events: - AutogiroApprovalFailed - debtor approval failed - AutogiroApprovalChanged - debtor approval status changed - AutogiroWithdrawalFailedOnInvoice - invoice withdrawal failed - AutogiroWithdrawalRenewedOnInvoice - invoice withdrawal renewed

Main Methods:

def _update_autogiro_on_creditordebtor(self)
Updates autogiro settings on creditordebtor

def _update_autogiro_on_invoice(self)
Updates autogiro event status on invoice


Debtor Webhook Event Handler

Class: DebtorWebhookEventHandler

Processes debtor-related webhook events.

Supported Events: - DebtorUpdated - debtor data changed in Billecta

Main Method:

def _update_debtor_in_lime(self)
- Validate debtor exists in Lime - Update debtor object with Billecta data - Log errors to billecta_error_message field


Invoice Action Webhook Event Handler

Class: InvoiceActionWebhookEventHandler

Processes invoice state change events.

Supported State Changes: - Attested - invoice finalized - InvoiceSent - invoice sent to customer - Completed - invoice paid/closed

Main Methods:

def _upsert_invoice_as_attested(self)
- Create/update invoice with attested status - Handle credit invoices and link to originals - Update order status if credit invoice

def _upsert_invoice_as_sent(self)
- Create/update invoice with sent status - Update invoice_sent_date

def _update_invoice_as_paid(self)
- Update invoice with paid status - Set paid_date and invoice_balance - Update order status to completed


Invoice Payment Webhook Event Handler

Class: InvoicePaymentWebhookEventHandler

Processes payment-related events.

Supported Events: - InvoicePaymentReceived - payment received - AmountWrittenOffOnInvoice - write-off recorded - AmountCreditedOnInvoice - credit recorded (fires twice: once for the debit invoice with ActionType=InvoiceAction, once for the credit invoice with ActionType=CreditInvoiceAction)

Main Method:

def _upsert_invoice_payment_in_lime(self)
- Create/update payment object in Lime - Link payment to invoice using ActionPublicId or OCR - Trigger task to fetch latest invoice data from Billecta - Skip overpayments (handled separately)


Overpayment Webhook Event Handler

Class: OverpaymentWebhookEventHandler

Processes overpayment events.

Supported Events: - Overpayment - payment exceeds invoice amount - OverpaymentMatchedToInvoice - overpayment applied to another invoice

Main Methods:

def _upsert_invoice_payment_in_lime(self)
- Create/update overpayment in Lime - Link to original invoice if available

def _match_overpayment_to_invoice_in_lime(self)
- Find existing overpayment - Link to new invoice it was applied to - Update status to "Used on Invoice"


Unmatched Payment Webhook Event Handler

Class: UnmatchedPaymentWebhookEventHandler

Processes unmatched payment events.

Supported Events: - UnmatchedPayment - payment without invoice link

Main Method:

def _unmatched_payment_webhook_event_handler(self)
- Match payment by UnhandledPaymentPublicId - Create/update payment in Lime - Link creditor and creditordebtor if provided - Set paymentstatus to "unmatched"


Reminder Invoice Webhook Event Handler

Class: ReminderInvoiceWebhookEventHandler

Processes reminder invoice creation events.

Supported Events: - ReminderInvoiceActionCreated - reminder invoice created

Main Method:

def _create_or_update_reminder_invoice(self, webhook_reminder_invoice: dict)
- Create/update reminder invoice in Lime - Link to source invoice - Raise exception if source invoice not found


Retrigger Failed Webhooks Handler

Class: RetriggerFailedWebhooksHandler

Manages daily webhook retry processing.

Purpose: Re-send failed webhooks from the last 48 hours for each creditor

Main Method:

def retrigger_failed_webhook_events_for_creditor_main(self, creditor_id: int, integration_monitor_log_id: int | None = None)
- Request Billecta to re-send failed webhooks for creditor - Log result to integration monitor - Returns count of webhooks resent


Debt Collection Handlers

Debt Collection Next Event Handler

Class: DebtCollectionNextEventHandler

Retrieves the next scheduled event date for a debt collection case.

Main Method:

def get_next_event_date(self) -> dict
- Validates debt collection case has Billecta ID - Requests next event information from Billecta API - Returns event date and event type - Handles errors gracefully

Use Case: Check when the next collection action will occur


Debt Collection Postpone Handler

Class: DebtCollectionPostponeHandler

Delays the next collection event for a debt collection case.

Main Method:

def postpone_next_event_in_billecta(self)
- Validates debt collection case has Billecta ID - Validates postponement duration is positive - Sends postponement request to Billecta API - Updates debt collection object with empty error message if successful - Logs errors to object's billecta_error_message field

Use Case: Debtor is in negotiations; delay next collection action


Cancel Debt Collection Handler

Class: CancelDebtcollectionHandler

Cancels an active debt collection case in Billecta.

Main Method:

def cancel_debtcollection_in_billecta(self)
- Validates debt collection case has valid actionpublicid (Billecta ID) - Sends cancellation request to Billecta API via PUT method - Clears error message on success - Logs and re-raises exceptions on failure

Requirements: - Debt collection object must exist in Lime CRM - Debt collection must have a valid actionpublicid (Billecta public ID)

Error Handling: - Raises DebtCollectionMissingActionPublicId if debt collection lacks actionpublicid - Catches and re-raises exceptions after updating error message field - Logs exceptions for debugging

Use Case: Debt collection should no longer proceed; cancel the active collection case


Debt Collection Webhook Event Handler

Class: DebtCollectionWebhookEventHandler

Processes webhook events related to debt collection cases.

Main Methods:

def handle_debtcollection_event(self, event_data: dict)
- Routes event to appropriate handler based on event type - Supported events: - DebtCollectionCaseCreated - New case created - DebtCollectionEventOccurred - Collection action taken - DebtCollectionCaseResolved - Case closed/resolved - DebtCollectionPaymentReceived - Payment received

Processing: - Creates/updates debt collection object in Lime - Links to related invoice or debtor - Updates case status - Logs event details

Use Case: Track debt collection case status and events from Billecta


Report Handlers

Report Base Handler

Class: ReportBaseHandler

Base class for all report generation handlers.

Main Methods:

def create_report(self, file_format: str = "xlsx", **kwargs) -> LimeObject
- Fetches data from Lime and Billecta - Applies filters and transformations - Generates report in requested format (pdf/xlsx) - Creates Lime Document object - Returns document object

def _fetch_report_data(self) -> dict
- Retrieves report data from configured sources - Applies any date ranges or filters - Returns structured data for report generation


Account Receivables Handler

Class: AccountReceivablesHandler

Generates account receivables (Kundreskontra) reports.

Main Method:

def create_account_receivables_data_report(
    self,
    date: str,
    exclude_invoices_with_period_outside_date: bool = False,
    is_period_specific: bool = False,
    file_format: str = "xlsx"
) -> LimeObject
- Fetches invoices for creditor up to specified date - Calculates: - Total invoiced amounts - Payments received - Outstanding balances - Aging of receivables - Generates report with invoice details and summary - Creates and returns Lime Document

Use Case: Generate accounts receivable aging reports for analysis


Account Reconciliation Handler

Class: AccountReconciliationHandler

Generates account reconciliation reports comparing Lime and Billecta.

Main Method:

def create_account_reconciliation_report(
    self,
    date: str,
    file_format: str = "xlsx"
) -> LimeObject
- Fetches invoice data from both Lime and Billecta - Compares balances and payment status - Identifies discrepancies: - Invoices in Lime but not Billecta - Invoices in Billecta but not Lime - Amount/status mismatches - Generates reconciliation report with variance analysis - Creates and returns Lime Document

Use Case: Verify data consistency and identify synchronization issues


Event Log Handlers

Billecta Event Log Handler

Class: BillectaEventLogHandler

Retrieves integration event logs from Billecta.

Main Method:

def get_billecta_event_log(self) -> dict
- Validates object exists in Lime and has Billecta ID - Requests event log from Billecta API - Parses and formats event data: - Event types and timestamps - Event status (success/error) - Event descriptions and details - Returns formatted event history

Supported Events: - Invoice events (Attested, Sent, Paid, etc.) - Payment events (Received, Failed, etc.) - Debtor events (Updated, Anonymized, etc.) - Order events (Created, Attested, etc.) - All other Billecta transaction events

Use Case: Audit trail and troubleshooting of object synchronization


Extended Webhook Handlers

Retrigger Failed Webhook Events Handler

Class: RetriggerFailedWebhookEventsHandler

Manages retry of failed webhook deliveries.

Main Method:

def retrigger_failed_webhook_events_for_creditor_main(self, creditor_id: int, integration_monitor_log_id: int | None = None)
- Requests Billecta to resend failed webhooks - Scope: Last 48 hours of failed events - Filters by creditor - Logs resend result to integration monitor - Returns count of webhooks resent

Schedule: Daily (typically at night, 03:00 UTC)
Purpose: Recover from missed webhook deliveries; ensure eventual processing

Use Case: Automatic recovery mechanism for failed webhook deliveries between Billecta and Lime


Integration Monitor Handler

Class: IntegrationMonitorHandler

Manages integration_monitor_batch and integration_monitor_log objects.

Functions: - Create batch objects for tracking bulk operations - Create log objects for individual operation tracking - Update log status (ok, error, running, donewitherror) - Calculate batch completion status


Tasks

Article Tasks

Upsert Articles in Billecta (Main)

@task
def upsert_articles_in_billecta_main(app: LimeApplication, articles_payload: dict)
  • Processes multiple articles
  • Creates one subtask per article
  • Tracks via integration monitor

Upsert Single Article

@task
def upsert_single_article_in_billecta_main(
    app: LimeApplication,
    article_id: str,
    integration_monitor_log_id: int | None = None
)
  • Upserts single article
  • For each creditor, sends API request
  • Updates creditorarticle with response data

Delete Articles in Billecta (Main)

@task
def delete_articles_in_billecta_main(app: LimeApplication, articles_payload: dict)
  • Processes multiple articles for deletion
  • Creates one subtask per article
  • Tracks via integration monitor

Delete Single Article

@task
def delete_single_article_in_billecta_main(
    app: LimeApplication,
    article_id: str,
    integration_monitor_log_id: int | None = None
)
  • Deletes single article from Billecta
  • For each creditor, sends delete request
  • Clears creditorarticle data

Creditor Tasks

Update Creditor in Billecta

@task
def update_creditor_in_billecta_main(app: LimeApplication, creditor_payload: dict)
  • Updates single creditor
  • Processes creditor via handler
  • Returns result to caller

Debtor Tasks

Upsert Debtors in Billecta (Main)

@task
def upsert_debtors_in_billecta_main(app: LimeApplication, debtors_payload: dict)
  • Processes multiple debtors
  • Creates one subtask per debtor

Upsert Single Debtor

@task
def upsert_single_debtor_in_billecta_main(
    app: LimeApplication,
    debtor_id: str,
    integration_monitor_log_id: int | None = None
)
  • Upserts single debtor
  • For each creditor, sends API request
  • Updates creditordebtor with response data

Anonymize Debtors in Billecta (Main)

@task
def anonymize_debtors_in_billecta_main(app: LimeApplication, debtors_payload: dict)
  • Processes multiple debtors for anonymization
  • Creates one subtask per debtor

Anonymize Single Debtor

@task
def anonymize_single_debtor_in_billecta_main(
    app: LimeApplication,
    debtor_id: str,
    integration_monitor_log_id: int | None = None
)
  • Anonymizes single debtor in Billecta
  • For each creditor relation, sends request
  • Updates integration monitor

Invoice Tasks

Credit Invoices in Billecta (Main)

@task
def credit_invoices_in_billecta_main(app: LimeApplication, invoices_payload: dict)
  • Processes multiple invoices
  • Creates one subtask per invoice

Credit Single Invoice

@task
def credit_single_invoice_in_billecta_main(
    app: LimeApplication,
    invoice_id: str,
    integration_monitor_log_id: int | None = None
)
  • Creates credit note for single invoice
  • Sends API request to Billecta
  • Updates integration monitor

Set Invoices As Expired (Scheduled)

@task
def set_invoices_as_expired(app: LimeApplication)

Schedule: Daily (typically at night)
Purpose: Mark overdue unpaid invoices as expired

  • Fetches invoices with invoice_expires < today and status "sent" or "subpaid"
  • Updates invoicestatus to "expired"
  • Processes in batches of 100
  • Tracks success/failure counters

Update Invoice in Lime with Billecta Data

@task
def update_invoice_in_lime_with_billecta_invoice_data(
    app: LimeApplication,
    invoice_id: int
)

Triggered: After payment webhook processing

  • Fetches latest invoice data from Billecta
  • Updates Lime invoice with Billecta data
  • Syncs status, amounts, and dates

Order Tasks

Upsert Orders in Billecta (Main)

@task
def upsert_orders_in_billecta_main(app: LimeApplication, orders_payload: dict)
  • Processes multiple orders
  • Creates one subtask per order
  • Returns tracking info to caller

Upsert & Attest Orders in Billecta (Main)

@task
def upsert_attest_orders_in_billecta_main(app: LimeApplication, orders_payload: dict)
  • Processes multiple orders
  • Creates one subtask per order with attest=True
  • Returns tracking info to caller

Upsert & Attest Single Order

@task
def upsert_attest_single_order_in_billecta_main(
    app: LimeApplication,
    order_id: str,
    attest: bool,
    integration_monitor_log_id: int | None = None
)
  • Upserts single order
  • Optionally attests if attest=True
  • Validates and creates debtors/articles as needed
  • Updates integration monitor

Attest Orders in Billecta (Main)

@task
def attest_orders_in_billecta_main(app: LimeApplication, orders_payload: dict)
  • Processes multiple orders for attestation
  • Creates one subtask per order

Attest Single Order

@task
def attest_single_order_in_billecta_main(
    app: LimeApplication,
    order_id: str,
    integration_monitor_log_id: int | None = None
)
  • Attests single order in Billecta
  • Validates order is in correct state
  • Updates integration monitor

Billecta Webhook Tasks

Retrigger Failed Webhook Events (Scheduled)

@task
def retrigger_failed_webhook_events_in_billecta_main(app: LimeApplication)

Schedule: Daily (typically at night)
Purpose: Re-trigger failed webhooks from last 48 hours

  • Creates one task per creditor
  • Each task requests Billecta to resend failed webhooks
  • Ensures eventual webhook delivery

Retrigger Failed Webhooks for Creditor

@task
def retrigger_failed_webhook_events_for_creditor_main(
    app: LimeApplication,
    creditor_id: int,
    integration_monitor_log_id: int | None = None
)
  • Requests Billecta to resend failed webhooks for creditor
  • Logs result to integration monitor
  • Returns count of webhooks resent

Integration Monitor Tasks

Finish Running Batches (Scheduled)

@task
def finish_running_imb(app: LimeApplication)

Schedule: Every 5 minutes (06:00-23:00 daily)
Purpose: Finalize completed integration monitor batches

Logic: - Fetches running batches - Checks if all child logs are completed - Sets batch status: - ok = all logs successful - donewitherror = any logs failed - Sets endtime to latest log's update time


Finish Running Batches (Nightly)

@task
def finish_running_imb_nightly(app: LimeApplication)

Schedule: 03:00 UTC daily
Purpose: Force-complete stalled batches

Logic: - Fetches all running batches - For each running log, check actual task status via task API - Update log status based on actual task state - Apply same completion logic as finish_running_imb - Prevents batches from remaining stuck in running state


Webhook Events

Supported Billecta Webhook Events

The integration supports the following webhook events from Billecta. See Billecta API documentation for full event details.

Event Type Handler Purpose
DebtorUpdated Debtor DebtorWebhookEventHandler Sync debtor changes
InvoiceActionAttested Invoice InvoiceActionWebhookEventHandler Update invoice as attested
InvoiceActionStateChanged Invoice InvoiceActionWebhookEventHandler Track invoice state (sent, completed)
InvoicePaymentReceived Payment InvoicePaymentWebhookEventHandler Record invoice payment
ReminderInvoiceActionCreated Invoice ReminderInvoiceWebhookEventHandler Create reminder invoice
Overpayment Payment OverpaymentWebhookEventHandler Sync overpayment
OverpaymentMatchedToInvoice Payment OverpaymentWebhookEventHandler Link overpayment to invoice
UnmatchedPayment Payment UnmatchedPaymentWebhookEventHandler Create unmatched payment
AmountWrittenOffOnInvoice Payment InvoicePaymentWebhookEventHandler Record write-off
AmountCreditedOnInvoice Payment InvoicePaymentWebhookEventHandler Record credit (debit & credit invoice)
AutogiroApprovalFailed Debtor AutogiroWebhookEventHandler Track autogiro approval failure
AutogiroApprovalChanged Debtor AutogiroWebhookEventHandler Update autogiro approval
AutogiroWithdrawalFailedOnInvoice Invoice AutogiroWebhookEventHandler Track autogiro withdrawal failure
AutogiroWithdrawalRenewedOnInvoice Invoice AutogiroWebhookEventHandler Update autogiro withdrawal

Webhook Processing Flow

  1. Receipt: Billecta sends webhook to integration endpoint
  2. Validation: Endpoint verifies webhook format and signature
  3. Routing: Endpoint identifies event type and selects handler
  4. Processing: Handler processes event and updates Lime objects
  5. Response: Endpoint returns 200 OK to Billecta
  6. Retries: If error returned, Billecta retries up to 5 times over 24 hours
  7. Daily Reconciliation: Nightly task re-triggers failed webhooks from last 48 hours

Error Handling

If webhook processing fails: - Handler logs error to object's billecta_error_message field - Error recorded in integration monitor - Billecta receives error response and retries automatically - Nightly reconciliation task may re-trigger manually