浏览代码

wip

master
Daniel 3 年前
父节点
当前提交
0b80487dec
共有 9 个文件被更改,包括 2872 次插入108 次删除
  1. +2097
    -0
      api2/ProductCollection.php
  2. +621
    -0
      api2/ProductCollectionSurcharge.php
  3. +126
    -49
      src/EventListener/PostCheckoutListener.php
  4. +6
    -29
      src/ExactApi/ApiExact.php
  5. +7
    -6
      src/ExactApi/IsotopeDatabaseHandler.php
  6. +9
    -0
      src/ExactApi/apiTestGetAccessToken.php
  7. +0
    -23
      src/ExactApi/apiUpdateProducts.php
  8. +1
    -1
      src/ExactApi/tokenData
  9. +5
    -0
      src/config.php

+ 2097
- 0
api2/ProductCollection.php
文件差异内容过多而无法显示
查看文件


+ 621
- 0
api2/ProductCollectionSurcharge.php 查看文件

@@ -0,0 +1,621 @@
<?php

/*
* Isotope eCommerce for Contao Open Source CMS
*
* Copyright (C) 2009 - 2019 terminal42 gmbh & Isotope eCommerce Workgroup
*
* @link https://isotopeecommerce.org
* @license https://opensource.org/licenses/lgpl-3.0.html
*/

namespace Isotope\Model;

use Contao\StringUtil;
use Contao\System;
use Isotope\Interfaces\IsotopeOrderableCollection;
use Isotope\Interfaces\IsotopePayment;
use Isotope\Interfaces\IsotopeProductCollection;
use Isotope\Interfaces\IsotopeProductCollectionSurcharge;
use Isotope\Interfaces\IsotopeShipping;
use Isotope\Isotope;
use Isotope\Model\ProductCollectionSurcharge\Tax;

