Add php files

This commit is contained in:
2025-05-12 15:44:39 +00:00
parent c951760058
commit 82d5804ac4
9534 changed files with 2638137 additions and 0 deletions

View File

@@ -0,0 +1,127 @@
<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
ini_set('display_errors', 1);
/*
DELETE FROM ecommerce_invoices_products WHERE invoice_id IN (
SELECT id FROM ecommerce_invoices WHERE origin='amazon b2b' AND register_date LIKE '2025-04-%');
DELETE FROM ecommerce_invoices WHERE origin='amazon b2b' AND register_date LIKE '2025-04-%';
*/
$filename = getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/amazonWDT/files/04-2025.csv';
$handle = fopen($filename, 'r');
if ($handle === false) {
die('Cannot open file: ' . $filename);
}
$b2b = [];
while (($data = fgetcsv($handle, 0, "\t")) !== false) {
if ($data[1] == 'WDT - B2B' && $data[8] == 'PL' && $data[9] != 'PL') {
$b2b[] = $data;
if ($data[20] != 'PLN') {
echo '~PLN';
die();
}
}
}
fclose($handle);
$groupedB2B = [];
foreach ($b2b as $el) {
if ($el[6] == 'Sprzedaz - Transport') {
$el[10] = '00195';
$el[11] = '1';
}
$groupedB2B[$el[21]][] = $el;
}
foreach ($groupedB2B as $invoiceNo => $invoice) {
if (checkInvoice($invoiceNo)) {
echo 'Invoice already exists' . PHP_EOL;
continue;
}
$totalNetto = 0;
$totalVat = 0;
$totalBrutto = 0;
foreach ($invoice as $item) {
$totalNetto += str_replace(',', '.', $item[17]);
$totalVat += str_replace(',', '.', $item[18]);
$totalBrutto += str_replace(',', '.', $item[19]);
}
$db = $GLOBALS['db'];
$db->query("SET NAMES utf8mb4");
$i = $invoice[0];
$type = '';
foreach ($invoice as $item) {
if ($item[6] == 'Sprzedaz - Produkt') {
$type = 'normal';
break;
} else if ($item[6] == 'Zwrot - Produkt') {
$type = 'correcting';
break;
}
}
$invoiceId = getId();
$query = sprintf("INSERT INTO ecommerce_invoices VALUES ('%s', '%s', '%s', '%s', '%s', 'amazon b2b', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%f', '%f', '%f', null, null, null, null, null);",
$invoiceId, $i[21], $type, formatDate($i[5]), formatDate($i[5]),
null, 'AmazonCustomer', $i[22], null, null, '',
'', null, 'PLN', $totalNetto, $totalBrutto, $totalVat);
$res = $db->query($query);
if (!$res) {
echo "Query error: ".$query.PHP_EOL;
}
foreach ($invoice as $p) {
// if last character is dot, remove it
if (substr($p[10], -1) == '.') {
$p[10] = substr($p[10], 0, -1);
}
if (substr($p[10], -1) == '-') {
$p[10] = substr($p[10], 0, -1);
}
if (checkProduct($p[10])) {
echo 'Cannot find product: '. $p[10] . PHP_EOL;
continue;
}
$productId = $db->fetchByAssoc($db->query(sprintf("SELECT id FROM ecmproducts WHERE code='%s' OR amazon_code='%s' AND deleted=0", $p[10], $p[10])))['id'];
$quantity = str_replace(',', '.', $p[11]);
$vatValue = str_replace(',', '.', $p[12]) * 100;
$netto = str_replace(',', '.', $p[17]) / $quantity;
$vat = str_replace(',', '.', $p[18]) / $quantity;
$brutto = str_replace(',', '.', $p[19]) / $quantity;
$query = sprintf("INSERT INTO ecommerce_invoices_products VALUES('%s', '%s', '%s', null, '%f', '%f', '%f', '%f', '%f', '%s')",
getId(), $productId, $invoiceId, $quantity, $netto, $brutto, $vat, $vatValue, $p[10]);
$res = $db->query($query);
if (!$res) {
echo "Query error: ".$query.PHP_EOL;
}
}
}
echo 'Koniec. Smutne.';
function checkProduct($code)
{
$db = $GLOBALS['db'];
$res = $db->query(sprintf("SELECT id FROM ecmproducts WHERE code='%s' OR amazon_code='%s' AND deleted=0", $code, $code));
return $res->num_rows > 0 ? false : true;
}
function checkInvoice($number) {
$db = $GLOBALS['db'];
$res = $db->query(sprintf("SELECT id FROM ecommerce_invoices WHERE document_no = '%s'", $number));
return $res->num_rows > 0;
}
function formatDate($date) {
$dateTime = DateTime::createFromFormat('d-m-Y', $date);
return $dateTime ? $dateTime->format('Y-m-d') : false;
}
function getId() {
$db = $GLOBALS['db'];
$res = $db->fetchByAssoc($db->query("SELECT UUID() as id;"));
return $res['id'];
}

View File

