Files
crm.twinpol.com/modules/EcmSales/bimit_importAllegroOrders2.php

474 lines
20 KiB
PHP
Raw Normal View History

2025-05-12 15:44:39 +00:00
<?php
$IMPORT_START_DATE = date('Y-m-dTH:i:s', strtotime("-20 days"));
$LIST_FILTER_DATE = date('Y-m-d H:i:s', strtotime("-7 days"));
global $sugar_config;
$allegro_config = loadConfiguration();
//registerDevice($allegro_config);
//getToken($allegro_config['basicAuth'], 'vCLvjGIHtkckM8CYj1VFRk5TAfpt5Bl0');
//UPDATE config SET value='eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiIxMTQ4ODUzMTYiLCJzY29wZSI6WyJhbGxlZ3JvOmFwaTpvcmRlcnM6cmVhZCIsImFsbGVncm86YXBpOnNoaXBtZW50czp3cml0ZSIsImFsbGVncm86YXBpOnNoaXBtZW50czpyZWFkIl0sImFsbGVncm9fYXBpIjp0cnVlLCJpc3MiOiJodHRwczovL2FsbGVncm8ucGwiLCJleHAiOjE3MTM4MTE5NzYsImp0aSI6IjIxNmFlYmZkLTFiMTAtNGRiYi05NWJhLThjYTc3NzE4MmUyNCIsImNsaWVudF9pZCI6IjA2OTM1ODMzNmRjMzQ2YzBhODgwMDNiZGE2YmFjN2QxIn0.gv0E_NdSnO-GrfRv01X4YGlEDsGJtv2QvahsgsJU9PDRqSOp2uoZtu5woF0SMkVHZaxPi2HmGvBzRmapIafzIghaB5sJ_kl6ncMUtqyUrWZKrCnsGnVOOtlyMOYSIKf3_VxwI58oS-12G8DoxEnhAgZkJvOYarBmO_7-GokDqLR7KSPuulpvQDsDhuoquMkdfvIn4WD7XmdjhSg-8tZmeDBsLlNLnhOJ06ORydjBEr7OltxqQ8Fz_G8kqfMfqUMsOJ1ljW0t2YKgjQuv9xkeKvVpQyXGsh1qMbn6v34_bsLSAUuCdC_urWtbhnqn83BUH3uH50njj2eas2UrN4CTSg' WHERE category='allegro' AND name='token';
//UPDATE config SET value='eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiIxMTQ4ODUzMTYiLCJzY29wZSI6WyJhbGxlZ3JvOmFwaTpvcmRlcnM6cmVhZCIsImFsbGVncm86YXBpOnNoaXBtZW50czp3cml0ZSIsImFsbGVncm86YXBpOnNoaXBtZW50czpyZWFkIl0sImFsbGVncm9fYXBpIjp0cnVlLCJhdGkiOiIyMTZhZWJmZC0xYjEwLTRkYmItOTViYS04Y2E3NzcxODJlMjQiLCJpc3MiOiJodHRwczovL2FsbGVncm8ucGwiLCJleHAiOjE3MjE1NDQ3NzYsImp0aSI6IjhiYWY1M2YyLTFiYzEtNDYxYi04NTVkLTI4MTJmNDViYjZiMCIsImNsaWVudF9pZCI6IjA2OTM1ODMzNmRjMzQ2YzBhODgwMDNiZGE2YmFjN2QxIn0.WL7kpDygTgIzSeIzZUPk24kW09Jmh3XqIZr-VJYc1_WreXjmGyKqRYzs36OJnSfp2mj5EkNxreyCe5XWmAg2SpMNF1YLqFo7DGBmutp5Zj9Yjjc-xfkz68pzhIP0Otb0-qvreKZfMPAg9oe1XLvW7F0x6Kcwvp0qk-5Rr6EsPR0VHVqYwNys2mSV2dkpCSamUJ7fqB12gAMLQ_pYwQLfveyoMgPyLx1ETq5F75231IbZYdXHOcdpPbqM9EuU5misqn0pC2-b3sfNhbI73lHmWXaJXdZ_3NDwDW_jSuqaMfEpkb60RQXwc7jTacSOsSettnw7dEOic2Q7d4vvFD7hFg' WHERE category='allegro' AND name='refreshToken';
//die();
$db = $GLOBALS['db'];
$dbRes = $db->query("SELECT event_id FROM allegro_orders ORDER BY date_entered DESC LIMIT 1");
$lastEventId = $db->fetchByAssoc($dbRes)['event_id'];
$events = loadOrderEvents($allegro_config['token'], $lastEventId);
if (isset($events->error)) {
if (refreshToken($allegro_config['refreshToken'], $allegro_config['basicAuth']) == true) {
$allegro_config = loadConfiguration();
$events = loadOrderEvents($allegro_config['token'], $lastEventId);
} else {
sendEmail('Nie udało się odświeżyć tokena. Skontaktuj się z Michałem Zielińskim');
die('Nie udało się odświeżyć tokena');
}
}
usort($events->events, function ($a, $b) {
return strtotime($b->occurredAt) - strtotime($a->occurredAt);
});
if (count($events->events) > 0) {
global $db;
foreach ($events->events as $event) {
if (date('Y-m-dTH:i:s', strtotime($event->occurredAt)) > $IMPORT_START_DATE) {
$order = loadOrder($event->order->checkoutForm->id, $allegro_config['token']);
$parsedOrder = json_decode($order);
$date = date("Y-m-d H:i:s", strtotime($parsedOrder->updatedAt));
$db->query("INSERT INTO allegro_orders VALUES ('".$event->order->checkoutForm->id."', '".$event->id."', '".$date."', '".base64_encode($order)."')");
}
}
}
$dbRes = $db->query("SELECT * FROM allegro_orders WHERE date_entered > '$LIST_FILTER_DATE' ORDER BY date_entered ASC");
$message = "";
while ($row = $db->fetchByAssoc($dbRes)) {
$order = json_decode(base64_decode(($row['payload'])));
$order->exists = isOrderExists($order->id);
if (!$order->exists) {
$order = loadOrder($order->id, $allegro_config['token']);
$sale = addOrder(json_decode($order));
$message .= "Dodano zamówienie Allegro <a href=\"https://crm.twinpol.com/index.php?module=EcmSales&action=DetailView&record=".$sale->id."\">ZS ".$sale->document_no."</a> <br><br>";
}
}
if (strlen($message)) {
sendEmail($message);
}
return;
function sendEmail($message) {
$mail = new PHPMailer2(true);
$mail->isSMTP();
$mail->setFrom('system@e5.pl', 'Twinpol CRM - usługa importu Allegro');
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'system@e5.pl';
$mail->Password = 'wqiz ekxn lysj zheu';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->CharSet = 'UTF-8';
$mail->addAddress('mz@bim-it.pl', 'Michał Zieliński');
$mail->addAddress('info@twinpol.com', 'Info');
$mail->isHTML(true);
$mail->Subject = "Import zamówienia Allegro";
$mail->Body = $message;
$mail->send();
}
function addOrder($order)
{
$sale = new EcmSale();
$clientId = null;
if (!isAccountExists($order->buyer->email)) {
$clientId = createAccount($order);
} else {
$clientId = getClient($order->buyer->email)['id'];
}
$client = new Account();
$client->retrieve($clientId);
$sale->parent_id = $client->id;
$sale->parent_name = $client->name;
$sale->parent_name_copy = $client->name;
$sale->parent_nip = $client->to_vatid;
$sale->parent_address_street = $client->register_address_street;
$sale->parent_address_city = $client->register_address_city;
$sale->parent_address_postalcode = $client->register_address_postalcode;
$sale->parent_address_country = $client->register_address_country;
$sale->type = 'sales_order';
if (
$order->payment->paidAmount->amount != $order->summary->totalToPay->amount
&& $order->payment->type == 'ONLINE'
) {
$sale->status = 's20';
} else {
$sale->status = 's30';
}
$sale->ecmlanguage = 'pl_pl';
$sale->currency_id = 'PLN';
$sale->pdf_type = 'K';
$sale->order_source = 'allegro';
$sale->order_source_id = $order->id;
$sale->assigned_user_id = '1';
//add mz@bim-it.pl
// change stock to allegro
$sale->stock_id = 'cf16804e-f698-5e09-2da3-6553588446ae';
$sale->register_date = date("d.m.Y", strtotime($order->updatedAt));
$sale->delivery_date = date("d.m.Y", strtotime($order->delivery->time->to));
$sale->send_date = date("d.m.Y", strtotime($order->delivery->time->dispatch->from));
if ($order->payment->type == 'ONLINE') {
$sale->payment_method = 'PRZEDPLATA';
$sale->payment_date = date("d.m.Y", strtotime($order->payment->finishedAt));
} else {
$sale->payment_method = 'ZA POBRANIEM';
}
if (isset($order->delivery->pickupPoint)) {
$sale->shipping_address_name = $order->delivery->pickupPoint->name . ' (' . $order->delivery->pickupPoint->description . ')';
$sale->shipping_address_street = $order->delivery->pickupPoint->address->street;
$sale->shipping_address_city = $order->delivery->pickupPoint->address->city;
$sale->shipping_address_postalcode = $order->delivery->pickupPoint->address->zipCode;
$sale->shipping_address_country = $order->delivery->pickupPoint->address->countryCode;
$sale->shipping_phone = $sale->shipping_phone = $order->delivery->address->phoneNumber;
} else {
if ($order->delivery->address->companyName) {
$sale->shipping_address_name = $order->delivery->address->companyName . ' ';
}
$sale->shipping_address_name .= $order->delivery->address->firstName . ' ' . $order->delivery->address->lastName;
$sale->shipping_address_street = $order->delivery->address->street;
$sale->shipping_address_city = $order->delivery->address->city;
$sale->shipping_address_postalcode = $order->delivery->address->zipCode;
$sale->shipping_address_country = $order->delivery->address->countryCode;
$sale->shipping_phone = $order->delivery->address->phoneNumber;
}
$sale->pdf_text =
$order->buyer->login
. PHP_EOL
. $order->delivery->method->name
. PHP_EOL
. $order->buyer->email;
$sale->position_list = array();
$counter = 0;
$sumNetto = 0;
foreach ($order->lineItems as $line) {
$productId = getProduct($line->offer->external->id);
$p = new EcmProduct();
$p->retrieve($productId);
$sale->position_list[$counter]['product_id'] = $p->id;
$sale->position_list[$counter]['position'] = $counter;
$sale->position_list[$counter]['product_code'] = $p->code;
$sale->position_list[$counter]['name'] = $p->name;
$sale->position_list[$counter]['discount'] = 0;
$sale->position_list[$counter]['unit_id'] = 1;
$sale->position_list[$counter]['unit_name'] = 'szt.';
$sale->position_list[$counter]['ecmvat_id'] = $p->vat_id;
$sale->position_list[$counter]['ecmvat_name'] = $p->vat_name;
$sale->position_list[$counter]['ecmvat_value'] = $p->vat_value;
$sale->position_list[$counter]['product_ean'] = $p->ean;
$sale->position_list[$counter]['quantity'] = $line->quantity;
$priceBrutto = $line->price->amount;
$priceNetto = round($priceBrutto / (1 + ($p->vat_value / 100)), 2);
$sale->position_list[$counter]['price_start'] = $priceNetto;
$sale->position_list[$counter]['price_netto'] = $priceNetto;
$sale->position_list[$counter]['total_netto'] = $priceNetto * $line->quantity;
$sumNetto += $sale->position_list[$counter]['total_netto'];
$counter++;
}
// delivery
if (floatval($order->delivery->cost->amount) > 0) {
$p = new EcmProduct();
$p->retrieve('165f364e-9301-25ac-5906-58e38f1de4ca');
$sale->position_list[$counter]['product_id'] = $p->id;
$sale->position_list[$counter]['position'] = $counter;
$sale->position_list[$counter]['product_code'] = $p->code;
$sale->position_list[$counter]['name'] = $p->name;
$sale->position_list[$counter]['discount'] = 0;
$sale->position_list[$counter]['unit_id'] = 1;
$sale->position_list[$counter]['unit_name'] = 'szt.';
$sale->position_list[$counter]['ecmvat_id'] = $p->vat_id;
$sale->position_list[$counter]['ecmvat_name'] = $p->vat_name;
$sale->position_list[$counter]['ecmvat_value'] = $p->vat_value;
$sale->position_list[$counter]['product_ean'] = $p->ean;
$sale->position_list[$counter]['quantity'] = 1;
$priceBrutto = $order->delivery->cost->amount;
$priceNetto = round($priceBrutto / (1 + ($p->vat_value / 100)), 2);
$sale->position_list[$counter]['price_start'] = $priceNetto;
$sale->position_list[$counter]['price_netto'] = $priceNetto;
$sale->position_list[$counter]['total_netto'] = $priceNetto;
$sumNetto += $sale->position_list[$counter]['total_netto'];
}
$sale->total_netto = $sumNetto;
$sale->save();
return $sale;
}
function createAccount($order)
{
require_once(getcwd() . "/include/SugarEmailAddress/SugarEmailAddress.php");
$account = new Account();
$name = '';
if ($order->invoice->required) {
if ($order->invoice->address->company) {
$name = $order->invoice->address->company->name;
} else {
$name = $order->invoice->address->naturalPerson->firstName . ' ' . $order->invoice->address->naturalPerson->lastName;
}
$account->to_vatid = $order->invoice->address->company->taxId;
} else if ($order->buyer->firstName || $order->buyer->lastName) {
$name = $order->buyer->firstName . ' ' . $order->buyer->lastName;
} else {
$name = $order->buyer->email;
}
$account->name = $name;
$account->index_dbf = $name;
$account->description = $order->buyer->login;
$account->phone_office = $order->buyer->phoneNumber;
$account->assigned_user_id = '1';
$account->isAllegroUser = true;
$account->account_type = 'rec';
$account->invoice_type = 'K';
if ($order->invoice->required) {
$account->shop_user = 'b2b';
$account->register_address_street = $order->invoice->address->street;
$account->register_address_city = $order->invoice->address->city;
$account->register_address_postalcode = $order->invoice->address->postCode;
$account->register_address_country = $order->invoice->address->countryCode;
$account->billing_address_street = $order->buyer->address->street;
$account->billing_address_city = $order->buyer->address->city;
$account->billing_address_postalcode = $order->buyer->address->postCode;
$account->billing_address_country = $order->buyer->address->countryCode;
} else {
$account->shop_user = 'b2c';
$account->register_address_street = $order->buyer->address->street;
$account->register_address_city = $order->buyer->address->city;
$account->register_address_postalcode = $order->buyer->address->postCode;
$account->register_address_country = $order->buyer->address->countryCode;
}
$account->save();
$email = new SugarEmailAddress();
$email->addAddress($order->buyer->email, true);
$email->save($account->id, "Accounts");
return $account->id;
}
function isOrderExists($allegroOrderId)
{
global $db;
$dbRes = $db->query("SELECT id FROM ecmsales WHERE deleted = 0 AND order_source = 'allegro' AND order_source_id = '" . $allegroOrderId . "'");
if ($db->getRowCount($dbRes) > 0) {
return true;
} else {
return false;
}
}
function getOrder($allegroOrderId)
{
global $db;
$dbRes = $db->query("SELECT id, document_no FROM ecmsales WHERE deleted = 0 AND order_source = 'allegro' AND order_source_id = '" . $allegroOrderId . "'");
return $db->fetchByAssoc($dbRes);
}
function getInvoice($orderId)
{
global $db;
$dbRes = $db->query("SELECT id, document_no FROM ecminvoiceouts WHERE deleted = 0 AND canceled = 0 AND so_id = '" . $orderId . "'");
return $db->fetchByAssoc($dbRes);
}
function getProduct($code)
{
global $db;
$dbRes = $db->query("SELECT id FROM ecmproducts WHERE deleted = 0 AND code = '" . $code . "'");
return $db->fetchByAssoc($dbRes)['id'];
}
function isAccountExists($email)
{
global $db;
$dbRes = $db->query("
SELECT a.id FROM email_addr_bean_rel AS rel
INNER JOIN email_addresses AS e ON e.id = rel.email_address_id
INNER JOIN accounts AS a ON a.id = rel.bean_id
WHERE e.email_address = '" . $email . "' AND a.deleted = 0;
");
if ($db->getRowCount($dbRes) > 0) {
return true;
} else {
return false;
}
}
function getClient($email)
{
global $db;
$dbRes = $db->query("
SELECT a.id, a.name FROM email_addr_bean_rel AS rel
INNER JOIN email_addresses AS e ON e.id = rel.email_address_id
INNER JOIN accounts AS a ON a.id = rel.bean_id
WHERE e.email_address = '" . $email . "' AND a.deleted = 0;
");
return $db->fetchByAssoc($dbRes);
}
function loadOrder($orderId, $token)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
'Accept: application/vnd.allegro.public.v1+json',
]);
curl_setopt($curl, CURLOPT_URL, "https://api.allegro.pl/order/checkout-forms/" . $orderId);
return curl_exec($curl);
}
function loadOrderEvents($token, $lastEventId)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
'Accept: application/vnd.allegro.public.v1+json',
]);
curl_setopt($curl, CURLOPT_URL, "https://api.allegro.pl/order/events?type=READY_FOR_PROCESSING&limit=500&from=".$lastEventId);
return json_decode(curl_exec($curl));
}
function refreshToken($refreshToken, $baseCredentials)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Authorization: Basic ' . $baseCredentials,
'Accept: application/vnd.allegro.public.v1+json',
]);
curl_setopt($curl, CURLOPT_URL, "https://allegro.pl/auth/oauth/token?grant_type=refresh_token&refresh_token=" . $refreshToken);
$res = json_decode(curl_exec($curl));
var_dump($res);
if (isset($res->error)) {
return false;
} else {
global $db;
$db->query("UPDATE config SET value='" . $res->access_token . "' WHERE category='allegro' AND name='token'");
$db->query("UPDATE config SET value='" . $res->refresh_token . "' WHERE category='allegro' AND name='refreshToken'");
return true;
}
}
function getToken($baseCredentials, $deviceCode)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Authorization: Basic '.$baseCredentials
]);
curl_setopt($curl, CURLOPT_URL, "https://allegro.pl/auth/oauth/token?grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=".$deviceCode);
$res = json_decode(curl_exec($curl));
var_dump($res);
echo '<br>';
echo 'Access: '.$res->access_token;
echo '<br>';
echo 'Refresh: '.$res->refresh_token;
}
function registerDevice($config)
{
$baseCredentials = $config['basicAuth'];
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic '.$baseCredentials,
]);
curl_setopt($curl, CURLOPT_URL, "https://allegro.pl/auth/oauth/device?client_id=".$config['clientId']);
$res = curl_exec($curl);
$authRes = json_decode($res);
var_dump($authRes);
}
function loadConfiguration()
{
global $db;
$dbRes = $db->query("SELECT * FROM config WHERE category='allegro'");
$config = [];
while ($row = $db->fetchByAssoc($dbRes)) {
$config[$row['name']] = $row['value'];
}
$config['basicAuth'] = base64_encode($config['clientId'] . ':' . $config['clientSecret']);
return $config;
}
function brecho()
{
$args = func_get_args();
echo '<pre>';
foreach ($args as $arg) {
var_dump($arg);
}
echo '</pre>';
}
function sendInvoiceToAllegro($invoiceId) {
global $db;
$dbRes = $db->query("SELECT * FROM ecminvoiceouts WHERE id='$invoiceId'");
// TODO Create invoice object in allegro
// TODO create iunvoice pdf
// TODO send invoice to allegro
}
function createInvoice($orderId, $document_no, $token) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
'Accept: application/vnd.allegro.public.v1+json',
]);
curl_setopt($curl, CURLOPT_URL, "https://api.{environment}/order/checkout-forms/".$orderId."/invoices");
// remove from document_no characters not allowed in filename
$name = preg_replace('/[^A-Za-z0-9\-]/', '', $document_no);
$body = array(
'file' => array(
'name' => $name.'.pdf',
),
'invoiceNumber' => $document_no
);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body));
//return curl_exec($curl);
}
function getInvoicePdf($invoiceId) {
}
function sendInvoice($orderId, $allegroInvoiceId, $data, $token) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
'Accept: application/pdf',
]);
curl_setopt($curl, CURLOPT_URL, "https://api.{environment}/order/checkout-forms/".$orderId."/invoices//".$allegroInvoiceId."/file");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}