/**
* Class Surcharge
*
* Provide methods to handle Isotope product collection surcharges.
*
* @property int $id
* @property int $pid
* @property int $sorting
* @property int $tstamp
* @property string $type
* @property int $source_id
* @property string $label
* @property string $price
* @property float $total_price
* @property float $tax_free_total_price
* @property string $tax_id
* @property bool $before_tax
* @property bool $addToTotal
* @property bool $applyRoundingIncrement
* @property array $products
*/
abstract class ProductCollectionSurcharge extends TypeAgent
{

/**
* Table name
* @var string
*/
protected static $strTable = 'tl_iso_product_collection_surcharge';

/**
* Interface to validate product collection surcharge
* @var string
*/
protected static $strInterface = '\Isotope\Interfaces\IsotopeProductCollectionSurcharge';

/**
* List of types (classes) for this model
* @var array
*/
protected static $arrModelTypes = array();

/**
* Tax amount for individual products
* @var array
*/
protected $arrProducts = array();

/**
* IDs of applicable taxes
* @var array
*/
protected $arrTaxIds = array();


/**
* Return if the surcharge has tax
*
* @return bool
*/
public function hasTax()
{
return ($this->tax_class > 0 || !empty($this->arrProducts)) ? true : false;
}

/**
* Get tax amount for an individual collection item
*
* @param ProductCollectionItem $objItem
*
* @return float
*/
public function getAmountForCollectionItem(ProductCollectionItem $objItem)
{
if (isset($this->arrProducts[$objItem->id])) {

return (float) $this->arrProducts[$objItem->id];
}

return 0;
}

/**
* Set tax amount for a collection item
*
* @param float $fltAmount
* @param ProductCollectionItem $objItem
*/
public function setAmountForCollectionItem($fltAmount, ProductCollectionItem $objItem)
{
if ($fltAmount != 0) {
$this->arrProducts[$objItem->id] = $fltAmount;
} else {
unset($this->arrProducts[$objItem->id]);
}
}

/**
* Update IDs of tax per product config
*
* @param array $arrIdMap
*
* @deprecated Deprecated since version 2.2, to be removed in 3.0.
* Surcharges are generated on the fly, so it does not make sense to convert item IDs
*/
public function convertCollectionItemIds($arrIdMap)
{
$arrProducts = array();

foreach ($this->arrProducts as $k => $v) {
if (isset($arrIdMap[$k])) {
$arrProducts[$arrIdMap[$k]] = $v;
}
}

$this->arrProducts = $arrProducts;
}


/**
* Split tax amount amongst collection products
*
* @param IsotopeProductCollection $objCollection
* @param \Model $objSource
*/
public function applySplittedTax(IsotopeProductCollection $objCollection, $objSource)
{
$this->tax_class = 0;
$this->before_tax = true;
$fltTotal = 0;

if (!$objSource->isPercentage()) {
$fltTotal = $objCollection->getTaxFreeSubtotal();

if ($fltTotal == 0) {
return;
}
}

foreach ($objCollection->getItems() as $objItem) {
if ($objSource->isPercentage()) {
$fltProductPrice = $objItem->getTotalPrice() / 100 * $objSource->getPercentage();
} else {
$fltProductPrice = $this->total_price / 100 * (100 / $fltTotal * $objItem->getTaxFreeTotalPrice());
}

$fltProductPrice = $fltProductPrice > 0 ? (floor($fltProductPrice * 100) / 100) : (ceil($fltProductPrice * 100) / 100);

$this->setAmountForCollectionItem($fltProductPrice, $objItem);
}
}

/**
* Add a tax number
*
* @param int $intId
*/
public function addTaxNumber($intId)
{
if (!\in_array($intId, $this->arrTaxIds)) {
$this->arrTaxIds[] = (int) $intId;
}
}

/**
* Get comma separated list of tax ids
*
* @return string
*/
public function getTaxNumbers()
{
return implode(',', $this->arrTaxIds);
}

/**
* Set the current record from an array
*
* @param array $arrData The data record
*
* @return \Model The model object
*/
public function setRow(array $arrData)
{
$this->arrProducts = StringUtil::deserialize($arrData['products']);
$this->arrTaxIds = explode(',', $arrData['tax_id']);

if (!\is_array($this->arrProducts)) {
$this->arrProducts = array();
}

if (!\is_array($this->arrTaxIds)) {
$this->arrTaxIds = array();
}

unset($arrData['products'], $arrData['tax_id']);

return parent::setRow($arrData);
}

/**
* Modify the current row before it is stored in the database
*
* @param array $arrSet The data array
*
* @return array The modified data array
*/
protected function preSave(array $arrSet)
{
$arrSet['products'] = serialize($this->arrProducts);
$arrSet['tax_id'] = implode(',', $this->arrTaxIds);

return $arrSet;
}


/**
* Generate surcharges for a collection
*
* Process:
* 1. Collect surcharges (e.g. shipping and billing) from Isotope core and submodules using hook
* 2. Split surcharges by "with or without tax"
* => surcharges without tax are placed after tax surcharges and ignored in the complex compilation step
* 3. Run through all product collection items and calculate their tax amount
* 4. Run through all surcharges with tax and calculate their tax amount
*
* @param IsotopeProductCollection|\Isotope\Model\ProductCollection\Order $objCollection
*
* @return array
*/
public static function findForCollection(IsotopeProductCollection $objCollection)
{
$arrPreTax = [];
$arrPostTax = [];
$arrTaxes = [];

// !HOOK: get collection surcharges
if (isset($GLOBALS['ISO_HOOKS']['findSurchargesForCollection']) && \is_array($GLOBALS['ISO_HOOKS']['findSurchargesForCollection'])) {
foreach ($GLOBALS['ISO_HOOKS']['findSurchargesForCollection'] as $callback) {
$arrResult = System::importStatic($callback[0])->{$callback[1]}($objCollection);

foreach ($arrResult as $objSurcharge) {
if (!($objSurcharge instanceof IsotopeProductCollectionSurcharge) || $objSurcharge instanceof Tax) {
throw new \InvalidArgumentException('Instance of ' . \get_class($objSurcharge) . ' is not a valid product collection surcharge.');
}

if ($objSurcharge->hasTax()) {
$arrPreTax[] = $objSurcharge;
} else {
$arrPostTax[] = $objSurcharge;
}
}
}
}

static::addTaxesForItems($arrTaxes, $objCollection, $arrPreTax);

static::addTaxesForSurcharges(
$arrTaxes,
$arrPreTax,
[
'billing' => $objCollection->getBillingAddress(),
'shipping' => $objCollection->getShippingAddress(),
]
);

return array_merge($arrPreTax, $arrTaxes, $arrPostTax);
}


/**
* Create a payment surcharge
*
* @param IsotopePayment $objPayment
* @param IsotopeProductCollection $objCollection
*
* @return Payment
*/
public static function createForPaymentInCollection(IsotopePayment $objPayment, IsotopeProductCollection $objCollection)
{
return static::buildSurcharge('Isotope\Model\ProductCollectionSurcharge\Payment', $GLOBALS['TL_LANG']['MSC']['paymentLabel'], $objPayment, $objCollection);
}

/**
* Create a shipping surcharge
*
* @param IsotopeShipping $objShipping
* @param IsotopeProductCollection $objCollection
*
* @return Shipping
*/
public static function createForShippingInCollection(IsotopeShipping $objShipping, IsotopeProductCollection $objCollection)
{
return static::buildSurcharge('Isotope\Model\ProductCollectionSurcharge\Shipping', $GLOBALS['TL_LANG']['MSC']['shippingLabel'], $objShipping, $objCollection);
}


/**
* Build a product collection surcharge for given class type
*
* @param string $strClass
* @param string $strLabel
* @param IsotopePayment|IsotopeShipping $objSource
* @param IsotopeProductCollection $objCollection
*
* @return ProductCollectionSurcharge
*/
protected static function buildSurcharge($strClass, $strLabel, $objSource, IsotopeProductCollection $objCollection)
{
$intTaxClass = $objSource->tax_class;

/** @var ProductCollectionSurcharge $objSurcharge */
$objSurcharge = new $strClass();
$objSurcharge->source_id = $objSource->id;
$objSurcharge->label = sprintf($strLabel, $objSource->getLabel());
$objSurcharge->price = ($objSource->isPercentage() ? $objSource->getPercentage() . '%' : '&nbsp;');
$objSurcharge->total_price = $objSource->getPrice();
$objSurcharge->tax_free_total_price = $objSurcharge->total_price;
$objSurcharge->tax_class = $intTaxClass;
$objSurcharge->before_tax = ($intTaxClass ? true : false);
$objSurcharge->addToTotal = true;

if ($intTaxClass == -1) {
$objSurcharge->applySplittedTax($objCollection, $objSource);
} elseif ($intTaxClass > 0) {

/** @var TaxClass $objTaxClass */
if (($objTaxClass = TaxClass::findByPk($intTaxClass)) !== null) {

/** @var TaxRate $objIncludes */
if (($objIncludes = $objTaxClass->getRelated('includes')) !== null) {

$fltPrice = $objSurcharge->total_price;
$arrAddresses = array(
'billing' => $objCollection->getBillingAddress(),
'shipping' => $objCollection->getShippingAddress(),
);

if ($objIncludes->isApplicable($fltPrice, $arrAddresses)) {
$fltTax = $objIncludes->calculateAmountIncludedInPrice($fltPrice);
$objSurcharge->tax_free_total_price = $fltPrice - $fltTax;
}
}
}
}

return $objSurcharge;
}

/**
* Create or add taxes for each collection item
*
* @param Tax[] $arrTaxes
* @param IsotopeOrderableCollection $objCollection
* @param ProductCollectionSurcharge[] $arrSurcharges
* @param Address[] $arrAddresses
*/
private static function addTaxesForItems(array &$arrTaxes, IsotopeProductCollection $objCollection, array $arrSurcharges, array $arrAddresses = null)
{
foreach ($objCollection->getItems() as $objItem) {

// This should never happen, but we can't calculate it
if (!$objItem->hasProduct()) {
continue;
}

$objProduct = $objItem->getProduct();

/** @var TaxClass $objTaxClass */
$objTaxClass = $objProduct->getPrice() ? $objProduct->getPrice()->getRelated('tax_class') : null;

// Skip products without tax class
if (null === $objTaxClass) {
continue;
}

$arrTaxIds = [];
$fltPrice = $objItem->getTotalPrice();

/** @var ProductCollectionSurcharge $objSurcharge */
foreach ($arrSurcharges as $objSurcharge) {
$fltPrice += $objSurcharge->getAmountForCollectionItem($objItem);
}

$productAddresses = $arrAddresses;

if (null === $productAddresses) {
$productAddresses = array(
'billing' => $objCollection->getBillingAddress(),
'shipping' => $objProduct->isExemptFromShipping() ? $objCollection->getBillingAddress() : $objCollection->getShippingAddress(),
);
}

/** @var TaxRate $objIncludes */
if (($objIncludes = $objTaxClass->getRelated('includes')) !== null
&& $objIncludes->isApplicable($fltPrice, $productAddresses)
) {
$addToTotal = static::getTaxAddState(false);
$total = $addToTotal ? $objIncludes->calculateAmountAddedToPrice($fltPrice) : $objIncludes->calculateAmountIncludedInPrice($fltPrice);

$arrTaxIds[] = static::addTax(
$arrTaxes,
$objTaxClass->id . '_' . $objIncludes->id,
($objTaxClass->getLabel() ?: $objIncludes->getLabel()),
$objIncludes->getAmount(),
$objIncludes->isPercentage(),
$total,
$objTaxClass->applyRoundingIncrement,
$addToTotal,
$objTaxClass->notNegative
);
}

/** @var TaxRate[] $objRates */
if (($objRates = $objTaxClass->getRelated('rates')) !== null) {
foreach ($objRates as $objTaxRate) {

if ($objTaxRate->isApplicable($fltPrice, $productAddresses)) {
$addToTotal = static::getTaxAddState(true);
$total = $addToTotal ? $objTaxRate->calculateAmountAddedToPrice($fltPrice) : $objTaxRate->calculateAmountIncludedInPrice($fltPrice);

$arrTaxIds[] = static::addTax(
$arrTaxes,
$objTaxRate->id,
$objTaxRate->getLabel(),
$objTaxRate->getAmount(),
$objTaxRate->isPercentage(),
$total,
$objTaxClass->applyRoundingIncrement,
$addToTotal,
$objTaxClass->notNegative
);

if ($objTaxRate->stop) {
break;
}
}
}
}

$strTaxId = implode(',', $arrTaxIds);

if ($objItem->tax_id != $strTaxId) {
$objCollection->updateItem($objItem, array('tax_id' => $strTaxId));
}

foreach ($arrSurcharges as $objSurcharge) {
if ($objSurcharge->getAmountForCollectionItem($objItem) > 0) {
foreach ($arrTaxIds as $taxId) {
$objSurcharge->addTaxNumber($taxId);
}
}
}
}
}

/**
* Create or add taxes for pre-tax collection surcharges
*
* @param Tax[] $arrTaxes
* @param ProductCollectionSurcharge[] $arrSurcharges
* @param Address[] $arrAddresses
*/
private static function addTaxesForSurcharges(array &$arrTaxes, array $arrSurcharges, array $arrAddresses)
{
foreach ($arrSurcharges as $objSurcharge) {

/** @var TaxClass $objTaxClass */
$objTaxClass = TaxClass::findByPk($objSurcharge->tax_class);

// Skip products without tax class
if (null === $objTaxClass) {
continue;
}

$fltPrice = $objSurcharge->total_price;

/** @var TaxRate $objIncludes */
if (($objIncludes = $objTaxClass->getRelated('includes')) !== null
&& $objIncludes->isApplicable($fltPrice, $arrAddresses)
) {
$addToTotal = static::getTaxAddState(false);
$fltPrice = $addToTotal ? $objIncludes->calculateAmountAddedToPrice($fltPrice) : $objIncludes->calculateAmountIncludedInPrice($fltPrice);

$taxId = static::addTax(
$arrTaxes,
$objTaxClass->id . '_' . $objIncludes->id,
($objTaxClass->getLabel() ?: $objIncludes->getLabel()),
$objIncludes->getAmount(),
$objIncludes->isPercentage(),
$fltPrice,
$objTaxClass->applyRoundingIncrement,
$addToTotal,
$objTaxClass->notNegative
);

$objSurcharge->addTaxNumber($taxId);
}

/** @var TaxRate[] $objRates */
if (($objRates = $objTaxClass->getRelated('rates')) !== null) {
foreach ($objRates as $objTaxRate) {

if ($objTaxRate->isApplicable($fltPrice, $arrAddresses)) {
$addToTotal = static::getTaxAddState(true);
$fltPrice = $addToTotal ? $objTaxRate->calculateAmountAddedToPrice($fltPrice) : $objTaxRate->calculateAmountIncludedInPrice($fltPrice);

$taxId = static::addTax(
$arrTaxes,
$objTaxRate->id,
$objTaxRate->getLabel(),
$objTaxRate->getAmount(),
$objTaxRate->isPercentage(),
$fltPrice,
$objTaxClass->applyRoundingIncrement,
$addToTotal,
$objTaxClass->notNegative
);

$objSurcharge->addTaxNumber($taxId);

if ($objTaxRate->stop) {
break;
}
}
}
}
}
}

/**
* Add tax amount to the array of taxes, creating a new instance of Tax model if necessary
*
* @param array $arrTaxes
* @param string $id
* @param string $label
* @param mixed $price
* @param bool $isPercentage
* @param float $total
* @param bool $applyRoundingIncrement
* @param bool $addToTotal
* @param bool $notNegative
*
* @return int
*/
private static function addTax(array &$arrTaxes, $id, $label, $price, $isPercentage, $total, $applyRoundingIncrement, $addToTotal, $notNegative)
{
$objTax = $arrTaxes[$id];

if (null === $objTax || !($objTax instanceof Tax)) {
$objTax = new Tax();
$objTax->label = $label;
$objTax->price = $price . ($isPercentage ? '%' : '');
$objTax->total_price = $total;
$objTax->addToTotal = $addToTotal;
$objTax->applyRoundingIncrement = $applyRoundingIncrement;

$arrTaxes[$id] = $objTax;
} else {
$objTax->total_price = ($objTax->total_price + $total);

if (is_numeric($objTax->price) && is_numeric($price)) {
$objTax->price += $price;
}
}

if ($notNegative && $objTax->total_price < 0) {
$objTax->total_price = 0;
}

$taxId = array_search($id, array_keys($arrTaxes)) + 1;
$objTax->addTaxNumber($taxId);

return $taxId;
}

/**
* Get "add to total" state for tax rate
*
* @param bool $default The legacy state (if tax was included in backend price)
*
* @return bool
*/
private static function getTaxAddState($default)
{
switch (Isotope::getConfig()->getPriceDisplay()) {
case Config::PRICE_DISPLAY_NET:
return true;

case Config::PRICE_DISPLAY_GROSS:
case Config::PRICE_DISPLAY_FIXED:
return false;

case Config::PRICE_DISPLAY_LEGACY:
default:
return $default;
}
}
}

