Manage invoice settings

@return void
492191
public function index()
    {
        if (!userHasPermission('admin:invoice:settings:*')) {
            unauthorised();
        }

        $oInput                = Factory::service('Input');
        $oDb                   = Factory::service('Database');
        $oAppSettingService    = Factory::service('AppSetting');
        $oPaymentDriverService = Factory::service('PaymentDriver', 'nails/module-invoice');
        $oInvoiceSkinService   = Factory::service('InvoiceSkin', 'nails/module-invoice');

        //  Process POST
        if ($oInput->post()) {

            //  Settings keys
            $sKeyPaymentDriver = $oPaymentDriverService->getSettingKey();
            $sKeyInvoiceSkin   = $oInvoiceSkinService->getSettingKey();

            //  Validation
            $oFormValidation = Factory::service('FormValidation');

            $oFormValidation->set_rules('business_name', '', '');
            $oFormValidation->set_rules('business_address', '', '');
            $oFormValidation->set_rules('business_phone', '', '');
            $oFormValidation->set_rules('business_email', '', 'valid_email');
            $oFormValidation->set_rules('business_vat_number', '', '');
            $oFormValidation->set_rules('business_', '', '');
            $oFormValidation->set_rules('default_additional_text', '', '');
            $oFormValidation->set_rules('default_payment_terms', '', '');
            $oFormValidation->set_rules('saved_cards_enabled', '', '');
            $oFormValidation->set_rules('saved_addresses_enabled', '', '');
            $oFormValidation->set_rules($sKeyPaymentDriver, '', '');
            $oFormValidation->set_rules($sKeyInvoiceSkin, '', '');

            $oFormValidation->set_message('valid_email', lang('fv_valid_email'));

            if ($oFormValidation->run()) {

                try {

                    $aSettings = [
                        'business_name'           => trim(strip_tags($oInput->post('business_name'))),
                        'business_address'        => trim(strip_tags($oInput->post('business_address'))),
                        'business_phone'          => trim(strip_tags($oInput->post('business_phone'))),
                        'business_email'          => trim(strip_tags($oInput->post('business_email'))),
                        'business_vat_number'     => trim(strip_tags($oInput->post('business_vat_number'))),
                        'default_additional_text' => trim(strip_tags($oInput->post('default_additional_text'))),
                        'default_payment_terms'   => (int) $oInput->post('default_payment_terms'),
                        'saved_cards_enabled'     => (bool) $oInput->post('saved_cards_enabled'),
                        'saved_addresses_enabled' => (bool) $oInput->post('saved_addresses_enabled'),
                    ];

                    $oDb->trans_begin();

                    //  Normal settings
                    if (!$oAppSettingService->set($aSettings, 'nails/module-invoice')) {
                        throw new NailsException($oAppSettingService->lastError(), 1);
                    }

                    //  Drivers & Skins
                    $oPaymentDriverService->saveEnabled($oInput->post($sKeyPaymentDriver));
                    $oInvoiceSkinService->saveEnabled($oInput->post($sKeyInvoiceSkin));

                    $oDb->trans_commit();
                    $this->data['success'] = 'Invoice &amp; Payment settings were saved.';

                } catch (\Exception $e) {
                    $oDb->trans_rollback();
                    $this->data['error'] = 'There was a problem saving settings. ' . $e->getMessage();
                }

            } else {
                $this->data['error'] = lang('fv_there_were_errors');
            }
        }

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

        //  Get data
        $this->data['settings'] = appSetting(null, 'nails/module-invoice', true);

        Helper::loadView('index');
    }
106198
public function view()
    {
        if (!userHasPermission('admin:invoice:payment:view')) {
            unauthorised();
        }

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

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

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

        $this->data['payment'] = $oPaymentModel->getById(
            $oUri->segment(5),
            ['expand' => $oPaymentModel::EXPAND_ALL]
        );

        if (!$this->data['payment']) {
            show404();
        }

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

        Helper::loadView('view');
    }
