<?php
namespace Nextag\Flow\Flow;
use Exception;
use Elasticsearch\ClientBuilder;
use Nextag\Checkout\Content\Checkout\CheckoutService;
use Shopware\Core\Content\Flow\Dispatching\Action\FlowAction;
use Shopware\Core\Framework\Event\FlowEvent;
use Nextag\Flow\Helper\Log;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
class ProcessOrderAction extends FlowAction
{
private Log $log;
private \Nextag\Mail\Helper\MailGenerator $mailGenerator;
private $checkoutService;
private $giftcardHelper;
private $promotionHelper;
private $orderExtensionRepository;
private $config;
private $wordpress;
private $productRepository;
private $languageRepository;
private $elasticClient = null;
protected $eventHelper;
protected $abacus;
protected $indexPrefix;
protected $hostname;
protected $port;
protected $locales;
protected $languageCache;
public function __construct(
\Shopware\Core\System\SystemConfig\SystemConfigService $config,
Log $log,
EntityRepositoryInterface $orderExtensionRepository,
\Nextag\Mail\Helper\MailGenerator $mailGenerator,
CheckoutService $checkoutService,
\Nextag\Giftcard\Helper\Giftcard $giftcardHelper,
\Nextag\Product\Helper\Event $eventHelper,
\Nextag\Giftcard\Helper\Promotion $promotionHelper,
\Nextag\Checkout\Helper\Abacus $abacus,
\Nextag\Connector\Helper\Wordpress $wordpress,
EntityRepositoryInterface $productRepository,
EntityRepositoryInterface $languageRepository
) {
$this->config = $config;
$this->log = $log;
$this->orderExtensionRepository = $orderExtensionRepository;
$this->checkoutService = $checkoutService;
$this->giftcardHelper = $giftcardHelper;
$this->eventHelper = $eventHelper;
$this->promotionHelper = $promotionHelper;
$this->mailGenerator = $mailGenerator;
$this->abacus = $abacus;
$this->wordpress = $wordpress;
$this->productRepository = $productRepository;
$this->languageRepository = $languageRepository;
}
public static function getName(): string
{
return 'action.flow.nextag.processorder';
}
public static function getSubscribedEvents(): array
{
return [
self::getName() => 'handle'
];
}
public function requirements(): array
{
return [];
}
public function handle(FlowEvent $event): void
{
try {
$this->log->info("Processorderaction start");
$language = "de";
$context = $event->getContext();
$config = $event->getConfig();
$order = null;
try {
$order = $event->getEvent()->getOrder();
} catch (Exception $e) {
$this->log->error($e);
$this->log->error(new \Exception("Flow ProcessOrder: Order not found"));
return;
}
if ($order === null) {
$this->log->error(new \Exception("Flow ProcessOrder: Order not found"));
return;
}
$this->log->info("Ordernumber: ".$order->getOrdernumber());
try {
if (isset($config["processgiftcards"]) && $config["processgiftcards"]["status"]) {
$this->log->info("process giftcards");
$this->giftcardHelper->processGiftcardsUsed($order, $context);
$this->giftcardHelper->processGiftcardsBuys($order, $language, $context);
}
if (isset($config["processpromotions"]) && $config["processpromotions"]["status"]) {
$this->log->info("process promotions");
$this->promotionHelper->processPromotionUsed($order, $context);
}
if (isset($config['processwordpressevents']) && $config['processwordpressevents']['status']) {
$this->log->info("processwordpressevents");
$this->wordpress->processWordpressEvents($order);
} else {
$this->log->info("not processwordpressevents");
}
} catch (Exception $e) {
$this->log->error($e);
}
$resultExportOrder = true;
try {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter("orderId", $order->getId()));
$orderExtension = $this->orderExtensionRepository->search($criteria, $context)->getEntities()->first();
$data = [];
if ($orderExtension) {
$data["id"] = $orderExtension->getId();
if ($orderExtension->getComment()) {
$data["comment"] = $orderExtension->getComment();
}
if ($orderExtension->getDeliverydate()) {
$data["deliverydate"] = $orderExtension->getDeliverydate();
}
if ($orderExtension->getDeliverytype()) {
$data["deliverytype"] = $orderExtension->getDeliverytype();
}
if ($orderExtension->getDeliverylocation()) {
$data["deliverylocation"] = $orderExtension->getDeliverylocation();
}
if ($orderExtension->getDeliverylocationcomment()) {
$data["deliverylocationcomment"] = $orderExtension->getDeliverylocationcomment();
}
if ($orderExtension->getGiftmessagefrom()) {
$data["giftmessagefrom"] = $orderExtension->getGiftmessagefrom();
}
if ($orderExtension->getGiftmessageto()) {
$data["giftmessageto"] = $orderExtension->getGiftmessageto();
}
if ($orderExtension->getGiftmessage()) {
$data["giftmessage"] = $orderExtension->getGiftmessage();
}
if ($orderExtension->getGiftbox1qty()) {
$data["giftbox1qty"] = $orderExtension->getGiftbox1qty();
}
if ($orderExtension->getGiftbox2qty()) {
$data["giftbox2qty"] = $orderExtension->getGiftbox2qty();
}
if ($orderExtension->getGiftbox3qty()) {
$data["giftbox3qty"] = $orderExtension->getGiftbox3qty();
}
if ($orderExtension->getGiftbox4qty()) {
$data["giftbox14qty"] = $orderExtension->getGiftbox4qty();
}
if ($orderExtension->getGiftbox5qty()) {
$data["giftbox5qty"] = $orderExtension->getGiftbox5qty();
}
if ($orderExtension->getGiftbox6qty()) {
$data["giftbox6qty"] = $orderExtension->getGiftbox6qty();
}
if ($orderExtension->getGiftbox7qty()) {
$data["giftbox7qty"] = $orderExtension->getGiftbox7qty();
}
if ($orderExtension->getGiftbox8qty()) {
$data["giftbox8qty"] = $orderExtension->getGiftbox8qty();
}
if ($orderExtension->getGiftbox1comment()) {
$data["giftbox1comment"] = $orderExtension->getGiftbox1comment();
}
if ($orderExtension->getGiftbox2comment()) {
$data["giftbox2comment"] = $orderExtension->getGiftbox2comment();
}
if ($orderExtension->getGiftbox3comment()) {
$data["giftbox3comment"] = $orderExtension->getGiftbox3comment();
}
if ($orderExtension->getGiftbox4comment()) {
$data["giftbox4comment"] = $orderExtension->getGiftbox4comment();
}
if ($orderExtension->getGiftbox5comment()) {
$data["giftbox5comment"] = $orderExtension->getGiftbox5comment();
}
if ($orderExtension->getGiftbox6comment()) {
$data["giftbox6comment"] = $orderExtension->getGiftbox6comment();
}
if ($orderExtension->getGiftbox7comment()) {
$data["giftbox7comment"] = $orderExtension->getGiftbox7comment();
}
if ($orderExtension->getGiftbox8comment()) {
$data["giftbox8comment"] = $orderExtension->getGiftbox8comment();
}
if ($orderExtension->getRetouren()) {
$data["retouren"] = $orderExtension->getRetouren();
}
if ($orderExtension->getVoigtkundennummer()) {
$data["voigtkundennummer"] = $orderExtension->getVoigtkundennummer();
}
if ($orderExtension->getLanguage()) {
$data["language"] = $orderExtension->getLanguage();
}
if ($resultExportOrder) {
$data["exportordererp"] = 1;
} else {
$data["exportordererp"] = 2;
}
$this->checkoutService->save($data, $event->getEvent());
}
} catch (Exception $e) {
$this->log->error($e);
}
$config["exportorder"]["result"] = $resultExportOrder;
$this->reduceProductStocks($context, $order);
$this->log->info("process order emails");
$this->mailGenerator->processOrderEmails($order, $config, $orderExtension);
$this->eventHelper->sendEvent($order,"de-CH");
try {
if ($config["exportorder"]["status"]) {
if ($this->config->get("NextagCheckout.config.abacusExportActive")) {
$this->log->info("Abacus order export active", false);
$this->abacus->exportOrder($order,$context);
} else {
$this->log->info("Abacus order export inactive",false);
}
}
} catch (Exception $e) {
$this->log->error($e);
}
$this->log->info("Processorderaction end");
} catch (\Exception $e) {
$this->log->error($e);
throw $e;
}
}
private function reduceProductStocks($context,$order) {
try {
$lc = $this->config->get("NextagFilter.config.languageCodes");
if ($lc) {
$this->locales = array_map(
'trim',
explode(",", $lc)
);
}
$criteria = new Criteria();
$criteria->addAssociation('locale');
$lc = $this->languageRepository->search($criteria, $context);
foreach ($lc as $k => $v) {
$this->languageCache[str_replace("-", "_", $v->getLocale()->getCode())] = $k;
}
foreach($order->getLineItems() as $lineItem) {
$customFields = $lineItem->getPayload()["customFields"];
$customData = [];
if (isset($lineItem->getPayload()["customData"]) && !is_array($lineItem->getPayload()["customData"])) {
$customData = json_decode($lineItem->getPayload()["customData"], true);
}
if (!isset($customData["isGiftcard"]) && !isset($lineItem->getPayload()["isShopPromotion"]) && !isset($lineItem->getPayload()["isUsedPromotion"]) && !isset($lineItem->getPayload()["isGiftcardUsed"])) {
$availableQty = $lineItem->getPayload()["stock"];
$quantity = $lineItem->getQuantity();
$newQuantity = $availableQty - $quantity;
if ($newQuantity < 0) {
$newQuantity = 0;
}
if ($newQuantity == 0) {
$d = [
"id" => $lineItem->getReferencedId(),
"stock" => $newQuantity,
"customFields" => [
"custom_produkt_label_produkt_ausverkauft" => true
]
];
} else {
$d = [
"id" => $lineItem->getReferencedId(),
"stock" => $newQuantity
];
}
$this->updateElasticsearchProduct($lineItem,$d);
$data[] = $d;
}
}
if (!empty($data)) {
$this->productRepository->upsert($data,$context);
}
} catch (Exception $e) {
$this->log->error($e);
}
}
private function updateElasticsearchProduct($lineItem, $data)
{
try {
//Elasticindexes updaten
$this->indexPrefix = $this->config->get("NextagFilter.config.elasticIndexprefix");
$this->hostname = $this->config->get("NextagFilter.config.elasticHostname");
$this->port = $this->config->get("NextagFilter.config.elasticPort");
if ($this->hostname) {
$hosts = [
$this->hostname . ":" . $this->port
];
if (!$this->elasticClient) {
$this->elasticClient = ClientBuilder::create()
->setHosts($hosts)->build();
}
}
foreach ($this->locales as $locale) {
if (isset($this->languageCache[$locale])) {
$languageId = $this->languageCache[$locale];
$alias = strtolower($this->indexPrefix . $languageId);
$searchParams = [
"index" => $alias,
"size" => 1,
"q" => "productNumber:".$lineItem->getPayload()["productNumber"]
];
$searchItem = $this->elasticClient->search($searchParams);
if (!empty($searchItem["hits"]["hits"])) {
$item = [
"stock" => $data["stock"]
];
if (isset($data["customFields"]) && isset($data["customFields"]["custom_produkt_label_produkt_ausverkauft"])) {
$item["custom_produkt_label_produkt_ausverkauft"] = $data["customFields"]["custom_produkt_label_produkt_ausverkauft"];
$item["custom_produkt_label_produkt_ausverkauft_lowercase"] = $data["customFields"]["custom_produkt_label_produkt_ausverkauft"];
}
$payload = [
'index' => $alias,
'id' => (string) $searchItem["hits"]["hits"][0]["_source"]["elasticid"],
'body' => ["doc" => $item]
];
//Update
$result = $this->elasticClient->update($payload);
}
}
}
} catch (\Exception $exception) {
$this->log->error($exception);
}
}
}