+ 126
- 49
src/EventListener/PostCheckoutListener.php 查看文件

@@ -6,58 +6,67 @@ namespace App\EventListener;
use Contao\CoreBundle\ServiceAnnotation\Hook;
use Contao\FrontendTemplate;
use Contao\Module;
use Contao\System;
use App\ExactApi\ApiExact;
use Isotope\Model\Address;
use Isotope\Model\Product;
use Isotope\Model\ProductCollection\Order;
use Isotope\Model\ProductCollectionItem;
use Isotope\Model\ProductCollectionSurcharge;

class PostCheckoutListener
{
const WAREHOUSE_ID = 'd8a6a9b8-d0ac-4d36-8d00-bd420d0d81f5';
const PAYMENT_CONDITION = 'PP';
const VAT_FACTOR = 1.19;

private Order $order;
private ApiExact $apiExact;
private $dbProductsBySku = [];
private $salesOrderItems = [];
private $billingCustomer = null;
private $shippingCustomer = null;

/**
* @Hook("postCheckout")
*/
// public function __invoke(int $userId, array $userData, Module $module): void
public function __invoke(Order $order, $item): void
{
$apiExact = new ApiExact();
$this->order = $order;
$this->apiExact = new ApiExact();

//ob_start();
$salesOrderItems = [];
/** @var ProductCollectionItem $orderItem */
foreach($order->getItems() as $orderItem) {
$salesOrderItems[] = $this->createOrderItem($orderItem);
// /** @var Product $orderItem */
// $product = $orderItem->getProduct();
// var_dump($orderItem->id);
// var_dump($orderItem->sku);
// var_dump($orderItem->quantity);
// var_dump($orderItem->tax_free_price);
//
// var_dump($product->id);
// var_dump($product->name);
// var_dump($product->is_set);
$this->setDbProducts();
$this->setOrderItems();
$this->setCustomers();

$surCharges = [];
/** @var ProductCollectionSurcharge $orderSurcharge */
foreach ($order->getSurcharges() as $orderSurcharge) {
$surCharges[] = $orderSurcharge;
}
//var_dump($apiExact->test());
// file_put_contents('dan.txt', ob_get_contents());
// ob_end_clean();



$shippingCustomer = null;
// if ($this->compareAddresses() === false) {
// $shippingCustomer = $apiExact->createCustomer(
// $this->createCustomerApiData($order->getShippingAddress())
// );
// }
//
$billingCustomer = $apiExact->createCustomer(
$this->createCustomerApiData($order->getBillingAddress())
);
$apiExact->createSalesOrder($this->createSalesOrderData($order, $billingCustomer, $shippingCustomer));
$this->apiExact->createSalesOrder($this->createSalesOrderData());

}

private function setDbProducts()
{
$db = System::getContainer()->get('database_connection');
$sql = "SELECT tip.*, tippt.price
FROM `tl_iso_product` tip, `tl_iso_product_price` tipp, `tl_iso_product_pricetier` tippt
WHERE tipp.pid = tip.id
AND tippt.pid = tipp.id";
$stmt = $db->query($sql);
$dbProducts = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($dbProducts as $dbProduct) {
$this->dbProductsBySku[$dbProduct['sku']] = $dbProduct;
}
// ob_start();
// var_dump($this->dbProductsBySku);
// file_put_contents('dan.txt', ob_get_contents());
// ob_end_clean();

}

@@ -89,34 +98,102 @@ class PostCheckoutListener
];
}