622936
protected function initializeSettings()
    {
        /** @var $typoScriptService TypoScriptService */
        $typoScriptService = $this->objectManager->get(TypoScriptService::class);

        // Make sure plugin.tx_solr.settings are available in the view as {settings}
        $this->settings = $typoScriptService->convertTypoScriptArrayToPlainArray(
            $this->typoScriptConfiguration->getObjectByPathOrDefault('plugin.tx_solr.settings.', [])
        );
    }
211016
private function invoice() {
		$invoiceService = df_o(InvoiceService::class); /** @var InvoiceService $invoiceService */
		/** @var Invoice|DfInvoice $result */
		if (!($result = $invoiceService->prepareInvoice($this->o()))) {
			throw new LE(__('We can\'t save the invoice right now.'));
		}
		if (!$result->getTotalQty()) {
			throw new LE(__('You can\'t create an invoice without products.'));
		}
		df_register('current_invoice', $result);
		/**
		 * 2016-03-26
		 * @used-by \Magento\Sales\Model\Order\Invoice::register()
		 * https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Sales/Model/Order/Invoice.php#L599-L609
		 * Используем именно @see \Magento\Sales\Model\Order\Invoice::CAPTURE_ONLINE,
		 * а не @see \Magento\Sales\Model\Order\Invoice::CAPTURE_OFFINE,
		 * чтобы была создана транзакция capture.
		 */
		$result->setRequestedCaptureCase(Invoice::CAPTURE_ONLINE);
		$result->register();
		return $result;
	}
111052
public function create()
    {
        if (!userHasPermission('admin:invoice:invoice:create')) {
            unauthorised();
        }

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

        //  Page Title
        $this->data['page']->title = 'Create Invoice';

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

        $oInput                    = Factory::service('Input');
        $this->data['customer_id'] = $oInput->get('customer_id');

        if ($oInput->post()) {
            if ($this->validatePost()) {
                $oInvoice = $this->oInvoiceModel->create($this->getObjectFromPost(), true);
                if (!empty($oInvoice)) {

                    //  Send invoice if needed
                    $this->sendInvoice($oInvoice);

                    $oSession = Factory::service('Session', 'nails/module-auth');
                    $oSession->setFlashData('success', 'Invoice created successfully.');

                    redirect('admin/invoice/invoice/index');

                } else {
                    $this->data['error'] = 'Failed to create invoice. ' . $this->oInvoiceModel->lastError();
                }

            } else {
                $this->data['error'] = lang('fv_there_were_errors');
            }
        }

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

        //  Page data
        $aItemUnits = $this->oInvoiceItemModel->getUnits();
        $aTaxes     = $this->oTaxModel->getAll();

        $this->data['invoiceStates'] = $this->oInvoiceModel->getSelectableStates();

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

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

            $aItems = $oInput->post('items') ?: [];
            //  Tidy up post data as expected by JS
            foreach ($aItems as &$aItem) {

                $aItem['label'] = html_entity_decode($aItem['label'], ENT_QUOTES, 'UTF-8');
                $aItem['body']  = html_entity_decode($aItem['body'], ENT_QUOTES, 'UTF-8');

                $sUnitCost                     = $aItem['unit_cost'];
                $aItem['unit_cost']            = new \stdClass();
                $aItem['unit_cost']->formatted = new \stdClass();
                $aItem['unit_cost']->formatted = !empty($sUnitCost) ? $sUnitCost : null;

                $aItem['tax']     = new \stdClass();
                $aItem['tax']->id = !empty($aItem['tax_id']) ? (int) $aItem['tax_id'] : null;

                $sUnit             = !empty($aItem['unit']) ? $aItem['unit'] : null;
                $aItem['unit']     = new \stdClass();
                $aItem['unit']->id = $sUnit;
            }

        } else {
            $aItems = [];
        }

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

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

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

        $oAsset = Factory::service('Asset');
        //  @todo (Pablo - 2018-11-30) - Load the minified version once the JS bundling has been sorted
        $oAsset->load('invoice.edit.js', 'nails/module-invoice');
        $oAsset->inline(
            'ko.applyBindings(
                new invoiceEdit(
                    ' . json_encode($aItemUnits) . ',
                    ' . json_encode($aTaxes) . ',
                    ' . json_encode($aItems) . ',
                    ' . json_encode($aCurrencies) . '
                )
            );',
            'JS'
        );

        //  Load views
        Helper::loadView('edit');
    }
