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/mundotennis/application/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/www/lrsys_apps/mundotennis/application/controllers/ps.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', 'ps');
$ui->assign('_title', $_L['Products n Services'] . '- ' . $config['CompanyName']);
$ui->assign('_st', $_L['Products n Services']);
$action = $routes['1'];
$user = User::_info();
$ui->assign('user', $user);

// Verifico quais Plugins estão instalados
$arr_pluginsInstalled = array();
$pluginsInstalled = ORM::for_table('sys_pl')->where('status', "1")->find_array();
foreach ($pluginsInstalled as $pl)
{
    $arr_pluginsInstalled[$pl['c']] = $pl;
}
$ui->assign('pluginsInstalled', $arr_pluginsInstalled);

switch ($action) {

    case 'modal-list':

        //lpillon - 26/01/2017 + andré(28/01/17)
        $data = ORM::for_table('sys_items')
                ->table_alias('i')
                ->select('i.*')
                ->select_expr("(select int_value from sys_items_unit u where u.id=i.unit_id )", 'u_unit')
                ->select_expr("(select st.current_stock from sys_items_stock st where st.sys_items_id=i.id )", 'current_stock')
                ->select_expr("(select initials from sys_items_unit u where u.id=i.unit_id )", 'u_initials')
                ->order_by_asc('i.name');

        if (!empty($_GET['notin'])) {
            $data->where_raw("i.id not in(" . $_GET['notin'] . ")");
        }

        $d = $data->find_many();

        echo '
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3>' . $_L['Products n Services'] . '</h3>
        </div>
       
        <div class="modal-body">
            <table class="table table-striped" id="items_table">
              <thead>
                <tr>
                    <th class="middle" width="4%">&nbsp;</th>
                    <th width="10%">' . $_L['Item Code'] . '</th>
                    <th width="10%">' . $_L['Image'] . '</th>                
                    <th width="">' . $_L['Item Name'] . '</th>
                    <th width="15%" colspan="2">' . $_L['Price'] . '</th>
                    <th class="hidden">ID</th>
                    <th class="hidden">UNIDADE</th>
                     <th class="hidden">Unit</th>
                    <th class="hidden">IMAGE</th>
                    <th class="hidden">STOCK</th>
                    <th class="hidden">gross_weight</th>
                    <th class="hidden">net_weight</th>
                </tr>
              </thead>
              <tbody>';

        foreach ($d as $ds) {
            $price = number_format($ds['sales_price'], 2, $config['dec_point'], $config['thousands_sep']);
            $product_images = ORM::for_table('sys_items_images')->where('sys_items_id', $ds['id'])->find_many();
            if (count($product_images) > 0) {
                $image = APP_URL . '/application/storage/product/img/' . $product_images[0]->src;
            } else {
                $image = APP_URL . '/ui/theme/lrsys/img/sem-imagem.jpg';
            }
            echo '
                <tr id="tr_' . $ds['id'] . '">
                    <td class="middle"><input type="checkbox" class="si"></td>
                    <td class="middle">' . $ds['id'] . '</td>
                    <td> <img width="100" style="max-height:100px" src="' . $image . '"/></td>
                    <td class="middle">' . $ds['description'] . '</td>
                    <td class="middle">' . $_c['currency_code'] . '</td>
                    <td class="middle price">' . $price . '</td>
                    <td class="hidden">' . $ds['id'] . '</td>
                    <td class="hidden">' . $ds['u_unit'] . '</td>
                    <td class="hidden">' . $ds['u_initials'] . '</td>
                    <td class="hidden">' . $image . '</td>
                    <td class="hidden">' . $ds['current_stock'] . '</td>
                    <td class="hidden">' . $ds['gross_weight'] . '</td>
                    <td class="hidden">' . $ds['net_weight'] . '</td>
                </tr>';
        }

        echo '
              </tbody>
            </table>
        </div>
        <div class="modal-footer">
            <button type="button" data-dismiss="modal" class="btn">' . $_L['Close'] . '</button>
            <button class="btn btn-primary update">' . $_L['Select'] . '</button>
        </div>';

        break;

    case 'modal-list-structure':
        $data = ORM::for_table('sys_items')
                ->table_alias('i')
                ->select('i.*')
                ->select_expr("(select int_value from sys_items_unit u where u.id=i.unit_id )", 'u_unit')
                ->select_expr("(select initials from sys_items_unit u where u.id=i.unit_id )", 'u_initials')
                ->where("i.type", "Product")
                ->order_by_asc('i.description');
        if (isset($_GET['item_id'])) {
            $data->where_raw("i.id not in(" . Arr::arr_to_str($_GET['item_id']) . ")");
        }
        $d = $data->find_many();

        echo '
<div class="modal-header">
	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
	<h3>' . $_L['Products'] . '</h3>
</div>
<div class="modal-body">
<table class="table table-striped" id="items_table">
      <thead>
        <tr>
          <th width="10%">#</th>
          <th width="20%">' . $_L['Item Code'] . '</th>
          <th width="53%">' . $_L['Item Name'] . '</th>
          <th width="15%" colspan="2">' . $_L['Price'] . '</th>
          <th class="hidden">ID</th>
          <th class="hidden">UNIDADE</th>
        </tr>
      </thead>
      <tbody>
       ';

        foreach ($d as $ds) {
            //var_dump($ds);die();
            $price = number_format($ds['sales_price'], 2, $config['dec_point'], $config['thousands_sep']);
            echo ' <tr id="tr_' . $ds['item_number'] . '">
                      <td><input type="checkbox" class="si"></td>
                      <td>' . $ds['item_number'] . '</td>
                      <td>' . $ds['description'] . '</td>
                      <td>' . $_c['currency_code'] . '</td>
                      <td class="price">' . $price . '</td>
                      <td class="hidden">' . $ds['id'] . '</td>
                      <td class="hidden">' . $ds['u_unit'] . '</td>
                      <td class="hidden">' . $ds['u_initials'] . '</td>
                    </tr>';
        }

        echo '

      </tbody>
    </table>

</div>
<div class="modal-footer">

	<button type="button" data-dismiss="modal" class="btn">' . $_L['Close'] . '</button>
	<button class="btn btn-primary update">' . $_L['Select'] . '</button>
</div>';

        break;


    case 'p-new':

        $ui->assign('type', 'Product');
        $ui->assign('title', $_L['Add Product']);
        $css_arr = array('dropzone/dropzone', 's2/css/select2.min', 'modal', 'dp/dist/datepicker.min');
        $js_arr = array('dropzone/dropzone', 'modal', 's2/js/select2.min', 'dp/dist/datepicker.min', 'numeric', 'jslib/add-product');
        $ui->assign('xheader', Asset::css($css_arr));
        $ui->assign('xfooter', Asset::js($js_arr));
        $ui->assign('xjq', '
            $(\'.amount\').autoNumeric(\'init\');
        ');
        $ui->assign('dataAtual', date('Y-m-d'));
        $max = ORM::for_table('sys_items')->max('id');
        $nxt = $max + 1;
        $ui->assign('nxt', $nxt);
        $ui->assign('product', null);
        $ui->assign('stock', null);
        $ui->assign('product_packing', null);
        $ui->assign('product_steps', null);
        $ui->assign('product_costs', null);
        //carrega os dados para o vetor javascript com o idioma do usuário
        //carrega as imagens do usuároi, para nao deixar lixo na base
        $product_images = ORM::for_table('sys_items_images')->where('user_id', $user->id)->find_many();
        $images = "";
        $imagesUser = "";
        if (count($product_images) > 0) {

            foreach ($product_images as $i) {
                //temporario 100 o tamanho
                $images.=' { name: "' . $i->src . '", size: 100,url:"' . APP_URL . '/application/storage/product/img/' . $i->src . '" },';
                $imagesUser.="," . $i->id;
            }
        } else {
            $images = "";
        }
        $ui->assign('images_user', substr($imagesUser, 1));

        $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[\'Add New Unit\'] = \'' . $_L['Add New Unit'] . '\';
        _L[\'Unit Name\'] = \'' . $_L['Unit Name'] . '\';
        _L[\'Unit Initials\'] = \'' . $_L['Unit Initials'] . '\';
        _L[\'Add New Location\'] = \'' . $_L['Add New Location'] . '\';
        _L[\'Location\'] = \'' . $_L['Location'] . '\';
        _L[\'Add New Category\'] = \'' . $_L['Add New Category'] . '\';
        _L[\'Category\'] = \'' . $_L['Category'] . '\';
        _L[\'Parent Category\'] = \'' . $_L['Parent Category'] . '\';         
        _L[\'Select Category\'] = \'' . $_L['Select Category'] . '\';  
        _L[\'Add New Packing\'] = \'' . $_L['Add New Packing'] . '\';
        _L[\'Add New Tag\'] = \'' . $_L['Add New Tag'] . '\';
        _L[\'Group Tags\'] = \'' . $_L['Group Tags'] . '\';
        _L[\'Tags\'] = \'' . $_L['Tags'] . '\';
        _L[\'Manufacturer Name\'] = \'' . $_L['Manufacturer Name'] . '\';
        _L[\'Code\'] = \'' . $_L['Code'] . '\';
        _L[\'Int Value\'] = \'' . $_L['Int Value'] . '\';
        _L[\'Yes\'] = \'' . $_L['Yes'] . '\';
        _L[\'No\'] = \'' . $_L['No'] . '\';
        _L[\'Withdrawal\'] = \'' . $_L['Withdrawal'] . '\';
        _L[\'Delivery\'] = \'' . $_L['Delivery'] . '\';
        _L[\'Select Client\'] = \'' . $_L['Select Client'] . '\';
        _L[\'There is a non-value price record, please enter this field first.\'] = \'' . $_L['There is a non-value price record, please enter this field first.'] . '\';  
        _L[\'All Type\'] = \'' . $_L['All Type'] . '\';
        _L[\'Apply for children\'] = \'' . $_L['Apply for children'] . '\';
        var existingFiles = [' . $images . '
        ];
         var _tagsSelecionadas = [];
         ');
        //chamma o metodo all da classe de dentro de autoload
        $ui->assign('sys_items_price_different', null);
        $ui->assign('clients', null);
        $ui->assign('segments',null);
        $ui->assign('origins', OriginICMS::all());
        $ui->display('add-product.tpl');
        break;

    case 'edit-product':
        ///route 2 recebe o id do produto
        $d = ORM::for_table('sys_items')->find_one($routes['2']);
        //adiciona os js necessários
        if ($d) {

            if ($d->sys_items_packing_id > 0) {
                $ui->assign('product_packing', ORM::for_table('sys_items_packing')->find_one($d->sys_items_packing_id));
            } else {
                $ui->assign('product_packing', null);
            }
            $ui->assign('product_steps', ORM::for_table('sys_items_step')->where('sys_items_id', $d->id)->order_by_asc('id')->find_many());
            $ui->assign('product_costs', ORM::for_table('sys_items_costs')->where('sys_items_id', $d->id)->order_by_asc('cost_date')->find_many());

            $ui->assign('packing', 'Product');
            $ui->assign('type', 'Product');
            $ui->assign('title', $_L['Edit Product']);
            $css_arr = array('dropzone/dropzone', 's2/css/select2.min', 'modal', 'dp/dist/datepicker.min');
            $js_arr = array('dropzone/dropzone', 'modal', 's2/js/select2.min', 'numeric', 'dp/dist/datepicker.min', 'jslib/add-product');
            $ui->assign('xheader', Asset::css($css_arr));
            $ui->assign('xfooter', Asset::js($js_arr));
            $ui->assign('xjq', '
            $(\'.amount\').autoNumeric(\'init\');
        ');
            $ui->assign('product', $d);
            $ui->assign('dataAtual', date('Y-m-d'));
            //carrega os dados do estoque
            $stocks = ORM::for_table('sys_items_stock')->where('sys_items_id', $d->id)->find_many();
            if (count($stocks) > 0) {
                $ui->assign('stock', $stocks[0]);
            } else {
                $ui->assign('stock', null);
            }
            $ui->assign('nxt', $d->item_number);

            //carrega as imagens
            $product_images = ORM::for_table('sys_items_images')->where('sys_items_id', $d->id)->find_many();
            $images = "";
            if (count($product_images) > 0) {
                foreach ($product_images as $i) {
                    //temporario 100 o tamanho
                    $images.=' { name: "' . $i->src . '", size: 100,url:"' . APP_URL . '/application/storage/product/img/' . $i->src . '" },';
                }
            }
            $ui->assign('images_user', '');

            //tags multiples para o form de edicao_product
            $tags = ORM::for_table('sys_items_having_tags')->where('sys_items_id', $d->id)->find_many();
            $tags_selecionadas = "";
            if (count($tags) > 0) {
                $i = 0;
                foreach ($tags as $t) {
                    $tags_selecionadas.= "_tagsSelecionadas[" . $i++ . "]=" . $t->sys_items_tags_id . ";";
                }
            }

            $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[\'Add New Unit\'] = \'' . $_L['Add New Unit'] . '\';
        _L[\'Unit Name\'] = \'' . $_L['Unit Name'] . '\';
        _L[\'Unit Initials\'] = \'' . $_L['Unit Initials'] . '\';
        _L[\'Add New Location\'] = \'' . $_L['Add New Location'] . '\';
        _L[\'Location\'] = \'' . $_L['Location'] . '\';
        _L[\'Add New Category\'] = \'' . $_L['Add New Category'] . '\';
        _L[\'Category\'] = \'' . $_L['Category'] . '\';
        _L[\'Parent Category\'] = \'' . $_L['Parent Category'] . '\';         
        _L[\'Select Category\'] = \'' . $_L['Select Category'] . '\';  
        _L[\'Add New Packing\'] = \'' . $_L['Add New Packing'] . '\';
        _L[\'Add New Tag\'] = \'' . $_L['Add New Tag'] . '\';
        _L[\'Group Tags\'] = \'' . $_L['Group Tags'] . '\';
        _L[\'Tags\'] = \'' . $_L['Tags'] . '\';
        _L[\'Int Value\'] = \'' . $_L['Int Value'] . '\';
        _L[\'Yes\'] = \'' . $_L['Yes'] . '\';
        _L[\'No\'] = \'' . $_L['No'] . '\';
        _L[\'Withdrawal\'] = \'' . $_L['Withdrawal'] . '\';
        _L[\'Delivery\'] = \'' . $_L['Delivery'] . '\';
        _L[\'Select Client\'] = \'' . $_L['Select Client'] . '\';
        _L[\'There is a non-value price record, please enter this field first.\'] = \'' . $_L['There is a non-value price record, please enter this field first.'] . '\';  
        _L[\'All Type\'] = \'' . $_L['All Type'] . '\';
        _L[\'Apply for children\'] = \'' . $_L['Apply for children'] . '\';


        var _tagsSelecionadas = []; ' . $tags_selecionadas . '
     
      
        var existingFiles = [' . $images . '];
    ');

            //guia de preços diferenciados

            $sys_items_price_different = ORM::for_table('sys_items_price')->where('sys_items_id', $d->id)->find_many();
            for ($i = 0; $i < count($sys_items_price_different); $i++) {
                $sys_items_price_especification = ORM::for_table('sys_items_price_especification')->where('sys_items_price_id', $sys_items_price_different[$i]->id)->find_many();
                $array_clients = array();
                $array_segments = array();

                foreach ($sys_items_price_especification as $registro) {

                    if ($registro->crm_account_id != null && $registro->crm_account_id >= 1) {
                        $array_clients[] = $registro->crm_account_id;
                    }
                    if ($registro->crm_segments_id != null && $registro->crm_segments_id >= 1) {
                        $array_segments[] = $registro->crm_segments_id;
                    }
                }
                $sys_items_price_different[$i]['array_clients'] = $array_clients;

                $sys_items_price_different[$i]['array_segments'] = $array_segments;
            }
            $ui->assign('sys_items_price_different', $sys_items_price_different);
            $ui->assign('clients', ORM::for_table('crm_accounts')->select('id')->select('account')->select('company')->select('email')->order_by_asc('account')->find_many());
            $ui->assign('segments', ORM::for_table('crm_segments')->find_many());


            //chamma o metodo all da classe de dentro de autoload
            $ui->assign('origins', OriginICMS::all());
            $ui->display('add-product.tpl');
        } else {
            r2('ps/p-list', 'e', $_L['Not Found']);
        }
        break;
    case 'product-add-image':
        $uploader = new Uploader();
        $uploader->setDir('application/storage/product/img/');
        $uploader->sameName(false);
        $uploader->setExtensions(array('jpg', 'jpeg', 'png', 'gif', 'pdf'));  //allowed extensions list//
        if ($uploader->uploadFile('file')) {   //txtFile is the filebrowse element name //
            $uploaded = $uploader->getUploadName(); //get uploaded file name, renames on upload//
            $file = $uploaded;
            $msg = $_L['Uploaded Successfully'];
            $success = 'Yes';

            $d = ORM::for_table('sys_items_images')->create();
            $d->src = $uploaded;
            if (isset($routes['2']) && $routes['2'] > 0) {
                $d->sys_items_id = $routes['2'];
            } else {
                //grava a imagem como pertencente ao usuário, antes dele salvar o novo produto
                $d->user_id = $user->id;
            }
            $d->save();
            $id = $d->id;
            //descobre os tamnahos da imagem

            list($width, $height, $type, $attr) = getimagesize('application/storage/product/img/' . $uploaded);
            $image = new Image();
            $image->source_path = 'application/storage/product/img/' . $uploaded;
            $image->target_path = 'application/storage/product/img/' . $uploaded;
            //verifica se precisa redimensionar
            if ($width > $height && $width > 800) {
                $image->resize(800);
            } else if ($height > $width && $height > 800) {
                $image->resize(null, 800);
            }
        } else {//upload failed
            $file = '';
            $msg = $uploader->getMessage();
            $success = 'No';
            $id = '';
        }

        $a = array(
            'success' => $success,
            'msg' => $msg,
            'file' => $file,
            'id' => $id
        );

        header('Content-Type: application/json');

        echo json_encode($a);
        break;
    case 'product-delete-image':
        $name = _post('name');
        $d = ORM::for_table('sys_items_images')->where("src", $name)->find_many();
        if (count($d) > 0) {
            $d[0]->delete();
            unlink('application/storage/product/img/' . $d[0]->src);
            $msg = $_L['Image Deleted Successfully'];
            $status = 'OK';
        } else {
            $msg = $_L['Not found'];
            $status = "ERROR";
        }
        $data = array(
            'status' => $status,
            'msg' => $msg,
        );
        header('Content-Type: application/json');
        echo json_encode($data);
        break;
    case 's-new':


        $ui->assign('type', 'Service');

        $css_arr = array('s2/css/select2.min');
        $js_arr = array('numeric', 'jslib/add-ps', 's2/js/select2.min');
        $ui->assign('xheader', Asset::css($css_arr));
        $ui->assign('xfooter', Asset::js($js_arr));


        $ui->assign('xjq', '
 $(\'.amount\').autoNumeric(\'init\');
 ');

        $max = ORM::for_table('sys_items')->max('id');
        $nxt = $max + 1;
        $ui->assign('nxt', $nxt);

        $ui->display('add-ps.tpl');
        break;


    case 'add-post':
        $name = _post('name');
        $description = _post('description');
        if($name == null)
        {
            $name = $description;
        }


        
        $notes = _post('product_notes');
        $sales_price = Finance::amount_fix(_post('sales_price'));
        $item_number = _post('item_number');
        $mercosur_nomenclature = preg_replace('/\D/', '', _post('mercosur_nomenclature'));
        $unit = _post('unit');
        $category = _post('category');
        $type = _post('type');
        $gross_weight = Finance::amount_fix(_post('gross_weight'));
        $net_weight = Finance::amount_fix(_post('net_weight'));
        $location = _post('location');
        $barcode_marketing = _post('barcode_marketing');
        $barcode = _post('barcode');
        $origin = _post('origin');
        $margin_discount = _post('margin_discount');
        
        // Leonardo Lopes - 14/06/2017
        $cod_nf = mb_strtoupper(_post('cod_nf'));

        //trata os campos obrigatórios
        $msg = '';
        if ($type == 'Product') {
            if ($description == '') {
                $msg .= $_L['Description'] . $_L['is required'];
            }
        } else {
            if ($name == '') {
                $msg .= $_L['Name'] . $_L['is required'];
            }
        }
        if (!is_numeric($net_weight)) {
            $net_weight = '0.00';
        }
        if (!is_numeric($gross_weight)) {
            $gross_weight = '0.00';
        }
        
        //TODO: CEDDI pediu pra retirar
        if ($sales_price == '') {
//            $msg .= $_L['Sales Price'] . $_L['is required'];
        }
        
        //TODO: Ceddi pediu pra retirar
        if ($mercosur_nomenclature == '') {
//            $msg .= $_L['Common nomenclature of Mercosur'] . $_L['is required'];
        }
        if ($unit == '') {
            $msg .= $_L['Unit'] . $_L['is required'];
        }



        if ($msg == '') {

            $d = ORM::for_table('sys_items')->create();

            $d->name = $name;
            $d->notes = $notes;
            $d->type_of_product = _post('type_of_product');
            $d->production = _post('production');
            $d->complementary_description = _post('complementary_description');
            $d->sales_price = $sales_price;
            $d->margin_discount = $margin_discount;
            $d->item_number = $item_number;
            
            // Leonardo Lopes - 14/06/2017
            $d->cod_nf = $cod_nf;
            
            $d->description = $description;
            $d->mercosur_nomenclature = $mercosur_nomenclature;
            $d->type = $type;
            $d->gross_weight = Finance::amount_fix($gross_weight);
            $d->net_weight = Finance::amount_fix($net_weight);
            if (!empty($location)) {
                $d->sys_items_location_id = $location;
            }
            $d->barcode_marketing = $barcode_marketing;
            $d->barcode = $barcode;
            if ($origin != '') {
                $d->sys_items_scr_id = $origin;
            }
            if (!empty($unit)) {
                $d->unit_id = $unit;
            }
            if (!empty($category)) {
                $d->category_id = $category;
            } else {
                $d->category_id = null;
            }
            $d->item_per_package = _post('item_per_package');
            $d->ipi_framework = _post("ipi_framework");
            $d->ipi_fixed_amount = Finance::amount_fix(_post("ipi_fixed_amount"));
            $d->ipi_code = _post("ipi_code");
            $d->cest_code = _post("cest_code");
            $d->status = _post('status');
            //    $d->cost_price = Finance::amount_fix(_post('cost_price'));
            if (!empty(_post('manufacturer'))) {
                $d->sys_items_manufacturer_id = _post("manufacturer");
            }
            //SALVA A EMBALAGEM
            $packing_type = _post("packing_type");
            if ($packing_type != '') {
                $packing_id = _post("packing");

                if ($packing_id == 0) {
                    $packing = ORM::for_table('sys_items_packing')->create();
                    $packing->type = $packing_type;
                    //adicona os valors possíves das medidas de cada tipo de embalagem
                    if ($packing_type == 'envelope') {
                        $packing->width = Finance::amount_fix(_post('pack_width'));
                        $packing->length = Finance::amount_fix(_post('pack_length'));
                        $packing->height = null;
                        $packing->diameter = null;
                        $packing->description = $_L['Envelope'] . ' ' . $packing->width . " x " . $packing->length;
                    } else if ($packing_type == 'package_box') {
                        $packing->width = Finance::amount_fix(_post('pack_width'));
                        $packing->length = Finance::amount_fix(_post('pack_length'));
                        $packing->height = Finance::amount_fix(_post('pack_height'));
                        $packing->diameter = null;
                        $packing->description = $_L['Package/Box'] . ' ' . $packing->width . " x " . $packing->length . " x " . $packing->height;
                    } else if ($packing_type == 'roller_cylinder') {

                        $packing->length = Finance::amount_fix(_post('pack_length'));
                        $packing->diameter = Finance::amount_fix(_post('pack_diameter'));
                        $packing->height = null;
                        $packing->width = null;
                        $packing->description = $_L['Roller/Cylinder'] . ' ' . $packing->length . " x " . $packing->diameter;
                    }
                    $packing->save();

                    $packing_id = $packing->id;
                }
                $d->sys_items_packing_id = $packing_id;
            }


            $d->e = '';
            if (!is_numeric($gross_weight)) {
                $gross_weight = '0.00';
            }
            
            // Verifico se o module_med_schedulling está instalado e se precisa vincular o produto à tabela TUSS
            if(_post('expense_item') > 0)
            {
                $d->tiss_expense = 'Y';
                $d->linked_tiss=  'Y';
                $d->tiss_procedures_id = _post('expense_item');
                $d->is_service = 0;
                $d->type = 'Product';
            }
            else
            {
                $d->tiss_expense = null;
                $d->linked_tiss=  null;
                $d->tiss_procedures_id = null;
            }
            
            // Salvo o produto
            $d->save();
            
            //se for produto adiciona o estoqyye 
            if ($type == 'Product') {
                //salva o estoque para o produto
                $stock = ORM::for_table('sys_items_stock')->create();
                $stock->sys_items_id = $d->id;
                $stock->current_stock = Finance::amount_fix(_post("current_stock"));
                $stock->minumum_stock = Finance::amount_fix(_post("minumum_stock"));
                $stock->maximum_stock = Finance::amount_fix(_post("maximum_stock"));
                $stock->control_stock = _post("control_stock");
                $stock->save();
                
                // cadastro no Módulo de Estoque
                $stock = ORM::for_table('sys_stock')
                        ->create();
                $stock->sys_items_id = $d->id;
                $stock->type = 'entry';
                $stock->date = date("Y-m-d");
                $stock->time = date("H:i:s");
                $stock->quantity = Finance::amount_fix(_post("current_stock"));
                $stock->unit_price = isset($_POST['cost_price']) ? $_POST['cost_price'] : '';
                $stock->observation = $_L['New Product'];
                $stock->dt_cadastro = date("Y-m-d H:i:s");
                $stock->save();
                
                //registras que as imagens do usuário pertencem ao produto
                $images = _post("images");
                if (!empty($images)) {
                    $img = explode(',', $images);
                    for ($i = 0; $i < count($img); $i++) {
                        $product_images = ORM::for_table('sys_items_images')->find_one($img[$i]);
                        $product_images->user_id = null;
                        $product_images->sys_items_id = $d->id;
                        $product_images->save();
                    }
                }
                //recebe as tags para adicionar
                $tags = isset($_POST['tags']) ? $_POST['tags'] : '';
                if (!empty($tags)) {
                    for ($i = 0; $i < count($tags); $i++) {
                        $product_tags = ORM::for_table('sys_items_having_tags')->create();
                        $product_tags->sys_items_id = $d->id;
                        $product_tags->sys_items_tags_id = $tags[$i];
                        $product_tags->save();
                    }
                }

                //recebe as tags para adicionar
                $descriptionStep = isset($_POST['description_step']) ? $_POST['description_step'] : '';
                if (!empty($descriptionStep)) {
                    for ($i = 0; $i < count($descriptionStep); $i++) {
                        $product_tags = ORM::for_table('sys_items_step')->create();
                        $product_tags->sys_items_id = $d->id;
                        $product_tags->description = $descriptionStep[$i];
                        $product_tags->save();
                    }
                }

                //recebe as tags para adicionar
                $itemId = isset($_POST['item_id']) ? $_POST['item_id'] : '';
                if (!empty($itemId)) {
                    $qty = isset($_POST['qty']) ? $_POST['qty'] : 1;
                    for ($i = 0; $i < count($itemId); $i++) {
                        $product_tags = ORM::for_table('sys_items_structure')->create();
                        $product_tags->sys_items_id = $d->id;
                        $product_tags->production_sys_item_id = $itemId[$i];
                        $product_tags->qty = Finance::amount_fix($qty[$i]);
                        $product_tags->save();
                    }
                }

                //recebe e adicona os custos
                $cost_price = isset($_POST['cost_price']) ? $_POST['cost_price'] : '';
                $cost_date = isset($_POST['cost_date']) ? $_POST['cost_date'] : '';
                $current_balance = isset($_POST['cost_current_balance']) ? $_POST['cost_current_balance'] : '';
                $previus_balance = isset($_POST['cost_previus_balance']) ? $_POST['cost_previus_balance'] : '';
                $recoverable_taxes = isset($_POST['cost_recoverable_taxes']) ? $_POST['cost_recoverable_taxes'] : '';
                $cost_average = isset($_POST['cost_average']) ? $_POST['cost_average'] : '';
                $cost_sales_price = isset($_POST['cost_sales_price']) ? $_POST['cost_sales_price'] : '';



                if (!empty($cost_price) && !empty($cost_date)) {
                    for ($i = 0; $i < count($cost_price); $i++) {
                        $product_costs = ORM::for_table('sys_items_costs')->create();
                        $product_costs->sys_items_id = $d->id;
                        $product_costs->cost_price = Finance::amount_fix($cost_price[$i]);
                        $product_costs->cost_date = $cost_date[$i];
                        $product_costs->current_balance = Finance::amount_fix($current_balance[$i]);
                        $product_costs->previus_balance = Finance::amount_fix($previus_balance[$i]);
                        $product_costs->recoverable_taxes = Finance::amount_fix($recoverable_taxes[$i]);
                        $product_costs->cost_average = Finance::amount_fix($cost_average[$i]);
                        $product_costs->sale_price = Finance::amount_fix($cost_sales_price[$i]);
                        $product_costs->save();
                    }
                }


                //tratar os preços diferenciados
                $product_row = isset($_POST['product_row']) ? $_POST['product_row'] : '';
                $product_prices = isset($_POST['product_prices']) ? $_POST['product_prices'] : '';
                $product_quantity = isset($_POST['product_quantity']) ? $_POST['product_quantity'] : '';
                $product_type_delivery = isset($_POST['product_type_delivery']) ? $_POST['product_type_delivery'] : 'All';
                $product_margin_discount = isset($_POST['product_margin_discount']) ? $_POST['product_margin_discount'] : 0;
                $apply_children_segments = isset($_POST['apply_children_segments']) ? $_POST['apply_children_segments'] : '';
                if (!empty($product_prices)) {
                    for ($i = 0; $i < count($product_prices); $i++) {
                        if (!empty($product_prices[$i])) {
                            $sys_items_price = ORM::for_table('sys_items_price')->create();
                            $sys_items_price->sys_items_id = $d->id;
                            $sys_items_price->sales_price = Finance::amount_fix($product_prices[$i]);
                            $sys_items_price->quantity = Finance::amount_fix($product_quantity[$i]);
                            $sys_items_price->type_delivery = $product_type_delivery[$i];
                            $sys_items_price->margin_discount = Finance::amount_fix($product_margin_discount[$i]);
                            $sys_items_price->apply_children_segments = isset($apply_children_segments[$i]) ? '1' : '0';
                            $sys_items_price->save();
                            $clients = isset($_POST[("product_clients_" . $product_row[$i])]) ? $_POST[("product_clients_" . $product_row[$i])] : 0;
                            for ($j = 0; $j < count($clients); $j++) {
                                if ($clients[$j] != "") {
                                    $sys_items_price_especification = ORM::for_table('sys_items_price_especification')->create();
                                    $sys_items_price_especification->sys_items_price_id = $sys_items_price->id;
                                    $sys_items_price_especification->crm_account_id = $clients[$j];
                                    $sys_items_price_especification->save();
                                }
                            }
                            $segments = isset($_POST["product_segment_" . $product_row[$i]]) ? $_POST["product_segment_" . $product_row[$i]] : 0;
                            for ($j = 0; $j < count($segments); $j++) {
                                if ($segments[$j] != "") {
                                    $sys_items_price_especification = ORM::for_table('sys_items_price_especification')->create();
                                    $sys_items_price_especification->sys_items_price_id = $sys_items_price->id;
                                    $sys_items_price_especification->crm_segments_id = $segments[$j];
                                    $sys_items_price_especification->save();
                                }
                            }
                        }
                    }
                }

                _msglog('s', $_L['Product Added Successfully']);
            } else {
                _msglog('s', $_L['Service Added Successfully']);
            }
            echo $d->id();
        } else {
            echo $msg;
        }
        break;


    case 'view':
//        $id  = $routes['2'];
//        $d = ORM::for_table('sys_items')->find_one($id);
//        if($d){
//
//            //find all activity for this user
//            $ac = ORM::for_table('sys_activity')->where('cid',$id)->limit(20)->order_by_desc('id')->find_many();
//            $ui->assign('ac',$ac);
//            $ui->assign('countries',Countries::all($d['country']));
//
//            $ui->assign('xheader', '
//<link rel="stylesheet" type="text/css" href="' . $_theme . '/lib/select2/select2.css"/>
//
//');
//            $ui->assign('xfooter', '
//<script type="text/javascript" src="' . $_theme . '/lib/select2/select2.min.js"></script>
//<script type="text/javascript" src="' . $_theme . '/lib/profile.js"></script>
//
//');
//
//            $ui->assign('xjq', '
// $("#country").select2();
//
// ');
//            $ui->assign('d',$d);
//            $ui->display('ps-view.tpl');
//
//        }
//        else{
//         //   r2(U . 'customers/list', 'e', $_L['Account_Not_Found']);
//
//        }

        break;




    case 'p-list':
        $paginator = Paginator::bootstrap('sys_items', 'type', 'Product');
        $d = ORM::for_table('sys_items')->where('type', 'Product')->offset($paginator['startpoint'])->limit($paginator['limit'])->order_by_desc('id')->find_many();
        $ui->assign('d', $d);
        $ui->assign('type', 'Product');
        $ui->assign('paginator', $paginator);
        $ui->assign('xheader', '
<link rel="stylesheet" type="text/css" href="' . $_theme . '/css/modal.css"/>

');
        $ui->assign('xfooter', '
        <script type="text/javascript" src="' . $_theme . '/lib/modal.js"></script>
<script type="text/javascript" src="' . $_theme . '/lib/ps-list.js"></script>

');
        $ui->display('ps-list.tpl');
        break;

    case 's-list':

        $paginator = Paginator::bootstrap('sys_items', 'type', 'Service');
        $d = ORM::for_table('sys_items')
            ->where('type', 'Service')
            ->where_null('tiss_procedures_id')
            ->offset($paginator['startpoint'])
            ->limit($paginator['limit'])
            ->order_by_desc('id')
            ->find_many();
        $ui->assign('d', $d);
        $ui->assign('type', 'Service');
        $ui->assign('paginator', $paginator);
        $ui->assign('xheader', '
<link rel="stylesheet" type="text/css" href="' . $_theme . '/css/modal.css"/>

');
        $ui->assign('xfooter', '
                <script type="text/javascript" src="' . $_theme . '/lib/modal.js"></script>
<script type="text/javascript" src="' . $_theme . '/lib/ps-list.js"></script>
');
        $ui->display('ps-list.tpl');
        break;


    case 'edit-post':
        $msg = '';
        
        $name = _post('name');
        $description = _post('description');
        if($name == null)
        {
            $name = $description;
        }
        
        $id = _post('id');
        $notes = _post('product_notes');
        $sales_price = Finance::amount_fix(_post('sales_price'));
        $item_number = _post('item_number');
        
        // Leonardo Lopes - 14/06/2017
        $cod_nf = mb_strtoupper(_post('cod_nf'));
        
        $mercosur_nomenclature = preg_replace('/\D/', '', _post('mercosur_nomenclature'));
        $unit = _post('unit');
        $category = _post('category');
        $type = _post('type');
        $gross_weight = Finance::amount_fix(_post('gross_weight'));
        $net_weight = Finance::amount_fix(_post('net_weight'));
        $location = _post('location');
        $barcode_marketing = _post('barcode_marketing');
        $barcode = _post('barcode');
        $origin = _post('origin');
        $margin_discount = _post('margin_discount');

        //trata os campos obrigatórios
        $msg = '';

        if ($type == 'Product') {
            if ($description == '') {
                $msg .= $_L['Description'] . $_L['is required'];
            }
        } else {
            if ($name == '') {
                $msg .= $_L['Name'] . $_L['is required'];
            }
        }
        if (!is_numeric($sales_price)) {
            $sales_price = '0.00';
        }
        if ($mercosur_nomenclature == '') {
            $msg .= $_L['Common nomenclature of Mercosur'] . $_L['is required'];
        }
        if ($unit == '') {
            $msg .= $_L['Unit'] . $_L['is required'];
        }


        if ($msg == '') {
            $d = ORM::for_table('sys_items')->find_one($id);
            if ($d) {
                $d->name = $name;
                $d->notes = $notes;
                $d->type_of_product = _post('type_of_product');
                $d->production = _post('production');
                $d->complementary_description = _post('complementary_description');
                $d->sales_price = $sales_price;
                $d->margin_discount = $margin_discount;
                $d->item_number = $item_number;
                
                // Leonardo Lopes - 14/06/2017
                $d->cod_nf = $cod_nf;
                
                $d->description = $description;
                $d->mercosur_nomenclature = $mercosur_nomenclature;
                $d->type = $type;
                $d->gross_weight = $gross_weight;
                $d->net_weight = $net_weight;
                if (!empty($location)) {
                    $d->sys_items_location_id = $location;
                }
                $d->barcode_marketing = $barcode_marketing;
                $d->barcode = $barcode;

                echo $origin;
                if ($origin != '') {
                    $d->sys_items_scr_id = $origin;
                }
                if (!empty($unit)) {
                    $d->unit_id = $unit;
                }

                if (!empty($category)) {
                    $d->category_id = $category;
                } else {
                    $d->category_id = null;
                }
                $d->item_per_package = _post('item_per_package');
                $d->ipi_framework = _post("ipi_framework");
                $d->ipi_fixed_amount = Finance::amount_fix(_post("ipi_fixed_amount"));
                $d->ipi_code = _post("ipi_code");
                $d->cest_code = _post("cest_code");
                $d->status = _post('status');
                //  $d->cost_price = Finance::amount_fix(_post('cost_price'));
                if (!empty(_post('manufacturer'))) {
                    $d->sys_items_manufacturer_id = _post("manufacturer");
                }
                //SALVA A EMBALAGEM
                $packing_type = _post("packing_type");
                if ($packing_type != '') {
                    $packing_id = _post("packing");
                    if ($packing_id == 0) {
                        $packing = ORM::for_table('sys_items_packing')->create();
                        $packing->type = $packing_type;
                        //adicona os valors possíves das medidas de cada tipo de embalagem
                        if ($packing_type == 'envelope') {
                            $packing->width = Finance::amount_fix(_post('pack_width'));
                            $packing->length = Finance::amount_fix(_post('pack_length'));
                            $packing->height = null;
                            $packing->diameter = null;
                            $packing->description = $_L['Envelope'] . ' ' . $packing->width . " x " . $packing->length;
                        } else if ($packing_type == 'package_box') {
                            $packing->width = Finance::amount_fix(_post('pack_width'));
                            $packing->length = Finance::amount_fix(_post('pack_length'));
                            $packing->height = Finance::amount_fix(_post('pack_height'));
                            $packing->diameter = null;
                            $packing->description = $_L['Package/Box'] . ' ' . $packing->width . " x " . $packing->length . " x " . $packing->height;
                        } else if ($packing_type == 'roller_cylinder') {
                            $packing->length = Finance::amount_fix(_post('pack_length'));
                            $packing->diameter = Finance::amount_fix(_post('pack_diameter'));
                            $packing->height = null;
                            $packing->weidth = null;
                            $packing->description = $_L['Roller/Cylinder'] . ' ' . $packing->length . " x " . $packing->diameter;
                        }
                        $packing->save();
                        $packing_id = $packing->id;
                    }
                    $d->sys_items_packing_id = $packing_id;
                }

                $d->e = '';
                
                if (!is_numeric($gross_weight)) {
                $gross_weight = '0.00';
            }
            
                // Verifico se o module_med_schedulling está instalado e se precisa vincular o produto à tabela TUSS
                if(_post('expense_item') > 0)
                {
                    $d->tiss_expense = 'Y';
                    $d->linked_tiss=  'Y';
                    $d->tiss_procedures_id = _post('expense_item');
                    $d->is_service = 0;
                    $d->type = 'Product';
                }
                else
                {
                    $d->tiss_expense = null;
                    $d->linked_tiss=  null;
                    $d->tiss_procedures_id = null;
                }

                $d->save();
                if ($type == 'Product') {

                    $stocks = ORM::for_table('sys_items_stock')->where('sys_items_id', $d->id)->find_many();
                    if (count($stocks) > 0) {
                        $stock = $stocks[0];
                    } else {
                        $stock = ORM::for_table('sys_items_stock')->create();
                    }
                    $stock->sys_items_id = $d->id;
//                    $stock->current_stock = Finance::amount_fix(_post("current_stock"));
                    $stock->minumum_stock = Finance::amount_fix(_post("minumum_stock"));
                    $stock->maximum_stock = Finance::amount_fix(_post("maximum_stock"));
                    $stock->control_stock = _post("control_stock");
                    $stock->save();


                    //registras que as imagens do usuário pertencem ao produto
                    $images = _post("images");
                    if (!empty($images)) {
                        $img = explode(',', $images);

                        for ($i = 0; $i < count($img); $i++) {
                            $product_images = ORM::for_table('sys_items_images')->find_one($img[$i]);
                            $product_images->user_id = null;
                            $product_images->sys_items_id = $d->id;
                            $product_images->save();
                        }
                    }

                    //recebe as tags para adicionar
                    $tags = isset($_POST['tags']) ? $_POST['tags'] : '';
                    //remove todas as tags

                    $x = ORM::for_table('sys_items_having_tags')->where('sys_items_id', $d->id)->delete_many();
                    if (!empty($tags)) {
                        for ($i = 0; $i < count($tags); $i++) {
                            $product_tags = ORM::for_table('sys_items_having_tags')->create();
                            $product_tags->sys_items_id = $d->id;
                            $product_tags->sys_items_tags_id = $tags[$i];
                            $product_tags->save();
                        }
                    }
                    //recebe as tags para adicionar
                    $descriptionStep = isset($_POST['description_step']) ? $_POST['description_step'] : '';
                    ORM::for_table('sys_items_step')->where('sys_items_id', $d->id)->delete_many();
                    if ($d->type_of_product == 'Finished product' || $d->type_of_product == 'Component') {
                        if (!empty($descriptionStep)) {
                            for ($i = 0; $i < count($descriptionStep); $i++) {
                                $product_tags = ORM::for_table('sys_items_step')->create();
                                $product_tags->sys_items_id = $d->id;
                                $product_tags->description = $descriptionStep[$i];
                                $product_tags->save();
                            }
                        }
                    }
                    //recebe as tags para adicionar
                    $itemId = isset($_POST['item_id']) ? $_POST['item_id'] : '';
                    ORM::for_table('sys_items_structure')->where('sys_items_id', $d->id)->delete_many();
                    if ($d->type_of_product == 'Finished product' || $d->type_of_product == 'Component') {
                        if (!empty($itemId)) {
                            $qty = isset($_POST['qty']) ? $_POST['qty'] : 1;
                            for ($i = 0; $i < count($itemId); $i++) {
                                $product_tags = ORM::for_table('sys_items_structure')->create();
                                $product_tags->sys_items_id = $d->id;
                                $product_tags->production_sys_item_id = $itemId[$i];
                                $product_tags->qty = Finance::amount_fix($qty[$i]);
                                $product_tags->save();
                            }
                        }
                    }


                    //recebe e adicona os custos
                    $cost_price = isset($_POST['cost_price']) ? $_POST['cost_price'] : '';
                    $cost_date = isset($_POST['cost_date']) ? $_POST['cost_date'] : '';
                    $current_balance = isset($_POST['cost_current_balance']) ? $_POST['cost_current_balance'] : '';
                    $previus_balance = isset($_POST['cost_previus_balance']) ? $_POST['cost_previus_balance'] : '';
                    $recoverable_taxes = isset($_POST['cost_recoverable_taxes']) ? $_POST['cost_recoverable_taxes'] : '';
                    $cost_average = isset($_POST['cost_average']) ? $_POST['cost_average'] : '';
                    $cost_sales_price = isset($_POST['cost_sales_price']) ? $_POST['cost_sales_price'] : '';

                    ORM::for_table('sys_items_costs')->where('sys_items_id', $d->id)->delete_many();


                    if (!empty($cost_price) && !empty($cost_date)) {
                        for ($i = 0; $i < count($cost_price); $i++) {
                            $product_costs = ORM::for_table('sys_items_costs')->create();
                            $product_costs->sys_items_id = $d->id;
                            $product_costs->cost_price = Finance::amount_fix($cost_price[$i]);
                            $product_costs->cost_date = $cost_date[$i];
                            $product_costs->current_balance = Finance::amount_fix($current_balance[$i]);
                            $product_costs->previus_balance = Finance::amount_fix($previus_balance[$i]);
                            $product_costs->recoverable_taxes = Finance::amount_fix($recoverable_taxes[$i]);
                            $product_costs->cost_average = Finance::amount_fix($cost_average[$i]);
                            $product_costs->sale_price = Finance::amount_fix($cost_sales_price[$i]);
                            $product_costs->save();
                        }
                    }


                    //tratar os preços diferenciados
                    //remove todos os registros, antes de incluir os novos                   
                    $sys_items_price_LIST = ORM::for_table('sys_items_price')->where('sys_items_id', $d->id)->find_many();
                    foreach ($sys_items_price_LIST as $p_price) {
                        ORM::for_table('sys_items_price_especification')->where('sys_items_price_id', $p_price->id)->delete_many();
                    }
                    ORM::for_table('sys_items_price')->where('sys_items_id', $d->id)->delete_many();

                    $product_row = isset($_POST['product_row']) ? $_POST['product_row'] : '';
                    $product_prices = isset($_POST['product_prices']) ? $_POST['product_prices'] : '';
                    $product_quantity = isset($_POST['product_quantity']) ? $_POST['product_quantity'] : '';
                    $product_type_delivery = isset($_POST['product_type_delivery']) ? $_POST['product_type_delivery'] : 'All';
                    $product_margin_discount = isset($_POST['product_margin_discount']) ? $_POST['product_margin_discount'] : 0;
                    $apply_children_segments = isset($_POST['apply_children_segments']) ? $_POST['apply_children_segments'] : '';
//                    var_dump($_POST['apply_children_segments']);exit;
                    if (!empty($product_prices)) {
                        for ($i = 0; $i < count($product_prices); $i++) {
                            if (!empty($product_prices[$i])) {
                                $sys_items_price = ORM::for_table('sys_items_price')->create();
                                $sys_items_price->sys_items_id = $d->id;
                                $sys_items_price->sales_price = Finance::amount_fix($product_prices[$i]);
                                $sys_items_price->quantity = Finance::amount_fix($product_quantity[$i]);
                                $sys_items_price->type_delivery = $product_type_delivery[$i];
                                $sys_items_price->margin_discount = Finance::amount_fix($product_margin_discount[$i]);
                                $sys_items_price->apply_children_segments = isset($apply_children_segments[$i]) ? '1' : '0';
                                $sys_items_price->save();
                                $clients = isset($_POST[("product_clients_" . $product_row[$i])]) ? $_POST[("product_clients_" . $product_row[$i])] : 0;
                                for ($j = 0; $j < count($clients); $j++) {
                                    if ($clients[$j] != "") {
                                        $sys_items_price_especification = ORM::for_table('sys_items_price_especification')->create();
                                        $sys_items_price_especification->sys_items_price_id = $sys_items_price->id;
                                        $sys_items_price_especification->crm_account_id = $clients[$j];
                                        $sys_items_price_especification->save();
                                    }
                                }
                                $segments = isset($_POST["product_segment_" . $product_row[$i]]) ? $_POST["product_segment_" . $product_row[$i]] : 0;
                                for ($j = 0; $j < count($segments); $j++) {
                                    if ($segments[$j] != "") {
                                        $sys_items_price_especification = ORM::for_table('sys_items_price_especification')->create();
                                        $sys_items_price_especification->sys_items_price_id = $sys_items_price->id;
                                        $sys_items_price_especification->crm_segments_id = $segments[$j];
                                        $sys_items_price_especification->save();
                                    }
                                }
                            }
                        }
                    }




                    _msglog('s', $_L['Edited Product Successfully']);
                } else {
                    _msglog('s', $_L['Edited Service Successfully']);
                }
                echo $d->id();
            } else {
                echo 'Not Found';
            }
        } else {
            echo $msg;
        }


        break;
    case 'delete':
        $id = $routes['2'];
        if ($_app_stage == 'Demo') {
            r2(U . 'accounts/list', 'e', 'Sorry! Deleting Account is disabled in the demo mode.');
        }
        $d = ORM::for_table('sys_accounts')->find_one($id);
        if ($d) {
            $d->delete();
            r2(U . 'accounts/list', 's', $_L['account_delete_successful']);
        }

        break;

    case 'edit-form':




        $id = $routes['2'];
        $d = ORM::for_table('sys_items')->find_one($id);
        if ($d) {
            $price = number_format(($d['sales_price']), 2, $config['dec_point'], $config['thousands_sep']);

            $unit = ORM::for_table('sys_items_unit')->order_by_asc('sorder')->find_many();
            $options_unit = '';
            foreach ($unit as $s) {
                $options_unit.='<option value="' . $s->id . '"' . ($s->id == $d['unit_id'] ? 'selected' : '') . ' >' . ((isset($_L[$s->name])) ? $_L[$s->name] : $s->name) . '</option>';
            }

            echo '
<div class="modal-header">
	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
	<h3>' . $_L['Edit'] . '</h3>
</div>
<div class="modal-body">

<form class="form-horizontal" role="form" id="edit_form" method="post">
  <div class="form-group">
    <label for="name" class="col-sm-2 control-label">' . $_L['Name'] . $_L['*'] . '</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" value="' . $d['name'] . '" name="name" id="name">
    </div>
  </div>
  <div class="form-group">
    <label for="rate" class="col-sm-2 control-label">' . $_L['Item Number'] . '</label>
    <div class="col-sm-2">
      <input type="text" class="form-control" name="item_number" value="' . $d['item_number'] . '" id="item_number">
      <input type="hidden" name="id" value="' . $d['id'] . '">
    <input type="hidden" name="type" value="Service">
    </div>
  </div>
  <div class="form-group">
    <label for="rate" class="col-sm-2 control-label">' . $_L['Price'] . $_L['*'] . '</label>
    <div class="col-sm-2">
      <input type="text" class="form-control amount" name="sales_price" value="' . $price . '" id="sales_price" data-a-sign="' . $_c['currency_code'] . '"  data-a-dec="' . $_c['dec_point'] . '" data-a-sep="' . $_c['thousands_sep'] . '" data-d-group="2">
      <input type="hidden" name="id" value="' . $d['id'] . '">
    </div>
  </div>
    <div class="form-group">
    <label for="name" class="col-sm-2 control-label">' . $_L['Description'] . '</label>
    <div class="col-sm-10">
      <textarea id="description" name="description" class="form-control" rows="3">' . $d['description'] . '</textarea>
    </div>
  </div>
  <div class="form-group">
                            <label class="col-lg-2 control-label"> ' . $_L['Common nomenclature of Mercosur'] . $_L['*'] . '</label>                         
                            <div class="col-lg-3">
                                <input type="text" value="' . $d['mercosur_nomenclature'] . '"  id="mercosur_nomenclature"  name="mercosur_nomenclature" class="form-control ncm" autocomplete="off">
                            </div>
                        </div>
                       
               
                       <div class="form-group"> 
                            <label class="col-lg-2 control-label">' . $_L['Unit'] . $_L['*'] . '</label>
                            <div class="col-lg-4">
                                <select name="unit" id="unit" class="form-control select2">
                                 ' . $options_unit . '</select>
                            </div>
                        </div>
</form>

</div>
<div class="modal-footer">

	<button type="button" data-dismiss="modal" class="btn">' . $_L['Close'] . '</button>
	<button id="update" class="btn btn-primary">' . $_L['Update'] . '</button>
</div>';
        } else {
            echo 'not found';
        }



        break;




    case 'json_get':

        header('Content-Type: application/json');

        $pid = route(2);

        $d = ORM::for_table('sys_items')->find_one($pid);

        if ($d) {

            $i = array();
            $i['sales_price'] = $d->sales_price;

            echo json_encode($i);
        }


        break;



















    case 'taxation':
        $id = $routes['2'];
        $servicoProduto = ORM::for_table('sys_items')->find_one($id);
        if ($servicoProduto) {
            $ui->assign('prod_serv', $servicoProduto);
            $ui->assign('type', $servicoProduto->type);
            $tributacao = ORM::for_table('sys_items_taxation')
                            ->table_alias('t')
                            ->select('t.*')
                            ->select('e.uf_state', 'uf')
                            ->select('c.desc_cfop', 'desc_cfop')
                            ->select('c.code_cfop', 'code_cfop')
                            ->left_outer_join('state', array('e.id', '=', 't.id_uf_state_destiny'), 'e')
                            ->left_outer_join('cfop', array('c.id', '=', 't.id_cfop'), 'c')
                            ->where('t.id_sys_items', $id)->order_by_asc('t.id')->find_many();
            $ui->assign('tributacao', $tributacao);

            $states = ORM::for_table('state')->order_by_asc('uf_state')->find_many();
            $ui->assign('states', $states);

            $cfop = ORM::for_table('cfop')->order_by_asc('id')->find_many();
            $ui->assign('cfop', $cfop);

            //busca os dados da empresa do usuário
            $listaConfigApp = ORM::for_table('app_fiscal_config')->find_many();
            foreach ($listaConfigApp as $da) {
                $dadosEmpresa[$da['key']] = $da['value'];
            }
            $estadoEmpresa = ORM::for_table('state')->find_one($dadosEmpresa['company_state_id']);
            $ui->assign('dadosEmpresa', $dadosEmpresa);
            $ui->assign('estadoEmpresa', $estadoEmpresa);

            $ui->assign('xheader', Asset::css(array('s2/css/select2.min', 'modal', 'dp/dist/datepicker.min', 'redactor/redactor')));

            $ui->assign('xfooter', Asset::js(array('s2/js/select2.min', 's2/js/i18n/' . lan(), 'numeric', 'taxation')));
            $ui->assign('xjq', '');

            $ui->display('manage_taxation.tpl');
        } else {
            r2(U . 'ps/list/', 'e', $_L['Erro Find Taxation']);
        }
        break;



    case 'taxation-add-post':
        $id = _post('id');
        $condition = _post('comparation_condition_state');
        $state = _post('state');
        $operation = _post('operation');
        $cst_pis_cofins = _post('cst_pis_cofins');
        $cfop = _post('cfop');
        $msg = '';
        if ($state == '') {
            $msg .= $_L['State Region'] . $_L['is required'];
        }

        if (is_numeric($cst_pis_cofins) == false) {
            $msg .= $_L['CST PIS/COFINS'] . $_L['is required'];
        }
        if (is_numeric($cfop) == false) {
            $msg .=$_L['Code Cfop'] . $_L['is required'];
        }
        $busca = ORM::for_table('sys_items_taxation')
                ->where('id_sys_items', $id)
                ->where('id_uf_state_destiny', $state)
                ->where('operation', $operation)
                ->where('comparation_condition_state', $condition)
                ->find_one();
        if ($busca) {
            $msg .= $_L['Existing Taxation Data'] . '<br>';
        }
        if ($msg == '') {
            $d = ORM::for_table('sys_items_taxation')->create();
            $d->id_sys_items = $id;
            $d->id_uf_state_destiny = $state;
            $d->operation = $operation;
            $d->comparation_condition_state = $condition;
            $d->cst_pis_cofins = $cst_pis_cofins;
            $d->id_cfop = $cfop;
            $d->save();
            $tid = $d->id();
            _log($_L['New Taxation'] . ' Cfop' . $cfop . ' | ID: ' . $tid . ']', 'Admin', $user['id']);
            _msglog('s', $_L['Taxation Added Successfully']);
            //  r2(U . 'tributacao/gerenciar/'.$id, 's', $_L['Tributacao Adicionada Sucesso'] );

            echo $tid;
        } else {
            echo $msg;
        }
        break;

    case 'taxation-delete-post':
        $id = _post('id');
        $d = ORM::for_table('sys_items_taxation')->find_one($id);
        if ($d) {
            $d->delete();
            r2(U . 'ps/taxation/' . $d->id_sys_items, 's', $_L['Taxation Deleted Successfully']);
        } else {
            r2(U . 'ps/list/', 'e', $_L['Taxation Error Delete']);
        }
        break;

    case 'modal_ipi_framework':
        $ui->display('modal_sys_items_ipi_framework.tpl');
        break;

    case 'ajax-product-structure':
        if ($routes['2'] == '') {
            echo "";
        } else {
            $d = ORM::for_table('sys_items')
                            ->table_alias('i')
                            ->select('i.*')
                            ->select('is.qty', "production_qty")
                            ->select_expr("(select int_value from sys_items_unit u where u.id=i.unit_id )", 'u_unit')
                            ->select_expr("(select initials from sys_items_unit u where u.id=i.unit_id )", 'u_initials')
                            ->left_outer_join('sys_items_structure', array('is.production_sys_item_id', '=', 'i.id'), 'is')
                            ->where("is.sys_items_id", intval($routes['2']))
                            ->order_by_asc('i.description')->find_many();
            $data = array();
            foreach ($d as $c) {
                $data[] = array(
                    'id' => $c->id,
                    'description' => $c->description,
                    'price' => $c->sales_price,
                    'item_unit' => $c->u_unit,
                    'item_sifr' => $c->u_initials,
                    'production_qty' => $c->production_qty,
                );
            }
            echo json_encode($data);
        }
        break;

    case 'ajax-list':
        if (isset($routes['2']))
        {
            $product_id = $routes['2'];
            $d = ORM::for_table('sys_items')
                        ->table_alias('i')
                        ->select('i.*')
                        ->where('id', $product_id)
                        ->select_expr("(select int_value from sys_items_unit u where u.id=i.unit_id )", 'u_unit')
                        ->select_expr("(select st.current_stock from sys_items_stock st where st.sys_items_id=i.id )", 'current_stock')
                        ->select_expr("(select initials from sys_items_unit u where u.id=i.unit_id )", 'u_initials')
                        ->order_by_asc('i.description')->find_many();
        }
        else
        {
            $d = ORM::for_table('sys_items')
                        ->table_alias('i')
                        ->select('i.*')
                        ->select_expr("(select int_value from sys_items_unit u where u.id=i.unit_id )", 'u_unit')
                        ->select_expr("(select st.current_stock from sys_items_stock st where st.sys_items_id=i.id )", 'current_stock')
                        ->select_expr("(select initials from sys_items_unit u where u.id=i.unit_id )", 'u_initials')
                        ->order_by_asc('i.description')->find_many();
        }
        
        $data = array();
        foreach ($d as $item) {
            $product_images = ORM::for_table('sys_items_images')->where('sys_items_id', $item['id'])->find_many();
            if (count($product_images) > 0) {
                $image = APP_URL . '/application/storage/product/img/' . $product_images[0]->src;
            } else {
                $image = APP_URL . '/ui/theme/lrsys/img/sem-imagem.jpg';
            }
            $price = number_format($item['sales_price'], 2, $config['dec_point'], $config['thousands_sep']);
            
            // pego os preços customizados para este produto
            $custom_prices = ORM::for_table('sys_items_price')->where('sys_items_id', $item['id'])->order_by_desc('sales_price')->find_array();
            $count_price = 0;
            foreach ($custom_prices as $custom_price)
            {
                $segment_ids = array();
                $account_ids = array();
                $price_especification = ORM::for_table('sys_items_price_especification')
                        ->where('sys_items_price_id', $custom_price['id'])->find_array();
                
                foreach ($price_especification as $especification)
                {
                    // pago os clientes que tem permissão para este preço
                    if($especification['crm_account_id'])
                    {
                        $account_ids[] = $especification['crm_account_id'];
                    }
                    
                    // pago os SEGMENTOS que tem permissão para este preço
                    if($especification['crm_segments_id'])
                    {
                        $segment_id = $especification['crm_segments_id'];
                        $segment_ids[] = $segment_id;
                        
                        
                        if($custom_price['apply_children_segments'] == 1)
                        {
                            $deep = false;
                            $array_segments = getChildren($segment_id, $deep);
                        
                            foreach ($array_segments as $segment)
                            {
                                $segment_ids[] = $segment;
                            }
                        }
                        
                    }
                }
                $segment_ids = array_unique($segment_ids);
                $custom_prices[$count_price]['account_ids'] = $account_ids;
                $custom_prices[$count_price]['segment_ids'] = $segment_ids;
                $count_price++;
            }
                
            $data[] = array(
                'id' => $item->id,
                'mercosur_nomenclature' => $item->mercosur_nomenclature==null?'':str_pad($item->mercosur_nomenclature, 8, "0", STR_PAD_LEFT),
                'description' => $item->description,
                'text'=> $item->id." - ".$item->description,
                'price' => $price,
                'item_unit' => $item->u_unit,
                'item_sifr' => $item->u_initials,
                'current_stock' => $item->current_stock,
                'gross_weight' => $item->gross_weight,
                'net_weight' => $item->net_weight,
                'image' => $image,
                'custom_prices' => $custom_prices,
                'margin_discount' => $item['margin_discount']
            );
        }
        echo json_encode($data);
    break;


    default:
        echo 'action not defined';
}


// Pego os filhos de um determinado Segmento
function getChildren($id, $deep = false) 
{
    $segments_array = array();
    
    // pego os filhos do segmento
    $segment_children = ORM::for_table('crm_segments')
                        ->where('id_parent', $id)->find_array();
    
    if(count($segment_children) >= 0)
    {
        foreach ($segment_children as $children)
        {
            $array_aux = getChildren($children['id']);
            $array_aux[] = $children['id'];
            $segments_array = $array_aux;
        }
        
    }
    return $segments_array;
}

Anon7 - 2022
AnonSec Team