private function createOrderItem(ProductCollectionItem $orderItem)
private function setOrderItems()
{
/** @var Product $orderItem */
$product = $orderItem->getProduct();
return [
'Description' => $product->name,
'Item' => $product->exact_id,
'UnitPrice' => (float) $orderItem->tax_free_price / (int) $orderItem->quantity,
'Quantity' => $orderItem->quantity
];
/** @var ProductCollectionItem $orderItem */
foreach($this->order->getItems() as $orderItem) {
/** @var Product $orderItem */
$product = $orderItem->getProduct();

if ($product->is_set === null) {
$name = $product->name;
$exactId = $product->exact_id;
$unitPrice = (float) $orderItem->tax_free_price / (int) $orderItem->quantity;
$quantity = $orderItem->quantity;
$this->salesOrderItems[] = [
'Description' => $name,
'Item' => $exactId,
'UnitPrice' => $unitPrice,
'Quantity' => $quantity
];
} else {
$productSet = $this->dbProductsBySku[$product->sku];
$quantity = $orderItem->quantity;
$setProducts = [];
$setPriceSingleProducts = 0.00;
for ($i = 1; $i <= 10; $i++) {
$num = sprintf("%02d", $i);
$fieldSku = 'set_product_' . $num;
$fieldQty = 'set_product_' . $num . '_qty';

if (
$productSet[$fieldSku] !== '' &&
array_key_exists($productSet[$fieldSku], $this->dbProductsBySku) &&
$productSet[$fieldQty] !== ''
) {
$dbSetProduct = $this->dbProductsBySku[$productSet[$fieldSku]];
$qty = (int) $productSet[$fieldQty];
$netPrice = (float) $dbSetProduct['price'] / self::VAT_FACTOR;
$setPriceSingleProducts += $netPrice * $qty;
$setProducts[] = [
'product' => $dbSetProduct,
'qty' => $qty,
'netPrice' => $netPrice
];
}
}
$setDiscountFactor = (float) $orderItem->tax_free_price / $setPriceSingleProducts;
ob_start();
var_dump($setProducts);
file_put_contents('flo.txt', ob_get_contents());
ob_end_clean();

foreach ($setProducts as $setProduct) {
$this->salesOrderItems[] = [
'Description' => $setProduct['product']['name'],
'Item' => $setProduct['product']['exact_id'],
'UnitPrice' => round($setProduct['netPrice'] * $setDiscountFactor, 2),
'Quantity' => $quantity * $setProduct['qty']
];
}
}
}
}