@@ -0,0 +1,92 @@
<?php
$filename = getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/amazonWDT/files/amazon-wz-04-2025.csv';
$handle = fopen($filename, 'r');
if ($handle === false) {
die('Cannot open file: ' . $filename);
}
$products = [];
$db = $GLOBALS['db'];
global $app_list_strings;
while (($data = fgetcsv($handle, 0, ";")) !== false) {
if ($data[2] != 'SKU' && $data[2] != '' && $data[3] != '') {
$p = array();
$p['product_code'] = $data[2];
if (substr($p['product_code'], -1) == '.' || substr($p['product_code'], -1) == '-') {
$p['product_code'] = substr($p['product_code'], 0, -1);
}
$p['quantity'] = floatval(str_replace(' ', '', $data[3]));
$p['total'] = floatval(str_replace(' ', '', str_replace(',', '.', $data[5])));
$p['price_netto'] = round($p['total'] / $p['quantity'], 2);
$fromDb = $db->fetchByAssoc($db->query("SELECT * FROM ecmproducts WHERE deleted=0 AND (code = '" . $p['product_code'] . "' OR amazon_code = '" . $p['product_code'] . "')"));
if (empty($fromDb)) {
echo 'Nie znaleziono produktu: ' . $p['product_code'] . PHP_EOL;
die('KONIEC');
}
$p['product_id'] = $fromDb['id'];
$p['name'] = $fromDb['name'];
$p['unit_id'] = $fromDb['unit_id'];
$p['unit_name'] = $app_list_strings['ecmproducts_unit_dom'][$p['unit_id']];
$p['ecmvat_name'] = '0%';
$p['ecmvat_value'] = 0;
$p['ecmvat_id'] = '9b783d21-5548-6653-e1d6-49610eb3f9dd';
$products[] = $p;
}
}
$mergedProducts = [];
foreach ($products as $product) {
if (!isset($mergedProducts[$product['product_id']])) {
$mergedProducts[$product['product_id']] = $product;
} else {
$mergedProducts[$product['product_id']]['quantity'] += $product['quantity'];
$mergedProducts[$product['product_id']]['total'] += $product['total'];
$mergedProducts[$product['product_id']]['price'] = round($mergedProducts[$product['product_id']]['total'] / $mergedProducts[$product['product_id']]['quantity'], 2);
}
}
$products = array_values($mergedProducts);
fclose($handle);
$sessionId = create_guid();
$_SESSION[$sessionId] = $products;
echo '<input title="Wystaw WZ" class="button primary" type="button" name="Edit" id="edit_button" value="Wystaw WZ"
onclick="window.open(\'index.php?module=EcmStockDocOuts&action=EditView&amazonWZ=' . $sessionId . '\')">';
function getStockStates($products)
{
$db = $GLOBALS['db'];
$query = "SELECT s.product_id, s.quantity FROM ecmstockstates AS s WHERE s.stock_id = 'add8ef6f-3d1f-5ccf-c486-64719142f096' AND s.product_id IN ('" . implode('\',\'', $products) . "')";
$res = $db->query($query);
$stockStates = array();
while ($row = $db->fetchByAssoc($res)) {
$stockStates[$row['product_id']] = isset($row['quantity']) ? intval($row['quantity']) : 0;
}
return $stockStates;
}
function getProductsForWZ($invoiceIds)
{
$db = $GLOBALS['db'];
$query = "SELECT ip.ecmproduct_id, SUM(ip.quantity) AS quantity, ip.price_netto
FROM ecommerce_invoices_products AS ip
WHERE invoice_id IN ('" . implode('\',\'', $invoiceIds) . "')
AND ip.ecmproduct_id NOT IN ('', '165f364e-9301-25ac-5906-58e38f1de4ca')
GROUP BY ip.ecmproduct_id, ip.price_netto;";
$res = $db->query($query);
$products = array();
while ($row = $db->fetchByAssoc($res)) {
$products[] = array(
'ecmproduct_id' => $row['ecmproduct_id'],
'quantity' => $row['quantity'],
'price_netto' => $row['price_netto'],
);
}
return $products;
}

View File

@@ -0,0 +1,123 @@
<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
ini_set('display_errors', 1);
/*
DELETE FROM ecommerce_invoices_products WHERE invoice_id IN (
SELECT id FROM ecommerce_invoices WHERE origin='amazon vat local' AND register_date LIKE '2025-02-%');
DELETE FROM ecommerce_invoices WHERE origin='amazon vat local' AND register_date LIKE '2025-02-%';
*/
$filename = getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/amazonWDT/files/04-2025.csv';
$handle = fopen($filename, 'r');
if ($handle === false) {
die('Cannot open file: ' . $filename);
}
$localVat = [];
while (($data = fgetcsv($handle, 0, "\t")) !== false) {
if ($data[1] == 'VAT - Lokalny' && $data[8] == 'PL' && $data[9] == 'PL') {
$localVat[] = $data;
if ($data[20] != 'PLN') {
echo '~PLN';
}
}
}
fclose($handle);
$groupedLocalVat = [];
foreach ($localVat as $vat) {
if ($vat[6] == 'Sprzedaz - Transport') {
$vat[10] = '00195';
$vat[11] = '1';
}
$groupedLocalVat[$vat[21]][] = $vat;
}
foreach ($groupedLocalVat as $invoiceNo => $invoice) {
if (checkInvoice($invoiceNo)) {
echo 'Invoice already exists' . PHP_EOL;
continue;
}
$totalNetto = 0;
$totalVat = 0;
$totalBrutto = 0;
foreach ($invoice as $item) {
$totalNetto += str_replace(',', '.', $item[17]);
$totalVat += str_replace(',', '.', $item[18]);
$totalBrutto += str_replace(',', '.', $item[19]);
}
$db = $GLOBALS['db'];
$db->query("SET NAMES utf8mb4");
$i = $invoice[0];
$type = '';
foreach ($invoice as $item) {
if ($item[6] == 'Sprzedaz - Produkt') {
$type = 'normal';
break;
} else if ($item[6] == 'Zwrot - Produkt') {
$type = 'correcting';
break;
}
}
$invoiceId = getId();
$query = sprintf("INSERT INTO ecommerce_invoices VALUES ('%s', '%s', '%s', '%s', '%s', 'amazon vat local', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%f', '%f', '%f', null, null, null, null, null);",
$invoiceId, $i[21], $type, formatDate($i[5]), formatDate($i[5]),
null, 'AmazonCustomer', $i[22], null, null, '',
'', null, 'PLN', $totalNetto, $totalBrutto, $totalVat);
$res = $db->query($query);
if (!$res) {
echo "Query error: ".$query.PHP_EOL;
}
foreach ($invoice as $p) {
// if last character is dot, remove it
if (substr($p[10], -1) == '.') {
$p[10] = substr($p[10], 0, -1);
}
if (checkProduct($p[10])) {
echo 'Cannot find product: '. $p[10] . PHP_EOL;
continue;
}
$productId = $db->fetchByAssoc($db->query(sprintf("SELECT id FROM ecmproducts WHERE code='%s' OR amazon_code='%s' AND deleted=0", $p[10], $p[10])))['id'];
$quantity = str_replace(',', '.', $p[11]);
$vatValue = str_replace(',', '.', $p[12]) * 100;
$netto = str_replace(',', '.', $p[17]) / $quantity;
$vat = str_replace(',', '.', $p[18]) / $quantity;
$brutto = str_replace(',', '.', $p[19]) / $quantity;
$query = sprintf("INSERT INTO ecommerce_invoices_products VALUES('%s', '%s', '%s', null, '%f', '%f', '%f', '%f', '%f', '%s')",
getId(), $productId, $invoiceId, $quantity, $netto, $brutto, $vat, $vatValue, $p[10]);
$res = $db->query($query);
if (!$res) {
echo "Query error: ".$query.PHP_EOL;
}
}
}
echo 'Koniec. Smutne.';
function checkProduct($code)
{
$db = $GLOBALS['db'];
$res = $db->query(sprintf("SELECT id FROM ecmproducts WHERE code='%s' OR amazon_code='%s' AND deleted=0", $code, $code));
return $res->num_rows > 0 ? false : true;
}
function checkInvoice($number) {
$db = $GLOBALS['db'];
$res = $db->query(sprintf("SELECT id FROM ecommerce_invoices WHERE document_no = '%s'", $number));
return $res->num_rows > 0;
}
function formatDate($date) {
$dateTime = DateTime::createFromFormat('d-m-Y', $date);
return $dateTime ? $dateTime->format('Y-m-d') : false;
}
function getId() {
$db = $GLOBALS['db'];
$res = $db->fetchByAssoc($db->query("SELECT UUID() as id;"));
return $res['id'];
}

