Jump to content

Attachment button not working in custom checkout page


Recommended Posts

Hello guys, I am using a module called order files to create fill attachment buttons in customer account and shopping cart it facilities customers to attach files for personalized making the product page less cluttered but the thing is the module displays the add button properly in position of shopping cart but it is not functional any items is the theme conflicting with the button or what might be the other possibilities and please tell me a solution. Iam using this alternate button module because there is already a conflict between product customizer and default prestashop product customizations button but this method too is failing, any help would be appreciated please help me solve this guys. 

fileupload not working.PNG

Link to comment
Share on other sites

<?php
/**
 * Orderfiles Prestashop module
 *
 * NOTICE OF LICENSE
 *
 * This file is licenced under the Software License Agreement.
 * With the purchase or the installation of the software in your application
 * you accept the licence agreement.
 *
 * You must not modify, adapt or create derivative works of this source code
 *
 *  @author    Wiktor Koźmiński
 *  @copyright 2017-2021 Silver Rose Wiktor Koźmiński
 *  @license   LICENSE.txt
 */

if (!defined('_PS_VERSION_')) {
    exit;
}

require_once 'src/orderfiles.loader.php';

class orderfiles extends Module
{
    protected $config_form = false;

    public function __construct()
    {
        $this->name = 'orderfiles';
        $this->tab = 'administration';
        $this->version = '2.4.1';
        $this->author = 'Wiktor Koźmiński';
        $this->need_instance = 0;
        $this->bootstrap = true;
        $this->module_key = 'a01386ce0f617245a5ffa910b6d5cacd';

        // used for PrestaTrust
        $this->author_address = '0x4AD7d84aC48AE66324d3325489f8539f411F75Fb';

        parent::__construct();

        $this->displayName = $this->l('Order Files');
        $this->description = $this->l('Attach PDF, images, or other types of files to orders');

        $this->ps_versions_compliancy = array('min' => '1.5', 'max' => '1.8');
    }

    /**
     * Don't forget to create update methods if needed:
     * http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update
     */
    public function install()
    {
        include(dirname(__FILE__).'/sql/install.php');
        
        if (!parent::install() ||
            !$this->registerHook('actionValidateOrder') ||
            !$this->registerHook('displayShoppingCartFooter') ||
            !$this->registerHook('displayAdminOrder') ||
            !$this->registerHook('header') ||
            !$this->registerHook('actionGetAdminOrderButtons') ||
            !$this->registerHook('displayBackOfficeHeader') ||
            !$this->registerHook('displayCustomerAccount')) {
            return false;
        }

        \Orderfiles\Common\ModuleTabs::install();
        return true;
    }

    public function uninstall()
    {
        \Orderfiles\Common\ModuleTabs::uninstall();
        $config = new Orderfiles\Common\Config();
        $filesManager = new Orderfiles\Files\FileManager(Db::getInstance(), $config);
        $filesManager->deleteAllFiles();
        include(dirname(__FILE__).'/sql/uninstall.php');
        return parent::uninstall();
    }

    public function hookActionGetAdminOrderButtons(array $params)
    {
        /** @var \PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButtonsCollection $bar */
        $bar = $params['actions_bar_buttons_collection'];
        $bar->add(
            new \PrestaShopBundle\Controller\Admin\Sell\Order\ActionsBarButton(
                'btn-action orderfiles-open-button', [], '<i class="material-icons" aria-hidden="true">folder_shared</i> '.$this->l('OrderFiles')
            )
        );
    }

    public function getContent()
    {
        $config = new Orderfiles\Common\Config();
        $filesManager = new Orderfiles\Files\FileManager(Db::getInstance(), $config);

        if (Tools::getValue('action') == 'updateConfig' && $this->validateConfigFields()) {
            $eid = $this->context->employee->id;
            $config->employeeNotifs[$eid] = array(
                'customer_upload' => (bool) Tools::getValue('notify_customerUploadedFile')
            );
            $config->update();
            $this->context->controller->informations[] = $this->l('Configuration was saved');
        }

        if (Tools::getValue('action') == 'removeFiles' && Tools::getValue('timeRange')) {
            $files = $filesManager->getFilesByDate(0, strtotime("-".Tools::getValue('timeRange')." days"));
            foreach ($files as $file) {
                $filesManager->deleteFile($file);
            }
        }

        $this->context->smarty->assign(array(
            'config' => $config,
            'employeeId' => $this->context->employee->id,
            'fileStats' => $filesManager->getRealFilesStats(),
        ));
        
        if (version_compare(_PS_VERSION_, '1.6.0', '>=') === true) {
            return $this->display(__FILE__, 'views/templates/admin/config_page_v16.tpl');
        } else {
            return $this->display(__FILE__, 'views/templates/admin/config_page_v15.tpl');
        }
    }

