AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.217.80
Web Server : Apache
System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64
User : lrsys ( 1015)
PHP Version : 5.6.40
Disable Function : exec,passthru,shell_exec,system
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/lrsys/www/lrsys_apps/rodeio/application/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/www/lrsys_apps/rodeio/application/controllers/orders.php
<?php

// *************************************************************************
// *                                                                       *
// * iBilling -  Accounting, Billing Software                              *
// * Copyright (c) Sadia Sharmin. All Rights Reserved                      *
// *                                                                       *
// *************************************************************************
// *                                                                       *
// * Email: sadiasharmin3139@gmail.com                                                *
// * Website: http://www.sadiasharmin.com                                  *
// *                                                                       *
// *************************************************************************
// *                                                                       *
// * This software is furnished under a license and may be used and copied *
// * only  in  accordance  with  the  terms  of such  license and with the *
// * inclusion of the above copyright notice.                              *
// * If you Purchased from Codecanyon, Please read the full License from   *
// * here- http://codecanyon.net/licenses/standard                         *
// *                                                                       *
// *************************************************************************
_auth();
$ui->assign('_application_menu', 'orders');
$ui->assign('_title', $_L['Orders'] . '- ' . $config['CompanyName']);
$ui->assign('_st', $_L['Orders']);
$action = $routes['1'];
$user = User::_info();
$ui->assign('user', $user);

Event::trigger('orders');