View File

@@ -0,0 +1,53 @@
<?php
// read all csv files in directory
$dir = getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/amazonWDT/files/';
$files = scandir($dir);
$csvFiles = [];
foreach ($files as $file) {
if (strpos($file, '.csv') !== false && strpos($file, '2025') == false) {
$csvFiles[] = $file;
}
}
// read files from csvFiles[] one by one
$report = [];
$sum = 0;
foreach ($csvFiles as $file) {
$filename = $dir . $file;
$handle = fopen($filename, 'r');
if ($handle === false) {
die('Cannot open file: ' . $filename);
}
// && ($data[10] == 'FR00148_1000_amz_de' || $data[10] == 'FR00148')
while (($data = fgetcsv($handle, 0, "\t")) !== false) {
if ($data[1] == 'Przemieszczenie - WDT' && $data[8] == 'PL' && $data[9] == 'CZ' && ($data[10] == 'FR00148_1000_amz_de' || $data[10] == 'FR00148') ) {
$sum += intval($data[11]);
$report[] = $data;
}
}
fclose($handle);
}
var_dump($sum);
//var_dump($report);
die();
$outputFilename = $dir . '../report.csv';
$outputHandle = fopen($outputFilename, 'w');
if ($outputHandle === false) {
die('Cannot open file for writing: ' . $outputFilename);
}
// Write header row if needed
if (!empty($report)) {
fputcsv($outputHandle, array_keys($report[0]), "\t");
}
// Write data rows
foreach ($report as $row) {
fputcsv($outputHandle, $row, "\t");
}
fclose($outputHandle);
?>

View File

@@ -0,0 +1,140 @@
<?php
$invoices = getInvoices('2024');
$products = array();
foreach ($invoices as $invoice) {
foreach ($invoice['products'] as $product) {
$products[] = $product['ecmproduct_id'];
}
}
$states = getStockStates($products);
$canProceed = [];
$cantProceed = [];
$missingProducts = [];
$msg = [];
foreach ($invoices as $invoice) {
if ($DEBUG) {
$msg[] = "Sprawdzam fakture: " . $invoice['document_no'] . "<br>";
}
$proceed = true; // hope :)
foreach ($invoice['products'] as $product) {
if ($DEBUG) {
$msg[] = "&nbsp;&nbsp;&nbsp;Sprawdzam produkt: " . $product['code'] . " (Ilość: " . $product['quantity'] . ")<br>";
$msg[] = "&nbsp;&nbsp;&nbsp;&nbspStan magazynowy: " . $states[$product['ecmproduct_id']] . "<br>";
}
if ($states[$product['ecmproduct_id']] < $product['quantity']) {
if ($DEBUG) {
$msg[] = "&nbsp;&nbsp;&nbsp;&nbsp<b>Nie ma wystarczającej ilości produktu w magazynie</b><br>";
}
if (!isset($missingProducts[$product['code']])) {
$missingProducts[$product['code']] = array();
$missingProducts[$product['code']]['id'] = $product['ecmproduct_id'];
$missingProducts[$product['code']]['code'] = $product['code'];
$missingProducts[$product['code']]['missing'] = $product['quantity'] - $states[$product['ecmproduct_id']];
} else {
$missingProducts[$product['code']]['missing'] += $product['quantity'] - $states[$product['ecmproduct_id']];
}
$proceed = false;
break;
}
}
if ($proceed) {
$canProceed[] = $invoice;
foreach ($invoice['products'] as $product) {
$states[$product['ecmproduct_id']] -= $product['quantity'];
}
} else {
$cantProceed[] = $invoice;
}
}
// create list of invoice ids from canProceed
$invoiceIds = array();
foreach ($canProceed as $invoice) {
$invoiceIds[] = $invoice['id'];
}
$sessionId = create_guid();
$_SESSION[$sessionId] = $invoiceIds;
if (count($cantProceed) == 0) {
echo '<input title="Wystaw WZ" class="button primary" type="button" name="Edit" id="edit_button" value="Wystaw WZ"
onclick="window.open(\'index.php?module=EcmStockDocOuts&action=EditView&ecommerceWZ=' . $sessionId . '\')">';
} else {
var_dump($cantProceed);
}
die();
function getInvoices($date)
{
$db = $GLOBALS['db'];
$invoices = array();
// fomat date from d.m.y to mysql format
$query = "SELECT ip.ecmproduct_id, ip.code, i.document_no, SUM(ip.quantity) AS quantity, i.register_date, i.id
FROM ecommerce_invoices_products AS ip
INNER JOIN ecommerce_invoices AS i ON ip.invoice_id = i.id AND i.register_date LIKE '$date%' AND i.type='normal'
AND i.origin IN ('amazon vat local')
WHERE ip.ecmproduct_id != '' AND ip.ecmproduct_id !='165f364e-9301-25ac-5906-58e38f1de4ca'
AND i.ecmstockdocout_id IS NULL
GROUP BY i.id, ip.ecmproduct_id
ORDER BY i.register_date;";
$res = $db->query($query);
while ($row = $db->fetchByAssoc($res)) {
if (!isset($invoices[$row['document_no']])) {
$invoices[$row['document_no']] = array();
$invoices[$row['document_no']]['document_no'] = $row['document_no'];
$invoices[$row['document_no']]['register_date'] = $row['register_date'];
$invoices[$row['document_no']]['id'] = $row['id'];
$invoices[$row['document_no']]['products'] = array();
$invoices[$row['document_no']]['products'][] = array(
'ecmproduct_id' => $row['ecmproduct_id'],
'code' => $row['code'],
'quantity' => $row['quantity'],
);
} else {
$invoices[$row['document_no']]['products'][] = array(
'ecmproduct_id' => $row['ecmproduct_id'],
'code' => $row['code'],
'quantity' => $row['quantity'],
);
}
}
$invoices = array_values($invoices);
usort($invoices, function ($a, $b) {
return $a['id'] - $b['id'];
});
return $invoices;
}
function getStockStates($products)
{
$db = $GLOBALS['db'];
$query = "SELECT s.product_id, s.quantity FROM ecmstockstates AS s WHERE s.stock_id = 'add8ef6f-3d1f-5ccf-c486-64719142f096' AND s.product_id IN ('" . implode('\',\'', $products) . "')";
$res = $db->query($query);
$stockStates = array();
while ($row = $db->fetchByAssoc($res)) {
$stockStates[$row['product_id']] = isset($row['quantity']) ? intval($row['quantity']) : 0;
}
return $stockStates;
}
function getProductsForWZ($invoiceIds)
{
$db = $GLOBALS['db'];
$query = "SELECT ip.ecmproduct_id, SUM(ip.quantity) AS quantity, ip.price_netto
FROM ecommerce_invoices_products AS ip
WHERE invoice_id IN ('" . implode('\',\'', $invoiceIds) . "')
AND ip.ecmproduct_id NOT IN ('', '165f364e-9301-25ac-5906-58e38f1de4ca')
GROUP BY ip.ecmproduct_id, ip.price_netto;";
$res = $db->query($query);
$products = array();
while ($row = $db->fetchByAssoc($res)) {
$products[] = array(
'ecmproduct_id' => $row['ecmproduct_id'],
'quantity' => $row['quantity'],
'price_netto' => $row['price_netto'],
);
}
return $products;
}

