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 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 
<?php
/* --------------------------------------------------------------
   OrdersOverviewTooltips.inc.php 2017-01-13
   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]
   --------------------------------------------------------------
*/

/**
 * Class OrdersOverviewTooltips
 *
 * This class generates the required HTML for the tooltips of each row in the orders overview table.
 * In order to be faster do not use any services but fetch the data directly with DB queries.
 *
 * @category   System
 * @package    Extensions
 * @subpackage Orders
 */
class OrdersOverviewTooltips
{
    /**
     * @var ContentView
     */
    protected $contentView;
    
    /**
     * @var CI_DB_query_builder
     */
    protected $db;
    
    
    /**
     * OrdersOverviewTooltips constructor.
     */
    public function __construct()
    {
        $this->db          = StaticGXCoreLoader::getDatabaseQueryBuilder();
        $this->contentView = MainFactory::create('ContentView');
        $this->contentView->set_escape_html(true);
        $this->contentView->set_flat_assigns(true);
        $this->contentView->set_template_dir(DIR_FS_ADMIN . 'html/content/orders/tooltips/');
    }
    
    
    /**
     * Get the row tooltip HTML for each displayed tooltip.
     *
     * @param OrderListItem $orderListItem Contains the order list item data.
     *
     * @return array
     */
    public function getRowTooltips(OrderListItem $orderListItem)
    {
        $rowTooltips = [
            'orderItems'         => $this->_getOrderItems($orderListItem),
            'invoices'           => $this->_getInvoice($orderListItem),
            'customerMemos'      => $this->_getCustomerMemos($orderListItem),
            'customerAddresses'  => $this->_getCustomerAddresses($orderListItem),
            'orderSumBlock'      => $this->_getOrderSumBlock($orderListItem),
            'orderStatusHistory' => $this->_getOrderStatusHistory($orderListItem),
            'trackingLinks'      => $this->_getTrackingLinks($orderListItem)
        ];
        
        return $rowTooltips;
    }
    
    
    /**
     * Renders and returns a template file.
     *
     * @param string $templateFile Template file to render.
     * @param array  $contentArray Content array which represent the variables of the template.
     *
     * @return string Rendered template.
     */
    protected function _render($templateFile, array $contentArray)
    {
        $this->contentView->set_content_template($templateFile);
        
        foreach($contentArray as $contentItemKey => $contentItemValue)
        {
            $this->contentView->set_content_data($contentItemKey, $contentItemValue);
        }
        
        return $this->contentView->get_html();
    }
    
    
    /**
     * Get Order Items Tooltip HTML
     *
     * @param OrderListItem $orderListItem
     *
     * @return string
     */
    protected function _getOrderItems(OrderListItem $orderListItem)
    {
        $templateData = [
            'id'          => $orderListItem->getOrderId(),
            'products'    => [],
            'total_price' => ''
        ];
        
        $orderCurrencyCode = $this->db->get_where('orders', ['orders_id' => $orderListItem->getOrderId()])
                                      ->row()->currency;
        
        $this->db->select('orders_products.orders_products_id, 
                            orders_products.products_quantity, 
                            orders_products.products_name, 
                            orders_products.products_model, 
                            orders_products.final_price, 
                            orders_products_quantity_units.unit_name')
                 ->from('orders_products')
                 ->join('orders_products_quantity_units',
                        'orders_products.orders_products_id = orders_products_quantity_units.orders_products_id',
                        'left outer')
                 ->where('orders_id', $orderListItem->getOrderId());
        
        $orderItems = $this->db->get()->result_array();
        
        foreach($orderItems as $orderItem)
        {
            $attributes = $this->db->select('products_options AS name, products_options_values AS value')
                                   ->from('orders_products_attributes')
                                   ->where('orders_products_id', $orderItem['orders_products_id'])
                                   ->get()
                                   ->result_array();
            
            $properties = $this->db->select('properties_name AS name, values_name AS value')
                                   ->from('orders_products_properties')
                                   ->where('orders_products_id', $orderItem['orders_products_id'])
                                   ->get()
                                   ->result_array();
            
            $gPrintContentManager = new GMGPrintContentManager();
            $gPrintResult         = $gPrintContentManager->get_orders_products_content($orderItem['orders_products_id'],
                                                                                       true);
            
            foreach($gPrintResult as $gPrintRow)
            {
                $attributes[] = [
                    'name'  => $gPrintRow['NAME'],
                    'value' => $gPrintRow['VALUE']
                ];
            }
            
            $templateData['products'][$orderItem['orders_products_id']] = [
                'quantity'   => (double)$orderItem['products_quantity'],
                'name'       => $orderItem['products_name'],
                'unit_name'  => $orderItem['unit_name'] ? : 'x',
                'model'      => $orderItem['products_model'],
                'price'      => number_format((double)$orderItem['final_price'], 2, ',', '.') . ' '
                                . $orderCurrencyCode,
                'attributes' => $attributes,
                'properties' => $properties
            ];
        }
        
        $totalPrice = $this->db->get_where('orders_total', [
            'orders_id' => $orderListItem->getOrderId(),
            'class'     => 'ot_total'
        ])->row_array();
        
        $templateData['total_price'] = trim(strip_tags($totalPrice['title'] . ' ' . $totalPrice['text']));
        
        return $this->_render('items.html', $templateData);
    }
    
    
    protected function _getInvoice(OrderListItem $orderListItem)
    {
        // Invoice Archive Read Service.
        $invoiceArchiveReadService = StaticGXCoreLoader::getService('InvoiceArchiveRead');
        
        // Template data.
        $templateData = [
            'invoices' => []
        ];
        
        // Get invoices by order ID.
        $invoices = $invoiceArchiveReadService->getInvoiceListByConditions(['order_id' => $orderListItem->getOrderId()]);
        
        // Iterate over each invoice and push their data to the template data array.
        if(!$invoices->isEmpty())
        {
            /** @var InvoiceListItem $invoice */
            foreach($invoices->getArray() as $invoice)
            {
                $templateData['invoices'][] = [
                    'number'   => $invoice->getInvoiceNumber(),
                    'date'     => $invoice->getInvoiceDate()->format('d.m.Y'),
                    'filename' => $invoice->getInvoiceFilename()
                ];
            }
        }
        
        return $this->_render('invoices.html', $templateData);
    }
    
    
    /**
     * Get Customer Memo Tooltip HTML
     *
     * @param OrderListItem $orderListItem
     *
     * @return string
     */
    protected function _getCustomerMemos(OrderListItem $orderListItem)
    {
        $templateData = [
            'memos' => []
        ];
        
        /** @var CustomerMemo $memo */
        foreach($orderListItem->getCustomerMemos()->getArray() as $memo)
        {
            $customer = $this->db->get_where('customers', ['customers_id' => $memo->getPosterId()])->row_array();
            
            $templateData['memos'][] = [
                'title'         => $memo->getTitle(),
                'text'          => $memo->getText(),
                'creation_date' => $memo->getCreationDate(),
                'poster_name'   => $customer['customers_firstname'] . ' ' . $customer['customers_lastname']
            ];
        }
        
        return $this->_render('customer_memos.html', $templateData);
    }
    
    
    /**
     * Get Customer Addresses Tooltip HTML
     *
     * @param OrderListItem $orderListItem
     *
     * @return string
     */
    protected function _getCustomerAddresses(OrderListItem $orderListItem)
    {
        $deliveryAddress = $orderListItem->getDeliveryAddress();
        $billingAddress  = $orderListItem->getBillingAddress();
        
        $templateData = [
            'has_separate_delivery_address' => $deliveryAddress !== $billingAddress,
            'customer_email'                => $orderListItem->getCustomerEmail(),
            'delivery'                      => [
                'firstname'               => $deliveryAddress->getFirstName(),
                'lastname'                => $deliveryAddress->getLastName(),
                'company'                 => $deliveryAddress->getCompany(),
                'street'                  => $deliveryAddress->getStreet(),
                'house_number'            => $deliveryAddress->getHouseNumber(),
                'additional_address_info' => $deliveryAddress->getAdditionalAddressInfo(),
                'postcode'                => $deliveryAddress->getPostcode(),
                'city'                    => $deliveryAddress->getCity(),
                'country'                 => $deliveryAddress->getCountry()
            ],
            'billing'                       => [
                'firstname'               => $billingAddress->getFirstName(),
                'lastname'                => $billingAddress->getLastName(),
                'company'                 => $billingAddress->getCompany(),
                'street'                  => $billingAddress->getStreet(),
                'house_number'            => $billingAddress->getHouseNumber(),
                'additional_address_info' => $billingAddress->getAdditionalAddressInfo(),
                'postcode'                => $billingAddress->getPostcode(),
                'city'                    => $billingAddress->getCity(),
                'country'                 => $billingAddress->getCountry()
            ]
        ];
        
        return $this->_render('customer_addresses.html', $templateData);
    }
    
    
    /**
     * Get Order Sum Block Tooltip HTML
     *
     * @param OrderListItem $orderListItem
     *
     * @return string
     */
    protected function _getOrderSumBlock(OrderListItem $orderListItem)
    {
        $templateData = [
            'sum_block' => []
        ];
        
        $orderTotals = $this->db->get_where('orders_total', ['orders_id' => $orderListItem->getOrderId()])
                                ->result_array();
        
        foreach($orderTotals as $orderTotal)
        {
            $templateData['sum_block'][] = [
                $orderTotal['title'] => $orderTotal['text']
            ];
        }
        
        return $this->_render('sum_block.html', $templateData);
    }
    
    
    /**
     * Get Order Status History Tooltip HTML
     *
     * @param OrderListItem $orderListItem
     *
     * @return string
     */
    protected function _getOrderStatusHistory(OrderListItem $orderListItem)
    {
        $templateData = [
            'status_history' => []
        ];
        
        $statusHistory = $this->db->select('orders_status_history.*, orders_status.orders_status_name AS status_name')
                                  ->from('orders_status_history')
                                  ->join('orders_status',
                                         'orders_status.orders_status_id = orders_status_history.orders_status_id',
                                         'left')
                                  ->where([
                                              'orders_status_history.orders_id' => $orderListItem->getOrderId(),
                                              'orders_status.language_id'       => $_SESSION['languages_id']
                                          ])
                                  ->get()
                                  ->result_array();
        
        foreach($statusHistory as $entry)
        {
            
            $templateData['status_history'][] = [
                'status_name'          => $entry['status_name'] ? : '',
                'comment'              => $entry['comments'],
                'date_added'           => date('d.m.Y H:i:s', strtotime($entry['date_added'])),
                'is_customer_notified' => (bool)$entry['customer_notified']
            ];
        }
        
        return $this->_render('status_history.html', $templateData);
    }
    
    
    /**
     * Get Shipping Costs Tooltip HTML
     *
     * @param OrderListItem $orderListItem
     *
     * @return string
     */
    protected function _getShippingCosts(OrderListItem $orderListItem)
    {
        $shippingCosts = $this->db->get_where('orders_total', [
            'orders_id' => $orderListItem->getOrderId(),
            'class'     => 'ot_shipping'
        ])->row()->text;
        
        $templateData = [
            'shipping_costs' => $shippingCosts ? : '-'
        ];
        
        return $this->_render('shipping_costs.html', $templateData);
    }
    
    
    /**
     * Get Tracking Links
     *
     * @param OrderListItem $orderListItem
     *
     * @return string
     */
    protected function _getTrackingLinks(OrderListItem $orderListItem)
    {
        if($orderListItem->getTrackingLinks()->count() === 0)
        {
            return '';
        }
        
        $rows = $this->db->get_where('orders_parcel_tracking_codes', ['order_id' => $orderListItem->getOrderId()])
                         ->result_array();
        
        $templateData = [
            'tracking_links' => []
        ];
        
        foreach($rows as $row)
        {
            $templateData['tracking_links'][] = [
                'service' => $row['parcel_service_name'],
                'code'    => $row['tracking_code'],
                'url'     => $row['url']
            ];
        }
        
        return $this->_render('tracking_links.html', $templateData);
    }
}