AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.217.114
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/erp/application/plugins/module_fish/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/www/lrsys_apps/erp/application/plugins/module_fish/controllers/SettlementController.php
<?php

include_once "Controller.php";
include_once __DIR__ . "/../models/SettlementModel.php";
include_once __DIR__ . "/../models/FoodProgramsModel.php";
include_once __DIR__ . "/../models/MovementModel.php";

class SettlementController extends Controller {

    /**
     * @var ID Tank
     */
    protected $id;

    /**
     * @var TankModel
     */
    protected $model;
    protected $modelProgram;
    protected $modelMovement;

    /**
     * @var Client ID
     */
    protected $client_id;

    /**
     * @param $ui
     * @param array $_L
     * @param array $config
     * @param $_pd
     */
    public function __construct($ui, $_L, $config, $_pd, $client_id = null) {
        parent::__construct($ui, $_L, $config, $_pd);
        $this->ui->assign('_title', $this->_L['Fish Description module'] . ' - ' . $this->config['CompanyName']);
        $this->model = new SettlementModel();
        $this->modelProgram = new FoodProgramsModel();
        $this->modelMovement = new MovementModel();
        $this->id = $this->routes[3];
        $this->client_id = $client_id;
    }

    /**
     * Show add to type tank
     */
    public function add() {
        // CARREGA CSS E JS'S
        $css_arr = array('s2/css/select2.min', 'dp/dist/datepicker.min',);

        $js_arr = array(
            's2/js/select2.min',
            'dp/dist/datepicker.min',
            'numeric',
            '/../../../application/plugins/module_fish/assets/js/default-settlement',
        );

        $assets_css = Asset::css($css_arr, date('Y-m-d H:i:s'));
        $assets_js = Asset::js($js_arr, date('Y-m-d H:i:s'));
        $this->ui->assign('settlement', json_decode(json_encode(array(
            'title_lote' => '',
            'date_settlement' => '',
            'average_weight' => '',
            'id' => '',
            'crm_accounts_id' => '',
            'specie_id' => ''
        ))));

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

        $this->ui->assign('jsvar', '
            _L[\'Module_Fish Select Associated\'] = \'' . $this->_L['Module_Fish Select Associated'] . '\';
            _L[\'Module_Fish Delete Lote Msg Associated\'] = \'' . $this->_L['Module_Fish Delete Lote Msg Associated'] . '\';                  
            _L[\'Module_Fish Insert the information lote\'] = \'' . $this->_L['Module_Fish Insert the information lote'] . '\';   
            _L[\'Module_Fish Select Tank\'] = \'' . $this->_L['Module_Fish Select Tank'] . '\';  
            _L[\'Module_Fish Select Lote\'] = \'' . $this->_L['Module_Fish Select Lote'] . '\';  
        ');
        $this->ui->assign('title', $this->_L['Module_Fish Add Settlement']);
        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);

        $this->ui->assign('_st', $this->_L['Module_Fish Settlement']);
        $this->ui->assign('_include', 'settlement/add');
        $this->ui->display('wrapper.tpl');
    }

    public function edit() {
        $this->id = $this->routes[3];

        if (empty($this->routes[3]) || !is_numeric($this->routes[3])) {
            die($this->_L['Id_Required']);
        }



        $sql = 'Select l.* ,ld.id as lote_id,lp.id as module_fish_lots_distribution_program_id,lp.module_fish_program_id, ca.account,s.id as specie_id,s.popular_name, s.scientific_name,ld.qty,t.id as id_tank,t.title_tank,p.id as program_id,p.name as name_program,'
                . '(select  b.average_weight from module_fish_lots_distribution_biometry b where b.module_fish_lots_distribution_id=ld.id order by id asc limit 1) as average_weight '
                . ', (select count(sub_mov2.id) from module_fish_movement sub_mov2 where sub_mov2.module_fish_lots_distribution_id=ld.id) as totalMoviment';
        $from = ' from module_fish_lots l '
                . ' LEFT JOIN module_fish_lots_distribution ld ON(ld.module_fish_lots_id=l.id)'
                . ' LEFT JOIN module_fish_lots_distribution_program lp ON(lp.module_fish_lots_distribution_id=ld.id)'
                . ' LEFT JOIN module_fish_tank t ON(ld.module_fish_tank_id=t.id)'
                . ' LEFT JOIN module_fish_food_programs p ON(lp.module_fish_program_id=p.id)'
                . ' LEFT JOIN crm_accounts ca ON(l.crm_accounts_id=ca.id)'
                . ' LEFT JOIN module_fish_species s ON(l.module_fish_species_id=s.id)'
                . " WHERE l.deleted_at IS NULL AND ld.deleted_at IS NULL ";
        $where = " AND ld.module_fish_movement_id IS NULL  AND l.id=" . $this->routes[3];
        $order = " ORDER BY ld.id";
        $allRecords = ORM::for_table('module_fish_lots')->raw_query($sql . $from . $where . $order)->find_many();

        if ($this->client_id > 0) {
            if ($allRecords[0]->crm_accounts_id != $this->client_id) {
                r2(U . ($this->client_id > 0 ? 'client/' : '') . 'module_fish/settlement/listSettlement', 's', $this->_L['Module_Fish Food_Programs_Del_Msg']);
            }
        }

        $this->ui->assign('settlement', $allRecords[0]);
        $this->ui->assign('items', $allRecords);
        // CARREGA CSS E JS'S
        $css_arr = array('s2/css/select2.min', 'dp/dist/datepicker.min',);

        $js_arr = array(
            's2/js/select2.min',
            'dp/dist/datepicker.min',
            'numeric',
            '/../../../application/plugins/module_fish/assets/js/default-settlement',
        );

        $assets_css = Asset::css($css_arr);
        $assets_js = Asset::js($js_arr);

        $this->ui->assign('jsvar', '
            _L[\'Module_Fish Select Associated\'] = \'' . $this->_L['Module_Fish Select Associated'] . '\';
            _L[\'Module_Fish Delete Lote Msg Associated\'] = \'' . $this->_L['Module_Fish Delete Lote Msg Associated'] . '\';                  
            _L[\'Module_Fish Insert the information lote\'] = \'' . $this->_L['Module_Fish Insert the information lote'] . '\';   

        ');
        $this->ui->assign('title', $this->_L['Module_Fish Edit Settlement']);
        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);

        $this->ui->assign('_st', $this->_L['Module_Fish Settlement']);
        $this->ui->assign('_include', 'settlement/add');
        $this->ui->display('wrapper.tpl');
    }

    public function listSettlement() {
        // LISTAR PROGRAMA ALIMENTAR
        $filter = array();
        $filter['items_per_page'] = 10;

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $filter['module_fish_species_id'] = filter_var(_post('module_fish_species_id'), FILTER_SANITIZE_STRING);
            $filter['crm_accounts_id'] = filter_var(_post('crm_accounts_id'), FILTER_SANITIZE_STRING);
            $filter['module_fish_lots_id'] = filter_var(_post('module_fish_lots_id'), FILTER_SANITIZE_STRING);
            $filter['module_fish_tank_id'] = filter_var(_post('module_fish_tank_id'), FILTER_SANITIZE_STRING);
            $filter['period'] = filter_var(_post('period'), FILTER_SANITIZE_STRING);
            $filter['period_ini'] = filter_var(_post('period_ini'), FILTER_SANITIZE_STRING);
            $filter['period_end'] = filter_var(_post('period_end'), FILTER_SANITIZE_STRING);
            $filter['items_per_page'] = filter_var(_post('items_per_page'), FILTER_SANITIZE_STRING);
        } else {
            if ($i = array_search('crm_accounts_id', $this->routes))
                $filter['crm_accounts_id'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_NUMBER_INT);
            if ($i = array_search('module_fish_species_id', $this->routes))
                $filter['module_fish_species_id'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_NUMBER_INT);
            if ($i = array_search('period', $this->routes))
                $filter['period'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_STRING);
            if ($i = array_search('period_ini', $this->routes))
                $filter['period_ini'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_STRING);
            if ($i = array_search('period_end', $this->routes))
                $filter['period_end'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_STRING);
            if ($i = array_search('items_per_page', $this->routes))
                $filter['items_per_page'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_STRING);
            if ($i = array_search('module_fish_lots_id', $this->routes))
                $filter['module_fish_lots_id'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_NUMBER_INT);
            if ($i = array_search('module_fish_tank_id', $this->routes))
                $filter['module_fish_tank_id'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_NUMBER_INT);
        }
        $sql = 'Select l.* ,ld.id as lote_id,lp.module_fish_program_id, ca.account,s.popular_name, s.scientific_name,ld.qty as initial_qty,t.id as id_tank,t.title_tank,p.name as name_program,'
                . '(select  b.average_weight from module_fish_lots_distribution_biometry b where b.module_fish_lots_distribution_id=ld.id order by id asc limit 1) as average_weight ';
        $from = ' from module_fish_lots l '
                . ' JOIN module_fish_lots_distribution ld ON(ld.module_fish_lots_id=l.id)'
                . ' LEFT JOIN module_fish_lots_distribution_program lp ON(lp.module_fish_lots_distribution_id=ld.id)'
                . ' LEFT JOIN module_fish_tank t ON(ld.module_fish_tank_id=t.id)'
                . ' LEFT JOIN module_fish_food_programs p ON(lp.module_fish_program_id=p.id)'
                . ' LEFT JOIN crm_accounts ca ON(l.crm_accounts_id=ca.id)'
                . ' LEFT JOIN module_fish_species s ON(l.module_fish_species_id=s.id)'
                . " WHERE l.deleted_at IS NULL AND  ld.deleted_at IS NULL ";
        $where = "";
        // Filtro por períodos
        if (isset($filter['period']) && $filter['period'] != '') {
            if ($filter['period'] == 'all')
                $where .= " AND l.date_settlement IS NOT NULL";
            if ($filter['period'] == 'day')
                $where .= " AND l.date_settlement = '" . date('Y-m-d') . "'";
            if ($filter['period'] == 'week')
                $where .= " AND WEEK(l.date_settlement) = WEEK('" . date('Y-m-d') . "')";
            if ($filter['period'] == 'month')
                $where .= " AND MONTH(l.date_settlement) = MONTH('" . date('Y-m-d') . "')";
            if ($filter['period'] == 'interval' && $filter['period_ini'] != '' && $filter['period_end'] != '')
                $where .= " AND l.date_settlement BETWEEN '" . $filter['period_ini'] .
                        "' AND '" . $filter['period_end'] . "'";
        }

        if ($this->client_id > 0) {
            $where .= " AND l.crm_accounts_id ='" . $this->client_id . "'";
        }

        if (isset($filter['crm_accounts_id']) && $filter['crm_accounts_id'] != '') {
            $where .= " AND l.crm_accounts_id=" . intval($filter['crm_accounts_id']);
            $this->ui->assign('account', ORM::for_table('crm_accounts')->find_one(intval($filter['crm_accounts_id'])));
        } else {
            $this->ui->assign('account', false);
        }

        if (isset($filter['module_fish_species_id']) && $filter['module_fish_species_id'] != '') {
            $where .= " AND l.module_fish_species_id=" . intval($filter['module_fish_species_id']);
            $this->ui->assign('species', ORM::for_table('module_fish_species')->find_one(intval($filter['module_fish_species_id'])));
        } else {
            $this->ui->assign('species', false);
        }


        if (isset($filter['module_fish_tank_id']) && $filter['module_fish_tank_id'] != '') {
            $where .= " AND t.id=" . intval($filter['module_fish_tank_id']);
            $this->ui->assign('tank_filter', ORM::for_table('module_fish_tank')->find_one(intval($filter['module_fish_tank_id'])));
        } else {
            $this->ui->assign('tank_filter', false);
        }


        if (isset($filter['module_fish_lots_id']) && $filter['module_fish_lots_id'] != '') {
            $where .= " AND l.id=" . intval($filter['module_fish_lots_id']);
            $this->ui->assign('lots_filter', ORM::for_table('module_fish_lots')->find_one(intval($filter['module_fish_lots_id'])));
            
        } else {
            $this->ui->assign('lots_filter', false);
        }

        if ($filter['items_per_page'] != 'all')
            $filter['items_per_page'] = ($filter['items_per_page'] > 0) ? $filter['items_per_page'] : 10;

        $sql .= $from . $where . ' order by ca.account asc, l.date_settlement DESC';
        $page = isset($this->routes['3']) ? $this->routes['3'] : 1;
        $paginator = new ModulePaginator('module_billing_records', $sql, $filter);
        $records = $paginator->setItemsPerPage($filter['items_per_page'])
                ->setCurrentPageNumber($page)
                ->run();
        $allRecords = ORM::for_table('module_fish_lots')->raw_query($sql)->find_many();
        $total = array();
        $totalBiomass = 0;
        $periodDespesca = ORM::for_table('module_fish_food_program_periods')
                ->table_alias('pp')
                ->select('pp.*')
                ->where("pp.module_fish_food_programs_id", $allRecords[0]->module_fish_program_id)
                ->limit(1)
                ->order_by_expr('pp.period_total DESC') //pega o ultimo periodo cadastrado para o programa
                ->find_many();


        $graph = array();


        for ($i = 0; $i < count($allRecords); $i++) {
            $weight_actual = $this->modelProgram->weigthEstimatedProgramLastBiometry($allRecords[$i]);
            $totalMovimented = $this->modelMovement->getTotalMovimentTankLote($allRecords[$i]->lote_id, $allRecords[$i]->id_tank, date('Y-m-d H:i:s'));
            $total[$allRecords[$i]->lote_id]['movimented'] = $totalMovimented;
            $total[$allRecords[$i]->lote_id]['totalBiomassReal'] = $weight_actual['weight_actual'] * ($allRecords[$i]->initial_qty + $totalMovimented);
            $total[$allRecords[$i]->lote_id]['weightReal'] = $weight_actual['weight_actual'];
            $totalBiomass += $total[$allRecords[$i]->lote_id]['totalBiomassReal'];
            $total[$allRecords[$i]->lote_id]['date_despesca'] = date('Y-m-d', strtotime("" . ($periodDespesca[0]->period_total - $weight_actual['diferecaBiometriaProgramDays']) . " days", strtotime($allRecords[$i]->date_settlement)));

            $sumFeedReal = ORM::for_table('module_fish_feeding')
                            ->select_expr('sum(qty) as total_feed')
                            ->where('module_fish_lots_distribution_id', $allRecords[$i]->lote_id)
                            ->where_raw("date<='" . date('Y-m-d') . "'")->find_many();

         
            
            if ($total[$allRecords[$i]->lote_id]['totalBiomassReal'] - ($allRecords[$i]->average_weight * $allRecords[$i]->initial_qty) > 0) {
                $total[$allRecords[$i]->lote_id]['conversionFoodReal'] = $sumFeedReal[0]->total_feed/($total[$allRecords[$i]->lote_id]['totalBiomassReal'] - ($allRecords[$i]->average_weight * $allRecords[$i]->initial_qty)) ;
            } else {
                $total[$allRecords[$i]->lote_id]['conversionFoodReal'] = 0;
            }

            $date_start = $allRecords[$i]->date_settlement;
            $date_end = $total[$allRecords[$i]->lote_id]['date_despesca'];
            if ((isset($filter['module_fish_lots_id']) && $filter['module_fish_lots_id'] != '')||($i>=($filter['items_per_page']*$page)-$filter['items_per_page'] && $i<=$filter['items_per_page']*$page)) {
                $di = new DateTime($date_start);
                $interval = $di->diff(new DateTime($date_end));

                $totalDias = $interval->days;

                for ($j = 0; $j <= $totalDias; $j++) {

                    $data_inicio = new DateTime($allRecords[$i]->date_settlement);
                    $data_fim = new DateTime(date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start))));
                    $total[$allRecords[$i]->lote_id]['date_feed'] = date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)));
                    // Resgata diferença entre as datas
                    $dateInterval = $data_inicio->diff($data_fim);
                    //echo $l->date_settlement." - ".$dateInterval->days."<br/>";
                    //calcula, com base no peso incial, qual é a posição da ração
                    //pega a ultima biometria
                    $biom = ORM::for_table('module_fish_lots_distribution_biometry')
                            ->table_alias('pp')
                            ->select('pp.*')
                            ->where("pp.module_fish_lots_distribution_id", $allRecords[$i]->lote_id)
                            ->where_raw("pp.date<='" . date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start))) . "'")
                            ->order_by_expr('pp.date desc')
                            ->limit(1)
                            ->find_many();
                    $diferecaBiometriaProgramDays = $this->modelProgram->positionLoteProgram($allRecords[$i]->module_fish_program_id, $allRecords[$i]->date_settlement, $biom[0]->average_weight, $biom[0]->date);


                    $weightReal = $this->modelProgram->weigthEstimatedProgram($allRecords[$i]->date_settlement, $allRecords[$i]->module_fish_program_id, date('Y-m-d', strtotime($diferecaBiometriaProgramDays . ' days', strtotime("+ " . $j . " days", strtotime($date_start)))), $allRecords[$i]->lote_id);
                    $periodoReal = ORM::for_table('module_fish_food_program_periods')
                            ->table_alias('pp')
                            ->select('pp.*')
                            ->where("pp.module_fish_food_programs_id", $allRecords[$i]->module_fish_program_id)
                            ->where_raw('pp.period_total >=' . ($dateInterval->days + $diferecaBiometriaProgramDays))
                            ->limit(1)
                            ->order_by_expr('pp.period_total ASC')
                            ->find_many();
                    if (count($periodoReal) == 0 && (($dateInterval->days + $diferecaBiometriaProgramDays) > 0)) {
                        //se nao achou umperíodo pega como base o último período  
                        $periodoReal = ORM::for_table('module_fish_food_program_periods')
                                ->table_alias('pp')
                                ->select('pp.*')
                                ->where("module_fish_food_programs_id", $allRecords[$i]->module_fish_program_id)
                                ->limit(1)
                                ->order_by_expr('pp.period_total DESC')
                                ->find_many();
                    }


                    $biomPrev = ORM::for_table('module_fish_lots_distribution_biometry')
                            ->table_alias('pp')
                            ->select('pp.*')
                            ->where("module_fish_lots_distribution_id", $allRecords[$i]->lote_id)
                            ->where_raw("pp.date<='" . date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start))) . "'")
                            ->order_by_expr('pp.date asc')
                            ->limit(1)
                            ->find_many();

                    $diferecaBiometriaProgramDaysPrev = $this->modelProgram->positionLoteProgram($allRecords[$i]->module_fish_program_id, $allRecords[$i]->date_settlement, $biomPrev[0]->average_weight, $biomPrev[0]->date);
                    $weightPrev = $this->modelProgram->weigthEstimatedProgram($allRecords[$i]->date_settlement, $allRecords[$i]->module_fish_program_id, date('Y-m-d', strtotime($diferecaBiometriaProgramDaysPrev . ' days', strtotime("+ " . $j . " days", strtotime($date_start)))), $allRecords[$i]->lote_id);

                    $periodoPrev = ORM::for_table('module_fish_food_program_periods')
                            ->table_alias('pp')
                            ->select('pp.*')
                            ->where("pp.module_fish_food_programs_id", $allRecords[$i]->module_fish_program_id)
                            ->where_raw('pp.period_total >=' . ($dateInterval->days + $diferecaBiometriaProgramDaysPrev))
                            ->limit(1)
                            ->order_by_expr('pp.period_total ASC')
                            ->find_many();
                    if (count($diferecaBiometriaProgramDaysPrev) == 0 && (($dateInterval->days + $diferecaBiometriaProgramDays) > 0)) {
                        //se nao achou um período pega como base o último período  
                        $periodoPrev = ORM::for_table('module_fish_food_program_periods')
                                ->table_alias('pp')
                                ->select('pp.*')
                                ->where("module_fish_food_programs_id", $allRecords[$i]->module_fish_program_id)
                                ->limit(1)
                                ->order_by_expr('pp.period_total DESC')
                                ->find_many();
                    }

                    //calcula a quantidade existente no tanque no momento dessa amostragem
                    $totalMovimented = $this->modelMovement->getTotalMovimentTankLote($allRecords[$i]->lote_id, $allRecords[$i]->id_tank, date('Y-m-d H:i:s', strtotime("+ " . $j . " days", strtotime($date_start))));

                    $sum = ORM::for_table('module_fish_feeding')
                                    ->select_expr('sum(qty) as total_feed')
                                    ->where('module_fish_lots_distribution_id', $allRecords[$i]->lote_id)
                                    ->where('date', date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start))))->find_many();

                    //armazena, as ultimas biomassas de cada lote_tanque,
                    //assim mantem de qualquer lote, a ultima vez que passou aqui
                    //é o que deve ser usado na biomassa

                    $total[$allRecords[$i]->lote_id]['totalBiomassPrev'] = ($weightPrev * ($allRecords[$i]->initial_qty + $totalMovimented));
                    if(strtotime(date('Y-m-d'))>= strtotime("+ " . $j . " days", strtotime($date_start))){
                         $total[$allRecords[$i]->lote_id]['totalBiomassPrevActual'] = ($weightPrev * ($allRecords[$i]->initial_qty + $totalMovimented));
                    }

                    if (isset($graph[$allRecords[$i]->id_tank]) && isset($graph[$allRecords[$i]->id_tank]['total_feed'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))])) {
                        $graph[$allRecords[$i]->id_tank]['total_feed'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] += ($sum[0]->total_feed);
                        $graph[$allRecords[$i]->id_tank]['total_feed_prev'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] += (($periodoReal[0]->consumption_day));
                        $graph[$allRecords[$i]->id_tank]['total_biomass_prev'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] += (($weightPrev * ($allRecords[$i]->initial_qty + $totalMovimented)));
                        $graph[$allRecords[$i]->id_tank]['total_biomass_real'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] += (($weightReal * ($allRecords[$i]->initial_qty + $totalMovimented)));
                         $graph[$allRecords[$i]->id_tank]['weightPrev'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] +=$weightPrev ;
                        $graph[$allRecords[$i]->id_tank]['weightReal'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] += $weightReal;
                    
//                          $total[$allRecords[$i]->lote_id]['total_feed'] += (($sum[0]->total_feed));
//                        $total[$allRecords[$i]->lote_id]['total_feed_prev'] += (($periodoReal[0]->consumption_day));
                        if(strtotime(date('Y-m-d'))<= strtotime("+ " . $j . " days", strtotime($date_start))){
                            $total[$allRecords[$i]->lote_id]['total_feed_prev_date_actual'] += (($periodoReal[0]->consumption_day));
                        }
                    } else {
                        $graph[$allRecords[$i]->id_tank]['id_tank'] = $allRecords[$i]->id_tank;
                        $graph[$allRecords[$i]->id_tank]['title_tank'] = $allRecords[$i]->title_tank;
//                        $total[$allRecords[$i]->lote_id]['total_feed'] = (($sum[0]->total_feed));
//                        $total[$allRecords[$i]->lote_id]['total_feed_prev'] = (($periodoReal[0]->consumption_day));
                        $graph[$allRecords[$i]->id_tank]['date'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] = "'" . date($this->config['df'], strtotime(date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start))))) . "'";
                        $graph[$allRecords[$i]->id_tank]['total_feed'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] = ($sum[0]->total_feed);
                        $graph[$allRecords[$i]->id_tank]['total_feed_prev'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] = (($periodoReal[0]->consumption_day));
                        $graph[$allRecords[$i]->id_tank]['total_biomass_prev'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] = (($weightPrev * ($allRecords[$i]->initial_qty + $totalMovimented)));
                        $graph[$allRecords[$i]->id_tank]['total_biomass_real'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] = (($weightReal * ($allRecords[$i]->initial_qty + $totalMovimented)));
                        $graph[$allRecords[$i]->id_tank]['weightPrev'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] =$weightPrev ;
                        $graph[$allRecords[$i]->id_tank]['weightReal'][date('Y-m-d', strtotime("+ " . $j . " days", strtotime($date_start)))] = $weightReal;
                     
                        if(strtotime(date('Y-m-d'))>= strtotime("+ " . $j . " days", strtotime($date_start))){
                            $total[$allRecords[$i]->lote_id]['total_feed_prev_date_actual'] = (($periodoReal[0]->consumption_day));
                        }
                    }
                }
            }
        }


        $css_arr = array(
            's2/css/select2.min',
            'dp/dist/datepicker.min',
            '/../../../application/plugins/module_fish/assets/css/default');

        $js_arr = array(
            's2/js/select2.min',
            'dp/dist/datepicker.min',
            'dashboard/graph', 'chart/echarts.min',
            '/../../../application/plugins/module_fish/assets/js/setlement-list'
        );
        $assets_css = Asset::css($css_arr);
        $assets_js = Asset::js($js_arr);

        $this->ui->assign('total', $total);


        $jsvar = '
            _L[\'Module_Fish Select Specie\'] = \'' . $this->_L['Module_Fish Select Specie'] . '\';
            _L[\'Module_Fish Select Associated\'] = \'' . $this->_L['Module_Fish Select Associated'] . '\';'
        ;
        if (count($graph) > 0 && (isset($filter['module_fish_lots_id']) && $filter['module_fish_lots_id'] != '')) {
            $jsGraph = "";
            foreach ($graph as $v) {
                foreach ($v['total_feed'] as $key => $value) {
                    $v['total_feed'][$key] = number_format($value, 3, ".", "");
                    $v['total_feed_prev'][$key] = number_format($v['total_feed_prev'][$key], 3, ".", "");
                    $v['total_biomass_prev'][$key] = number_format($v['total_biomass_prev'][$key], 3, ".", "");
                    $v['total_biomass_real'][$key] = number_format($v['total_biomass_real'][$key], 3, ".", "");
                    $v['weightPrev'][$key] = number_format($v['weightPrev'][$key], 3, ".", "");
                    $v['weightReal'][$key] = number_format($v['weightReal'][$key], 3, ".", "");
 
                }

                $jsGraph = showGraph(array('Realizado', 'Previsto'), $this->_L['Module_Fish Feeding'] . $this->_L['Module_Fish / Day'] . " - " . $v['title_tank'], "graph_feed_" . $v['id_tank'], array($v['total_feed'], $v['total_feed_prev']), $v['date'], false, array("#ff0000", "#0000FF"))
                        . showGraph(array('Real', 'Previsto'), $this->_L['Module_Fish Biomass'] . $this->_L['Module_Fish / Day'] . " - " . $v['title_tank'], "graph_biomass_" . $v['id_tank'], array($v['total_biomass_real'], $v['total_biomass_prev']), $v['date'], false, array("#ff0000", "#0000FF"))
                        . showGraph(array('Real', 'Previsto'), $this->_L['Module_Fish average weight'] . $this->_L['Module_Fish / Day'] . " - " . $v['title_tank'], "weight_" . $v['id_tank'], array($v['weightReal'], $v['weightPrev']), $v['date'], false, array("#ff0000", "#0000FF"));
            }
            $this->ui->assign('jsvar', $jsvar . $jsGraph);
            $this->ui->assign('graphs', $graph);
        } else {
            $this->ui->assign('graphs', false);
        }

        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);
        $totalQty = ORM::for_table('crm_accounts')->raw_query("select sum(ld.qty) as total " . $from . $where)->find_many();
        $totalTank = ORM::for_table('crm_accounts')->raw_query("select distinct(t.id)" . $from . $where)->find_many();

        $bottomBar = array(
            array('type' => 'float3', 'info' => $this->_L['Module_Fish Biomass Actual'] . " kg", 'value' => $totalBiomass),
            array('type' => 'int', 'info' => $this->_L['Module_Fish Total fish'], 'value' => $totalQty[0]->total),
            array('type' => 'int', 'info' => $this->_L['Module_Fish Number Tanks'], 'value' => count($totalTank)),
        );
        $this->ui->assign('bottomBar', $bottomBar);


        $this->ui->assign('filter', $filter);
        $this->ui->assign('settlements', $records);
        $this->ui->assign('paginator', $paginator);
        $this->ui->assign('_st', $this->_L['Fish Description module']);
        $this->ui->assign('_include', 'settlement/list');
        $this->ui->display('wrapper.tpl');
    }

    /**
     * Insert add to type diary
     */
    public function post() {
        $data = $_POST;
        $msg = "";

        if (!isset($data['crm_accounts_id']) || empty($data['crm_accounts_id'])) {
            $msg .= $this->_L['Associated'] . $this->_L['is required'];
        }
        if ($this->client_id > 0) {
            if ($data['crm_accounts_id'] != $this->client_id) {
                $msg .= $this->_L['Associated'] . " " . $this->_L['Not Permited'];
            }
        }

        if (!isset($data['title_lote']) || empty($data['title_lote'])) {
            $msg .= $this->_L['Module_Fish Title Lote'] . $this->_L['is required'];
        } else {
            if (empty($data['id'])) {
                $uniqueTitle = ORM::for_table('module_fish_lots')
                        ->where('title_lote', $data['title_lote'])
                        ->find_many();
                if (count($uniqueTitle) > 0) {
                    $msg .= $this->_L['Module_Fish Title Lote'] . " " . $this->_L['is unique'] . "<br/>";
                }
            }
        }
        if (!isset($data['date_settlement']) || empty($data['date_settlement'])) {
            $msg .= $this->_L['Module_Fish Date Settlement'] . $this->_L['is required'];
        }
        if (!isset($data['average_weight']) || empty($data['average_weight'])) {
            $msg .= $this->_L['Module_Fish average weight'] . $this->_L['is required'];
        }
        if (!isset($data['module_fish_species_id']) || empty($data['module_fish_species_id'])) {
            $msg .= $this->_L['Species_List_Fish'] . $this->_L['is required'];
        }

        if (isset($data['tank'])) {
            for ($i = 0; $i < count($data['qty']); $i++) {
                if (!isset($data['program'][$i]) || empty($data['program'][$i])) {
                    $msg .= ($i + 1) . "° " . $this->_L['Module_Fish Program'] . $this->_L['is required'];
                }
                if (!isset($data['tank'][$i]) || empty($data['tank'][$i])) {
                    $msg .= ($i + 1) . "° " . $this->_L['Module_Fish Tank'] . $this->_L['is required'];
                }
                if (!isset($data['qty'][$i]) || empty($data['qty'][$i])) {
                    $msg .= ($i + 1) . "° " . $this->_L['Quantity'] . $this->_L['is required'];
                }
            }
        }
        if (empty($msg)) {
            if (empty($data['id'])) {
                $settlement = $this->model->createSettlement($data);
            } else {
                $settlement = $this->model->updateSettlement($data, $this->model->getOne($data['id']));
            }
            $this->model->insertLot($data, $settlement);
            if (empty($data['id'])) {
                _notify($this->_L['Module_Fish Settlement added successfully'], 's');
            } else {
                _notify($this->_L['Module_Fish Settlement updated successfully'], 's');
            }
            echo json_encode(array('status' => 'OK', 'msg' => ''));
        } else {
            echo json_encode(array('status' => 'ERROR', 'msg' => $msg));
        }
    }

    public function delete() {
        $this->data = $_POST;
        if (empty($this->data['id'])) {
            die($this->_L['Id_Required']);
        }
        if (!is_numeric($this->data['id'])) {
            $id = str_replace('lot', '', $this->data['id']);
            if (!is_numeric($id)) {
                die($this->_L['Id_Required']);
            }
            $d = ORM::for_table('module_fish_lots')->find_one($id);
            $d->delete();
            r2(U . ($this->client_id > 0 ? 'client/' : '') . 'module_fish/settlement/listSettlement', 's', $this->_L['delete_successful']);
        } else {
            $r = ORM::for_table('module_fish_lots_distribution')->find_one($this->data['id']);
            $movements = ORM::for_table('module_fish_movement')->where('module_fish_lots_distribution_id', $r->id)->find_many();
            if (count($movements) == 0) {
                $x = ORM::for_table('module_fish_lots_distribution_biometry')->where('module_fish_lots_distribution_id', $r->id)->delete_many();
                $x = ORM::for_table('module_fish_lots_distribution_program')->where('module_fish_lots_distribution_id', $r->id)->delete_many();
                $r->delete();


                $distribution = ORM::for_table('module_fish_lots_distribution')->where("module_fish_lots_id", $r->module_fish_lots_id)->find_many();
                if (count($distribution) == 0) {
                    $x = ORM::for_table('module_fish_lots')->where('id', $r->module_fish_lots_id)->delete_many();
                }

                r2(U . ($this->client_id > 0 ? 'client/' : '') . 'module_fish/settlement/listSettlement', 's', $this->_L['delete_successful']);
            } else {
                r2(U . ($this->client_id > 0 ? 'client/' : '') . 'module_fish/settlement/listSettlement', 'e', $this->_L['Module_Fish Not permited Settlement']);
            }
        }
    }

}