View File

@@ -0,0 +1,148 @@
<?php
// show all php errors
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
ini_set('display_errors', 1);
// read csv file tab separated
$filename = getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/amazonWDT/files/04-2025.csv';
$handle = fopen($filename, 'r');
if ($handle === false) {
die('Cannot open file: ' . $filename);
}
$de = [];
$cz = [];
while (($data = fgetcsv($handle, 0, "\t")) !== false) {
if (count($data) == 1 && $data[0] == null) {
continue;
}
if ($data[1] != 'Przemieszczenie - WDT') {
continue;
}
if ($data[8] == 'PL' && $data[9] == 'DE') {
$de[] = $data;
}
if ($data[8] == 'PL' && $data[9] == 'CZ') {
$cz[] = $data;
}
}
fclose($handle);
//if (count($de) == 0) {
// die('No data for DE');
//}
//createInvoice('DE', $de);
if (count($cz) == 0) {
die('No data for CZ');
}
createInvoice('CZ', $cz, true);
function createInvoice($type, $products, $DO_REAL_SAVE = false)
{
$db = $GLOBALS['db'];
$invoice = new EcmInvoiceOut();
if ($type == 'DE') {
$invoice->parent_id = 'a711623a-0217-41bd-ecf6-664c84553473';
$invoice->parent_name = 'Twinpol DE';
$invoice->parent_nip = '367123377';
}
if ($type == 'CZ') {
$invoice->parent_id = 'bf60a128-0b62-4154-c21f-6797718a6354';
$invoice->parent_name = 'Twinpol CZ';
$invoice->parent_nip = 'CZ687253791';
}
$invoice->parent_address_street = 'Aleja Lipowa 48';
$invoice->parent_address_postalcode = '87-126';
$invoice->parent_address_city = 'Obrowo';
$invoice->type = 'normal';
$date = '30.04.2025';
$invoice->register_date = $date;
$invoice->sell_date = $date;
$invoice->validtill_date = $date;
$invoice->payment_date = $invoice->register_date;
$invoice->payment_date_days = 0;
$invoice->payment_method = '1568e47e-1732-e0ad-0000-67b6377f26df';
$invoice->pdf_type = "K";
$invoice->currency_id = 'PLN';
global $current_user;
$invoice->created_by = $current_user->id;
$invoice->assigned_user_id = $current_user->id;
$invoice->wz_id = '';
$invoice->wz_name = '';
$invoice->position_list = [];
foreach ($products as $p) {
// if last character is dot, remove it
if (substr($p[10], -1) == '.') {
$p[10] = substr($p[10], 0, -1);
}
$fromDb = $db->fetchByAssoc($db->query("SELECT id, name, code, product_category_id, unit_id FROM ecmproducts WHERE code = '$p[10]' OR amazon_code = '$p[10]'"));
if ($fromDb == false) {
var_dump($p);
die('Product not found in DB');
}
$prod = searchProduct($fromDb['id'], $invoice->position_list);
if ($prod) {
$prod['quantity'] += intval($p[11]);
$prod['total_netto'] += floatval(str_replace(",", ".", $p[17]));
$prod['total_brutto'] += floatval(str_replace(",", ".", $p[17]));
$prod['price_start'] = round($prod['total_netto'] / $prod['quantity'], 2);
$prod['price_netto'] = $prod['price_start'];
$prod['price_brutto'] = $prod['price_netto'];
foreach ($invoice->position_list as $key => $value) {
if ($value['product_id'] == $prod['product_id']) {
$invoice->position_list[$key] = $prod;
}
}
} else {
$prod['product_id'] = $fromDb['id'];
$prod['name'] = $fromDb['name'];
$prod['product_code'] = $fromDb['code'];
$prod['quantity'] = intval($p[11]);
$prod['total_netto'] = floatval(str_replace(",", ".", $p[17]));
$prod['total_brutto'] = floatval(str_replace(",", ".", $p[17]));
$prod['total_vat'] = 0;
$prod['price_start'] = round($prod['total_netto'] / $prod['quantity'], 2);
$prod['price_netto'] = $prod['price_start'];
$prod['price_brutto'] = $prod['price_netto'];
$prod['ecmvat_id'] = '9b783d21-5548-6653-e1d6-49610eb3f9dd';
$prod['ecmvat_name'] = '0%';
$prod['ecmvat_value'] = 0;
$prod['ecmproductcategory_id'] = $fromDb['product_category_id'];
$prod['dd_unit_id'] = $fromDb['unit_id'];
global $app_list_strings;
$prod['dd_unit_name'] = $app_list_strings['ecmproducts_unit_dom'][$fromDb['unit_id']];
$invoice->position_list[] = $prod;
}
}
if ($DO_REAL_SAVE) {
$id = $invoice->save();
echo $id;
} else {
var_dump($invoice->position_list);
}
}
function searchProduct($productId, $products)
{
foreach ($products as $p) {
if ($p['product_id'] == $productId) {
return $p;
}
}
return false;
}