63833
def cli(env, limit, closed=False, get_all=False):
    """"""

    manager = AccountManager(env.client)
    invoices = manager.get_invoices(limit, closed, get_all)

    table = formatting.Table([
        "Id", "Created", "Type", "Status", "Starting Balance", "Ending Balance", "Invoice Amount", "Items"
    ])
    table.align['Starting Balance'] = 'l'
    table.align['Ending Balance'] = 'l'
    table.align['Invoice Amount'] = 'l'
    table.align['Items'] = 'l'
    if isinstance(invoices, dict):
        invoices = [invoices]
    for invoice in invoices:
        table.add_row([
            invoice.get('id'),
            utils.clean_time(invoice.get('createDate'), out_format="%Y-%m-%d"),
            invoice.get('typeCode'),
            invoice.get('statusCode'),
            invoice.get('startingBalance'),
            invoice.get('endingBalance'),
            invoice.get('invoiceTotalAmount'),
            invoice.get('itemCount')
        ])
    env.fout(table)
113700
protected function setSettings()
    {
        if (empty($this->params['shopgate_settings']) || !is_array($this->params['shopgate_settings'])) {
            throw new ShopgateLibraryException(
                ShopgateLibraryException::PLUGIN_API_NO_SHOPGATE_SETTINGS,
                'Request: ' . var_export($this->params, true)
            );
        }
        // settings that may never be changed:
        $shopgateSettingsBlacklist = array(
            'shop_number',
            'customer_number',
            'apikey',
            'plugin_name',
            'export_folder_path',
            'log_folder_path',
            'cache_folder_path',
            'items_csv_filename',
            'categories_csv_filename',
            'reviews_csv_filename',
            'access_log_filename',
            'error_log_filename',
            'request_log_filename',
            'debug_log_filename',
            'redirect_keyword_cache_filename',
            'redirect_skip_keyword_cache_filename',
        );

        // filter the new settings
        $shopgateSettingsNew = array();
        $shopgateSettingsOld = $this->config->toArray();
        foreach ($this->params['shopgate_settings'] as $setting) {
            if (!isset($setting['name'])) {
                throw new ShopgateLibraryException(
                    ShopgateLibraryException::PLUGIN_API_NO_SHOPGATE_SETTINGS,
                    'Wrong format: ' . var_export($setting, true)
                );
            }

            if (in_array($setting['name'], $shopgateSettingsBlacklist)) {
                continue;
            }

            if (!in_array($setting['name'], array_keys($shopgateSettingsOld))) {
                continue;
            }

            $shopgateSettingsNew[$setting['name']] = isset($setting['value'])
                ? $setting['value']
                : null;
        }

        $this->config->load($shopgateSettingsNew);
        $this->config->save(array_keys($shopgateSettingsNew), true);

        $diff = array();
        foreach ($shopgateSettingsNew as $setting => $value) {
            $diff[] = array('name' => $setting, 'old' => $shopgateSettingsOld[$setting], 'new' => $value);
        }

        // set data and return response
        if (empty($this->response)) {
            $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id);
        }
        $this->responseData['shopgate_settings'] = $diff;
    }
144172
public function editSettings()
    {
        $this->setTitleEditSettings();
        $this->setBreadcrumbEditSettings();

        $this->setData('imagestyles', $this->image_style->getList());
        $this->setData('settings', $this->module->getSettings('mobile'));
        $this->setData('imagestyle_fields', $this->getImageStyleFieldsSettings());

        $this->submitSettings();
        $this->outputEditSettings();
    }