switch ($action) {

    case 'list':
        $ui->assign('jsvar', '
_L[\'are_you_sure\'] = \'' . $_L['are_you_sure'] . '\';
 ');
        $mode_css = '';
        $mode_js = '';
        $mode_css = Asset::css('footable/css/footable.core.min');
        $mode_js = Asset::js(array('footable/js/footable.all.min', 'numeric', 'orders/list'));
        $d = ORM::for_table('sys_orders')
                        ->table_alias('o')
                        ->select('o.*')
                        ->select('c.account', 'account')
                        ->left_outer_join('crm_accounts', array('c.id', '=', 'o.crm_accounts_id'), 'c')
                        ->order_by_desc('o.id')->find_many();
        $ui->assign('d', $d);
        $ui->assign('xheader', $mode_css);
        $ui->assign('xfooter', $mode_js);

        $xjq = '
        $(\'.amount\').autoNumeric(\'init\', {
        aSign: \'' . $config['currency_code'] . ' \',
        dGroup: ' . $config['thousand_separator_placement'] . ',
        aPad: ' . $config['currency_decimal_digits'] . ',
        pSign: \'' . $config['currency_symbol_position'] . '\',
        aDec: \'' . $config['dec_point'] . '\',
        aSep: \'' . $config['thousands_sep'] . '\'
        });
     ';
        $ui->assign('xjq', $xjq);
        $ui->display('orders_list.tpl');
        break;

    case 'edit':

        Event::trigger('orders/edit/');

        $id = $routes['2'];
        $d = ORM::for_table('sys_orders')->find_one($id);
//        var_dump($d);exit;
        if ($d) {

            $currencies = Model::factory('Models_Currency')->find_array();
            $ui->assign('currencies', $currencies);

            $ui->assign('i', $d);
            $items = ORM::for_table('sys_invoiceitems')->where('invoiceid', $id)->order_by_asc('id')->find_many();
            // $ui->assign('items', $items);
            //lpillon 28/01/2017
            $itens_passar = 0;
            foreach ($items as $value) {
                if ($itens_passar == 0)
                    $itens_passar = $value['sys_item_id'];
                else
                    $itens_passar .= "," . $value['sys_item_id'];
            }
            //carrega as imagens dos produtos
            for ($i = 0; $i < count($items); $i++) {
                $product_images = ORM::for_table('sys_items_images')->where('sys_items_id', $items[$i]['sys_item_id'])->find_many();
                if (count($product_images) > 0) {
                    $items[$i]['image'] = APP_URL . '/application/storage/product/img/' . $product_images[0]->src;
                } else {
                    $items[$i]['image'] = APP_URL . '/ui/theme/lrsys/img/sem-imagem.jpg';
                }
            }

            $ui->assign('items', $items);

            $itensUnit = ORM::for_table('sys_items')->where_raw("id in(" . $itens_passar . ")")->find_many();
            $ui->assign('itensUnit', $itensUnit);
            $undades = ORM::for_table('sys_items_unit')->find_many();
            $ui->assign('undades', $undades);

//find the user
            $a = ORM::for_table('crm_accounts')->find_one($d['userid']);
            $ui->assign('a', $a);
            $ui->assign('d', $d);
            $ui->assign('_st', $_L['Add Invoice']);
            $c = ORM::for_table('crm_accounts')->select('id')->select('account')->select('company')->find_many();
            $ui->assign('c', $c);

            $t = ORM::for_table('sys_tax')->find_many();
            $ui->assign('t', $t);

//default idate ddate
            $ui->assign('idate', date('Y-m-d'));

            if ($config['i_driver'] == 'default') {
                $js_file = 'edit-invoice-v2';
                $tpl_file = 'edit-invoice.tpl';
            } elseif ($config['i_driver'] == 'v2') {
                $js_file = 'edit_invoice_v2n';
                $tpl_file = 'edit_invoice_v2.tpl';
            } else {
                $js_file = 'edit-invoice-v2';
                $tpl_file = 'orders_edit.tpl';
            }
            $tpl_file = 'orders_edit.tpl';
            $ui->assign('xheader', Asset::css(array('s2/css/select2.min', 'modal', 'dp/dist/datepicker.min', 'redactor/redactor')));
            $ui->assign('xfooter', Asset::js(array('redactor/redactor.min', 's2/js/select2.min', 's2/js/i18n/' . lan(), 'dp/dist/datepicker.min', 'dp/i18n/' . $config['language'], 'numeric', 'modal', 'modal-add-contact', 'modal_edit_contact_address', $js_file)));

            $ui->assign('xjq', '

 $(\'.amount\').autoNumeric(\'init\', {

    aSign: \'' . $config['currency_code'] . ' \',
    dGroup: ' . $config['thousand_separator_placement'] . ',
    aPad: ' . $config['currency_decimal_digits'] . ',
    pSign: \'' . $config['currency_symbol_position'] . '\',
    aDec: \'' . $config['dec_point'] . '\',
    aSep: \'' . $config['thousands_sep'] . '\'

    });

 ');

            //ADICIONA os dados para exibir nas mensagens em JS do MODAL
            $ui->assign('jsvar', '
        _L[\'CPF Invalid\'] = \'' . $_L['CPF Invalid'] . '\';
        _L[\'CNPJ Invalid\'] = \'' . $_L['CNPJ Invalid'] . '\';
         ');

            // Busca os meios de pagamentos
            $pmethods = ORM::for_table('sys_pmethods')
                    ->order_by_asc('sorder')
                    ->find_array();
            $ui->assign('payment_methods', $pmethods);

            // Busca as contas
//            $accounts = ORM::for_table('sys_accounts')
//                    ->table_alias('acc')
//                    ->select('acc.id')
//                    ->select('acc.account')
//                    ->select('acc.description')
//                    ->select('bfv.field')
//                    ->select('bfv.value')
//                    ->join('sys_accounts_banks_fields_values', 'acc.id = bfv.id_account', 'bfv')
//                    ->group_by('acc.id')
//                    ->find_array();
            $ui->assign('accounts', null);

            $ui->display($tpl_file);
        } else {
            echo 'Invoice Not Found';
        }
//find all clients.

        break;
        
    case 'add':
        // find all customers
        $c = ORM::for_table('crm_accounts')->select('id')->select('account')->select('company')->select('email')->order_by_desc('id')->find_many();
        $ui->assign('c', $c);

        // find all products

        $p = ORM::for_table('sys_items')->select('id')->select('name')->find_array();

        $ui->assign('p', $p);

        if (isset($routes['3']) AND ( $routes['3'] != '')) {
            $p_cid = $routes['3'];
            $p_d = ORM::for_table('crm_accounts')->find_one($p_cid);
            if ($p_d) {
                $ui->assign('p_cid', $p_cid);
            }
        } else {
            $ui->assign('p_cid', '');
        }

        $max = ORM::for_table('sys_orders')->max('id');
        $nxt = $max + 1;
        //validaçao para caso tenha algum pedido no base, e nao pegue a numeração correta
        if ($nxt < 1000) {
            $nxt == 1000;
        }

        $ui->assign('orderNumber', $nxt);
        $ui->assign('items', null);
        $ui->assign('d', null);
        $ui->assign('numberItens', null);
        $ui->assign('qtdItens', null);
        $ui->assign('netWeight', null);
        $ui->assign('grossWeight', null);
        $ui->assign('totalProduct', null);
        $ui->assign('total', null);
        $ui->assign('ipi', null);
        $ui->assign('icmsst', null);
        $ui->assign('date', date('Y-m-d'));


        //CARREGA A LISTA DE estados
        $e = ORM::for_table('state')->order_by_asc('state_name')->find_many();
        $ui->assign('state', $e);


        // Busca os meios de pagamentos
        $pmethods = ORM::for_table('sys_pmethods')
                ->order_by_asc('sorder')
                ->find_array();
        $ui->assign('payment_methods', $pmethods);

        $pmethods = ORM::for_table('shipping_method')
                ->order_by_asc('sorder')
                ->find_array();
        $ui->assign('shipping_method', $pmethods);

        $css_arr = array('s2/css/select2.min', 'modal', 'dp/dist/datepicker.min');


        $mode_js = Asset::js(array('s2/js/select2.min', 's2/js/i18n/' . lan(), 'dp/dist/datepicker.min', 'dp/i18n/' . $config['language'], 'numeric', 'modal', 'modal-add-contact', 'modal_edit_contact_address', 'orders/add'));
        $ui->assign('xheader', Asset::css($css_arr));

        $ui->assign('xfooter', $mode_js);

        $ui->assign('xjq', '
        function ib_amount() {    
        }
         $(\'.amount\').autoNumeric(\'init\', {
            aSign: \'' . $config['currency_code'] . ' \',
            dGroup: ' . $config['thousand_separator_placement'] . ',
            aPad: ' . $config['currency_decimal_digits'] . ',
            pSign: \'' . $config['currency_symbol_position'] . '\',
            aDec: \'' . $config['dec_point'] . '\',
            aSep: \'' . $config['thousands_sep'] . '\'

            });
             $(".select2").select2({
            theme: "bootstrap"
            });
            $(\'.integer\').autoNumeric(\'init\', {aSep: \'\', aDec: \'' . $config['dec_point'] . '\', mDec: 0, aSign: \' \', pSign: \'s\'});
        ');

        $ui->assign('jsvar', '
            _L[\'are_you_sure\'] = \'' . $_L['are_you_sure'] . '\';
            _L[\'Save\'] = \'' . $_L['Save'] . '\';
            _L[\'OK\'] = \'' . $_L['OK'] . '\';
             _L[\'Remove\'] = \'' . $_L['Remove'] . '\';  
            _L[\'Select\'] = \'' . $_L['Select'] . '\';  
            _L[\'Cancel\'] = \'' . $_L['Cancel'] . '\';
            _L[\'Name\'] = \'' . $_L['Name'] . '\';
            _L[\'Add New Nature Of Operation\'] = \'' . $_L['Add New Nature Of Operation'] . '\';
            _L[\'Select Nature Of Operation\'] = \'' . $_L['Select Nature Of Operation'] . '\';
            _L[\'Select Client\'] = \'' . $_L['Select Client'] . '\';
            _L[\'Select Salesman\'] = \'' . $_L['Select Salesman'] . '\';
            _L[\'not enough stock available:\'] = \'' . $_L['not enough stock available:'] . '\';   
            _L[\'stock available:\'] = \'' . $_L['stock available:'] . '\';   
            _L[\'Add New Tag\'] = \'' . $_L['Add New Tag'] . '\';   
            _L[\'Tags\'] = \'' . $_L['Tags'] . '\';   
            _L[\'Select State\'] = \'' . $_L['Select State'] . '\';   
            _L[\'Select City\'] = \'' . $_L['Select City'] . '\';   
            _L[\'Select the item first.\'] = \'' . $_L['Select the item first.'] . '\'; 
            _L[\'Select\'] = \'' . $_L['Select'] . '\'; 
            _L[\'There are no items to add\'] = \'' . $_L['There are no items to add'] . '\';     
            _L[\'CPF Invalid\'] = \'' . $_L['CPF Invalid'] . '\';
            _L[\'CNPJ Invalid\'] = \'' . $_L['CNPJ Invalid'] . '\';
        ');

        $ui->display('orders_add.tpl');

        break;

    case 'post':
        $client = _post('client');

        $msg = '';
        if ($client == '') {
            $msg .= $_L['select_a_contact'] . ' <br> ';
        }

        if (isset($_POST['amount'])) {
            $qty = $_POST['qty'];
            $description = $_POST['desc'];
            $item_id = $_POST['id_product'];
            $i = '0';
            //validação de estoque
            foreach ($description as $item) {
                $stock = ORM::for_table('sys_items_stock')->where('sys_items_id', $item_id[$i])->find_many();
                if (count($stock) > 0) {
                    if ($stock[0]->current_stock < Finance::amount_fix($qty[$i])) {
                        $msg.= $item . " " . $_L['not enough stock available:'] . " " . $stock[0]->current_stock . "<br/>";
                    }
                }
                if(Finance::amount_fix($qty[$i])<=0){
                      $msg.= $item . " " . $_L['can not be registered with quantity 0 "zero"']. "<br/>";
                }
               if(empty($item_id[$i])){
                      $msg.= $_L['Select the item first.']. "<br/>";
                }
                $i++;
            }
        } else {
            $msg .= $_L['at_least_one_item_required'] . ' <br> ';
        }

        if ($msg == '') {

            $d = ORM::for_table('sys_orders')->create();
            empty(_post('nature_operation')) ? '' : $d->nature_operation_id = _post('nature_operation');
            $d->crm_accounts_id = $client;

            //grava o endereço, ou informado pelo usuário ou buscado do banco do cadastro do cliente, no pedido
            $d->delivery_address = !empty(_post('delivery_address')) ? _post('delivery_address') : 'other';
            if ($d->delivery_address == 'other') {
                if (intval(_post('state'))) {
                    $d->state_id = _post('state');
                }

                if (intval(_post('city')) > 0) {
                    $d->city_id = _post('city');
                }
                $d->zip = _post('zip');
                $d->address = _post('address');
                $d->neighborhood = _post('neighborhood');
                $d->number = _post('number');
                $d->complement = _post('complement');
            } else {
                $address = ORM::for_table('crm_accounts_address')->where('crm_account_id', $d->crm_accounts_id)->where('type_address', $d->delivery_address)->find_many();
                if (count($address) > 0) {
                    if (intval($address[0]->state_id)) {
                        $d->state_id = $address[0]->state_id;
                    }

                    if (intval($address[0]->city_id) > 0) {
                        $d->city_id = $address[0]->city_id;
                    }
                    $d->zip = $address[0]->zip;
                    $d->address = $address[0]->address;
                    $d->neighborhood = $address[0]->neighborhood;
                    $d->number = $address[0]->number;
                    $d->complement = $address[0]->complement;
                }
            }
            empty(_post('salesman')) ? '' : $d->salesman_id = _post('salesman');
            $d->gross_weight = Finance::amount_fix(_post('gross_weight'));
            $d->net_weight = Finance::amount_fix(_post('net_weight'));
            
            // pego os valores dos produtos
            $amount = $_POST['amount'];
            $array_item_discount = $_POST['item_discount'];
            $i = 0;
            $sTotal = 0;
            $sDiscount = 0;
            foreach ($amount as $samount) {
                $samount = Finance::amount_fix($samount);
                $a[$i] = $samount;
                /* @since v 2.0 */
                $sqty = $qty[$i];
                
                // desconto
                $item_discount[$i] = Finance::amount_fix($array_item_discount[$i]);
                $sDiscount += $item_discount[$i] * ($sqty);
                $sqty = Finance::amount_fix($sqty);

                $sTotal += $samount * ($sqty);
                $lamount = $samount * ($sqty);
                $i++;
            }

            $fTotal = $sTotal;

            $d->sub_total = $sTotal;


            // calculate discount
            
            if($sDiscount == 0)
            {
                $discount_amount = Finance::amount_fix(_post('discount'));
                $discount_type = _post('type_discount');
                $discount_value = '0.00';

                if ($discount_amount == '0' OR $discount_amount == '') {
                    $actual_discount = '0.00';
                } else {
                    if ($discount_type == 'f') {

                        $actual_discount = $discount_amount;
                        $discount_value = $discount_amount;
                    } else {

                        $discount_type = 'p';
                        $actual_discount = ($sTotal * $discount_amount) / 100;
                        $discount_value = $discount_amount;
                    }
                }
            }
            else
            {
                $discount_type      = 'f';
                $actual_discount    = $sDiscount;
                $discount_value     = $sDiscount;
            }
            
            $actual_discount = number_format((float) $actual_discount, 2, '.', '');
            $fTotal = $fTotal - $actual_discount;   


            $d->freight = Finance::amount_fix(_post('freight'));
            $d->total = $fTotal + $d->freight;

            $d->discount_type = $discount_type;
            $d->discount_value = Finance::amount_fix($discount_value);
            $d->discount = $actual_discount;
            empty(_post('sales_date')) ? '' : $d->sales_date = _postDate('sales_date', $_c);
            empty(_post('expected_date')) ? '' : $d->expected_date = _postDate('expected_date', $_c);
            $d->payment_method = _post('mtdopgto');
            empty(_post('shipping_method')) ? '' : $d->shipping_method_id = _post('shipping_method');
            $d->tracking_code = _post('tracking_code');
            $d->craw_url = _post('craw_url');
            $d->conveyor_id = _post('conveyor_id');
            $d->freight_by = _post('freight_by');
            $d->qtd_volumes = _post('qtd_volumes');
            $d->notes = _post('notes');
            $d->internal_remarks = _post('internal_remarks');
            if (isset($_POST['tags']) AND ( $_POST['tags']) != '') {
                $tags = $_POST['tags'];
            } else {
                $tags = '';
            }
            $d->tags = Arr::arr_to_str($tags);
            //salva status inicial do pedido
            $d->status = 'Open';

            // registro da data e hora da criação do pedido
            $d->date_added = date("Y-m-d H:i:s");
            
            $d->save();

            $order_id = $d->id();
            $description = $_POST['desc'];
            $item_id = $_POST['id_product'];

            $i = '0';
            foreach ($description as $item) {
                $samount = $a[$i];
                $sqty = $qty[$i];
                $sqty = Finance::amount_fix($sqty);
                $samount = Finance::amount_fix($samount);
                $ltotal = ($samount) * ($sqty);
                $sys_orders_items = ORM::for_table('sys_orders_items')->create();
                $sys_orders_items->sys_orders_id = $order_id;
                $sys_orders_items->description = $item;
                $sys_orders_items->qty = $sqty;
                $sys_orders_items->amount = $samount;
                $sys_orders_items->discount = $item_discount[$i];
                $sys_orders_items->total = $ltotal;
                $sys_orders_items->sys_item_id = $item_id[$i];

                $sys_orders_items->save();
                
                
                // sensibilizo o estoque
                $stock = ORM::for_table('sys_stock')
                            ->create();
                $stock->sys_items_id = $item_id[$i];
                $stock->type = 'out';
                $stock->date = date("Y-m-d");
                $stock->time = date("H:i:s");
                $stock->quantity = $sqty;
                $stock->unit_price = $samount - $item_discount[$i];
                $stock->observation = $_L['ORDERS_ORDER_NUMBER'].':'.$order_id;
                $stock->dt_cadastro = date("Y-m-d H:i:s");
                $stock->sys_orders_id = $order_id;
                $stock->save();
                
                //TODO: VERIFICAR SE REALMENTE TEM PRODUTO SUFICIENTE NO ESTOQUE.
                // CASO NÃO TENHA, CANCELAR TODOS OS ITEMS DO PEDIDO E RETORNAR MENSAGEM DE ERRO.
                // 
                // 
                // atualizo o saldo de produtos
                $current_stock   = ORM::for_table('sys_items_stock')
                                    ->select('current_stock')
                                    ->where('sys_items_id', $item_id[$i])
                                    ->find_many();
                $b = ORM::for_table('sys_items_stock')
                    ->where('sys_items_id',$item_id[$i])->find_result_set()
                    ->set('current_stock', $current_stock[0]['current_stock'] - $sqty)
                    ->save();
                
                $i++;
            }

            $generate_invoice = _post('generate_invoice');
            if ($generate_invoice == 'Yes') {
                $d->status = 'Approved';
                $u = ORM::for_table('crm_accounts')->find_one($client);
                $id = convertInvoice($d, $u->account);
                $d->sys_invoice_id = $id;
                $d->save();
            }

            echo $order_id;
        } else {
            echo $msg;
        }


        break;

    case 'convert_invoice':
        $oid = route(2);
        $order = ORM::for_table('sys_orders')
                ->table_alias('o')
                ->select('o.*')
                ->select('c.account', 'account')
                ->left_outer_join('crm_accounts', array('c.id', '=', 'o.crm_accounts_id'), 'c')
                ->find_one($oid);
        if ($order->status == 'Open') {
            $id = convertInvoice($order, $order->account);
            $order = ORM::for_table('sys_orders')->find_one($order->id);
            $order->status = 'Approved';
            $order->sys_invoice_id = $id;
            $order->save();
            r2(U . "orders/view/" . $order->id, 's', $_L['Invoice Created']);
        } else {
            r2(U . "orders/list/", 'e', $_L['Not Permited']);
        }
        break;
    case 'view':


        $oid = route(2);

        // find the orders

        $order = ORM::for_table('sys_orders')
                ->table_alias('o')
                ->select('o.*')
                ->select('c.account', 'account')
                ->left_outer_join('crm_accounts', array('c.id', '=', 'o.crm_accounts_id'), 'c')
                ->find_one($oid);

        if ($order) {

            $ui->assign('jsvar', '
_L[\'data_updated\'] = \'' . $_L['Data Updated'] . '\';
_L[\'email_sent\'] = \'' . $_L['Email Sent'] . '\';
 ');




            $ui->assign('xfooter', Asset::js(array('tinymce/tinymce.min', 'numeric', 'orders/view')));

            $ui->assign('order', $order);

            $xjq = '

    $(\'.amount\').autoNumeric(\'init\', {

    aSign: \'' . $config['currency_code'] . ' \',
    dGroup: ' . $config['thousand_separator_placement'] . ',
    aPad: ' . $config['currency_decimal_digits'] . ',
    pSign: \'' . $config['currency_symbol_position'] . '\',
    aDec: \'' . $config['dec_point'] . '\',
    aSep: \'' . $config['thousands_sep'] . '\'

    });

 ';

            $ui->assign('xjq', $xjq);

            $ui->display('orders_view.tpl');
        } else {
            i_close('Order Not Found');
        }


        break;

    case 'set':

        $id = route(2);
        $status = route(3);

        $allowed_status = array('Pending', 'Active', 'Cancelled', 'Fraud', 'Processing');

        if (in_array($status, $allowed_status)) {
            
        } else {
            $msg = 'Invalid Status';
        }

        $d = ORM::for_table('sys_orders')->find_one($id);

        if ($d) {

            $d->status = $status;
            $d->save();

            $msg = $_L['Data Updated'];
        } else {
            $msg = 'Order not found';
        }


        r2(U . 'orders/view/' . $id . '/', 's', $msg);



        break;



    case 'save_activation':

        $oid = _post('oid');

        $activation_subject = $_POST['activation_subject'];

        $activation_message = $_POST['activation_message'];

        $send_email = _post('send_email');

        if ($activation_message == '' || $activation_message == '') {
            i_close($_L['All Fields are Required']);
        }




        $d = ORM::for_table('sys_orders')->find_one($oid);

        if ($d) {

            $cid = $d->cid;

            $d->activation_subject = $activation_subject;
            $d->activation_message = $activation_message;

            $d->save();


            if ($send_email == 'yes') {

                // Send Email

                $client = ORM::for_table('crm_accounts')->find_one($cid);

                if ($client) {

                    if ($client->email != '') {
                        Ib_Email::_send($client->account, $client->email, $activation_subject, $activation_message, $cid);
                    }
                }
            }




            echo $d->id();
        } else {

            echo 'Order not found';
        }



        break;


    case 'module':

        $id = route(2);



        $d = ORM::for_table('sys_orders')->find_one($id);

        if ($d) {

            Event::trigger('orders/modules/');

            r2(U . 'orders/view/' . $id . '/', 's', $_L['Data Updated']);
        } else {
            $msg = 'Order not found';
        }





        break;








    default:
        echo 'action not defined';
}

function convertInvoice($q, $nameClient) {
    $today = date('Y-m-d');
    $idate = $today;
    $its = strtotime($idate);
    $duedate = $today;

    $dd = $today;

    $invoicenum = '';
    $vtoken = _raid(10);
    $ptoken = _raid(10);
    $d = ORM::for_table('sys_invoices')->create();
    $d->userid = $q['crm_accounts_id'];
    $d->account = $nameClient;
    $d->date = $idate;
    $d->duedate = $dd;
    $d->subtotal = $q['sub_total'];
    $d->discount_type = $q['discount_type'];
    $d->discount_value = $q['discount_value'];
    $d->discount = $q['discount'];
    $d->total = $q['total'];
    $d->vtoken = $vtoken;
    $d->ptoken = $ptoken;
    $d->status = 'Unpaid';
    $d->notes = $q['notes'];
    $d->invoicenum = $invoicenum;
    $d->tax2 = '0.00';
    $d->tax = '0.00';
    $d->taxname = '';
    $d->taxrate2 = '0.00';
    $d->taxrate = '0.00';
    $d->paymentmethod = $q['payment_method'];
    $d->sys_accounts_id = $q['crm_accounts_id'];
    $d->freight = $q['freight'];
    $d->paymentcondition = 0;
    $d->sys_orders_id = $q['id'];
    $d->freight_by = $q['freight_by'];
    
    
    // pego o endereço
    // TODO: tratar diferentes endereços para Cobrança e Entrega no mesmo pedido
    $estado = ORM::for_table('state')->find_one($q['state_id']);
    $city = ORM::for_table('city')->find_one($q['city_id']);
    $d->billing_street = $q['address'].', '.$q['number'];
    $d->billing_city = $city['city_name'];
    $d->billing_state = $estado['state_name'];
    $d->billing_zip = $q['zip'];
    $d->billing_country = 'Brasil';
    $d->shipping_street = $q['address'].', '.$q['number'];
    $d->shipping_city = $city['city_name'];
    $d->shipping_state = $estado['state_name'];
    $d->shipping_zip = $q['zip'];
    $d->shipping_country = 'Brasil';
    
    if ($d->freight_by == 'Free shipping') {
        $d->freight = 0;
    } else {
        $d->freight = $q['freight'];
    }
    $d->save();

    $invoiceid = $d->id();

    $taxed = '0';
    $i = '0';

    $items = ORM::for_table('sys_orders_items')->where('sys_orders_id', $q['id'])->order_by_asc('id')->find_many();

    foreach ($items as $item) {

        $d = ORM::for_table('sys_invoiceitems')->create();
        $d->invoiceid = $invoiceid;
        $d->userid = $q['crm_accounts_id'];
        $d->description = $item['description'];
        $d->qty = $item['qty'];
        $d->amount = $item['amount'];
        $d->discount = $item['discount'];
        $d->total = $item['total'];


        $d->taxed = '0';

        //others
        $d->type = '';
        $d->relid = '0';
        $d->itemcode = '';
        $d->taxamount = '0.00';
        $d->duedate = date('Y-m-d');
        $d->paymentmethod = '';
        $d->notes = '';
        $d->sys_item_id = $item['sys_item_id'];

        $d->save();
        $i++;
    }
    
    // Insiro no Contas a Receber
    $id = 0;
    $idaccount          = $q['crm_accounts_id'];
    $expiry_br          = $dd;
    $value              = $q['total'];
    $emission_date      = implode('-', array_reverse(explode('/', _post('emission_date'))));
    $document_number    = $invoiceid;
    $historic           = 'Fatura Gerada | Nº:'.$invoiceid;
    $idcategory         = 86;
    $id_cost_center     = '';
    $id_payment_method  = $q['payment_method'];
    $occurrence         = 'Única';
    $occurrence_installments = '';
    $competence         = '';
    $images             = '';
    $type               = 'Income';

    $attachment = ($images != "") ? json_encode(explode(',', $images), JSON_FORCE_OBJECT) : '';

    $expiry_date = new DateTime();
    list($year, $month, $day) = (explode('-', $expiry_br));
    $expiry_date->setDate($year, $month, $day);

    $value = str_replace(',', '.', str_replace('.', '', $value));
    
    
    if($occurrence == 'Mensal') {
            $id_parent_record = null;
            for($i=1; $i<=12; $i++) {
                    $record = ORM::for_table('module_billing_records')->create();
                    $record->id_account = $idaccount;
                    $record->id_parent_record = $id_parent_record;
                    $record->expiry = $expiry_date->format('Y-m-d');
                    $record->value = $value;
                    $record->balance = $value;
                    $record->emission_date = $emission_date;
                    $record->document_number = $document_number;
                    $record->historic = $historic;
                    $record->id_category = $idcategory;
                    $record->id_cost_center = $id_cost_center;
                    $record->id_payment_method = $id_payment_method;
                    $record->occurrence = $occurrence;
                    $record->occurrence_expiry = $expiry_date->format('d');
                    $record->occurrence_installments = $occurrence_installments;
                    $record->attachment = $attachment;
                    $record->competence = $competence;
                    $record->type = $type;
                    $record->status = ($expiry_date > (new DateTime('now')) ? 'Em aberto' : 'Atrasada');
                    $record->sys_invoices_id = $invoiceid;
                    $record->save();
                    $id_record = $record->id();

                    if($i == 1) {
                            $id_parent_record = $id_record;
                    }

                    if(isset($_POST['markers']) && count($_POST['markers']) > 0) {
                            foreach($_POST['markers'] as $marker) {
                                    $records_tags = ORM::for_table('module_billing_records_tags')->create();
                                    $records_tags->id_record = $id_record;
                                    $records_tags->id_tag = $marker;
                                    $records_tags->save();
                            }
                    }

                    $expiry_date->add(new DateInterval('P1M'));
            }
    }

    if($occurrence == 'Parcelada') {
            // TODO Estipular um limite máximo de parcelas
            if ($occurrence_installments > 1) {
                    $installment_value = ($value / $occurrence_installments);
                    $id_parent_record = null;
                    for($i=1; $i<=$occurrence_installments; $i++) {
                            $record = ORM::for_table('module_billing_records')->create();
                            $record->id_account = $idaccount;
                            $record->id_parent_record = $id_parent_record;
                            $record->expiry = $expiry_date->format('Y-m-d');
                            $record->value = $installment_value;
                            $record->balance = $installment_value;
                            $record->emission_date = $emission_date;
                            $record->document_number = $document_number;
                            $record->historic = $historic . " - {$_L['Installment']} ({$i}/{$occurrence_installments})";
                            $record->id_category = $idcategory;
                            $record->id_cost_center = $id_cost_center;
                            $record->id_payment_method = $id_payment_method;
                            $record->occurrence = $occurrence;
                            $record->occurrence_expiry = $expiry_date->format('d');
                            $record->occurrence_installments = $occurrence_installments;
                            $record->competence = $competence;
                            $record->attachment = $attachment;
                            $record->type = $type;
                            $record->status = ($expiry_date > (new DateTime('now')) ? 'Em aberto' : 'Atrasada');
                            $record->sys_invoices_id = $invoiceid;
                            $record->save();
                            $id_record = $record->id();

                            if($i == 1) {
                                    $id_parent_record = $id_record;
                            }

                            if(isset($_POST['markers']) && count($_POST['markers']) > 0) {
                                    foreach($_POST['markers'] as $marker) {
                                            $records_tags = ORM::for_table('module_billing_records_tags')->create();
                                            $records_tags->id_record = $id_record;
                                            $records_tags->id_tag = $marker;
                                            $records_tags->save();
                                    }
                            }

                            $expiry_date->add(new DateInterval('P1M'));
                    }
            }
            else {
                    r2(U.'module_billing/billing/income', 'e', $_L['Number of installments must be greater than 1']);
            }
    }

    if($occurrence == 'Única') {
            $record = ORM::for_table('module_billing_records')->create();
            $record->id_account = $idaccount;
            $record->expiry = $expiry_date->format('Y-m-d');
            $record->value = $value;
            $record->balance = $value;
            $record->emission_date = $emission_date;
            $record->document_number = $document_number;
            $record->historic = $historic;
            $record->id_category = $idcategory;
            $record->id_cost_center = $id_cost_center;
            $record->id_payment_method = $id_payment_method;
            $record->occurrence = $occurrence;
            $record->occurrence_expiry = $expiry_date->format('d');
            $record->occurrence_installments = $occurrence_installments;
            $record->attachment = $attachment;
            $record->competence = $competence;
            $record->type = $type;
            $record->status = ($expiry_date > (new DateTime('now')) ? 'Em aberto' : 'Atrasada');
            $record->sys_invoices_id = $invoiceid;
            $record->save();
            $id_record = $record->id();

            // Insere as tags na tabela N:N
//            if(isset($_POST['markers']) && count($_POST['markers']) > 0) {
//                    foreach($_POST['markers'] as $marker) {
//                            $records_tags = ORM::for_table('module_billing_records_tags')->create();
//                            $records_tags->id_record = $id_record;
//                            $records_tags->id_tag = $marker;
//                            $records_tags->save();
//                    }
//            }
    }

//    r2(U . 'module_billing/billing/income', 's', $_L['Income added successfully']);
    
    
    
    
//                    var_dump($params);exit;
//    var_dump(Syscurl::_post('http://leo.erp.lrsys.com.br/?ng=module_billing/billing/add_income_post/json', $params));
//    exit;
    return $invoiceid;
}

Anon7 - 2022
AnonSec Team