View File

@@ -0,0 +1,209 @@
<?php
// show all php errors
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
ini_set('display_errors', 1);
// read csv file tab separated
$filename = getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/amazonWDT/files/01-2025.csv';
$handle = fopen($filename, 'r');
if ($handle === false) {
die('Cannot open file: ' . $filename);
}
$de = [];
$cz = [];
while (($data = fgetcsv($handle, 0, "\t")) !== false) {
if (count($data) == 1 && $data[0] == null) {
continue;
}
if ($data[1] != 'Przemieszczenie - WNT') {
continue;
}
if ($data[8] == 'DE' && $data[9] == 'PL') {
$de[] = $data;
}
if ($data[8] == 'CZ' && $data[9] == 'PL') {
$cz[] = $data;
}
}
fclose($handle);
/*
if (count($de) == 0) {
var_dump('No data for DE');
} else {
createFVKOR('DE', $de);
}
if (count($cz) == 0) {
var_dump('No data for CZ');
} else {
createFVKOR('CZ', $cz);
}
*/
//var_dump($cz);
createFVKOR('DE', $de);
die();
function createFVKOR($type, $products, $DO_REAL_SAVE = false)
{
$db = $GLOBALS['db'];
$invoice = new EcmInvoiceOut();
if ($type == 'DE') {
$invoice->parent_id = 'a711623a-0217-41bd-ecf6-664c84553473';
$invoice->parent_name = 'Twinpol DE';
$invoice->parent_nip = '367123377';
}
if ($type == 'CZ') {
$invoice->parent_id = 'bf60a128-0b62-4154-c21f-6797718a6354';
$invoice->parent_name = 'Twinpol CZ';
$invoice->parent_nip = 'CZ687253791';
}
$invoice->parent_address_street = 'Aleja Lipowa 48';
$invoice->parent_address_postalcode = '87-126';
$invoice->parent_address_city = 'Obrowo';
$invoice->type = 'correct';
$date = '31.01.2025';
$invoice->register_date = $date;
$invoice->sell_date = $date;
$invoice->validtill_date = $date;
$invoice->payment_date = $invoice->register_date;
$invoice->payment_date_days = 0;
$invoice->payment_method = '1568e47e-1732-e0ad-0000-67b6377f26df';
$invoice->pdf_type = "K";
$invoice->currency_id = 'PLN';
global $current_user;
$invoice->created_by = $current_user->id;
$invoice->assigned_user_id = $current_user->id;
$invoice->wz_id = '';
$invoice->wz_name = '';
$invoice->position_list = groupProductsAndFindFV($products, $invoice->parent_id, $date);
$invoiceId = $invoice->position_list[0]['old_ecminvoiceout_id'];
foreach ($invoice->position_list as $p) {
if ($p['old_ecminvoiceout_id'] != $invoiceId) {
die('Different ecminvoiceout_id in position_list');
}
}
$invoice->id = $invoice->position_list[0]['old_ecminvoiceout_id'];
var_dump($invoice->position_list);
if ($DO_REAL_SAVE) {
$id = $invoice->save();
echo $id;
}
}
function groupProductsAndFindFV($products, $client, $date)
{
$db = $GLOBALS['db'];
$position_list = [];
foreach ($products as $p) {
// if last character is dot, remove it
if (substr($p[10], -1) == '.') {
$p[10] = substr($p[10], 0, -1);
}
$fromDb = $db->fetchByAssoc($db->query("SELECT id, name, code, product_category_id, unit_id FROM ecmproducts WHERE code = '$p[10]' OR amazon_code = '$p[10]'"));
if ($fromDb == false) {
var_dump($p);
continue;
}
$prod = searchProduct($fromDb['id'], $position_list);
if ($prod) {
$prod['quantity'] += intval($p[11]);
$prod['total_netto'] += floatval(str_replace(",", ".", $p[17]));
foreach ($position_list as $key => $value) {
if ($value['product_id'] == $prod['product_id']) {
$position_list[$key] = $prod;
}
}
} else {
$prod['product_id'] = $fromDb['id'];
$prod['name'] = $fromDb['name'];
$prod['product_code'] = $fromDb['code'];
$prod['quantity'] = intval($p[11]);
$prod['total_netto'] = floatval(str_replace(",", ".", $p[17]));
$prod['total_vat'] = 0;
$prod['ecmvat_id'] = '9b783d21-5548-6653-e1d6-49610eb3f9dd';
$prod['ecmvat_name'] = '0%';
$prod['ecmvat_value'] = 0;
$prod['ecmproductcategory_id'] = $fromDb['product_category_id'];
$prod['dd_unit_id'] = $fromDb['unit_id'];
global $app_list_strings;
$prod['dd_unit_name'] = $app_list_strings['ecmproducts_unit_dom'][$fromDb['unit_id']];
$position_list[] = $prod;
}
}
// find FV
$date = explode(".", $date);
$date = $date[2] . '-' . $date[1] . '-' . $date[0];
$final_list = [];
var_dump($position_list);
foreach ($position_list as $prod) {
$qty = $prod['quantity'];
$prodId = $prod['product_id'];
$query = "
SELECT ii.*, i.id AS invoiceId
FROM ecminvoiceoutitems AS ii
INNER JOIN ecminvoiceouts AS i
ON i.id = ii.ecminvoiceout_id
WHERE ii.quantity >= $qty AND ii.ecmproduct_id = '$prodId'
AND i.type = 'normal' AND i.parent_id = '$client' AND i.register_date < '$date'
ORDER BY i.register_date DESC LIMIT 0,1
";
$fromFV = $db->fetchByAssoc($db->query($query));
if ($fromFV == null) {
die('Nie znaleziono produktu'. $query);
}
$prod['product_itemold_id'] = $fromFV['id'];
$prod['old_total_netto'] = floatval($fromFV['total_netto']);
$prod['old_total_vat'] = floatval($fromFV['total_vat']);
$prod['old_total_brutto'] = floatval($fromFV['total_brutto']);
$prod['old_quantity'] = floatval($fromFV['quantity']);
$prod['total_netto'] = $prod['old_total_netto'] - $prod['total_netto'];
$prod['quantity'] = $prod['old_quantity'] - $prod['quantity'];
$prod['price_netto'] = $prod['total_netto'] / $prod['quantity'];
$prod['price_brutto'] = $prod['price_netto'];
$prod['price_start'] = $prod['price_netto'];
$prod['total_netto'] = $prod['quantity'] * $prod['price_netto'];
$prod['total_brutto'] = $prod['total_netto'];
$prod['old_ecminvoiceout_id'] = $fromFV['invoiceId'];
$final_list[] = $prod;
$fromFV['old_ecminvoiceout_id'] = $fromFV['invoiceId'];
$fromFV['product_corrected'] = 'true';
$final_list[] = $fromFV;
}
return $final_list;
}
function searchProduct($productId, $products)
{
foreach ($products as $p) {
if ($p['product_id'] == $productId) {
return $p;
}
}
return false;
}