1218057
public function registerSettings() {
        if (!isset($this->toolInfo['settings']['groups']))
            return;

        $watch = !empty($this->toolInfo['settings']['watch']);
        if ($watch) {
            add_action("pre_update_option", function ($value, $option, $old_value) {
                if (!get_transient("settings_changed_".$this->toolName)) {
                    set_transient("settings_changed_".$this->toolName, true);
                }

                return $value;
            }, 10, 3);
        }


        $groups=$this->toolInfo['settings']['groups'];
        foreach($groups as $group => $groupInfo) {
            $groupWatch = !empty($groupInfo['watch']);

            $this->registerSettingsSection($group,$groupInfo['title'],$groupInfo['description']);
            if (isset($groupInfo['options']))  {
                foreach($groupInfo['options'] as $option => $optionInfo)  {
                    $optionWatch = !empty($optionInfo['watch']);

                    $this->registerSetting($option);

                    if ($groupWatch || $optionWatch) {
                        add_action("update_option_$option", function ($setting, $oldValue=null, $newValue=null) {
                            if (!get_transient("settings_changed_".$this->toolName)) {
                                set_transient("settings_changed_".$this->toolName, true);
                            }
                        }, 10, 3);
                    }

                    if (isset($optionInfo['type']))  {
                    	$description = arrayPath($optionInfo,'description',null);
                    	$conditions = arrayPath($optionInfo,'conditions',null);
                    	$placeholder = arrayPath($optionInfo,'placeholder',null);
                    	$default = arrayPath($optionInfo,'default',null);
                        $increment = arrayPath($optionInfo,'increment',null);
                        $min = arrayPath($optionInfo,'min',1);
                        $max = arrayPath($optionInfo,'max',1000);

                        switch($optionInfo['type'])  {
                            case 'text-field':
                                $this->registerTextFieldSetting($option,$optionInfo['title'],$group,$description,$placeholder,$conditions);
                                break;
                            case 'text-area':
                                $this->registerTextAreaFieldSetting($option,$optionInfo['title'],$group,$description, $placeholder, $conditions);
                                break;
                            case 'password':
                                $this->registerPasswordFieldSetting($option,$optionInfo['title'],$group,$description, $placeholder, $conditions);
                                break;
                            case 'checkbox':
                                $this->registerCheckboxFieldSetting($option,$optionInfo['title'],$group,$description, $default, $conditions);
                                break;
                            case 'number':
                                $this->registerNumberFieldSetting($option,$optionInfo['title'],$group,$description, $default, $conditions, $min, $max, $increment);
                                break;
	                        case 'select':
		                        $this->registerSelectSetting($option,$optionInfo['options'],$optionInfo['title'],$group,$description, $conditions);
		                        break;
	                        case 'custom':
		                        $this->registerCustomFieldSetting($option,'__CUSTOMREMOVE__',$group,$optionInfo['callback'],$description, $conditions);
		                        break;
                        }
                    }
                }
            }
        }
    }
2880
public function applyDetailSettings()
    {
        $this->resetOrder();

        $agenda   = $this->loader->getAgenda();
        $dbLookup = $this->util->getDbLookup();
        $empty    = $this->util->getTranslated()->getEmptyDropdownArray();

        $this->setIfExists('gec_id_organization', 'label', $this->_('Organization'),
                'elementClass', 'Exhibitor',
                'multiOptions', $empty + $dbLookup->getOrganizations());

        $this->setIfExists('gec_status',         'label', $this->_('Status'),
                'multiOptions', $agenda->getEpisodeStatusCodes());

        $this->setIfExists('gec_startdate',      'label', $this->_('Start date'),
                'dateFormat',  'dd-MM-yyyy',
                'description', $this->_('dd-mm-yyyy'));
        $this->setIfExists('gec_enddate',        'label', $this->_('End date'),
                'dateFormat',  'dd-MM-yyyy',
                'description', $this->_('dd-mm-yyyy'));

        $this->setIfExists('gec_id_attended_by', 'label', $this->_('With'),
                'multiOptions', $empty + $agenda->getHealthcareStaff());

        $this->setIfExists('gec_subject',        'label', $this->_('Subject'));
        $this->setIfExists('gec_comment',        'label', $this->_('Comment'));
        $this->setIfExists('gec_diagnosis',      'label', $this->_('Diagnosis'));
        $this->set('appointment_count',     'label', $this->_('Appointments'));

        $jsonType = new JsonData(10);
        $jsonType->apply($this, 'gec_diagnosis_data', true);
        $jsonType->apply($this, 'gec_extra_data',     true);

        if ($this->currentUser->hasPrivilege('pr.episodes.rawdata')) {
            $this->setIfExists('gec_diagnosis_data', 'label', $this->_('Diagnosis data'));
            $this->setIfExists('gec_extra_data',     'label', $this->_('Extra data'));
        }

        $this->refreshGroupSettings();

        return $this;
    }