function showGraph($title, $description, $identificador, $valueSeries, $listDay, $showBackground = false, $color = "#2196f3") {
    global $_L;
    $series = "{
                    name:'" . $title[0] . "',
                    type:'line',    
                    smooth:true,
                    color: [
                    '" . $color[0] . "'
                    ]," .
            ($showBackground ? "itemStyle: {normal: {areaStyle: {type: 'default'}}}," : "")
            . " data:[" . "'" . (count($valueSeries[0]) == 0 ? '' : implode("','", $valueSeries[0])) . "']
                }"
            .
            ",{
                    name:'" . $title[1] . "',
                    type:'line',    
                    smooth:true,
                    color: [
                    '" . $color[1] . "'
                    ]," .
            ($showBackground ? "itemStyle: {normal: {areaStyle: {type: 'default'}}}," : "")
            . " data:[" . "'" . (count($valueSeries[1]) == 0 ? '' : implode("','", $valueSeries[1])) . "']
                }"
    ;

    return " $(function() { var " . $identificador . "_opt =  {
            title : {
                text:'" . $description . "',
                subtext: ''
            },
            tooltip : {
                trigger: 'axis'
            },
             legend: {
                data:['" . $title[0] . "','" . $title[1] . "']
            },
            toolbox: {
                show : true,
                feature : {
                    mark : {show: true},
                    dataView : {show: true, readOnly: false, title : _L['Data View'],
                        lang: [_L['Data View'], _L['Cancel'], _L['Reset']] },
                    magicType : {show: true, title : {
                        line : 'Line',
                        bar : 'Bar',
                        stack : 'Stack',
                        tiled : 'Tiled',
                        force: 'Force',
                        chord: 'Chord',
                        pie: 'Pie',
                        funnel: 'Funnel'
                    }, type: ['line', 'bar', 'stack', 'tiled']},
                    restore : {show: true, title : 'Reset'},
                    saveAsImage : {show: true, title : _L['Save as Image'],
                        type : 'png',
                        lang : [_L['Click to Save']]}
                }
            },
            calculable : true,
            xAxis : [
                {
                    type : 'category',
                    boundaryGap : false,
                    data :[" . implode(",", $listDay) . "]
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series :
                    [
                " . $series . "
            ]
        };
        var " . $identificador . " = echarts.init(document.getElementById('" . $identificador . "'));
        " . $identificador . ".setOption(" . $identificador . "_opt);
    });";
}

Anon7 - 2022
AnonSec Team