    private function validateConfigFields()
    {
        $valid = true;
        
        if (Tools::getValue('config_maxFilesPerOrder') && !Validate::isInt(Tools::getValue('config_maxFilesPerOrder'))) {
            $this->context->controller->errors[] = $this->l('Max files per order must be a number');
            $valid = false;
        }

        if (Tools::getValue('config_maxFileSizeInKB') && !Validate::isInt(Tools::getValue('config_maxFileSizeInKB'))) {
            $this->context->controller->errors[] = $this->l('Max file size in KB be a number');
            $valid = false;
        }

        return $valid;
    }

    public function hookDisplayShoppingCartFooter($params)
    {
        $config = new Orderfiles\Common\Config();
        $filesManager = new Orderfiles\Files\FileManager(Db::getInstance(), $config);

        if ((int)$config->isCartUploadEnabled != 1) {
            return;
        }

        $this->context->smarty->assign(array(
            'files' => $filesManager->getFilesByCartId($this->context->cart->id),
        ));

        if (version_compare(_PS_VERSION_, '1.7.0', '>=') === true) {
            return $this->display(__FILE__, 'cart_page_v17.tpl');
        } elseif (version_compare(_PS_VERSION_, '1.6.0', '>=') === true) {
            return $this->display(__FILE__, 'cart_page_v16.tpl');
        } else {
            return $this->display(__FILE__, 'cart_page_v15.tpl');
        }
    }

    /**
     * Add the CSS & JavaScript files you want to be added on the FO.
     */
    public function hookHeader()
    {
        $config = new Orderfiles\Common\Config();
        if ((int)$config->isCartUploadEnabled != 1) {
            return;
        }

        $pageName = trim($this->context->controller->php_self);
        $availablePages = array('order', 'order-opc');

        if (version_compare(_PS_VERSION_, '1.7.0', '>=') === true) {
            $availablePages = array('cart');
        }

        if (!in_array($pageName, $availablePages)) {
            return;
        }

        $this->context->controller->addCSS($this->_path.'views/css/cartpage.css');
        $this->context->controller->addJS($this->_path.'views/js/progressbar.min.js');
        $this->context->controller->addJS($this->_path.'views/js/moment-with-locales.min.js');
        $this->context->controller->addJS($this->_path.'views/js/orderfilesuploader.min.js');
        // $this->context->controller->addJS($this->_path.'views/js/src/OrderFilesUploader.js'); //dev
    }

    /**
     * Checks if there were files attached to orders cart. If so, updates file info
     * with order ID and author name
     * @param  array $params
     * @return void
     */
    public function hookActionValidateOrder($params)
    {
        if (!isset($params['order']) || !isset($params['cart']) || !isset($params['customer'])) {
            return;
        }

        $config = new Orderfiles\Common\Config();
        $filesManager = new Orderfiles\Files\FileManager(Db::getInstance(), $config);
        $author = $params['customer']->firstname.' '.$params['customer']->lastname;

        $files = $filesManager->getFilesByCartId($params['cart']->id);
        foreach ($files as $fileInfo) {
            $fileInfo->orderId = (int) $params['order']->id;
            $fileInfo->author = $author;
            $filesManager->save($fileInfo);
        }

        if (!count($files)) {
            return;
        }

        $order = new Order($params['order']->id);
        foreach ($config->employeeNotifs as $eId => $eNotif) {
            if (!isset($eNotif['customer_upload']) || !$eNotif['customer_upload']) {
                continue;
            }

            $employee = new Employee($eId);
            \Orderfiles\Common\ModuleMailer::notifyAboutCustomerUpload($employee, $order, $files);
        }
    }

    public function hookDisplayBackOfficeHeader(array $params)
    {
        $this->context->controller->addJS($this->getPathUri().'views/js/orderfiles.class.min.v200.js');
        $this->context->controller->addCSS($this->getPathUri().'views/css/orderpage.css');
    }