1237301
public function editSettingsAction()
    {
        if ($this->pool->emergencyHandler->checkMaxCall() === true) {
            // Called too often, we might get into trouble here!
            return $this;
        }

        $this->pool->reset();

        // We will not check this for the cookie config, to avoid people locking
        // themselves out.
        $this->pool->emergencyHandler->setDisable(true);

        // Find caller.
        $caller = $this->callerFinder->findCaller('Cookie Configuration', array());
        $this->pool->chunks->addMetadata($caller);

        // Render it.
        $footer = $this->outputFooter($caller, true);
        $this->pool->chunks->detectEncoding($footer);

        $this->outputService
            ->addChunkString($this->pool->render->renderHeader('Edit local settings', $this->outputCssAndJs()))
            ->addChunkString($footer);
        $this->pool->emergencyHandler->setDisable(false);
        $this->outputService->finalize();

        return $this;
    }
527446
protected function setExportTmpAndLogSettings()
    {
        $this->setExportFolderPath(
            $this->directory->getPath(DirectoryList::TMP) . DS . 'shopgate' . DS . $this->getShopNumber()
        );
        $this->createFolderIfNotExist($this->getExportFolderPath());

        $this->setLogFolderPath(
            $this->directory->getPath(DirectoryList::LOG) . DS . 'shopgate' . DS . $this->getShopNumber()
        );
        $this->createFolderIfNotExist($this->getLogFolderPath());

        $this->setCacheFolderPath(
            $this->directory->getPath(DirectoryList::TMP) . DS . 'shopgate' . DS . $this->getShopNumber()
        );
        $this->createFolderIfNotExist($this->getCacheFolderPath());
    }
402774
public function save()
    {
        $data = $this->twisto->requestJson('POST', 'invoice/' . urlencode($this->invoice_id) . '/edit/', $this->serialize());
        $this->deserialize($data);
    }
86126
public function invoiceHasStrategyLine()
    {
        $result = false;
        foreach ($this->invoiceLines as $line) {
            if ($line[Meta::VatRateSource] === Creator::VatRateSource_Strategy) {
                $result = true;
                break;
            }
        }
        return $result;
    }