View File

@@ -0,0 +1,143 @@
<?php
$db = $GLOBALS['db'];
global $app_list_strings;
if (!isset($_GET['source'])) {
$_GET['source'] = '';
}
if (!isset($_GET['date'])) {
$_GET['date'] = date('Y-m', strtotime('-1 month'));
}
if (!isset($_GET['type'])) {
$_GET['type'] = '';
}
if (isset($_GET['ajax'])) {
switch ($_GET['ajax']) {
case 'exportToRewizor':
exportToRewizor($_GET['source'], $_GET['date'], $_GET['type']);
break;
}
} else {
show();
}
function show()
{
$smarty = new Sugar_Smarty();
$inv = getInvoices($_GET['source'], $_GET['date'], $_GET['type']);
$total_netto = 0;
$total_brutto = 0;
$total_vat = 0;
foreach ($inv as $invoice) {
$total_netto += $invoice['total_netto'];
$total_brutto += $invoice['total_brutto'];
$total_vat += $invoice['total_vat'];
}
// format totals with 2 decimals
$total_netto = number_format($total_netto, 2, '.', '');
$total_brutto = number_format($total_brutto, 2, '.', '');
$total_vat = number_format($total_vat, 2, '.', '');
$smarty->assign("data", $inv);
$smarty->assign("totalNetto", $total_netto);
$smarty->assign("totalBrutto", $total_brutto);
$smarty->assign("totalVat", $total_vat);
$smarty->assign("sources", getSources());
$smarty->assign("source", $_GET['source']);
$smarty->assign("dates", getDates());
$smarty->assign("date", $_GET['date']);
$smarty->assign("type", $_GET['type']);
echo $smarty->display(getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/ecommerceInvoicesListView.tpl');
}
function getInvoices($source, $date, $type)
{
$db = $GLOBALS['db'];
if ($source =='') $source = '%';
$date .= '%';
$query = "SELECT i.*, wz.document_no AS wz_document_no, wz.id AS wz_id FROM ecommerce_invoices AS i
LEFT JOIN ecmstockdocouts AS wz on wz.id = i.ecmstockdocout_id
";
$query .= " WHERE i.origin LIKE '$source' AND i.register_date LIKE '$date'";
if ($type !='') {
$query.=" AND i.type='$type'";
}
$query .= " ORDER BY i.register_date";
$result = $db->query($query);
$invoices = array();
while ($row = $db->fetchByAssoc($result)) {
// format date in row register_date from mysql format into d.m.Y
$row['register_date'] = date('d.m.Y', strtotime($row['register_date']));
$row['sell_date'] = date('d.m.Y', strtotime($row['sell_date']));
$row['products'] = getInvoicProducts($row['id']);
$invoices[] = $row;
}
return $invoices;
}
function getInvoicProducts($invoiceId) {
$db = $GLOBALS['db'];
$query = sprintf("SELECT p.id, p.code, p.name, ip.price_netto, ip.price_brutto, ip.quantity, ip.code as ecommerce_code, ip.vat_value FROM ecommerce_invoices_products as ip INNER JOIN ecmproducts AS p ON ip.ecmproduct_id = p.id WHERE ip.invoice_id='%s'", $invoiceId);
$result = $db->query($query);
$products = array();
while ($row = $db->fetchByAssoc($result)) {
$row['vat_value'] =str_replace(".00","",$row['vat_value']);
$products[] = $row;
}
return $products;
}
function getDates()
{
$dates = array();
$date = new DateTime();
$dates[] = $date->format('Y-m');
while ($date->format('Y-m') != '2024-01') {
$date->modify('-1 month');
$dates[] = $date->format('Y-m');
}
return $dates;
}
function getSources() {
$db = $GLOBALS['db'];
$sources = array();
$res = $db->query("SELECT DISTINCT origin FROM ecommerce_invoices");
while ($row = $db->fetchByAssoc($res)) {
$sources[]= $row['origin'];
}
return $sources;
}
function exportToRewizor($source, $date, $type)
{
$smarty = new Sugar_Smarty();
$invoices = getInvoices($source, $date, $type);
foreach ($invoices as &$i) {
$i['register_date'] = date("Ymd000000",strtotime($i['register_date']));
$i['sell_date'] = date("Ymd000000",strtotime($i['sell_date']));
// create 20 characters length hash from parent_name
$i['parent_hash'] = substr(md5($i['parent_name']), 0, 20);
$i['parent_short_name'] = substr($i['parent_name'], 0, 40);
if ($type == 'correcting') {
$db = $GLOBALS['db'];
$fv = $db->fetchByAssoc($db->query(sprintf("SELECT document_no, register_date FROM ecommerce_invoices WHERE id='%s'", $i['corrected_invoice_id'])));
$i['corrected_document_no'] = $fv['document_no'];
$i['corrected_register_date'] = date("Ymd000000",strtotime(date('d.m.Y', strtotime($fv['register_date']))));
}
}
$smarty->assign("data", $invoices);
if ($type == 'normal') {
$result = $smarty->display(getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/rewizor.tpl');
} else {
$result = $smarty->display(getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/rewizor_fvkor.tpl');
}
// encode result as ansi
echo $result;
//echo mb_convert_encoding($result, 'ANSI', 'UTF-8');
}
function brecho($var)
{
echo '<pre>';
print_r($var);
echo '</pre>';
}

View File

@@ -0,0 +1,119 @@
<?php
brecho("Import Amazon");
$filePath = "modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/amazonXML/9_2024.csv";
if (!file_exists($filePath)) {
echo "Error: File not found";
exit();
}
$file = fopen($filePath, 'r');
if (!$file) {
echo "Error: Unable to open file";
exit();
}
$invoices = array();
$lineNumber = -1;
while (($d = fgetcsv($file)) !== false) {
$lineNumber++;
if ($lineNumber == 0) {
continue;
}
$documentNo = $d[51];
$isReturn = false;
if ($d[3] == 'RETURN') {
$isReturn = true;
//brecho("Korekta!");
//brecho($d);
continue;
} else if ($d[4] != 'FALSE' || $d[3] != 'SHIPMENT' || $documentNo == 'N/A') {
continue;
}
if (!isset($invoices[$documentNo])) {
$invoices[$documentNo] = array();
}
$invoices[$documentNo]['items'][] = $d;
$invoices[$documentNo]['document_no'] = $documentNo;
$invoices[$documentNo]['id'] = $d[8];
$invoices[$documentNo]['order_no'] = $d[5];
$invoices[$documentNo]['register_date'] = new DateTime($d[6]);
$invoices[$documentNo]['sell_date'] = new DateTime($d[2]);
$invoices[$documentNo]['parent_nip'] = $d[43];
$invoices[$documentNo]['total_brutto'] = array_sum(array_column($invoices[$documentNo]['items'], 23));
$invoices[$documentNo]['total_netto'] = array_sum(array_column($invoices[$documentNo]['items'], 25));
$invoices[$documentNo]['total_vat'] = array_sum(array_column($invoices[$documentNo]['items'], 24));
$invoices[$documentNo]['currency'] = $d[15];
$invoices[$documentNo]['parent_address_city'] = str_replace("'", "",$d[59]);
$invoices[$documentNo]['parent_address_postalcode'] = str_replace("'", "",$d[62]);
$invoices[$documentNo]['parent_address_country'] = str_replace("'", "",$d[61]);
$invoices[$documentNo]['url'] = $d[52];
}
fclose($file);
brecho("Ilość faktur: ".count($invoices));
foreach ($invoices as $documentNo => $invoice) {
$add = true;
foreach ($invoice['items'] as $item) {
if (!checkProduct($item[10])) {
brecho("Brak produktu: " . $item[10]);
$add = false;
}
}
if ($add && !checkInvoice($invoice['id'])) {
addInvoice($invoice);
}
}
brecho("Koniec. Smutne.");
function addInvoice($i) {
brecho($i['document_no']);
$db = $GLOBALS['db'];
$db->query("SET NAMES utf8mb4");
$query = sprintf("INSERT INTO ecommerce_invoices VALUES ('%d', '%s', '%s', '%s', '%s', 'amazon', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%f', '%f', '%f', '%s');",
$i['id'], $i['document_no'], 'normal', $i['register_date']->format("Y-m-d"), $i['sell_date']->format("Y-m-d"),
$i['order_no'], 'AmazonCustomer', $i['parent_nip'], $i['parent_address_city'], $i['parent_address_postalcode'], '',
'', $i['parent_address_country'], $i['currency'], $i['total_netto'], $i['total_brutto'], $i['total_vat'], $i['url']);
$db->query($query);
brecho($query);
foreach ($i['items'] as $p) {
addProduct($i['id'], $p);
}
}
function addProduct($invoiceId, $p) {
$db = $GLOBALS['db'];
$id = $db->fetchByAssoc($db->query(sprintf("SELECT id FROM ecmproducts WHERE code ='%s' OR amazon_code = '%s'", $p[10], $p[10])))['id'];
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
$query = sprintf("INSERT INTO ecommerce_invoices_products VALUES('%s', '%s', '%s', '%d', '%f', '%f', '%f', '%f', '%s')",
$uuid, $id, $invoiceId, $p[11], $p[25], $p[23], $p[24], $p[13]*100, $p[10]);
$db->query($query);
}
function checkProduct($code)
{
$db = $GLOBALS['db'];
$res = $db->query(sprintf("SELECT id FROM ecmproducts WHERE code='%s' OR amazon_code='%s' AND deleted=0", $code, $code));
return $res->num_rows > 0;
}
function checkInvoice($id) {
$db = $GLOBALS['db'];
$res = $db->query(sprintf("SELECT id FROM ecommerce_invoices WHERE id = '%s'", $id));
return $res->num_rows > 0;
}
function brecho($msg)
{
echo "<br><br>";
var_dump($msg);
echo "<br><br>";
}

View File

@@ -0,0 +1,235 @@
<?php
// serie faktur baselinker
// FV Polska (stare) - 15356
// FV Polska - 7688
// FV Niemcy - 15357
// FVKOR Polska - 17314
// FVKOR domyślna - 7689
/*
DELETE p
FROM ecommerce_invoices_products p
LEFT JOIN ecommerce_invoices i ON p.invoice_id = i.id
WHERE i.id IS NULL;
*/
function importFV($seriesId)
{
$baselinker_config = loadConfiguration();
$db = $GLOBALS['db'];
$IMPORT_START_ID = 1531694;
$dbRes = $db->query("SELECT id FROM ecommerce_invoices WHERE origin = 'allegro' AND type = 'normal' AND series_id = '$seriesId' ORDER BY id DESC LIMIT 1");
$lastImportId = $db->fetchByAssoc($dbRes)['id'];
if ($lastImportId == null) {
$lastImportId = $IMPORT_START_ID;
} else {
$lastImportId++; //get next
}
$invoicesRes = loadInvoices($baselinker_config['token'], $lastImportId, $seriesId);
$invoices = $invoicesRes->invoices;
usort($invoices, function ($a, $b) {
return $a->date_add - $b->date_add;
});
if (count($invoices) > 0) {
foreach ($invoices as $invoice) {
$invoice->order_source = getInvoiceSource($baselinker_config['token'], $invoice->order_id);
$invoice->total_price_vat = $invoice->total_price_brutto - $invoice->total_price_netto;
$invoice->series_id = $seriesId;
addInvoice($invoice);
}
}
return true;
}
function importFVKOR($seriesId)
{
$baselinker_config = loadConfiguration();
$db = $GLOBALS['db'];
$IMPORT_CORRECTION_START_ID = 2106464;
$dbRes = $db->query("SELECT id FROM ecommerce_invoices WHERE origin = 'Allegro' AND type = 'correcting' AND series_id = '$seriesId' ORDER BY id DESC LIMIT 1");
$lastImportId = $db->fetchByAssoc($dbRes)['id'];
if ($lastImportId == null) {
$lastImportId = $IMPORT_CORRECTION_START_ID;
} else {
$lastImportId++; //get next
}
$invoicesRes = loadInvoices($baselinker_config['token'], $lastImportId, $seriesId);
$invoices = $invoicesRes->invoices;
usort($invoices, function ($a, $b) {
return $a->date_add - $b->date_add;
});
if (count($invoices) > 0) {
foreach ($invoices as $invoice) {
$invoice->order_source = getInvoiceSource($baselinker_config['token'], $invoice->correcting_to_invoice_id);
$total = getCorrectTotals($invoice);
$invoice->series_id = $seriesId;
$invoice->total_price_netto = $total['netto'];
$invoice->total_price_brutto = $total['brutto'];
$invoice->total_price_vat = $total['vat'];
$invoice->order_source = $total['order_source'];
addInvoice($invoice);
}
}
}
function addInvoice($i)
{
$db = $GLOBALS['db'];
$name = strlen($i->invoice_nip) > 0 ?
$i->invoice_company :
$i->invoice_fullname;
$db->query("SET NAMES utf8mb4");
$query = sprintf(
"INSERT INTO ecommerce_invoices VALUES ('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%f', '%f', '%f', '%s', '%s', null, null, '%s');",
$i->invoice_id,
$i->number,
$i->type,
date("Y-m-d", $i->date_add),
date("Y-m-d", $i->date_sell),
$i->order_source,
$i->order_id,
$name,
$i->invoice_nip,
$i->invoice_city,
$i->invoice_postcode,
$i->invoice_address,
$i->invoice_country,
$i->invoice_country_code,
$i->currency,
$i->total_price_netto,
$i->total_price_brutto,
$i->total_price_vat,
'',
$i->correcting_to_invoice_id,
$i->series_id
);
$db->query($query);
if ($db->last_error) {
return;
}
// delete products for this invoice if exists
$db->query(sprintf("DELETE FROM ecommerce_invoices_products WHERE invoice_id='%s'", $i->invoice_id));
foreach ($i->items as $p) {
addProduct($i->invoice_id, $p);
}
}
function addProduct($invoiceId, $p)
{
$db = $GLOBALS['db'];
$id = $p->is_shipment == 1 ? '165f364e-9301-25ac-5906-58e38f1de4ca' : $db->fetchByAssoc($db->query(sprintf("SELECT id FROM ecmproducts WHERE code ='%s'", $p->sku)))['id'];
// generate random uuid v4
$uuid = sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
);
$query = sprintf(
"INSERT INTO ecommerce_invoices_products VALUES('%s', '%s', '%s', '%s', '%d', '%f', '%f', '%f', '%f', '%s')",
$uuid,
$id,
$invoiceId,
$p->order_product_id,
$p->quantity,
$p->price_netto,
$p->price_brutto,
$p->price_brutto - $p->price_netto,
$p->tax_rate,
$p->sku
);
$db->query($query);
}
function loadConfiguration()
{
global $db;
$dbRes = $db->query("SELECT * FROM config WHERE category='baselinker'");
$config = [];
while ($row = $db->fetchByAssoc($dbRes)) {
$config[$row['name']] = $row['value'];
}
return $config;
}
function loadInvoices($token, $lastImportId, $seriesId)
{
$methodParams = '{
"id_from": ' . $lastImportId . ',
"get_external_invoices": false,
"series_id": ' . $seriesId . '
}';
$apiParams = [
"method" => "getInvoices",
"parameters" => $methodParams
];
$curl = curl_init("https://api.baselinker.com/connector.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken: " . $token]);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$response = json_decode(curl_exec($curl));
return $response;
}
function getInvoiceSource($token, $orderId)
{
$methodParams = '{
"order_id": ' . $orderId . '
}';
$apiParams = [
"method" => "getOrders",
"parameters" => $methodParams
];
$curl = curl_init("https://api.baselinker.com/connector.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken: " . $token]);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$res = json_decode(curl_exec($curl));
return $res->orders[0]->order_source;
}
function getCorrectTotals($invoice)
{
$db = $GLOBALS['db'];
$i = $db->fetchByAssoc($db->query(sprintf("SELECT * FROM ecommerce_invoices WHERE id='%s'", $invoice->correcting_to_invoice_id)));
if (!isset($i)) {
die(); // w tym przypadku nie wszystkie FV są zaciągnięte. Trzeba przerwać skrypt i odpalić następnym razem
}
$c = $db->fetchByAssoc($db->query(sprintf("SELECT SUM(total_netto) as total_netto, SUM(total_brutto) as total_brutto FROM ecommerce_invoices WHERE corrected_invoice_id='%s'", $invoice->correcting_to_invoice_id)));
$total_netto = $invoice->total_price_netto - (float) $i['total_netto'] - (float) $c['total_netto'];
$total_brutto = $invoice->total_price_brutto - (float) $i['total_brutto'] - (float) $c['total_brutto'];
$total_vat = $total_brutto - $total_netto;
return array(
'netto' => $total_netto,
'brutto' => $total_brutto,
'vat' => $total_vat,
'order_source' => $i['origin']
);
}
function brecho($msg)
{
echo '<br><pre>';
var_dump($msg);
echo PHP_EOL;
echo '</pre><br>';
}