To integrate the code from the firebed/aade-mydata repository (version 5.x) into the existing mydata module for Dolibarr, you will need to carefully plan the integration to ensure compatibility with Dolibarr's architecture, the existing mydata module functionality, and the AADE MyDATA API. Below is a step-by-step guide to achieve this:
1. Understand the firebed/aade-mydata Repository
The firebed/aade-mydata repository provides a PHP library for interacting with the AADE MyDATA API. It offers a well-defined structure for sending invoices, querying data, and handling responses in compliance with the AADE MyDATA specifications.
Key features of firebed/aade-mydata:
Invoice creation and serialization: It structures data into XML for the AADE MyDATA API.
API communication: It handles POST requests to the API endpoints.
Error handling: Manages responses and error codes.
Simplified models: Provides classes for invoices, counterparties, and other entities.
2. Identify Integration Points
In the mydata module, the integration points for firebed/aade-mydata are primarily in:
Invoice processing logic: Replace or enhance the existing XML generation in mydata.php.
API communication: Replace the HTTP_Request2 implementation with firebed/aade-mydata's library for sending and receiving data.
Error handling: Leverage firebed/aade-mydata's error-handling mechanism to simplify the code.
3. Add firebed/aade-mydata as a Dependency
a. Install via Composer
Navigate to the mydata module directory.
Add firebed/aade-mydata to the project using Composer:
bash
composer require firebed/aade-mydata:^5.0
Ensure the vendor directory is included in your Dolibarr installation.
b. Autoload the Library
Ensure the autoload.php file generated by Composer is loaded in mydata.php:
The current mydata.php script manually generates XML strings for invoices. Replace this with firebed/aade-mydata's Invoice class to construct invoices programmatically.
Use firebed/aade-mydata's error-handling features to manage API responses. Modify the existing error-handling logic in mydata.php to process errors returned by the library:
The firebed/aade-mydata library may require specific configuration settings. Update the setup.php file in the mydata module to support additional settings, such as:
AADE_MYDATA_BASE_URL (for switching between production and development environments).
Credentials (aade-user-id and Ocp-Apim-Subscription-Key).
8. Test the Integration
Thoroughly test the module after integration:
Send invoices to the AADE API in both development and production environments.
Validate the AADE API responses for success and error scenarios.
Check the database updates (e.g., mydata_reply and mydata_check fields).
9. Update Documentation
Update the README.md file of the mydata module to include:
Dependencies (e.g., firebed/aade-mydata).
Configuration instructions for the new integration.
Final Remarks
The integration of firebed/aade-mydata simplifies the mydata module by leveraging a dedicated library for XML generation and API communication. It reduces custom code complexity, ensures compliance with AADE specifications, and provides a more maintainable solution for handling MyDATA invoices.
Here's the complete replacement for the mydata.php file in the mydata module using the firebed/aade-mydata library. This code replaces the existing logic with the library's features, including invoice creation, XML generation, API communication, and error handling.
Revised mydata.php
php
<?php
// Include necessary libraries
require_once DOL_DOCUMENT_ROOT . '/custom/mydata/vendor/autoload.php'; // Autoload for firebed/aade-mydata
require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; // Dolibarr utilities
use Firebed\AadeMyData\Http\MyDataClient;
use Firebed\AadeMyData\Models\Invoice;
use Firebed\AadeMyData\Models\Issuer;
use Firebed\AadeMyData\Models\Counterpart;
use Firebed\AadeMyData\Models\InvoiceDetails;
// Database and configuration
$con = mysqli_connect($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name);
$con->set_charset("utf8mb4");
if ($con->connect_errno) {
printf("Database connection failed: %s\n", $con->connect_error);
exit();
}
// Determine the API endpoint (development or production)
$mydataBaseURL = MYDATA_DEV ? MyDataClient::BASE_URL_DEV : MyDataClient::BASE_URL_PROD;
// Initialize the MyDATA client
$client = new MyDataClient(
getDolGlobalString('MYDATA_AADE_USER'),
getDolGlobalString('MYDATA_AADE_KEY'),
$mydataBaseURL
);
// Query to fetch invoices that need to be sent to MyDATA
$query = "SELECT
f.rowid, f.datef as issue_date, f.total_ttc, f.multicurrency_total_ht as net_value,
f.multicurrency_total_tva as vat_amount, f.multicurrency_total_ttc as gross_value,
[Redacted Person] as customer_name, s.tva_intra as customer_vat,
c.code as country_code,
fe.mydata_type, fe.mydata_reply, fe.mydata_check
FROM {$dolibarr_main_db_prefix}facture f
LEFT JOIN {$dolibarr_main_db_prefix}societe s ON s.rowid = f.fk_soc
LEFT JOIN {$dolibarr_main_db_prefix}c_country c ON c.rowid = s.fk_pays
LEFT JOIN {$dolibarr_main_db_prefix}facture_extrafields fe ON fe.fk_object = f.rowid
WHERE f.fk_statut IN (1, 2, 3, 4, 5)
AND COALESCE(fe.mydata_check, 0) = 0
ORDER BY f.datef DESC";
$result = mysqli_query($con, $query) or trigger_error("Query Failed! SQL: $query - Error: " . mysqli_error($con), E_USER_ERROR);
// Process each invoice
while ($row = $result->fetch_assoc()) {
// Extract invoice data
$invoiceId = $row['rowid'];
$issueDate = $row['issue_date'];
$netValue = abs(number_format($row['net_value'], 2, '.', ''));
$vatAmount = abs(number_format($row['vat_amount'], 2, '.', ''));
$grossValue = abs(number_format($row['gross_value'], 2, '.', ''));
$customerName = htmlspecialchars($row['customer_name'], ENT_QUOTES, 'UTF-8');
$customerVAT = $row['customer_vat'];
$countryCode = $row['country_code'] ?? 'GR'; // Default to Greece if country is missing
$mydataType = $row['mydata_type'];
// Determine the invoice type (e.g., 1.1 for sales, 2.1 for services, etc.)
switch ($mydataType) {
case 0: $invoiceType = '1.1'; break; // Sales Invoice
case 1: $invoiceType = '2.1'; break; // Service Invoice
default: $invoiceType = '1.1'; break; // Default to Sales Invoice
}
// Create the invoice object
$invoice = new Invoice();
$invoice->setIssuer(new Issuer(preg_replace('/\D/', '', getDolGlobalString('MAIN_INFO_TVAINTRA')), 'GR', '0'));
$invoice->setCounterpart(new Counterpart(preg_replace('/\D/', '', $customerVAT), $countryCode, '0', $customerName));
$invoice->setInvoiceHeader('1', $invoiceId, $issueDate, $invoiceType, 'EUR'); // Set series = 1 and currency = EUR
// Add invoice details
$details = new InvoiceDetails();
$details->setNetValue($netValue);
$details->setVatAmount($vatAmount);
$details->setVatCategory(1); // Default VAT category (24%)
$invoice->addInvoiceDetails($details);
// Add invoice summary
$invoice->setInvoiceSummary($netValue, $vatAmount, $grossValue);
try {
// Send the invoice to MyDATA
$response = $client->sendInvoices($invoice);
if ($response->isSuccessful()) {
$invoiceMark = $response->getInvoiceMark();
$qrUrl = $response->getQrCodeUrl();
// Update the database with MyDATA response
$updateQuery = "
UPDATE {$dolibarr_main_db_prefix}facture_extrafields
SET mydata_reply = 'Success [Mark: $invoiceMark]',
mydata_reply_QR = '$qrUrl',
mydata_check = 1
WHERE fk_object = $invoiceId";
mysqli_query($con, $updateQuery);
echo "Invoice $invoiceId sent successfully with Mark $invoiceMark.<br>";
} else {
// Handle errors in the MyDATA response
$errors = $response->getErrors();
foreach ($errors as $error) {
echo "Error for Invoice $invoiceId: Code {$error->getCode()}, Message: {$error->getMessage()}<br>";
}
// Update the database with error response
$errorMessages = implode('; ', array_map(fn($e) => $e->getMessage(), $errors));
$updateQuery = "
UPDATE {$dolibarr_main_db_prefix}facture_extrafields
SET mydata_reply = 'Error: $errorMessages'
WHERE fk_object = $invoiceId";
mysqli_query($con, $updateQuery);
}
} catch (Exception $e) {
// Handle exceptions during API communication
echo "Exception for Invoice $invoiceId: {$e->getMessage()}<br>";
// Update the database with exception message
$updateQuery = "
UPDATE {$dolibarr_main_db_prefix}facture_extrafields
SET mydata_reply = 'Exception: {$e->getMessage()}'
WHERE fk_object = $invoiceId";
mysqli_query($con, $updateQuery);
}
}
// Close the database connection
mysqli_close($con);
?>
Explanation
Dependency Inclusion:
The firebed/aade-mydata library is loaded using Composer's autoload.
Database Query:
Fetches invoices from the database (facture table) that have not been sent to MyDATA (mydata_check = 0).
Invoice Creation:
Creates an Invoice object using the firebed/aade-mydata library.
Sets the issuer, counterpart, and invoice details.
Invoice Details:
Adds details such as netValue, vatAmount, and vatCategory.
API Communication:
Uses the MyDataClient::sendInvoices() method to send the invoice to the AADE API.
Response Handling:
If successful, updates the facture_extrafields table with the invoice mark and QR code URL.
On errors, logs the error messages in the database.
On exceptions, logs the exception message.
Error Handling:
Handles API errors and exceptions gracefully and updates the database with appropriate messages.
Database Updates:
Updates the mydata_reply and mydata_check fields in the facture_extrafields table to track the MyDATA submission status.
Testing
Local Testing:
Run the script in a development environment with test invoices.
Ensure the database is updated correctly after successful and failed submissions.
Production Testing:
Switch to the production AADE API endpoint (MyDataClient::BASE_URL_PROD).
Test with real invoices and verify the responses.
This implementation is modular, uses best practices, and ensures compatibility with the AADE MyDATA API. Let me know if you need further assistance!