1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 
<?php
/* --------------------------------------------------------------
   OrdersModalsAjaxController.inc.php 2017-11-08
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2017 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

require_once DIR_FS_CATALOG . 'admin/includes/gm/classes/GMOrderFormat.php';

/**
 * Class OrdersModalsAjaxController
 *
 * AJAX controller for the orders modals.
 *
 * @category   System
 * @package    AdminHttpViewControllers
 * @extends    AdminHttpViewController
 */
class OrdersModalsAjaxController extends AdminHttpViewController
{
    /**
     * @var LanguageTextManager
     */
    protected $languageTextManager;
    
    /**
     * Initialize Controller
     *
     * @throws Exception
     */
    public function init()
    {
        $this->languageTextManager = MainFactory::create('LanguageTextManager');
        $this->_validatePageToken();
    }
    
    
    /**
     * Stores a tracking number for a specific order.
     *
     * @return JsonHttpControllerResponse
     *
     * @throws Exception
     * @throws UnexpectedValueException
     */
    public function actionStoreTrackingNumber()
    {
        $orderId         = $this->_getPostData('orderId');
        $trackingNumber  = $this->_getPostData('trackingNumber');
        $parcelServiceId = $this->_getPostData('parcelServiceId');
        
        $response = ['error'];
        
        if($parcelServiceId > 0)
        {
            $parcelServiceReader      = MainFactory::create('ParcelServiceReader');
            $parcelTrackingCodeWriter = MainFactory::create('ParcelTrackingCodeWriter');
            
            try
            {
                $parcelTrackingCodeWriter->insertTrackingCode($orderId, $trackingNumber, $parcelServiceId,
                                                              $parcelServiceReader);
                
                $response = ['success'];
            }
            catch(Exception $e)
            {
                $response = AjaxException::response($e); 
            }
        }
        
        return MainFactory::create('JsonHttpControllerResponse', $response);
    }
    
    
    /**
     * Change order status.
     *
     * @return JsonHttpControllerResponse
     *
     * @throws InvalidArgumentException
     */
    public function actionChangeOrderStatus()
    {
        $orderActions = MainFactory::create('OrderActions');
        
        $orderIds               = $this->_getPostData('selectedOrders');
        $statusId               = new IdType((int)$this->_getPostData('statusId'));
        $comment                = new StringType($this->_getPostData('comment'));
        $notifyCustomer         = new BoolType($this->_getPostData('notifyCustomer'));
        $sendParcelTrackingCode = new BoolType($this->_getPostData('sendParcelTrackingCode'));
        $sendComment            = new BoolType($this->_getPostData('sendComment'));
        $customerId             = new IdType($_SESSION['customer_id']);
        
        $logger = LogControl::get_instance();
        $logger->notice($_SESSION['customer_id']);
        
        try
        {
            foreach($orderIds as $orderId)
            {
                $orderActions->changeOrderStatus(new IdType($orderId), $statusId, $comment, $notifyCustomer,
                                                 $sendParcelTrackingCode, $sendComment, $customerId);
            }
            
            $response = ['success']; 
        }
        catch(Exception $e)
        {
            $response = AjaxException::response($e); 
        }
        
        return MainFactory::create('JsonHttpControllerResponse', $response);
    }
    
    
    /**
     * Download Bulk Invoices PDF.
     *
     * This method will provide a concatenated file of invoice PDFs. Provide a GET parameter "o" that contain
     * the selected order IDs.
     *
     * Notice: The "o" is used instead of "orderIds" because the final URL must be as small as possible (some
     * browsers do not work with GET URL of 100 orders).
     *
     * @see OrderActions
     */
    public function actionBulkPdfInvoices()
    {
        $orderActions = MainFactory::create('OrderActions');
        $orderIds     = $this->_getQueryParameter('o');
        $orderActions->bulkPdfInvoices($orderIds);
        return MainFactory::create('HttpControllerResponse', '');
    }
    
    
    /**
     * Download Bulk Packing Slips PDF.
     *
     * This method will provide a concatenated file of packing slip PDFs. Provide a GET parameter "o" that contain
     * the selected order IDs.
     *
     * Notice: The "o" is used instead of "orderIds" because the final URL must be as small as possible (some
     * browsers do not work with GET URL of 100 orders).
     *
     * @see OrderActions
     */
    public function actionBulkPdfPackingSlips()
    {
        $orderActions = MainFactory::create('OrderActions');
        $orderIds     = $this->_getQueryParameter('o');
        $orderActions->bulkPdfPackingSlips($orderIds);
        return MainFactory::create('HttpControllerResponse', '');
    }
    
    
    /**
     * Cancel Order Callback
     *
     * This method uses the OrderActions class to cancel an order and fulfill the requirements of the cancellation
     * (re-stock product, inform customer ...).
     *
     * @return JsonHttpControllerResponse
     */
    public function actionCancelOrder()
    {
        $orderActions = MainFactory::create('OrderActions');
        
        $orderIds                  = $this->_getPostData('selectedOrders');
        $restockQuantity           = new BoolType($this->_getPostData('reStock') === 'true');
        $recalculateShippingStatus = new BoolType($this->_getPostData('reShip') === 'true');
        $resetArticleStatus        = new BoolType($this->_getPostData('reActivate') === 'true');
        $notifyCustomer            = new BoolType($this->_getPostData('notifyCustomer') === 'true');
        $sendComment               = new BoolType($this->_getPostData('sendComments') === 'true');
        $comment                   = new StringType($this->_getPostData('cancellationComments'));
        
        $orderActions->cancelOrder($orderIds, $restockQuantity, $recalculateShippingStatus, $resetArticleStatus,
                                   $notifyCustomer, $sendComment, $comment);
        
        $urls = [];
        
        if($this->_getPostData('cancelInvoice') === 'true')
        {
            /** @var InvoiceArchiveReadService $invoiceArchiveReadService */
            $invoiceArchiveReadService = StaticGXCoreLoader::getService('InvoiceArchiveRead');
            
            foreach($orderIds as $orderId)
            {
                $invoices = $invoiceArchiveReadService->getInvoiceListByConditions(['order_id' => $orderId], null, null, new StringType('invoice_date DESC'));
                
                if(!$invoices->isEmpty())
                {
                    /** @var InvoiceListItem $invoice */
                    $invoice = $invoices->getItem(0);
                    
                    if(!$invoice->isCancellationInvoice())
                    {
                        $urls[] = 'gm_pdf_order.php?oID=' . (int)$orderId . '&type=invoice&cancel_invoice_id=' . $invoice->getInvoiceId();
                    }
                }
            }
        }
        
        return MainFactory::create('JsonHttpControllerResponse', ['urls' => $urls]);
    }
    
    
    /**
     * Delete Order Callback
     *
     * This method uses the OrderActions class to delete an order and fulfill the requirements of the removal
     * (re-stock product, re-activate ...).
     *
     * @return JsonHttpControllerResponse
     */
    public function actionDeleteOrder()
    {
        $orderActions = MainFactory::create('OrderActions');
        $db           = StaticGXCoreLoader::getDatabaseQueryBuilder();
        
        $orderIds                   = $this->_getPostData('selectedOrders');
        $restockQuantity            = new BoolType($this->_getPostData('reStock') === 'true');
        $recalculateShippingStatus  = new BoolType($this->_getPostData('reShip') === 'true');
        $resetProductShippingStatus = new BoolType($this->_getPostData('reActivate') === 'true');
        
        foreach($orderIds as $orderId)
        {
            $orderActions->removeOrderById(new IdType($orderId), $restockQuantity, $recalculateShippingStatus,
                                           $resetProductShippingStatus);
            
            $db->set('order_id', 0)->where('order_id', $orderId)->update('invoices');
            $db->set('order_id', 0)->where('order_id', $orderId)->update('packing_slips');
        }
        
        return MainFactory::create('JsonHttpControllerResponse', []);
    }
    
    
    /**
     * Get Email-Invoice Subject
     */
    public function actionGetEmailInvoiceSubject()
    {
        
        /** @var InvoiceArchiveReadService $invoiceReader */
        $invoiceReader   = StaticGXCoreLoader::getService('InvoiceArchiveRead');
        $orderId         = $this->_getQueryParameter('id');
        $invoices        = $invoiceReader->getInvoiceListByConditions(['order_id' => $orderId]);
        $invoiceIdExists = $invoices->isEmpty();
        $invoiceNumbers  = [];
        $dateFormat      = $this->languageTextManager->get_text('DATE_FORMAT', 'language_settings', (int)$_SESSION['languages_id']);
        $subject = gm_get_content('GM_PDF_EMAIL_SUBJECT', $_SESSION['languages_id']);
        
        if($invoices->count() === 1)
        {
            /** @var InvoiceListItem $invoice */
            $invoice = $invoices->getItem(0);
            
            $invoiceNumbers[$invoice->getInvoiceId()] = $invoice->getInvoiceNumber();
            
            $orderDate     = $invoice->getOrderDatePurchased();
            $invoiceNumber = $invoice->getInvoiceNumber();
        }
        elseif($invoices->count() > 1)
        {
            /** @var InvoiceListItem $invoice */
            foreach($invoices as $invoice)
            {
                $invoiceNumbers[$invoice->getInvoiceId()] = $invoice->getInvoiceNumber();
            }
            
            $subject = gm_get_content('GM_PDF_INVOICES_EMAIL_SUBJECT', $_SESSION['languages_id']);
            
            $orderDate     = $invoice->getOrderDatePurchased();
            $invoiceNumber = $invoice->getInvoiceNumber();
        }
        else
        {
            $orderDate     = new DateTime($this->_getQueryParameter('date'));
            $orderFormat   = new GMOrderFormat();
            $next_id       = $orderFormat->get_next_id('GM_NEXT_INVOICE_ID');
            $invoiceNumber = str_replace('{INVOICE_ID}', $next_id, gm_get_conf('GM_INVOICE_ID'));
        }
        
        $subject = str_replace(['{ORDER_ID}', '{DATE}', '{INVOICE_ID}', '{INVOICE_NUMBERS}'], [
            $orderId,
            $orderDate->format($dateFormat),
            $invoiceNumber,
            implode(', ', $invoiceNumbers)
        ], $subject);
        
        // Return the response back to the client. 
        return MainFactory::create('JsonHttpControllerResponse', [
            'subject'         => $subject,
            'invoiceIdExists' => $invoiceIdExists,
            'invoiceNumbers'  => $invoiceNumbers
        ]);
    }
    
    
    /**
     * Get Email-Invoice Subject (Raw Data)
     *
     * Currently the invoice ID can only be found in by parsing the PDF filename in the /export/invoice directory.
     *
     * This method will return the email subject data instead of the pre-made string.
     */
    public function actionGetEmailInvoiceSubjectData()
    {
        $invoiceId = $this->_getPostData('invoiceId');
        
        /** @var InvoiceArchiveReadService $invoiceReader */
        $invoiceReader   = StaticGXCoreLoader::getService('InvoiceArchiveRead');
        $invoiceListItem = $invoiceReader->getInvoiceListItemById(new IdType($invoiceId));
        
        //$filename = basename(array_pop(glob(DIR_FS_CATALOG . 'export/invoice/' . $orderId . '*')));
        //
        //$invoiceId = explode('__', $filename)[1];
        
        $dateFormat = $this->languageTextManager->get_text('DATE_FORMAT', 'language_settings', (int)$_SESSION['languages_id']);
        //$orderDate  = new DateTime($this->_getQueryParameter('date'));
        
        $subjectData = [
            'invoiceNumber' => $invoiceListItem->getInvoiceNumber(),
            'invoiceDate'   => $invoiceListItem->getInvoiceDate()->format($dateFormat)
        ];
        
        return MainFactory::create('JsonHttpControllerResponse', $subjectData);
    }

    /**
     * Get amount of invoices for an order.
     */
    public function actionGetInvoiceCount()
    {
        $orderId = (int)$this->_getQueryParameter('orderId');

        /** @var InvoiceArchiveReadService $invoiceArchiveReadService */
        $invoiceArchiveReadService = StaticGXCoreLoader::getService('InvoiceArchiveRead');
        $invoices = $invoiceArchiveReadService->getInvoiceListByConditions(['order_id' => $orderId]);

        return MainFactory::create('JsonHttpControllerResponse', ['count' => $invoices->count()]);
    }
}