private function setCustomers()
{
if ($this->compareAddresses($this->order) === false) {
$this->shippingCustomer = $this->apiExact->createCustomer(
$this->createCustomerApiData($this->order->getShippingAddress())
);
}

$this->billingCustomer = $this->apiExact->createCustomer(
$this->createCustomerApiData($this->order->getBillingAddress())
);
}

private function createSalesOrderData(Order $order, $billingCustomer, $salesOrderItems, $shippingCustomer = null)
private function createSalesOrderData()
{
$date = new \DateTime('now');
$res = [
'Description' => $billingCustomer['Name'],
'Description' => $this->order->id,
'OrderDate' => $date->format('m/d/Y H:i:s'),
'OrderedBy' => $billingCustomer['ID'],
'OrderedBy' => $this->billingCustomer->ID,
'WarehouseID' => self::WAREHOUSE_ID,
'SalesOrderLines' => [
$salesOrderItems
]
'SalesOrderLines' => $this->salesOrderItems,
'PaymentCondition' => self::PAYMENT_CONDITION,
];
if ($shippingCustomer !== null) {
$res['DeliverTo'] = $shippingCustomer['ID'];
if ($this->shippingCustomer !== null) {
$res['DeliverTo'] = $this->shippingCustomer->ID;
}

// if ($discount !== null) {
// $res['Discount'] = $shippingCustomer->ID;
// }
ob_start();
var_dump($res);
file_put_contents('dan.txt', ob_get_contents());
ob_end_clean();
return $res;
}
}