1155686
public function applyFormatting()
    {
        $this->resetOrder();

        $dbLookup   = $this->util->getDbLookup();
        $translated = $this->util->getTranslated();

        // Token id & respondent
        $this->set('gto_id_token',           'label', $this->_('Token'),
                'elementClass', 'Exhibitor',
                'formatFunction', 'strtoupper'
                );
        $this->set('gr2o_patient_nr',        'label', $this->_('Respondent nr'),
                'elementClass', 'Exhibitor'
                );
        $this->set('respondent_name',        'label', $this->_('Respondent name'),
                'elementClass', 'Exhibitor'
                );
        $this->set('gto_id_organization',    'label', $this->_('Organization'),
                'elementClass', 'Exhibitor',
                'multiOptions', $dbLookup->getOrganizationsWithRespondents()
                );

        // Track, round & survey
        $this->set('gtr_track_name',         'label', $this->_('Track'),
                'elementClass', 'Exhibitor'
                );
        $this->set('gr2t_track_info',        'label', $this->_('Description'),
                'elementClass', 'Exhibitor'
                );
        $this->set('gto_round_description',  'label', $this->_('Round'),
                'elementClass', 'Exhibitor'
                );
        $this->set('gsu_survey_name',        'label', $this->_('Survey'),
                'elementClass', 'Exhibitor'
                );
        $this->set('ggp_name',               'label', $this->_('Assigned to'),
                'elementClass', 'Exhibitor'
                );

        // Token, editable part
        $manual = $translated->getDateCalculationOptions();
        $this->set('gto_valid_from_manual',  'label', $this->_('Set valid from'),
                'description', $this->_('Manually set dates are fixed an will never be (re)calculated.'),
                'elementClass', 'Radio',
                'multiOptions', $manual,
                'separator', ' '
                );
        $this->set('gto_valid_from',         'label', $this->_('Valid from'),
                'elementClass', 'Date',
                'formatFunction', $translated->formatDateNever,
                'tdClass', 'date');
        $this->set('gto_valid_until_manual', 'label', $this->_('Set valid until'),
                'description', $this->_('Manually set dates are fixed an will never be (re)calculated.'),
                'elementClass', 'Radio',
                'multiOptions', $manual,
                'separator', ' '
                );
        $this->set('gto_valid_until',        'label', $this->_('Valid until'),
                'elementClass', 'Date',
                'formatFunction', $translated->formatDateForever,
                'tdClass', 'date');
        $this->set('gto_comment',            'label', $this->_('Comments'),
                'cols', 50,
                'elementClass', 'Textarea',
                'rows', 3,
                'tdClass', 'pre'
                );

        // Token, display part
        $this->set('gto_mail_sent_date',     'label', $this->_('Last contact'),
                'elementClass', 'Exhibitor',
                'formatFunction', $translated->formatDateNever,
                'tdClass', 'date');
        $this->set('gto_mail_sent_num',      'label', $this->_('Number of contact moments'),
                'elementClass', 'Exhibitor'
                );
        $this->set('gto_completion_time',    'label', $this->_('Completed'),
                'elementClass', 'Exhibitor',
                'formatFunction', $translated->formatDateNa,
                'tdClass', 'date');
        $this->set('gto_duration_in_sec',    'label', $this->_('Duration in seconds'),
                'elementClass', 'Exhibitor'
                );
        $this->set('gto_result',             'label', $this->_('Score'),
                'elementClass', 'Exhibitor'
                );
        $this->set('grc_description',        'label', $this->_('Reception code'),
                'formatFunction', array($this->translate, '_'),
                'elementClass', 'Exhibitor'
                );
        $this->set('gto_changed',            'label', $this->_('Changed on'),
                'elementClass', 'Exhibitor',
                'formatFunction', $translated->formatDateUnknown
                );
        $this->set('assigned_by',            'label', $this->_('Assigned by'),
                'elementClass', 'Exhibitor'
                );

        $this->refreshGroupSettings();

        return $this;
    }
402022
public function delete()
    {
        if (!empty($this->iId)) {
            $oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice');
            if (!$oInvoiceModel->delete($this->iId)) {
                throw new InvoiceException('Failed to delete invoice.');
            }
        }

        return $this;
    }
190867
protected function doSetupDevelopmentSettings() {
    $source = __DIR__ . '/../dist/development.services.yml';
    $destination = $this->getSitesDirectory() . '/development.services.yml';
    $this->write('Make sure that Twig cache is disabled in <comment>%s</comment>', $this->shortenDirectory($destination));
    copy($source, $destination);

    $destination = $this->getDefaultDirectory() . '/default.settings.php';
    $content = file_get_contents($destination);
    $ignore_directory_setting = sprintf('$settings[\'file_scan_ignore_directories\'][] = \'%s\';', $this->getBuildRoot());
    if (strstr($content, $ignore_directory_setting) === FALSE) {
      file_put_contents($destination, $ignore_directory_setting . PHP_EOL, FILE_APPEND);
    }
    $this->write('Add build directory to list of ignored paths in <comment>%s</comment>.', $this->shortenDirectory($destination));

    $destination = $this->getDefaultDirectory() . '/settings.local.php';
    $source = $this->getSitesDirectory() . '/example.settings.local.php';
    $content = file_get_contents($source);
    $content = str_replace('# $settings[\'cache\'][\'bins\']', '$settings[\'cache\'][\'bins\']', $content);
    file_put_contents($destination, $content);
    $this->write('Setup local development settings at <comment>%s</comment>.', $this->shortenDirectory($destination));
    $this->write('Note: local development settings file is disabled by default, enable it by un-commenting related lines in your settings.php file.');
  }