    public function hookDisplayAdminOrder($params)
    {
        $config = new Orderfiles\Common\Config();
        $filesManager = new Orderfiles\Files\FileManager(Db::getInstance(), $config);

        // just levave it here for backward compatibilty pursposes
        $this->context->controller->addJS($this->_path.'views/js/orderfiles.class.min.v200.js');
        $this->context->controller->addCSS($this->_path.'views/css/orderpage.css');

        $orderId = $params['id_order'];

        if (isset($_FILES) && count($_FILES) && isset($_FILES['orderfile'])) {
            $this->handleFileUpload($_FILES['orderfile'], $orderId, $config, $filesManager);
        }

        $canDelete = true;
        if ((int)$config->onlySuperAdminDelete && !$this->context->employee->isSuperAdmin()) {
            $canDelete = false; 
        }

        if ($canDelete && Tools::getValue('fileDelete') && Tools::getValue('fileId')) {
            $this->handleFileDelete(Tools::getValue('fileId'), $filesManager);
        }

        if (version_compare(_PS_VERSION_, '1.7.7', '>=') === true) {
            $thisUrl = $this->context->link->getAdminLink('AdminOrders', true, ['route' => 'admin_orders_view', 'orderId' => $orderId]);
        } else {
            $thisUrl = $this->context->link->getAdminLink('AdminOrders') . '&vieworder&id_order=' . $orderId;
        }

        $this->context->smarty->assign(array(
            'path' => $this->_path,
            'orderId' => $orderId,
            'config' => $config,
            'canDelete' => $canDelete,
            'files' => $filesManager->getFilesByOrderId($orderId),
            'orderFilesCtrlUrl' => $this->context->link->getAdminLink('AdminOrderfilesMain'),
            'thisUrl' => $thisUrl
        ));

        if (version_compare(_PS_VERSION_, '1.7.7', '>=') === true) {
            return $this->display(__FILE__, 'views/templates/admin/hook_admin_order_v1771.tpl');
        } else if (version_compare(_PS_VERSION_, '1.6.0', '>=') === true) {
            return $this->display(__FILE__, 'views/templates/admin/hook_admin_order_v16.tpl');
        } else {
            return $this->display(__FILE__, 'views/templates/admin/hook_admin_order_v15.tpl');
        }
    }

    public function hookDisplayCustomerAccount()
    {
        // since 2.3.1 customer page is always enabled, and employee can enable/disable upload panel
        /*$config = new Orderfiles\Common\Config();
        if ((int)$config->isCustomerAccountUploadEnabled != 1) {
            return;
        }*/

        if (version_compare(_PS_VERSION_, '1.7.0', '>=') === true) {
            return $this->display(__FILE__, 'customer_account_btn_v17.tpl');
        } elseif (version_compare(_PS_VERSION_, '1.6.0', '>=') === true) {
            return $this->display(__FILE__, 'customer_account_btn_v16.tpl');
        } else {
            return $this->display(__FILE__, 'customer_account_btn_v15.tpl');
        }
    }

    /**
     * Perform file delete. Errors are passed directly into controller
     * @param  integer     $fileId
     * @param  FileManager $filesManager
     * @return void
     */
    private function handleFileDelete($fileId, $filesManager)
    {
        $file = $filesManager->getFileById($fileId);
        if ($file === null) {
            $this->context->controller->errors[] = $this->l('There is no file with this ID');
            return;
        }

        try {
            $filesManager->deleteFile($file);
            $this->context->controller->informations[] = $this->l('File was deleted');
        } catch (\Exception $e) {
            $this->context->controller->errors[] = $this->l('Failed to delete file: ') . $e->getMessage();
        }
    }

    private function handleFileUpload(array $fileInfo, $orderId, $config, $filesManager)
    {
        if (isset($fileInfo['error']) && $fileInfo['error'] == UPLOAD_ERR_INI_SIZE) {
            $this->context->controller->errors[] = $this->l('The uploaded file exceeds the upload_max_filesize directive in php.ini');
            return;
        }

        if ($config->maxFilesPerOrder && count($filesManager->getFilesByOrderId($orderId)) >= (int)$config->maxFilesPerOrder) {
            $this->context->controller->errors[] = $this->l('Max files per order exceeds');
            return;
        }

        $fileSizeKB = (int)$fileInfo['size']/1024;
        if ($config->maxFileSizeInKB && $fileSizeKB > $config->maxFileSizeInKB) {
            $this->context->controller->errors[] = $this->l('Given file is too large. Max size is: ') . $config->maxFileSizeInKB . 'KB';
            return;
        }

        $author = $this->context->employee->firstname.' '.$this->context->employee->lastname;
        
        $file = new Orderfiles\Files\FileInfo();
        $file->name = $fileInfo['name'];
        $file->author = $author;
        $file->desc = Tools::getValue('file_desc', "");
        $file->orderId = (int) $orderId;
        $file->isVisibleToCustomer = (int) Tools::getValue('is_visible_to_customer', "0") ? true : false;
        $file->isEditableByCustomer = (int) Tools::getValue('is_editable_by_customer', "0") ? true : false;

        try {
            $file = $filesManager->addFileToOrder($file, file_get_contents($fileInfo['tmp_name']));
            $this->context->controller->informations[] = $this->l('File was saved on disk');
        } catch (\Exception $e) {
            return $this->context->controller->errors[] = $this->l('Failed to save file: ') . $e->getMessage();
        }

        if ((int) Tools::getValue('send_file_to_customer', 0)) {
            $order = new Order($orderId);
            \Orderfiles\Common\ModuleMailer::sendFileToCustomer($this->l('New file has been uploaded to order'), $order, $file);
        }
    }
}
 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...