+ 6
- 29
src/ExactApi/ApiExact.php 查看文件

@@ -12,16 +12,12 @@ class ApiExact
const CLIENT_ID = "5a04d118-349c-4750-aac3-fa3a386999c6";
const CLIENT_SECRET = "E7Wuqcsp4Lih";

const ACCESS_TOKEN_VALID_DURATION = 600 - 50;
const ITEM_GROUP_UUID = 'df17bdaf-2af7-4e9f-8d60-326e36b57764';
const PRODUCT_CODE_PREFIX = "WR";

public function getAccessToken()
{
$tokenData = json_decode(file_get_contents(__DIR__ . '/tokenData', true));
ob_start();
var_dump($tokenData);
ob_end_clean();

if (!property_exists($tokenData, 'expiry_time') || (int)$tokenData->expiry_time < time()) {
$postData = array(
@@ -44,10 +40,9 @@ class ApiExact
$jsonResult = json_decode($response);

if (property_exists($jsonResult, 'error')) {
$msg = $jsonResult->error;
throw new \Exception($msg);
return $tokenData->access_token;
}
$jsonResult->expiry_time = time() + self::ACCESS_TOKEN_VALID_DURATION;
$jsonResult->expiry_time = time() + (int) $jsonResult->expires_in;
file_put_contents(__DIR__ . '/tokenData', json_encode($jsonResult));

$tokenData = json_decode(file_get_contents(__DIR__ . '/tokenData', true));
@@ -96,33 +91,15 @@ class ApiExact
public function createCustomer($customerData)
{
$url = self::API_URL_WNR . "/crm/Accounts";
return json_decode($this->postApiData($url, $customerData));
$res = $this->postApiData($url, $customerData);
return json_decode($res)->d;
}

public function createSalesOrder($salesOrderData)
{
$url = self::API_URL_WNR . "/salesorder/SalesOrders";
// $parameters = [
// 'Description' => 'Daniel Knudsen',
// 'OrderDate' => '07/13/2022 17:00:00',
// 'OrderedBy' => '9ba706a3-d6f5-40c8-8d4f-e55a37692cef',
// 'WarehouseID' => 'd8a6a9b8-d0ac-4d36-8d00-bd420d0d81f5',
// 'SalesOrderLines' => [
// [
// 'Description' => 'TEST: Reinigungstuch grün',
// 'Item' => '9dcd8b50-5de6-4f15-a51a-c51282292383',
// 'UnitPrice' => '2.45',
// 'Quantity' => '3'
// ],
// [
// 'Description' => 'TEST: McQuade´s E-Bike Kettenrückführ - Tool',
// 'Item' => '0e04113f-1299-4d3c-b65e-01e83ca5b3b2',
// 'UnitPrice' => '476.00',
// 'Quantity' => '1'
// ],
// ]
// ];
return json_decode($this->postApiData($url, $salesOrderData));
$res = $this->postApiData($url, $salesOrderData);
return json_decode($res)->d;
}

private function getApiData($url)


+ 7
- 6
src/ExactApi/IsotopeDatabaseHandler.php 查看文件

@@ -183,11 +183,12 @@ class IsotopeDatabaseHandler

private function convertShippingWeight(Product $product)
{
$shippingWeight = $product->getGrossWeight() !== '' ?
$product->getGrossWeight() :
$product->getNetWeight();
return ((int) $shippingWeight === 0 || $shippingWeight === '') ?
'' :
'a:2:{s:4:"unit";s:2:"kg";s:5:"value";s:3:"' . $shippingWeight . '";}';
$shippingWeight = $product->getGrossWeight() ?? $product->getNetWeight();
if ($shippingWeight !== null) {
$length = \mb_strlen( (string) $shippingWeight);
return 'a:2:{s:4:"unit";s:2:"kg";s:5:"value";s:'.$length.':"' . $shippingWeight . '";}';
} else {
return '';
}
}
}

+ 9
- 0
src/ExactApi/apiTestGetAccessToken.php 查看文件

@@ -0,0 +1,9 @@
<?php

require __DIR__ . '/ApiExact.php';
require __DIR__ . '/IsotopeDatabaseHandler.php';
//namespace App\ExactApi;
//use App\ExactApi\ApiExact;

$apiExact = new ApiExact();
echo $apiExact->getAccessToken() . "\n";

+ 0
- 23
src/ExactApi/apiUpdateProducts.php 查看文件

@@ -1,23 +0,0 @@
<?php
//require __DIR__ . '/ApiExact.php';
//require __DIR__ . '/IsotopeDatabaseHandler.php';

namespace App\ExactApi;
//use App\ExactApi\ApiExact;
//use App\ExactApi\IsotopeDatabaseHandler;

//use App\ExactApi\ApiExact as ApiExact;
//use App\ExactApi\IsotopeDatabaseHandler as IsotopeDatabaseHandler;

//include_once('App\ExactApi\ApiExact.php');
//include_once('App\ExactApi\IsotopeDatabaseHandler.php');

require_once './ApiExact.php';
require_once './IsotopeDatabaseHandler.php';

$apiConnector = new ApiExact();
$databaseHandler = new IsotopeDatabaseHandler();

//echo $apiConnector->getAccessToken() . "\n";
$products = $apiConnector->getProducts();
$databaseHandler->processProducts($products);

+ 1
- 1
src/ExactApi/tokenData 查看文件

@@ -1 +1 @@
{"access_token":"stampDE001.gAAAAKLeomGUJnO_59CX7KmwE4tkt1bPxLR7EfU5E2eHjj6LeU2dAPfkRstKdlJJoudf3y6ehyKwF5wQQ1SljbA5sRrGwQsw4M876o0RRtxVHwyR6_QSoM7kP3qj7HfJLEDWjY-KrlJf_rlKtZZ2sRGJkX9jbd-4XDA_uqQECkf2NnIfVAIAAIAAAAC2ADvWhSjIjtyvs4_rhH9HzqaVKUbQthUoKf6StMSX4O5GzilHhM2cQCQJly_7hbpKHJMe4o167cPYIQLTeOilQdlQh21nhGykWfOKtXG31h210WtT2bg8Kc0MtrHQGi_f161wE_xINPXr-H7GTcXLe4klIGUkv0kmmmUacNoDUDfU1fPRTCCFvmkRnE7iBzd116aY9XMVw6mDucFExI9U-dLOD8IFWCPa9U6DSd50T7WoglDHC8Enh-J92C1c8kAhCCiGyA5GHyb9S1eJAnHFDYz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XoaUYnHx8hRzGeUk6s4fKy07nTMgUSmd8tWd_bCyaFxASgxv6Lnggh7plUIt-v8er290lm6xd6_0LJk9rFWqbBkLmSwIgL-xwkMFQP2iGC4ljPoLkMRHBKdqdbI","token_type":"bearer","expires_in":"600","refresh_token":"stampDE001.vhK0!IAAAAKjrezKWeYTHhtfVcl116j1YPQQGxeoEQsp0FsJzSa2Q8QEAAAHEvZm9p-Qv7g9WYZwQ8oFXlfacvvuDKRkEwNVK6wXj3vDKUhzqH9MNZkMLlid-FO76Rjg3YYk15cYB1s6GPzuqkpVtA-tYZdQoYA8gynmgb--UaI46_LVGkyQ_GwvxA61JN69xtp24Gx62pRyPD1F3U7j4iA1DAUd9cEkTdSAUsspjLIoGPEu_BL468V0UzetjkwCNbBkl_xNjRJF9cR_klTTyfUich0H8LDhUb-1koqHJLpPMK3MfIhKDAbyKArhzSXYLGs7cNI_o9LaD7bN4cxHq21SWF-ub1hTL7q_SGW6zHGjzohLUSUuwFIa-l5BSFc1otkY-bFVBTlnAT2LFb6DPNjfaLSa9idbXCk-hthCH6WJZ7lD2eAqbG7SPKIV60OAEhIQRSrN70MCeQmbRhivNjbDyhpC7UMWYloFXltc3b-3wt6YT-uyEr89rBkA5vIA5o-AC2dYmHWZ2Vy4bWxKaX6I31worvQkEiZ21J_7rFRQOixvKTvti0wgtC9GhTi3fRoaNxt2yrP94_BNlS0MMU4dZloIWRerBzSc-2PsojQGEmeAD_s-JieoVyR3uhTjzJ9tRlW4Xnjt2vr94iy2ZD_5yV_tPqsXH8NHbJWMewTl76C0hXXYKPey-caCNyS7EEcGo3vDgYqtD5t6V","expiry_time":1658142612}

+ 5
- 0
src/config.php 查看文件

@@ -0,0 +1,5 @@
<?php

// contao/config.php
use App\EventListener\PostCheckoutListener;
$GLOBALS['ISO_HOOKS']['postCheckout'][] = [PostCheckoutListener::class, '__invoke'];

正在加载...
取消
保存