Browse invoices

@throws \Nails\Common\Exception\FactoryException
490747
public function index()
    {
        if (!userHasPermission('admin:invoice:invoice:manage')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        //  Are we dealing with a filtered view?
        $oInput         = Factory::service('Input');
        $oCustomerModel = Factory::model('Customer', 'nails/module-invoice');
        $iCustomerId    = $oInput->get('customer_id');

        if ($iCustomerId) {
            $oCustomer = $oCustomerModel->getbyId($iCustomerId);
        }

        // --------------------------------------------------------------------------

        //  Set method info
        $this->data['page']->title = empty($oCustomer) ? 'Manage Invoices' : possessive($oCustomer->label) . ' invoices';

        // --------------------------------------------------------------------------

        $sTableAlias = $this->oInvoiceModel->getTableAlias();

        //  Get pagination and search/sort variables
        $iPage      = $oInput->get('page') ? $oInput->get('page') : 0;
        $iPerPage   = $oInput->get('perPage') ? $oInput->get('perPage') : 50;
        $sSortOn    = $oInput->get('sortOn') ? $oInput->get('sortOn') : $sTableAlias . '.created';
        $sSortOrder = $oInput->get('sortOrder') ? $oInput->get('sortOrder') : 'desc';
        $sKeywords  = $oInput->get('keywords') ? $oInput->get('keywords') : '';

        // --------------------------------------------------------------------------

        //  Define the sortable columns
        $aSortColumns = [
            $sTableAlias . '.created'  => 'Created Date',
            $sTableAlias . '.modified' => 'Modified Date',
            $sTableAlias . '.state'    => 'Invoice State',
        ];

        // --------------------------------------------------------------------------

        //  Define the filters
        $aCbFilters = [];

        //  States
        $aStateOptions = [];
        $aStates       = $this->oInvoiceModel->getStates();

        foreach ($aStates as $sState => $sLabel) {
            $aStateOptions[] = [
                $sLabel,
                $sState,
                true,
            ];
        }

        $aCbFilters[] = Helper::searchFilterObject(
            $sTableAlias . '.state',
            'State',
            $aStateOptions
        );

        //  Currencies
        $oCurrency        = Factory::service('Currency', 'nails/module-currency');
        $aCurrencyOptions = [];
        $aCurrencies      = $oCurrency->getAllEnabled();

        foreach ($aCurrencies as $oCurrency) {
            $aCurrencyOptions[] = [
                $oCurrency->code,
                $oCurrency->code,
                true,
            ];
        }

        $aCbFilters[] = Helper::searchFilterObject(
            $sTableAlias . '.currency',
            'Currency',
            $aCurrencyOptions
        );

        // --------------------------------------------------------------------------

        //  Define the $aData variable for the queries
        $aData = [
            'where'     => array_filter([
                !empty($oCustomer) ? ['customer_id', $oCustomer->id] : null,
            ]),
            'sort'      => [
                [$sSortOn, $sSortOrder],
            ],
            'expand'    => ['customer', 'payments'],
            'keywords'  => $sKeywords,
            'cbFilters' => $aCbFilters,
        ];

        //  Get the items for the page
        $iTotalRows             = $this->oInvoiceModel->countAll($aData);
        $this->data['invoices'] = $this->oInvoiceModel->getAll($iPage, $iPerPage, $aData);

        //  Set Search and Pagination objects for the view
        $this->data['search']     = Helper::searchObject(true, $aSortColumns, $sSortOn, $sSortOrder, $iPerPage, $sKeywords, $aCbFilters);
        $this->data['pagination'] = Helper::paginationObject($iPage, $iPerPage, $iTotalRows);

        //  Add a header button
        if (userHasPermission('admin:invoice:invoice:create')) {
            Helper::addHeaderButton(
                'admin/invoice/invoice/create',
                'Create Invoice'
            );
        }

        // --------------------------------------------------------------------------

        Helper::loadView('index');
    }
527390
public function index()
    {
        $this->authorize('readList', File::class);
        $input  = $this->validator->validate('list');
        $params = $this->processor->process($input)->getProcessedFields();
        $query  = QueryBuilder::with($params['filter'], $params['orderBy'], $params['query']);
        $query->setPageSize($params['perPage']);
        $results = $this->fileRepo->getFiles($query, $params['page']);
        return $this->respondWithSuccess($results, new FileTransformer);
    }
633082
public function invoices($params = null)
    {
        $params = $params ?: [];
        $params['customer'] = $this->id;
        $invoices = Invoice::all($params, $this->_opts);
        return $invoices;
    }
463533
public function index() {
        if ($this->overrideAction('index')) {
            return;
        }

        $this->paginate = array_merge(array(
            'limit' => 25,
            'order' => array($this->Model->alias . '.' . $this->Model->displayField => 'ASC'),
            'contain' => array_keys($this->Model->belongsTo)
        ), $this->Model->admin['paginate']);

        $this->AdminToolbar->setBelongsToData($this->Model);

        // Filters
        if (!empty($this->request->params['named'])) {
            $this->paginate['conditions'] = $this->AdminToolbar->parseFilterConditions($this->Model, $this->request->params['named']);
        }

        // Batch delete
        if ($this->request->is('post')) {
            if (!$this->Model->admin['batchProcess']) {
                throw new ForbiddenException(__d('admin', 'Batch Access Protected'));
            }

            $action = $this->request->data[$this->Model->alias]['batch_action'];
            $items = $this->request->data[$this->Model->alias]['items'];
            $processed = array();

            foreach ($items as $id) {
                if (!$id) {
                    continue;
                }

                if ($action === 'delete_item') {
                    if ($this->Model->delete($id, true)) {
                        $processed[] = $id;
                    }
                } else {
                    if (call_user_func(array($this->Model, $action), $id)) {
                        $processed[] = $id;
                    }
                }
            }

            $count = count($processed);

            if ($count > 0) {
                $this->AdminToolbar->logAction(ActionLog::BATCH_DELETE, $this->Model, '', sprintf('Processed IDs: %s', implode(', ', $processed)));
                $this->AdminToolbar->setFlashMessage(__d('admin', '%s %s have been processed', array($count, mb_strtolower($this->Model->pluralName))));

                $this->request->data[$this->Model->alias] = array();
            }
        }

        $this->set('results', $this->paginate($this->Model));
        $this->overrideView('index');
    }
662785
public function index()
    {
        $oUri     = Factory::service('Uri');
        $oEmailer = Factory::service('Emailer', 'nails/module-email');
        $sRef     = $oUri->segment(3);
        $sGuid    = $oUri->segment(4);
        $sHash    = $oUri->segment(5);

        // --------------------------------------------------------------------------

        //  Fetch the email
        if (is_numeric($sRef)) {
            $oEmail = $oEmailer->getById($sRef);
        } else {
            $oEmail = $oEmailer->getByRef($sRef);
        }

        if (!$oEmail || !$oEmailer->validateHash($oEmail->ref, $sGuid, $sHash)) {
            show404();
        }

        if (Environment::is(Environment::ENV_DEV)) {

            $oAsset = Factory::service('Asset');
            $oAsset->load('debugger.min.css', 'nails/module-email');

            Factory::service('View')
                ->setData([
                    'oEmail' => $oEmail,
                ])
                ->load([
                    'structure/header/blank',
                    'email/view',
                    'structure/footer/blank',
                ]);

        } else {
            $oOutput = Factory::service('Output');
            $oOutput->set_output($oEmail->body->html);
        }
    }
837217
public function listReportPayment()
    {
        $this->setTitleListReportPayment();
        $this->setBreadcrumbListReportPayment();
        $this->setFilterListReportPayment();
        $this->setPagerListReportPayment();

        $this->setData('methods', (array) $this->getListReportPayment());
        $this->outputListReportPayment();
    }
624020
public function showInvoiceAction(Request $request, $number)
    {
        
        $em = $this->container->get('doctrine')->getManager();
        /** @var Invoice $invoice */
        $invoice = $em->getRepository('EcommerceBundle:Invoice')->findOneBy(array(
            'invoiceNumber' => $number
        ));

        if (!$invoice ||
            false === $this->container->get('checkout_manager')->isCurrentUserOwner($invoice->getTransaction())) {
            throw new AccessDeniedException();
        }

        /** @var CheckoutManager $checkoutManager */
        $checkoutManager = $this->container->get('checkout_manager');

        $delivery = $invoice->getTransaction()->getDelivery();
        $totals = $checkoutManager->calculateTotals($invoice->getTransaction(), $delivery);

        return array(
                'delivery' => $delivery,
                'invoice'  => $invoice,
                'totals'   => $totals,
            );
    }
792442
public function edit()
    {
        if (!userHasPermission('admin:invoice:customer:edit')) {
            unauthorised();
        }

        $oCustomerModel = Factory::model('Customer', 'nails/module-invoice');
        $oUri           = Factory::service('Uri');

        $itemId             = (int) $oUri->segment(5);
        $this->data['item'] = $oCustomerModel->getById(
            $itemId,
            ['expand' => $oCustomerModel::EXPAND_ALL]
        );

        if (empty($this->data['item'])) {
            show404();
        }

        // --------------------------------------------------------------------------

        $oInput = Factory::service('Input');
        if ($oInput->post()) {

            try {

                $this->formValidation();

                if (!$oCustomerModel->update($itemId, $this->prepPostData())) {
                    throw new NailsException('Failed to update item. ' . $oCustomerModel->lastError(), 1);
                }

                $oSession = Factory::service('Session', 'nails/module-auth');
                $oSession->setFlashData('success', 'Item updated successfully.');
                redirect('admin/invoice/customer');

            } catch (\Exception $e) {
                $this->data['error'] = $e->getMessage();
            }
        }

        // --------------------------------------------------------------------------

        $this->data['page']->title = 'Edit customer';
        Helper::loadView('edit');
    }
725077
public function invoiceAction(Request $request)
    {
        /** @var \Ekyna\Component\Sale\Order\OrderInterface $order */
        $order = $this->get('ekyna_order.order.repository')->findOneBy([
            'id' => $request->attributes->get('orderId', null), 
            'type' => OrderTypes::TYPE_ORDER
        ]);
        if (null === $order) {
            throw new NotFoundHttpException('Order not found.');
        }

        // Admin or owner security check
        if(!($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $order->getUser() == $this->getUser())) {
            throw new AccessDeniedHttpException('You are not allowed to view this resource.');
        }

        $response = new Response();
        $response->setLastModified($order->getUpdatedAt());
        if ($response->isNotModified($request)) {
            return $response;
        }

        $content = $this->renderView('EkynaOrderBundle:Document:invoice.html.twig', [
            'order' => $order,
        ]);

        $format = $request->attributes->get('_format', 'html');
        if ('html' === $format) {
            $response->setContent($content);
        } elseif ('pdf' === $format) {
            $response->setContent($this->get('knp_snappy.pdf')->getOutputFromHtml($content));
            $response->headers->add(['Content-Type' => 'application/pdf']);
        } else {
            throw new NotFoundHttpException('Unsupported format.');
        }

        if ($request->query->get('_download', false)) {
            $filename = sprintf('order-%s.%s', $order->getNumber(), $format);
            $contentDisposition = $response->headers->makeDisposition(
                ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename
            );
            $response->headers->set('Content-Disposition', $contentDisposition);
        }

        return $response;
    }
39356
public function index()
    {
        $pagination = new Pagination();
        $pattern = StaticFilter::filter(
            'text',
            $this->getController()->request->getQuery('pattern', null)
        );
        $this->view = 'scaffold/index';
        $descriptor =  $this->getDescriptor();

        /** @var Select $query */
        $query = call_user_func_array([$this->getModelName(), 'find'], []);
        $field = $descriptor->getDisplayField();
        $tableName = $descriptor->getDescriptor()->getEntity()->getTableName();
        $query->where(
            [
                "{$tableName}.{$field} LIKE :pattern" => [
                    ':pattern' => "%{$pattern}%"
                ]
            ]
        );
        $pagination->setTotal($query->count());
        $query->limit(
            $pagination->rowsPerPage,
            $pagination->offset
        );
        $records = $query->all();
        $this->set(compact('pagination', 'records', 'pattern', 'descriptor'));
    }
713543
public function view()
    {
        if (!userHasPermission('admin:invoice:invoice:edit')) {
            unauthorised();
        }

        $oUri                  = Factory::service('Uri');
        $oModel                = $this->oInvoiceModel;
        $iInvoiceId            = (int) $oUri->segment(5);
        $this->data['invoice'] = $this->oInvoiceModel->getById(
            $iInvoiceId,
            ['expand' => $oModel::EXPAND_ALL]
        );

        if (!$this->data['invoice'] || $this->data['invoice']->state->id == 'DRAFT') {
            show404();
        }

        $this->data['page']->title = 'View Invoice &rsaquo; ' . $this->data['invoice']->ref;

        $oAsset = Factory::service('Asset');
        $oAsset->load('admin.invoice.view.min.js', 'nails/module-invoice');

        Helper::loadView('view');
    }
1090198
public function index() {
        $this->paginate = array_merge(array(
            'limit' => 25,
            'order' => array('ItemReport.' . $this->Model->displayField => 'ASC'),
            'contain' => array_keys($this->Model->belongsTo),
            'conditions' => array('ItemReport.status' => ItemReport::PENDING)
        ), $this->Model->admin['paginate']);

        $this->AdminToolbar->setBelongsToData($this->Model);

        $this->request->data['ItemReport']['status'] = ItemReport::PENDING;

        // Filters
        if (!empty($this->request->params['named'])) {
            $this->paginate['conditions'] = $this->AdminToolbar->parseFilterConditions($this->Model, $this->request->params['named']);
        }

        $this->set('results', $this->paginate($this->Model));
    }
383021
public function findPayments($invoiceData)
    {
        $pays  = [];
        $sPays = [];
        $bPays = [];

        if (array_key_exists('varSym', $invoiceData) && !empty($invoiceData['varSym'])) {
            $sPays = $this->findPayment(['varSym' => $invoiceData['varSym']]);
            if (is_array($sPays)) {
                $pays = $sPays;
            }
        }

        if (array_key_exists('specSym', $invoiceData) && !empty($invoiceData['specSym'])) {
            $sPays = $this->findPayment(['specSym' => $invoiceData['specSym']]);
            if (is_array($bPays)) {
                $pays = $bPays;
            }
        }

        if (array_key_exists('buc', $invoiceData) && !empty($invoiceData['buc'])) {
            $bPays = $this->findPayment(['buc' => $invoiceData['buc']]);
            if ($bPays) {
                foreach ($bPays as $payID => $payment) {
                    if (!array_key_exists($payID, $pays)) {
                        $pays[$payID] = $payment;
                    }
                }
            }
        }

        return $pays;
    }
256546
public function getInvoice(): ?Invoice
    {
        $invoice = null;

        if($this->invoiceId !== null)
            $invoice = Invoice::getById($this->invoiceId);

        /** @var Invoice $invoice */
        return $invoice;
    }
20390
public function index()
    {
        $oCdn    = Factory::service('Cdn', 'nails/module-cdn');
        $oInput  = Factory::service('Input');
        $oLogger = Factory::service('Logger');

        //  Check if there was a bad token
        if ($this->badToken) {
            $oLogger->line('CDN: Serve: Bad Token');
            $this->serveBadSrc([
                'error' => 'Bad Token',
            ]);
        }

        // --------------------------------------------------------------------------

        //  Look up the object in the DB
        $object = $oCdn->getObject($this->object, $this->bucket);

        if (!$object) {

            /**
             * If trashed=1 GET param is set and user is a logged in admin with
             * can_browse_trash permission then have a look in the trash
             */

            if ($oInput->get('trashed') && userHasPermission('admin:cdn:trash:browse')) {

                $object = $oCdn->getObjectFromTrash($this->object, $this->bucket);

                if (!$object) {
                    //  Cool, guess it really doesn't exist
                    $oLogger->line('CDN: Serve: Object not defined');
                    $this->serveBadSrc([
                        'error' => 'Object not defined',
                    ]);
                }

            } else {
                $oLogger->line('CDN: Serve: Object not defined');
                $this->serveBadSrc([
                    'error' => 'Object not defined',
                ]);
            }
        }

        // --------------------------------------------------------------------------

        /**
         * Check the request headers; avoid hitting the disk at all if possible. If
         * the Etag matches then send a Not-Modified header and terminate execution.
         */

        if ($this->serveNotModified($this->bucket . $this->object)) {
            if ($object) {
                if ($oInput->get('dl')) {
                    $oCdn->objectIncrementCount('DOWNLOAD', $object->id);
                } else {
                    $oCdn->objectIncrementCount('SERVE', $object->id);
                }
            }

            return;
        }

        // --------------------------------------------------------------------------

        //  Fetch source
        $usefile = $oCdn->objectLocalPath($object->id);

        if (!$usefile) {

            $oLogger->line('CDN: Serve: File does not exist');
            $oLogger->line('CDN: Serve: ' . $oCdn->lastError());

            if (isSuperuser()) {
                $this->serveBadSrc([
                    'error' => 'File not found: ' . $usefile,
                ]);
            } else {
                $this->serveBadSrc([
                    'error' => 'File not found',
                ]);
            }
        }

        // --------------------------------------------------------------------------

        //  Determine headers to send. Are we forcing the download?
        if ($oInput->get('dl')) {

            header('Content-Description: File Transfer', true);
            header('Content-Type: application/octet-stream', true);
            header('Content-Transfer-Encoding: binary', true);
            header('Expires: 0', true);
            header('Cache-Control: must-revalidate', true);
            header('Pragma: public', true);

            //  If the object is known about, add some extra headers
            if ($object) {

                header('Content-Disposition: attachment; filename="' . $object->file->name->human . '"', true);
                header('Content-Length: ' . $object->file->size->bytes, true);

            } else {

                header('Content-Disposition: attachment; filename="' . $this->object . '"', true);
            }

        } else {

            //  Determine headers to send
            header('Content-Type: ' . $object->file->mime, true);

            $stats = stat($usefile);
            $this->setCacheHeaders($stats[9], $this->bucket . $this->object, false);

            // --------------------------------------------------------------------------

            //  If the object is known about, add some extra headers
            if ($object) {
                header('Content-Length: ' . $object->file->size->bytes, true);
            }
        }

        // --------------------------------------------------------------------------

        //  Send the contents of the file to the browser
        //  If a particular range of bytes is being requested then send those.
        //  header('Accept-Ranges: bytes');
        if (isset($_SERVER['HTTP_RANGE'])) {

            //  @todo - support ranges
            //  See http://www.media-division.com/the-right-way-to-handle-file-downloads-in-php/

        } else {

            Factory::helper('file');
            readFileChunked($usefile);
        }

        // --------------------------------------------------------------------------

        //  Bump the counter
        if ($object) {
            if ($oInput->get('dl')) {
                $oCdn->objectIncrementCount('DOWNLOAD', $object->id);
            } else {
                $oCdn->objectIncrementCount('SERVE', $object->id);
            }
        }

        // --------------------------------------------------------------------------

        /**
         * Kill script, th, th, that's all folks. Stop the output class from hijacking
         * our headers and setting an incorrect Content-Type
         */

        exit(0);
    }
376604
public function getInvoices(): InvoiceCollection
    {
        if($this->invoiceIds !== null && $this->invoiceIds !== [])
        {
            $allInvoices = Invoice::get();
            $invoices = [];

            foreach($this->invoiceIds as $id)
                $invoices = $allInvoices->where("id", $id);

            return new InvoiceCollection($invoices);
        }

        return new InvoiceCollection();
    }
228976
public function create()
    {
        if (!userHasPermission('admin:invoice:customer:create')) {
            unauthorised();
        }

        $oInput = Factory::service('Input');
        if ($oInput->post()) {

            try {

                $this->formValidation();
                $oCustomerModel = Factory::model('Customer', 'nails/module-invoice');
                if (!$oCustomerModel->create($this->prepPostData())) {
                    throw new NailsException('Failed to create item. ' . $oCustomerModel->lastError(), 1);
                }

                $oSession = Factory::service('Session', 'nails/module-auth');
                $oSession->setFlashData('success', 'Item created successfully.');
                redirect('admin/invoice/customer');

            } catch (\Exception $e) {
                $this->data['error'] = $e->getMessage();
            }
        }

        $this->data['page']->title = 'Create customer';
        Helper::loadView('edit');
    }