function getPastDates($number)
{
    $datestring = "%d-%m-%Y";
    $time = time();
    $datestring = mdate($datestring, $time);
    $splitted_date = explode("-", $datestring);
    $year = (int) $splitted_date[2];
    $month = (int) $splitted_date[1];
    $day = (int) $splitted_date[0];
    $dates = array();
    foreach ($programs as $key => $value) {
        $ordByProg[$value] = 0;
    }
    $dates[$day . '-' . $month . '-' . $year] = $ordByProg;
    for ($i = 0; $i < $number - 1; $i++) {
        if ($day - 1 > 0) {
            $day = $day - 1;
            $dates[$day . '-' . $month . '-' . $year] = '';
        } else {
            if ($month - 1 > 0) {
                $month = $month - 1;
                $day = days_in_month($month, $year);
            } else {
                $month = 12;
                $year = $year - 1;
                $day = days_in_month($month, $year);
            }
            $dates[$day . '-' . $month . '-' . $year] = '';
        }
    }
    return array_reverse($dates);
}
 function filter($condition = FALSE)
 {
     $days_in_this_month = days_in_month(date('m'), date('Y'));
     $lastday_in_month = date('Y') . "-" . date('m') . "-" . $days_in_this_month;
     $firstday_in_month = date('Y') . "-" . date('m') . "-01";
     $this->view_data['estimates_paid_this_month'] = Invoice::count(array('conditions' => 'paid_date <= ' . $lastday_in_month . ' and paid_date >= ' . $firstday_in_month . ' AND estimate != 0'));
     $this->view_data['estimates_due_this_month'] = Invoice::count(array('conditions' => 'due_date <= ' . $lastday_in_month . ' and due_date >= ' . $firstday_in_month . ' AND estimate != 0'));
     switch ($condition) {
         case 'open':
             $this->view_data['estimates'] = Invoice::find('all', array('conditions' => array('estimate_status = ? and estimate != ?', 'Open', 0)));
             break;
         case 'sent':
             $this->view_data['estimates'] = Invoice::find('all', array('conditions' => array('estimate_status = ? and estimate != ?', 'Sent', 0)));
             break;
         case 'accepted':
             $this->view_data['estimates'] = Invoice::find('all', array('conditions' => array('estimate_status = ? and estimate != ?', 'Accepted', 0)));
             break;
         case 'declined':
             $this->view_data['estimates'] = Invoice::find('all', array('conditions' => array('estimate_status = ? and estimate != ?', 'Declined', 0)));
             break;
         case 'invoiced':
             $this->view_data['estimates'] = Invoice::find('all', array('conditions' => array('estimate_status = ? and estimate != ?', 'Invoiced', 0)));
             break;
         default:
             $this->view_data['estimates'] = Invoice::find('all', array('conditions' => array('estimate != ?', 0)));
             break;
     }
     $this->content_view = 'estimates/all';
 }
Exemple #3
0
 /**
  * Get visits by chosen month.
  * @param  int $month Month
  * @return array
  */
 public function get_visits_stats($month, $format = true)
 {
     $this->load->helper('date');
     // First get total visits by date from database
     $this->db->where('MONTH(date)', $month);
     $this->db->group_by('DAY(date)');
     $this->db->select('date, COUNT(*) AS total');
     $result = $this->db->get('site_views')->result();
     // Set starting variables
     $monthStartDay = date('Y-' . $month . '-01');
     $numberOfDaysInMonth = days_in_month($month);
     // Fill all dates with zero views
     $range = array();
     for ($i = 0; $i <= $numberOfDaysInMonth; $i++) {
         $dateIncrement = date("Y-m-d", strtotime($monthStartDay . " +" . $i . " day"));
         $range[$dateIncrement] = 0;
     }
     // Remove starting day of next month
     array_pop($range);
     // Fill dates with real values
     foreach ($result as $visit) {
         $formatDate = date('Y-m-d', strtotime($visit->date));
         $range[$formatDate] = $visit->total;
     }
     if ($format) {
         return $this->format_js_data($range);
     } else {
         return $range;
     }
 }
Exemple #4
0
 function add_month_to_unix_time($unix_time = 0, $multiply = 1)
 {
     if ($unix_time <= 0) {
         $unix_time = now();
     }
     $month = date('n', $unix_time);
     return $unix_time + 86400 * days_in_month($month) * $multiply;
 }
Exemple #5
0
 static function genehotel($mes)
 {
     $CI =& get_instance();
     $udia = days_in_month(substr($mes, 4), substr($mes, 0, 4));
     $fdesde = $mes . '01';
     $fhasta = $mes . $udia;
     // BORRA LA GENERADA ANTERIOR
     $CI->db->simple_query("DELETE FROM siva WHERE EXTRACT(YEAR_MONTH FROM fechal) = {$mes} AND fuente='FH' ");
     // ARREGLA LAS TASAS NULAS EN SFAC
     $CI->db->simple_query("UPDATE hfac SET tasa=0, montasa=0, reducida=0, monredu=0, sobretasa=0, monadic=0, exento=0 WHERE (tasa IS NULL OR montasa IS NULL) AND EXTRACT(YEAR_MONTH FROM fecha)={$mes} ");
     $mSQL = "INSERT INTO siva\n\t\t\t(id, libro, tipo, fuente, sucursal, fecha, numero, numhasta,  caja, nfiscal,  nhfiscal,\n\t\t\treferen, planilla, clipro, nombre, contribu, rif, registro,\n\t\t\tnacional, exento, general, geneimpu,\n\t\t\tadicional, adicimpu,  reducida,  reduimpu, stotal, impuesto,\n\t\t\tgtotal, reiva, fechal, fafecta)\n\t\t\tSELECT 0 AS id,\n\t\t\t'V' AS libro,\n\t\t\tIF(a.tipo='D','NC',IF(a.tipo='F','FC',CONCAT('F',a.tipo))) AS tipo,\n\t\t\t'FH' AS fuente,\n\t\t\t'00' AS sucursal,\n\t\t\ta.fecha_ou,\n\t\t\ta.num_fac,\n\t\t\t' ' AS numhasta,\n\t\t\t' ' AS caja,\n\t\t\t' ' AS nfiscal,\n\t\t\t'  ' AS nhfiscal,\n\t\t\tIF(a.tipo='E',a.num_fac,a.num_fac ) AS referen,\n\t\t\t'  ' AS planilla,\n\t\t\ta.cod_cli AS clipro,\n\t\t\tIF(a.tipo='X','DOCUMENTO ANULADO.......',if(c.nombre='',a.nombre,c.nombre)),\n\t\t\tIF(c.tiva='C','CO','NO') AS contribu,\n\t\t\tIF(c.rifci='', a.cedula, c.rifci ),\n\t\t\t'01' AS registro,\n\t\t\t'S' AS nacional,\n\t\t\t0   AS exento,\n\t\t\ta.total*(a.tipo<>'X') AS general,\n\t\t\ta.iva*(a.tipo<>'X') AS geneimpu,\n\t\t\t0 AS adicional,\n\t\t\t0 AS adicimpu,\n\t\t\t0 AS reducida,\n\t\t\t0 AS reduimpu,\n\t\t\ta.total*(a.tipo<>'X') AS stotal,\n\t\t\ta.iva*(a.tipo<>'X')    AS impuesto,\n\t\t\ta.totalg*(a.tipo<>'X') AS gtotal,\n\t\t\t0 AS reiva,\n\t\t\t" . $mes . "01 AS fechal,\n\t\t\t0 AS fafecta\n\t\t\tFROM hfac AS a\n\t\t\tLEFT JOIN scli AS c ON a.cod_cli=c.cliente\n\t\t\tWHERE a.fecha_ou BETWEEN {$fdesde} AND {$fhasta} AND a.tipo NOT IN ('P','T')";
     $flag = $CI->db->simple_query($mSQL);
     if (!$flag) {
         memowrite($mSQL, 'genehotel');
     }
     //CARGA LAS RETENCIONES DE IVA DE CONTADO
     $mSQL = "SELECT * FROM sfpa WHERE tipo='RI' AND\tf_factura BETWEEN {$fdesde} AND {$fhasta} AND tipo_doc='FE' ";
     $query = $CI->db->query($mSQL);
     if ($query->num_rows() > 0) {
         foreach ($query->result() as $row) {
             $mSQL = "UPDATE siva SET reiva=" . $row->monto . ", comprobante='20" . $row->num_ref . "' WHERE tipo='" . $row->tipo_doc . "' AND numero='" . $row->numero . "' AND libro='V' AND fechal BETWEEN {$fdesde} AND {$fhasta} ";
             $flag = $CI->db->simple_query($mSQL);
             if (!$flag) {
                 memowrite($mSQL, 'genehotel');
             }
         }
     }
     //CARGA LAS RETENCIONES DE IVA DESDE SMOV
     $mSQL = "SELECT a.tipo_doc, a.fecha, a.numero, c.nombre, c.rifci, a.cod_cli, b.monto,\n\t\t\t\ta.numero AS afecta, a.fecha AS fafecta, a.reteiva, a.transac, a.nroriva, a.emiriva, a.recriva\n\t\t\tFROM itccli AS a JOIN smov AS b ON a.transac=b.transac\n\t\t\t\tLEFT JOIN scli AS c ON a.cod_cli=c.cliente\n\t\t\tWHERE b.fecha BETWEEN {$fdesde} AND {$fhasta} AND b.cod_cli='REIVA'\n\t\t\t\tAND a.reteiva>0 AND b.monto>b.abonos ";
     $query = $CI->db->query($mSQL);
     if ($query->num_rows() > 0) {
         foreach ($query->result() as $row) {
             $mSQL = "UPDATE siva SET reiva=" . $row->reteiva . ", comprobante='" . $row->nroriva . "', fecharece='{$row->recriva}'  WHERE tipo='" . $row->tipo_doc . "' AND numero='" . $row->numero . "' AND libro='V' AND fechal BETWEEN {$fdesde} AND {$fhasta} ";
             $flag = $CI->db->simple_query($mSQL);
             if (!$flag) {
                 memowrite($mSQL, 'genehotel');
             }
         }
     }
 }
Exemple #6
0
 function filter($userid = FALSE, $year = FALSE, $month = FALSE)
 {
     $this->view_data['userlist'] = User::find('all', array('conditions' => array('status = ?', 'active')));
     $this->view_data['username'] = User::find_by_id($userid);
     $this->view_data['user_id'] = $userid;
     $this->view_data['year'] = $year;
     $this->view_data['month'] = $month;
     $search = "";
     $stats_search = "";
     if ($userid) {
         $search .= "user_id = {$userid} and ";
         $stats_search = " AND user_id = {$userid} ";
     }
     if ($month && $year) {
         $search .= "date >= '{$year}-{$month}-01' and date <= '{$year}-{$month}-31'";
     } else {
         $search .= "date >= '{$year}-01-01' and date <= '{$year}-12-31'";
     }
     //statistic
     $graph_month = $month != 0 ? $month : date('m');
     if ($month == 0) {
         $lastday_in_month = strtotime($year . "-12-31");
         $firstday_in_month = strtotime($year . "-01-01");
         $this->view_data['days_in_this_month'] = 12;
         $this->view_data['expenses_this_month'] = Expense::count(array('conditions' => 'UNIX_TIMESTAMP(`date`) <= ' . $lastday_in_month . ' and UNIX_TIMESTAMP(`date`) >= ' . $firstday_in_month . $stats_search));
         $this->view_data['expenses_owed_this_month'] = Expense::find_by_sql('select sum(value) AS "owed" from expenses where UNIX_TIMESTAMP(`date`) >= "' . $firstday_in_month . '" AND UNIX_TIMESTAMP(`date`) <= "' . $lastday_in_month . '"' . $stats_search);
         $this->view_data['expenses_due_this_month_graph'] = Expense::find_by_sql('select sum(value) AS "owed", MONTH(`date`) as `date` from expenses where UNIX_TIMESTAMP(`date`) >= "' . $firstday_in_month . '" AND UNIX_TIMESTAMP(`date`) <= "' . $lastday_in_month . '"' . $stats_search . ' Group By MONTH(`date`)');
     } else {
         $days_in_this_month = days_in_month($graph_month, $year);
         $lastday_in_month = strtotime($year . "-" . $graph_month . "-" . $days_in_this_month);
         $firstday_in_month = strtotime($year . "-" . $graph_month . "-01");
         $this->view_data['days_in_this_month'] = $days_in_this_month;
         $this->view_data['expenses_this_month'] = Expense::count(array('conditions' => 'UNIX_TIMESTAMP(`date`) <= ' . $lastday_in_month . ' and UNIX_TIMESTAMP(`date`) >= ' . $firstday_in_month . $stats_search));
         $this->view_data['expenses_owed_this_month'] = Expense::find_by_sql('select sum(value) AS "owed" from expenses where UNIX_TIMESTAMP(`date`) >= "' . $firstday_in_month . '" AND UNIX_TIMESTAMP(`date`) <= "' . $lastday_in_month . '"' . $stats_search);
         $this->view_data['expenses_due_this_month_graph'] = Expense::find_by_sql('select sum(value) AS "owed", `date` from expenses where UNIX_TIMESTAMP(`date`) >= "' . $firstday_in_month . '" AND UNIX_TIMESTAMP(`date`) <= "' . $lastday_in_month . '"' . $stats_search . ' Group By `date`');
     }
     $this->view_data['expenses'] = Expense::find('all', array('conditions' => array("{$search}")));
     $this->content_view = 'expenses/all';
 }
 function filter($condition = FALSE)
 {
     $days_in_this_month = days_in_month(date('m'), date('Y'));
     $lastday_in_month = date('Y') . "-" . date('m') . "-" . $days_in_this_month;
     $firstday_in_month = date('Y') . "-" . date('m') . "-01";
     $this->view_data['invoices_paid_this_month'] = Invoice::count(array('conditions' => 'paid_date <= ' . $lastday_in_month . ' and paid_date >= ' . $firstday_in_month . ''));
     $this->view_data['invoices_due_this_month'] = Invoice::count(array('conditions' => 'due_date <= ' . $lastday_in_month . ' and due_date >= ' . $firstday_in_month . ''));
     switch ($condition) {
         case 'open':
             $this->view_data['invoices'] = Invoice::find('all', array('conditions' => array('status = ?', 'Open')));
             break;
         case 'sent':
             $this->view_data['invoices'] = Invoice::find('all', array('conditions' => array('status = ?', 'Sent')));
             break;
         case 'paid':
             $this->view_data['invoices'] = Invoice::find('all', array('conditions' => array('status = ?', 'Paid')));
             break;
         default:
             $this->view_data['invoices'] = Invoice::all();
             break;
     }
     $this->content_view = 'invoices/all';
 }
Exemple #8
0
 public function date_helper()
 {
     $this->load->helper('date');
     // echo mdate("%M %d %Y - %H:%i%a", time());				# Prints Current date and time. e.g: Aug 03 2015 - 03:10am
     // echo unix_to_human(time()); 								# e.g: 2015-08-03 03:21 AM
     // echo nice_date(unix_to_human(time()), 'M d Y, G:ia');	# e.g: Aug 03 2015, 3:50am
     echo "<h3>Hello, this is the date helper.</h3>";
     /**
      *	The timespan() function is very useful when you want to calculate the span of time.
      *	Or in other words, you want to calculate how many years, months, weeks, hours and minutes have passed since a particular time until to a specific time.
      **/
     $past = '1079621429';
     # This is dated: March 18, 2004 at 03:50PM
     $present = time();
     # This is the time right now
     $units = 3;
     # This will limit the information to display, max is 5.
     echo '<p>', timespan($past, $present, $units), '</p>';
     /**
      *	When we want to know how many number of days does a month have, we often make mistakes.
      *	And that is because of leap year and non-leap years.
      *	So this function, days_in_month() will help us.
      **/
     $month = 06;
     $year = 2005;
     echo '<p>' . days_in_month($month, $year) . ' days.</p>';
 }
Exemple #9
0
function find_day_in_month($startday, $weekday, $month, $year)
{
    $daysinmonth = days_in_month($month, $year);
    if ($weekday == -1) {
        // Don't care about weekday, so return:
        //    abs($startday) if $startday != -1
        //    $daysinmonth otherwise
        return $startday == -1 ? $daysinmonth : abs($startday);
    }
    // From now on we 're looking for a specific weekday
    // Give "end of month" its actual value, since we know it
    if ($startday == -1) {
        $startday = -1 * $daysinmonth;
    }
    // Starting from day $startday, the sign is the direction
    if ($startday < 1) {
        $startday = abs($startday);
        $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
        // This is the last such weekday of the month
        $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
        if ($lastinmonth > $daysinmonth) {
            $lastinmonth -= 7;
        }
        // Find the first such weekday <= $startday
        while ($lastinmonth > $startday) {
            $lastinmonth -= 7;
        }
        return $lastinmonth;
    } else {
        $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
        $diff = $weekday - $indexweekday;
        if ($diff < 0) {
            $diff += 7;
        }
        // This is the first such weekday of the month equal to or after $startday
        $firstfromindex = $startday + $diff;
        return $firstfromindex;
    }
}
 /**
  * Register Member
  *
  * Create a member profile
  *
  * @return	mixed
  */
 public function _register_member()
 {
     $this->load->helper('security');
     $data = array();
     if ($this->input->post('group_id')) {
         if (!$this->cp->allowed_group('can_admin_mbr_groups')) {
             show_error(lang('unauthorized_access'));
         }
         $data['group_id'] = $this->input->post('group_id');
     }
     // -------------------------------------------
     // 'cp_members_member_create_start' hook.
     //  - Take over member creation when done through the CP
     //  - Added 1.4.2
     //
     $this->extensions->call('cp_members_member_create_start');
     if ($this->extensions->end_script === TRUE) {
         return;
     }
     //
     // -------------------------------------------
     // If the screen name field is empty, we'll assign is
     // from the username field.
     $data['screen_name'] = $this->input->post('screen_name') ? $this->input->post('screen_name') : $this->input->post('username');
     // Get the password information from Auth
     $this->load->library('auth');
     $hashed_password = $this->auth->hash_password($this->input->post('password'));
     // Assign the query data
     $data['username'] = $this->input->post('username');
     $data['password'] = $hashed_password['password'];
     $data['salt'] = $hashed_password['salt'];
     $data['unique_id'] = random_string('encrypt');
     $data['crypt_key'] = $this->functions->random('encrypt', 16);
     $data['email'] = $this->input->post('email');
     $data['ip_address'] = $this->input->ip_address();
     $data['join_date'] = $this->localize->now;
     $data['language'] = $this->config->item('deft_lang');
     $data['timezone'] = $this->config->item('default_site_timezone');
     $data['date_format'] = $this->config->item('date_format') ? $this->config->item('date_format') : '%n/%j/%y';
     $data['time_format'] = $this->config->item('time_format') ? $this->config->item('time_format') : '12';
     $data['include_seconds'] = $this->config->item('include_seconds') ? $this->config->item('include_seconds') : 'n';
     // Was a member group ID submitted?
     $data['group_id'] = !$this->input->post('group_id') ? 2 : $_POST['group_id'];
     $base_fields = array('bday_y', 'bday_m', 'bday_d', 'url', 'location', 'occupation', 'interests', 'aol_im', 'icq', 'yahoo_im', 'msn_im', 'bio');
     foreach ($base_fields as $val) {
         $data[$val] = $this->input->post($val) === FALSE ? '' : $this->input->post($val, TRUE);
     }
     if (is_numeric($data['bday_d']) && is_numeric($data['bday_m'])) {
         $this->load->helper('date');
         $year = $data['bday_y'] != '' ? $data['bday_y'] : date('Y');
         $mdays = days_in_month($data['bday_m'], $year);
         if ($data['bday_d'] > $mdays) {
             $data['bday_d'] = $mdays;
         }
     }
     // Clear out invalid values for strict mode
     foreach (array('bday_y', 'bday_m', 'bday_d') as $val) {
         if ($data[$val] == '') {
             unset($data[$val]);
         }
     }
     if ($data['url'] == 'http://') {
         $data['url'] = '';
     }
     // Extended profile fields
     $cust_fields = FALSE;
     $query = $this->member_model->get_all_member_fields(array(array('m_field_cp_reg' => 'y')), FALSE);
     if ($query->num_rows() > 0) {
         foreach ($query->result_array() as $row) {
             if ($this->input->post('m_field_id_' . $row['m_field_id']) !== FALSE) {
                 $cust_fields['m_field_id_' . $row['m_field_id']] = $this->input->post('m_field_id_' . $row['m_field_id'], TRUE);
             }
         }
     }
     $member_id = $this->member_model->create_member($data, $cust_fields);
     // Write log file
     $message = lang('new_member_added');
     $this->logger->log_action($message . NBS . NBS . stripslashes($data['username']));
     // -------------------------------------------
     // 'cp_members_member_create' hook.
     //  - Additional processing when a member is created through the CP
     //
     $this->extensions->call('cp_members_member_create', $member_id, $data);
     if ($this->extensions->end_script === TRUE) {
         return;
     }
     //
     // -------------------------------------------
     // Update Stats
     $this->stats->update_member_stats();
     $this->session->set_flashdata(array('message_success' => $message . NBS . '<b>' . stripslashes($data['username']) . '</b>', 'username' => stripslashes($data['screen_name'])));
     $this->functions->redirect(BASE . AMP . 'C=members' . AMP . 'M=view_all_members');
 }
Exemple #11
0
 public function get_calendar($calendar, $reload_url, $focus = null)
 {
     /* BENCHMARK */
     $this->benchmark->mark('func_get_calendar_start');
     $this->load->helper('data_helper');
     $this->load->model('slider_model');
     // default focus if not set
     if (null == $focus) {
         $focus = date('m-Y', time());
     }
     // get event array
     $events = json_decode($calendar['event_json'], true);
     // event nodes
     $event_nodes = $this->node_model->get_nodes(array('event.calendar_id' => $calendar['node_id'], 'type' => 'event'), 1);
     $this->event_nodes = $this->node_model->nodes_by_id($event_nodes);
     // set calendar into object and user, event default, colours etc
     $this->calendar = $calendar;
     $this->calendar['user'] = $this->node_model->get_node($this->calendar['user_id'], 'user');
     $event_default = $this->config->item('event_default');
     $this->colours = $event_default['colours'];
     // now
     $this->now = get_now();
     // break date
     $fdate_bits = date_bits($focus, '-');
     // get focus day and start of chunk
     $limit = array();
     if (is_numeric($focus)) {
         $cgran = 'year';
         $focus .= "0101";
         $limit['start'] = $focus;
         $sel_year = substr($limit['start'], 0, 4);
         $limit['end'] = $sel_year . "1232";
         // one day more than December this year will ensure only this year is output
     } elseif (8 == strlen($focus) or 7 == strlen($focus)) {
         $cgran = 'month';
         $month = is_numeric($fdate_bits[0]) ? $fdate_bits[0] : $this->month_names[strtolower($fdate_bits[0])];
         $focus = $fdate_bits[1] . $month . "01";
         $limit['start'] = $focus;
         $limit['end'] = substr($limit['start'], 0, 6) . "32";
         // one day more than any month will ensure only this month is output
     } elseif (10 == strlen($focus) or 11 == strlen($focus)) {
         $cgran = 'day';
         $month = is_numeric($fdate_bits[1]) ? $fdate_bits[1] : $this->month_names[strtolower($fdate_bits[1])];
         $focus = $fdate_bits[2] . $month . $fdate_bits[0];
         $limit['start'] = $focus;
         $limit['end'] = $limit['start'];
     } else {
         $cgran = 'month';
         $focus = str_replace('-', '', $this->now['string']);
         $limit['start'] = substr($focus, 0, 6) . "01";
         $limit['end'] = substr($focus, 0, 6) . "32";
         // one day more than any month will ensure only this month is output
     }
     // open the calendar
     $cale = '';
     $cal['meta_data'] = $calendar;
     $cal['granularity'] = $cgran;
     // back links
     $cal['back_links'] = array();
     if ('month' == $cgran) {
         // get bits
         $yf = $fdate_bits[1];
         // granularity links
         $cal['back_links']['year'] = "/" . $reload_url . "/" . $yf;
     } elseif ('day' == $cgran) {
         // get bits
         $yf = $fdate_bits[2];
         $mf = $fdate_bits[1] . '-' . $fdate_bits[2];
         // granularity links
         $cal['back_links']['year'] = "/" . $reload_url . "/" . $yf;
         $cal['back_links']['month'] = "/" . $reload_url . "/" . $mf;
     }
     // end limit
     // open the main calendar div
     // scroller
     // next and previous links
     $cal['next'] = array();
     $cal['previous'] = array();
     if ('day' == $cgran) {
         // open calendar
         $cale .= "<div id='day_chunk'>";
         // next and previous
         $y = substr($limit['start'], 0, 4);
         $m = substr($limit['start'], 4, 2);
         $d = substr($limit['start'], 6, 2);
         if ('01' == $d && '01' == $m) {
             $n = '02-01-' . $y;
             $l = '31-12-' . ($y - 1);
         } elseif ('31' == $d && '12' == $m) {
             $n = '01-01-' . ($y + 1);
             $l = '30-12-' . $y;
         } else {
             if ('01' == $d) {
                 $lm = $m - 1;
                 if ($lm < 10 ? $lm = '0' . $lm : ($lm = $lm)) {
                 }
                 $n = '02-' . $m . '-' . $y;
                 $l = days_in_month($m - 1, $y) . '-' . $lm . '-' . $y;
             } elseif ($d == days_in_month($m, $y)) {
                 $nm = $m + 1;
                 if ($nm < 10 ? $nm = '0' . $nm : ($nm = $nm)) {
                 }
                 $n = '01-' . $nm . '-' . $y;
                 $l = days_in_month($m, $y) - 1 . '-' . $m . '-' . $y;
             } else {
                 $nd = $d + 1;
                 $ld = $d - 1;
                 if ($nd < 10 ? $nd = '0' . $nd : ($nd = $nd)) {
                 }
                 if ($ld < 10 ? $ld = '0' . $ld : ($ld = $ld)) {
                 }
                 $n = $nd . '-' . $m . '-' . $y;
                 $l = $ld . '-' . $m . '-' . $y;
             }
         }
         // add next and previous
         $cal['next'] = array('link' => "/" . $reload_url . "/" . $n, 'label' => 'tomorrow');
         $cal['previous'] = array('link' => "/" . $reload_url . "/" . $l, 'label' => 'yesterday');
     } elseif ('month' == $cgran) {
         // open calendar
         $cale .= "<div id='month_chunk'>";
         // next and previous
         $y = substr($limit['start'], 0, 4);
         $m = substr($limit['start'], 4, 2);
         if (1 == $m) {
             // month name or num
             if (is_numeric($fdate_bits[0])) {
                 $nm = '02';
                 $lm = '12';
             } else {
                 $nm = 'feb';
                 $lm = 'dec';
             }
             $n = $nm . '-' . $y;
             $l = $lm . '-' . ($y - 1);
         } elseif (12 == $m) {
             // month name or num
             if (is_numeric($fdate_bits[0])) {
                 $nm = '01';
                 $lm = '11';
             } else {
                 $nm = 'jan';
                 $lm = 'nov';
             }
             $n = $nm . '-' . ($y + 1);
             $l = $lm . '-' . $y;
         } else {
             // month name or num
             if (is_numeric($fdate_bits[0])) {
                 $nm = $m + 1;
                 $lm = $m - 1;
                 if ($nm < 10 ? $nm = '0' . $nm : ($nm = $nm)) {
                 }
                 if ($lm < 10 ? $lm = '0' . $lm : ($lm = $lm)) {
                 }
             } else {
                 $nm = $this->month_nums[$m + 1];
                 $lm = $this->month_nums[$m - 1];
             }
             $n = $nm . '-' . $y;
             $l = $lm . '-' . $y;
         }
         // add next and previous
         $cal['next'] = array('link' => "/" . $reload_url . "/" . $n, 'label' => 'next month');
         $cal['previous'] = array('link' => "/" . $reload_url . "/" . $l, 'label' => 'last month');
     } elseif ('year' == $cgran) {
         // open calendar
         $cale .= "<div id='year_chunk'>";
         // next and previous
         $cal['next'] = array('link' => "/" . $reload_url . "/" . ($sel_year + 1), 'label' => 'next year');
         $cal['previous'] = array('link' => "/" . $reload_url . "/" . ($sel_year - 1), 'label' => 'last year');
     }
     // day names in convenient array
     $this->day_names = array('skip_zero', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');
     // output chunk
     $cal['cells'] = array();
     foreach ($events as $k => $v) {
         if ($k >= $limit['start'] && $k <= $limit['end']) {
             $cal['cells'][$k] = $v;
             /*dev_dump($k);
               dev_dump($v);*/
             // date details
             /*    $y=substr($k,0,4);
                                     $m=substr($k,4,2);
                                     $d=substr($k,6,2);
                                     $ym=substr($k,0,6);
                                     $ymd=$k;
                                     $day_name=strtolower(format_date($y."-".$m."-".$d,'D'));
                                     $day_num=format_date($y."-".$m."-".$d,'N');
                                     $date=format_date($y."-".$m."-".$d,'d m Y');
                                     $link_date=$d."-".$m."-".$y;
             
                                 // open month
                                     if (in_array($cgran,array('year','month')) &&
                                         '01'==$d)
                                     {
                                         // open the month div
                                             $cale.="<div class='m'>";
             
                                         // if this is a year calendar then show a month name and link
                                             if ('year'==$cgran)
                                             {
                                                 if (1==$this->config->item('full_month_names') ? $mname=$this->month_nums['f'.$m] : $mname=$this->month_nums[$m] );
                                                 $cale.="<span class='mh'><a href='/".$reload_url."/".$this->month_nums[$m]."-".$y."'>".$mname."</a></span>";
                                             }
             
                                         // add a row of day names
                                             $cale.="<div class='dhs'>";
                                             $cale.="<span class='d dh mon'>mon</span>";
                                             $cale.="<span class='d dh tue'>tue</span>";
                                             $cale.="<span class='d dh wed'>wed</span>";
                                             $cale.="<span class='d dh thu'>thu</span>";
                                             $cale.="<span class='d dh fri'>fri</span>";
                                             $cale.="<span class='d dh sat'>sat</span>";
                                             $cale.="<span class='d dh sun'>sun</span>";
                                             $cale.="</div>";
             
                                         // fill the month output with dead cells
                                             for ($x=1;$x<$day_num;$x++)
                                             {
                                                 $cale.="<span class='d dc ".$this->day_names[$x]."'></span>";
                                             }
                                     }
             
                                 // open day and mark now (but not if its a day granularity, then we mark the half hour)
                                     if ( $k==$this->now['numeric'] && $cgran!='day' ? $extra_class=' now ' : $extra_class='' );
             
                                     // set a class if the day has visible events
                                         if (count($v['e'])>0)
                                         {
                                             foreach ($v['e'] as $check_id=>$val)
                                             {
                                                 if (1==$this->event_nodes[$check_id]['visible'])
                                                 {
                                                     $extra_class.='has_e';
                                                     break;
                                                 }
                                             }
                                         }
             
                                     $cale.="<div id='d".$ymd."' class='d ".$day_name." ".$extra_class."'>";
             
                                 // add exclusivity field
                                     $exs='';
                                     if (is_array($v['x']))
                                     {
                                         foreach ($v['x'] as $xk=>$xv)
                                         {
                                             $exs.=$xk.'-'.$xv.'_';
                                         }
                                     }
                                     $cale.="<input id='x".$ymd."' type='hidden' value='".$exs."'/>";
             
                                 // date
                                     if (isset($this->date_formats['calendar']) ? $date_text=date($this->date_formats['calendar'],strtotime($y."-".$m."-".$d)) : $date_text=$day_name." ".$date );
                                     if ('day'==$cgran)
                                     {
                                         $cale.="<span id='date_".$ymd."' class='master_date'>".$date_text."</span>";
                                     }
                                     elseif ('month'==$cgran)
                                     {
                                         if (0==$this->calendar['gran_link_through'])
                                         {
                                             $cale.="<span class='date'>".$date_text."</span>";
                                         }
                                         else
                                         {
                                             $cale.="<span class='date'><a href='/".$reload_url."/".$link_date."'>".$date_text."</a></span>";
                                         }
                                     }
                                     else
                                     {
                                         if (0==$this->calendar['gran_link_through'])
                                         {
                                             $cale.="<span class='date'>".day_suffix($d)."</span>";
                                         }
                                         else
                                         {
                                             $cale.="<span class='date'><a href='/".$reload_url."/".$link_date."'>".$d."</a></span>";
                                         }
                                     }
             
                                 // if the granularity is day by day then we break the day cell down further into half hours
                                 // we then iterate over the events inside this but the day by day calendar only hits the outer loop once
                                 // high detail calendars will be unusual and maybe a bit heavier to handle
                                     if ('day'==$cgran or
                                         1==$calendar['high_detail'])
                                     {
                                         // if marked as 'd' then all day - this may be the case for more than one event on this day so we must check all
                                             foreach ($v['e'] as $meta_id=>$day_event)
                                             {
                                                 // use zero to get the first array element - if it is 'd' (today) then there will only be one
                                                     if ('d'==$day_event['t'][0]['t'])
                                                     {
                                                         // output a cell
                                                             $cale.="<div id='allday_".$meta_id."' class='half_hour all_day'>";
                                                             $cale.="<span class='time'>all day</span>";
                                                             $cale.="</div>";
                                                     }
                                             }
             
                                         // now do all the half hour slots for the day
             
                                             foreach ($this->times as $t)
                                             {
                                                 // time as number
                                                     $tnum=str_replace(':','',$t['time']);
             
                                                 // highlight now
                                                     $extra_class=
                                                     (   $this->now['time_numeric']>=$tnum &&
                                                         $this->now['time_numeric']<=$tnum+29 &&
                                                         $this->now['numeric']==$k) ? ' now ' : '';
             
                                                 // open the half hour output slot - only if there is an event or its high detail
                                                     $cale.="<div id='time_".$tnum."' class='".$extra_class." time_".$tnum."'>";
                                                     $cale.="<span class='time'>".$t['label']."</span>";
                                                     $cale.="</div>";
                                             }
                                     }
                                     else
                                     {
                                         // events - just normal output for months
                                             if ('month'==$cgran)
                                             {
                                                 $view_link="";
                                                 $event_counter=0;
                                             }
                                             else
                                             {
                                                 $cale.="<a class='bview' href='/".$reload_url."/".$link_date."'>vw</a>";
                                             }
                                     }
             
                                 // close day
                                     $cale.="</div>";
             
                                 // close month
                                     if ($d==days_in_month($m,$y))
                                     {
                                         $cale.="</div>";
                                     }*/
         }
     }
     /* BENCHMARK */
     $this->benchmark->mark('func_get_calendar_end');
     return $cal;
 }
Exemple #12
0
/**
 * Calculates when the day appears in specific month
 *
 * @package core
 * @category time
 * @param int $startday starting day of the month
 * @param int $weekday The day when week starts (normally taken from user preferences)
 * @param int $month The month whose day is sought
 * @param int $year The year of the month whose day is sought
 * @return int
 */
function find_day_in_month($startday, $weekday, $month, $year)
{
    $calendartype = \core_calendar\type_factory::get_calendar_instance();
    $daysinmonth = days_in_month($month, $year);
    $daysinweek = count($calendartype->get_weekdays());
    if ($weekday == -1) {
        // Don't care about weekday, so return:
        //    abs($startday) if $startday != -1
        //    $daysinmonth otherwise.
        return $startday == -1 ? $daysinmonth : abs($startday);
    }
    // From now on we 're looking for a specific weekday.
    // Give "end of month" its actual value, since we know it.
    if ($startday == -1) {
        $startday = -1 * $daysinmonth;
    }
    // Starting from day $startday, the sign is the direction.
    if ($startday < 1) {
        $startday = abs($startday);
        $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
        // This is the last such weekday of the month.
        $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
        if ($lastinmonth > $daysinmonth) {
            $lastinmonth -= $daysinweek;
        }
        // Find the first such weekday <= $startday.
        while ($lastinmonth > $startday) {
            $lastinmonth -= $daysinweek;
        }
        return $lastinmonth;
    } else {
        $indexweekday = dayofweek($startday, $month, $year);
        $diff = $weekday - $indexweekday;
        if ($diff < 0) {
            $diff += $daysinweek;
        }
        // This is the first such weekday of the month equal to or after $startday.
        $firstfromindex = $startday + $diff;
        return $firstfromindex;
    }
}
 /**
  * Fetch Days in Month
  *
  * Returns the number of days for the given month/year
  * Takes leap years into consideration
  *
  * @access	public
  * @param	string
  * @param	string
  * @return	int
  */
 function fetch_days_in_month($month, $year)
 {
     ee()->load->library('logger');
     ee()->logger->deprecated('2.6', 'Date helper\'s days_in_month()');
     ee()->load->helper('date');
     return days_in_month($month, $year);
 }
 public function add_cells($cells, $start_year, $end)
 {
     /* BENCHMARK */
     $this->benchmark->mark('func_add_cells_start');
     for ($y = $start_year; $y < 2100; $y++) {
         for ($m = 1; $m < 13; $m++) {
             // tell the array which month day it is
             $month_day_count = array('1' => 0, '2' => 0, '3' => 0, '4' => 0, '5' => 0, '6' => 0, '7' => 0);
             if ($y >= $start_year) {
                 for ($d = 1; $d <= days_in_month($m, $y); $d++) {
                     // format with leading zeros
                     if ($d < 10 ? $day = '0' . $d : ($day = $d)) {
                     }
                     if ($m < 10 ? $month = '0' . $m : ($month = $m)) {
                     }
                     // count the days in the month
                     $day_num = format_date($y . "-" . $month . "-" . $day, 'N');
                     $month_day_count[$day_num]++;
                     // add new cell to calendar - only if one doesn't already exist
                     if (!isset($cells[$y . $month . $day])) {
                         $cells[$y . $month . $day] = array('e' => array(), 'dn' => $day_num, 'md' => $month_day_count[$day_num] . " " . $day_num, 'x' => array());
                     }
                     // break if we have reached the last day
                     if ($y . $month . $day == $end) {
                         break 3;
                     }
                 }
             }
         }
     }
     return $cells;
     /* BENCHMARK */
     $this->benchmark->mark('func_add_cells_end');
 }
Exemple #15
0
 function ajax_refresh_subtotal()
 {
     $rid = $this->input->get('hosting_id');
     $checkin = $this->input->get('checkin');
     $checkout = $this->input->get('checkout');
     $guests = $this->input->get('number_of_guests');
     $res = array();
     $checkin_ts = strtotime($checkin);
     $checkout_ts = strtotime($checkout);
     $first_day_weekly = strtotime('-' . date('w', $checkin_ts) . ' day', $checkin_ts);
     $first_day_monthly = mktime(0, 0, 0, date('m', $checkin_ts), 1, date('Y', $checkin_ts));
     $nights = ($checkout_ts - $checkin_ts) / 86400;
     $room = $this->rooms_model->get_room_prices($rid);
     // TODO Translate
     if (!$room) {
         $res['reason_message'] = 'Property not exists';
     }
     $room = $room[0];
     if (!$room->active) {
         $res['reason_message'] = 'Property turend off';
     } else {
         if ($nights < $room->min_nights) {
             $res['reason_message'] = 'Min nights is ' . $room->min_nights;
         } else {
             if ($nights > $room->max_nights) {
                 $res['reason_message'] = 'Max nights is ' . $room->max_nights;
             } else {
                 if ($guests > $room->person_capacity) {
                     $res['reason_message'] = 'Max guests is ' . $room->person_capacity;
                 }
             }
         }
     }
     if (!empty($res['reason_message'])) {
         $res['available'] = FALSE;
         echo json_encode($res);
         return;
     }
     $this->load->model('calendar_model');
     $this->load->helper('date');
     $daily_list = $this->calendar_model->get_daily($rid, $checkin, $checkout);
     if (!empty($daily_list)) {
         foreach ($daily_list as $i) {
             if (!$i->available) {
                 $res['available'] = FALSE;
                 $res['reason_message'] = 'Those dates are not available';
                 // TODO translate
                 $res['daily_list'] = $daily_list;
                 echo json_encode($res);
                 return;
             }
         }
     }
     $d = $m = $w = 0;
     $monthly_price_default = $room->monthly_price_native > 0 ? $room->monthly_price_native : $room->price_native;
     $weekly_price_default = $room->weekly_price_native > 0 ? $room->weekly_price_native : $room->price_native;
     if ($nights >= 28) {
         $monthly_list = $this->calendar_model->get_monthly($rid, $first_day_monthly, $checkout);
         $res['monthly_list'] = $monthly_list;
         // for debug
         $days_in_month = days_in_month(date('m', $checkin_ts), date('Y', $checkin_ts));
         if (!empty($monthly_list[0]) && strtotime($monthly_list[0]->date) < $checkin_ts) {
             $monthly_price = round($monthly_list[$m++]->price / $days_in_month, 2);
         } else {
             $monthly_price = round($room->monthly_price_native / $days_in_month, 2);
         }
         // TODO: exchange
     }
     if ($nights >= 7) {
         $weekly_list = $this->calendar_model->get_weekly($rid, $first_day_weekly, $checkout);
         $res['weekly_list'] = $weekly_list;
         // for debug
         if (!empty($weekly_list[0]) && strtotime($weekly_list[0]->date) < $checkin_ts) {
             $weekly_price = round($weekly_list[$w++]->price / 7, 2);
         } else {
             $weekly_price = round($room->weekly_price_native / 7, 2);
         }
         // TODO: exchange
     }
     $total_price = 0;
     for ($i = $checkin_ts, $d; $i <= $checkout_ts; $i += 86400) {
         // 가격기준 정하기 (월/주/일)
         if (isset($montly_price) && date('m', $i) == 1) {
             unset($monthly_price);
             $days_in_month = days_in_month(time('m', $i), time('Y', $i));
             if (!empty($monthly_list[$m]) && strtotime($monthly_list[$m]) == $i) {
                 $monthly_price = round($monthly_list[$m++]->price / $days_in_month, 2);
             } else {
                 $monthly_price = round($room->monthly_price_native / $days_in_month, 2);
             }
             // TODO: exchange
         } else {
             if (isset($weekly_price) && date('w', $i) == 0) {
                 unset($weekly_price);
                 if (!empty($weekly_list[$w]) && strtotime($weekly_list[$w]->date) == $i) {
                     $weekly_price = round($weekly_list[$w++]->price / 7, 2);
                 } else {
                     $weekly_price = round($room->weekly_price_native / 7, 2);
                 }
                 // TODO: exchange
             }
         }
         if (isset($monthly_price)) {
             $total_price += $monthly_price;
         } else {
             if (isset($weekly_price)) {
                 $total_price += $weekly_price;
             } else {
                 if (!empty($daily_list[$d]) && strtotime($daily_list[$d]->date == $i)) {
                     $total_price += $daily_list[$d++]->price;
                 } else {
                     $total_price += $room->price_native;
                 }
             }
         }
         // TODO: exchange
     }
     $res['nights'] = $nights;
     $res['available'] = TRUE;
     $res['price_per_night'] = CURRENT_CURRENCY_SYMBOL . round($total_price / $nights, 0);
     if ($guests > $room->guests_included) {
         $total_price += ($guests - $room->guests_included) * $nights * $room->price_for_extra_person_native;
         // TODO exchange
     }
     if ($room->extras_price_native > 0) {
         $total_price += $room->extras_price_native;
         // TODO exchange
     }
     $res['service_fee'] = CURRENT_CURRENCY_SYMBOL . round($total_price / 10);
     // TODO determine service fee policy
     $res['total_price'] = CURRENT_CURRENCY_SYMBOL . $total_price;
     echo json_encode($res);
 }
function displayCalendar($formframes, $mainforms = "", $viewHandles, $dateHandles, $filters, $viewPrefixes, $scopes, $hidden, $type = "month", $start = "", $multiPageData = "")
{
    global $xoopsDB, $xoopsUser;
    global $xoopsTpl;
    // Set some required variables
    $mid = getFormulizeModId();
    for ($i = 0; $i < count($formframes); $i++) {
        unset($fid);
        unset($frid);
        if ($mainforms[$i]) {
            list($fid, $frid) = getFormFramework($formframes[$i], $mainforms[$i]);
        } else {
            list($fid, $frid) = getFormFramework($formframes[$i]);
        }
        $fids[] = $fid;
        $frids[] = $frid;
    }
    $gperm_handler =& xoops_gethandler('groupperm');
    $member_handler =& xoops_gethandler('member');
    $groups = $xoopsUser ? $xoopsUser->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
    $uid = $xoopsUser ? $xoopsUser->getVar('uid') : 0;
    foreach ($fids as $thisFid) {
        // check that the user is allowed to see all the fids
        if (!($scheck = security_check($thisFid, "", $uid, "", $groups, $mid, $gperm_handler))) {
            print "<p>" . _NO_PERM . "</p>";
            return;
        }
    }
    $currentURL = getCurrentURL();
    // get the current view, ie: the month
    if ($_POST['calview']) {
        // if we're recieving a view from a form submission...
        $settings['calview'] = $_POST['calview'];
    } else {
        if (!$start) {
            // nothing passed from form, and no default value specified, so use current date
            $today = getDate();
            if ($today['mon'] < 10) {
                $today['mon'] = "0" . $today['mon'];
            }
            $settings['calview'] = $today['year'] . "-" . $today['mon'];
        } else {
            $settings['calview'] = $start;
        }
    }
    $settings['calfrid'] = $_POST['calfrid'];
    $settings['calfid'] = $_POST['calfid'];
    $settings['calhidden'] = $hidden;
    // check to see if a switch to a form has been requested
    $settings['ventry'] = $_POST['ventry'];
    if ($settings['ventry']) {
        if ($_POST['ventry'] == "addnew") {
            $this_ent = "";
            $dateOverride = $_POST['adddate'];
        } elseif ($_POST['ventry'] == "proxy") {
            // support for proxies not currently written
            $this_ent = "proxy";
        } else {
            $this_ent = $_POST['ventry'];
        }
        if ($_POST['calfrid']) {
            if (isset($multiPageData[$_POST['calfid']])) {
                if (is_numeric($multiPageData[$_POST['calfid']])) {
                    // numeric value indicates a screen id
                    $screenData = readScreenId($multiPageData[$_POST['calfid']], $_POST['calfid']);
                    if (is_array($screenData)) {
                        $multiPageData = $screenData;
                    }
                }
                include_once XOOPS_ROOT_PATH . "/modules/formulize/include/formdisplaypages.php";
                displayFormPages($_POST['calfrid'], $this_ent, $_POST['calfid'], $multiPageData[$_POST['calfid']]['pages'], $multiPageData[$_POST['calfid']]['conditions'], $multiPageData[$_POST['calfid']]['introtext'], $multiPageData[$_POST['calfid']]['thankstext'], $currentURL, _formulize_CAL_RETURNFROMMULTI, $settings, $dateOverride, $multiPageData[$_POST['calfid']]['printall']);
            } else {
                displayForm($_POST['calfrid'], $this_ent, $_POST['calfid'], $currentURL, "", $settings, "", $dateOverride, 1, 1);
                // first "" is the done text, second is the onetoonetitles, last two 1s are the overrides for multi form behaviour
            }
            return;
        } else {
            if (isset($multiPageData[$_POST['calfid']])) {
                if (is_numeric($multiPageData[$_POST['calfid']])) {
                    // numeric value indicates a screen id
                    $screenData = readScreenId($multiPageData[$_POST['calfid']], $_POST['calfid']);
                    if (is_array($screenData)) {
                        $multiPageData = $screenData;
                    }
                }
                include_once XOOPS_ROOT_PATH . "/modules/formulize/include/formdisplaypages.php";
                displayFormPages($_POST['calfid'], $this_ent, "", $multiPageData[$_POST['calfid']]['pages'], $multiPageData[$_POST['calfid']]['conditions'], $multiPageData[$_POST['calfid']]['introtext'], $multiPageData[$_POST['calfid']]['thankstext'], $currentURL, _formulize_CAL_RETURNFROMMULTI, $settings, $dateOverride, $multiPageData[$_POST['calfid']]['printall']);
            } else {
                displayForm($_POST['calfid'], $this_ent, "", $currentURL, "", $settings, "", $dateOverride, 1, 1);
                // "" is the done text
            }
            return;
        }
    }
    // handle deletion if requested, added sept 18 2005
    if ($_POST['delentry']) {
        deleteEntry($_POST['delentry'], $_POST['delfrid'], $_POST['delfid'], $gperm_handler, $member_handler, $mid);
    }
    // get the data for all the fids
    // 1. convert the scopes for each one
    // 2. do the extraction (filter by calview)
    include_once XOOPS_ROOT_PATH . "/modules/formulize/include/extract.php";
    for ($i = 0; $i < count($fids); $i++) {
        $scope = "";
        if ($scopes[$i]) {
            list($scope, $throwAwayCurrentView) = buildScope($scopes[$i], $member_handler, $gperm_handler, $uid, $groups, $fids[$i], $mid);
        }
        if (is_array($dateHandles[$i])) {
            $dateField = $dateHandles[$i][0];
            $dateField2 = $dateHandles[$i][1];
        } else {
            $dateField = $dateHandles[$i];
            $dateField2 = "";
        }
        if (!$frids[$i]) {
            $filterDH = $dateField;
            $filterDH2 = $dateField2;
        } else {
            $filterDH = $dateField;
            $filterDH2 = $dateField2;
        }
        // new, complex filter format is:
        // $filter[0][0] -- andor setting for filter 0
        // $filter[0][1] -- filter for filter 0
        $filter = array();
        $filter[0][0] = "OR";
        $filter[0][1] = $filterDH . "/**/" . $settings['calview'];
        if ($filterDH2) {
            $filter[0][1] .= "][" . $filterDH2 . "/**/" . $settings['calview'];
        }
        if ($filters[$i]) {
            $filter[1][0] = "AND";
            $filter[1][1] = $filters[$i];
        }
        $data[$i] = getData($frids[$i], $fids[$i], $filter, "AND", $scope);
        $data[$i] = resultSort($data[$i], $dateField);
    }
    // need the formatting magic to go here, to whip it all into a nice calendar
    // basic display of data is below
    // demonstrates linking to a form for updating/viewing that entry
    // demonstrates altering the calview setting to change months
    // need to do something a little more complex for adding a new entry, since we have to know for which fid/frid pair the add operation is being requested.
    // probably best to leave out adding for now and leave it as a future feature.  It can always be custom added within a pageworks page if necessary for a particular calendar
    $rights = $gperm_handler->checkRight("add_own_entry", $fid, $groups, $mid);
    // information to pass to the template
    global $calendarData;
    // initialize language constants
    global $arrayMonthNames;
    global $arrayWeekNames;
    global $dateMonthStartDay;
    $arrayMonthNames = array(_formulize_CAL_MONTH_01, _formulize_CAL_MONTH_02, _formulize_CAL_MONTH_03, _formulize_CAL_MONTH_04, _formulize_CAL_MONTH_05, _formulize_CAL_MONTH_06, _formulize_CAL_MONTH_07, _formulize_CAL_MONTH_08, _formulize_CAL_MONTH_09, _formulize_CAL_MONTH_10, _formulize_CAL_MONTH_11, _formulize_CAL_MONTH_12);
    if ($type == "mini_month") {
        $arrayWeekNames = array(_formulize_CAL_WEEK_1_3ABRV, _formulize_CAL_WEEK_2_3ABRV, _formulize_CAL_WEEK_3_3ABRV, _formulize_CAL_WEEK_4_3ABRV, _formulize_CAL_WEEK_5_3ABRV, _formulize_CAL_WEEK_6_3ABRV, _formulize_CAL_WEEK_7_3ABRV);
    } else {
        $arrayWeekNames = array(_formulize_CAL_WEEK_1, _formulize_CAL_WEEK_2, _formulize_CAL_WEEK_3, _formulize_CAL_WEEK_4, _formulize_CAL_WEEK_5, _formulize_CAL_WEEK_6, _formulize_CAL_WEEK_7);
    }
    // convert string date into parts
    $arrayDate = getdate(strtotime($settings['calview'] . "-01"));
    $dateMonth = $arrayDate["mon"];
    $dateDay = $arrayDate["mday"];
    $dateYear = $arrayDate["year"];
    // get the number of days in the month.
    $dateMonthDays = days_in_month($dateMonth, $dateYear);
    // get the month's first week start day.
    $dateMonthStartDay = $arrayDate["wday"];
    // get the number of weeks.
    $dateMonthWeeks = week_in_month($dateMonthDays) + 1;
    // intialize MONTH template information
    // each cell is an array:
    // [0] - is control information, where each entry is an array:
    //     [0] - day number
    //     [1] - send date
    // [1] - is an array containing all items, where each item is also an array:
    //     [0] - $ids[0]
    //     [1] - $frids[$i]
    //     [2] - $fids[$i]
    //     [3] - $textToDisplay
    //     [4] - true/false based on user's right to delete this item (based on either delete own, or delete others permission)
    if ($type == "month" || $type == "mini_month" || $type == "micro_month") {
        // initialize grid: convert the data set into a grid of 7 columns for
        //  days and a row for each week
        $displayDay = "";
        for ($intWeeks = 0; $intWeeks < $dateMonthWeeks; $intWeeks++) {
            $calendarData[$intWeeks] = array();
            for ($intDays = 0; $intDays < 7; $intDays++) {
                // check to see if the processing day is the start day.
                if ($intWeeks == 0 && $displayDay == "") {
                    if ($intDays == $dateMonthStartDay) {
                        $displayDay = 1;
                    }
                } else {
                    if ($displayDay != "") {
                        $displayDay++;
                        if ($displayDay > $dateMonthDays) {
                            $displayDay = "";
                        }
                    }
                }
                $calendarData[$intWeeks][$intDays] = array();
                $calendarData[$intWeeks][$intDays][0][0] = $displayDay;
                $calendarData[$intWeeks][$intDays][0][1] = $dateYear . "-" . $dateMonth . "-" . ($displayDay < 10 ? "0" . $displayDay : $displayDay);
                //$calendarData[$intWeeks][$intDays][1] = array();
            }
        }
        // Initialize template variables
        $xoopsTpl->assign('previousMonth', $dateMonth - 1 < 1 ? $dateYear - 1 . "-12" : $dateYear . "-" . ($dateMonth - 1 < 10 ? "0" . ($dateMonth - 1) : $dateMonth - 1));
        $xoopsTpl->assign('nextMonth', $dateMonth + 1 > 12 ? $dateYear + 1 . "-01" : $dateYear . "-" . ($dateMonth + 1 < 10 ? "0" . ($dateMonth + 1) : $dateMonth + 1));
        $monthSelector = array();
        $numberOfMonths = count($arrayMonthNames);
        for ($intMonth = 0; $intMonth < $numberOfMonths; $intMonth++) {
            $monthName = $arrayMonthNames[$intMonth];
            $monthSelector[$intMonth + 1 < 10 ? "0" . ($intMonth + 1) : $intMonth + 1] = $monthName;
        }
        $xoopsTpl->assign('monthSelector', $monthSelector);
        $yearSelector = array();
        $startYear = $dateYear - 4;
        $endYear = $dateYear + 3;
        for ($intYear = $startYear; $intYear <= $endYear; $intYear++) {
            $yearSelector[] = $intYear;
        }
        $xoopsTpl->assign('yearSelector', $yearSelector);
    }
    // process data set(s)
    for ($i = 0; $i < count($data); $i++) {
        foreach ($data[$i] as $id => $entry) {
            if (!$frids[$i]) {
                if (is_array($viewHandles[$i])) {
                    $formhandle = getFormHandleFromEntry($entry, $viewHandles[$i][0]);
                } else {
                    $formhandle = getFormHandleFromEntry($entry, $viewHandles[$i]);
                }
            } else {
                $formhandle = $mainforms[$i];
            }
            $ids = internalRecordIds($entry, $formhandle);
            if (is_array($viewHandles[$i])) {
                $needsep = 0;
                // make sure that no data is keep from previous processing
                $textToDisplay = "";
                foreach ($viewHandles[$i] as $thisVH) {
                    if ($needsep) {
                        $textToDisplay .= ", ";
                    }
                    $needsep = 1;
                    $textToDisplay .= display($entry, $thisVH);
                }
            } else {
                $textToDisplay = display($entry, $viewHandles[$i]);
            }
            if ($viewPrefixes[$i]) {
                $textToDisplay = $viewPrefixes[$i] . $textToDisplay;
            }
            $calendarDataItem = array();
            $calendarDataItem[0] = $ids[0];
            $calendarDataItem[1] = $frids[$i];
            $calendarDataItem[2] = $fids[$i];
            $calendarDataItem[3] = $textToDisplay;
            $calendarDataItem[4] = ($i == 0 and formulizePermHandler::user_can_delete_entry($fids[$i], display($entry, "uid"), $ids[0]));
            if ($type == "month" || $type == "mini_month" || $type == "micro_month") {
                if (is_array($dateHandles[$i])) {
                    $startValue = display($entry, $dateHandles[$i][0]);
                    $endValue = display($entry, $dateHandles[$i][1]);
                    if ($startValue && $endValue) {
                        $startDate = strtotime($startValue);
                        $endDate = strtotime($endValue);
                        for ($x = $startDate; $x <= $endDate; $x = $x + 86400) {
                            $arrayDate = getdate($x);
                            if ($arrayDate["mon"] == $dateMonth) {
                                $calendarData = assignItem($arrayDate, $calendarDataItem, $calendarData);
                            }
                        }
                    } else {
                        if ($startValue) {
                            $startDate = strtotime($startValue);
                            $arrayDate = getdate($startDate);
                            $calendarData = assignItem($arrayDate, $calendarDataItem, $calendarData);
                        } else {
                            $endDate = strtotime($endValue);
                            $arrayDate = getdate($endDate);
                            $calendarData = assignItem($arrayDate, $calendarDataItem, $calendarData);
                        }
                    }
                } else {
                    $currentDate = display($entry, $dateHandles[$i]);
                    $arrayDate = getdate(strtotime($currentDate));
                    $calendarData = assignItem($arrayDate, $calendarDataItem, $calendarData);
                }
            }
        }
    }
    // Initialize common template variables
    $xoopsTpl->assign('cal_type', $type);
    $xoopsTpl->assign('rights', $rights);
    $xoopsTpl->assign('frids', $frids[0]);
    $xoopsTpl->assign('fids', $fids[0]);
    $xoopsTpl->assign('addItem', _formulize_CAL_ADD_ITEM);
    $xoopsTpl->assign('rowStyleEven', true);
    $xoopsTpl->assign('MonthNames', $arrayMonthNames);
    $xoopsTpl->assign('WeekNames', $arrayWeekNames);
    $xoopsTpl->assign('dateMonthZeroIndex', $dateMonth - 1);
    $xoopsTpl->assign('dateMonth', $dateMonth);
    $xoopsTpl->assign('dateYear', $dateYear);
    $xoopsTpl->assign('currentURL', $currentURL);
    $xoopsTpl->assign('hidden', $hidden);
    $xoopsTpl->assign('calview', $settings['calview']);
    $xoopsTpl->assign('calendarData', $calendarData);
    $xoopsTpl->assign('delete', _formulize_DELETE);
    $xoopsTpl->assign('delconf', _formulize_DELCONF);
    // force template to be drawn
    $xoopsTpl->display("db:calendar_" . $type . ".html");
}
Exemple #17
0
 function analisis($mes = null)
 {
     if (empty($mes)) {
         return '';
     }
     $this->load->helper('date');
     $udia = days_in_month(substr($mes, 4), substr($mes, 0, 4));
     $fdesde = $mes . '01';
     $fhasta = $mes . $udia;
     $mSQL = "SELECT a.usuario,COUNT(*) AS reg , a.tipo FROM sitemslog AS a\n\t\tWHERE a.fecha BETWEEN {$fdesde} AND {$fhasta}\n\t\tGROUP BY a.usuario,a.tipo\n\t\tUNION ALL\n\t\tSELECT usuario,COUNT(*) AS reg,'FACTURADO' FROM sitems \n\t\tWHERE fecha BETWEEN {$fdesde} AND {$fhasta} GROUP BY usuario";
     $query = $this->db->query($mSQL);
     foreach ($query->result() as $row) {
         $campo = strtolower($row->tipo);
         $usr = $this->db->escape($row->usuario);
         $reg = $this->db->escape($row->reg);
         $sql = "INSERT INTO sitemsest (periodo,usuario,{$campo}) VALUES ({$mes},{$usr},{$reg}) ON DUPLICATE KEY UPDATE {$campo}={$reg}";
         $ban = $this->db->simple_query($sql);
     }
 }
Exemple #18
0
    function filteredgrid()
    {
        $this->rapyd->load("datafilter2", "datagrid");
        $mSPRV = array('tabla' => 'sprv', 'columnas' => array('proveed' => 'C&oacute;odigo', 'nombre' => 'Nombre', 'contacto' => 'Contacto'), 'filtro' => array('proveed' => 'C&oacute;digo', 'nombre' => 'Nombre'), 'retornar' => array('proveed' => 'proveed'), 'titulo' => 'Buscar Proveedor');
        $bSPRV = $this->datasis->modbus($mSPRV);
        $link2 = site_url('inventario/common/get_linea');
        $link3 = site_url('inventario/common/get_grupo');
        $script = '
		$(document).ready(function(){

			$("#depto").change(function(){
				depto();
				$.post("' . $link2 . '",{ depto:$(this).val() },function(data){$("#linea").html(data);})
				$.post("' . $link3 . '",{ linea:"" },function(data){$("#grupo").html(data);})
			});
			$("#linea").change(function(){
				linea();
				$.post("' . $link3 . '",{ linea:$(this).val() },function(data){$("#grupo").html(data);})
			});

			$("#grupo").change(function(){
				grupo();
			});
			depto();
			linea();
			grupo();
		});

		function depto(){
			if($("#depto").val()!=""){
				$("#nom_depto").attr("disabled","disabled");
			}
			else{
				$("#nom_depto").attr("disabled","");
			}
		}

		function linea(){
			if($("#linea").val()!=""){
				$("#nom_linea").attr("disabled","disabled");
			}
			else{
				$("#nom_linea").attr("disabled","");
			}
		}

		function grupo(){
			if($("#grupo").val()!=""){
				$("#nom_grupo").attr("disabled","disabled");
			}
			else{
				$("#nom_grupo").attr("disabled","");
			}
		}
		';
        //filter
        $filter = new DataFilter2("Filtro por Producto");
        $filter->script($script);
        $filter->db->select('a.codigo');
        $filter->db->select('a.descrip');
        $filter->db->select('s.exmin');
        $filter->db->select('s.id');
        $filter->db->from('eventas as a');
        $filter->db->join("grup as b", "a.grupo=b.grupo ", 'LEFT');
        $filter->db->join("sinv as s", "a.codigo=s.codigo ", 'LEFT');
        $filter->db->groupby('a.codigo');
        $filter->fechad = new dateonlyField("Desde", "fechad", 'm/Y');
        $filter->fechah = new dateonlyField("Hasta", "fechah", 'm/Y');
        $filter->fechad->dbformat = 'Y-m-';
        $filter->fechah->dbformat = 'Y-m-';
        $filter->fechah->rule = "required";
        $filter->fechad->rule = "required";
        $filter->fechad->clause = $filter->fechah->clause = '';
        $filter->fechad->insertValue = date("Y-m-d", mktime(0, 0, 0, date('m') - 12, date('j'), date('Y')));
        $filter->fechah->insertValue = date("Y-m-d");
        $filter->codigo = new inputField("C&oacute;digo", "codigo");
        $filter->codigo->size = 25;
        /*$filter->descrip = new inputField("Descripci&oacute;n", "descrip");
        		$filter->descrip->db_name='CONCAT_WS(" ",a.descrip,a.descrip2)';
        		$filter->descrip -> size=25;
        
        		$filter->tipo = new dropdownField("Tipo", "tipo");
        		$filter->tipo->db_name=("a.tipo");
        		$filter->tipo->option("","Todos");
        		$filter->tipo->option("Articulo","Art&iacute;culo");
        		$filter->tipo->option("Servicio","Servicio");
        		$filter->tipo->option("Descartar","Descartar");
        		$filter->tipo->option("Consumo","Consumo");
        		$filter->tipo->option("Fraccion","Fracci&oacute;n");
        		$filter->tipo ->style='width:220px;';
        
        		$filter->clave = new inputField("Clave", "clave");
        		$filter->clave -> size=25;
        
        		$filter->activo = new dropdownField("Activo", "activo");
        		$filter->activo->option("","");
        		$filter->activo->option("S","Si");
        		$filter->activo->option("N","No");
        		$filter->activo ->style='width:220px;';
        
        		$filter->proveed = new inputField("Proveedor", "proveed");
        		$filter->proveed->append($bSPRV);
        		$filter->proveed->clause ="in";
        		$filter->proveed->db_name='( a.prov1, a.prov2, a.prov3 )';
        		$filter->proveed -> size=25;
        
        		$filter->depto2 = new inputField("Departamento", "nom_depto");
        		$filter->depto2->db_name="d.descrip";
        		$filter->depto2 -> size=10;
        
        		$filter->depto = new dropdownField("Departamento","depto");
        		$filter->depto->db_name="d.depto";
        		$filter->depto->option("","Seleccione un Departamento");
        		$filter->depto->options("SELECT depto, descrip FROM dpto WHERE tipo='I' ORDER BY depto");
        		$filter->depto->in="depto2";
        
        		$filter->linea = new inputField("Linea", "nom_linea");
        		$filter->linea->db_name="c.descrip";
        		$filter->linea -> size=10;
        
        		$filter->linea2 = new dropdownField("L&iacute;nea","linea");
        		$filter->linea2->db_name="c.linea";
        		$filter->linea2->option("","Seleccione un Departamento primero");
        		$filter->linea2->in="linea";
        		$depto=$filter->getval('depto');
        		if($depto!==FALSE){
        			$filter->linea2->options("SELECT linea, descrip FROM line WHERE depto='$depto' ORDER BY descrip");
        		}else{
        			$filter->linea2->option("","Seleccione un Departamento primero");
        		}
        
        		$filter->grupo2 = new inputField("Grupo", "nom_grupo");
        		$filter->grupo2->db_name="b.nom_grup";
        		$filter->grupo2 -> size=10;
        
        		$filter->grupo = new dropdownField("Grupo", "grupo");
        		$filter->grupo->db_name="b.grupo";
        		$filter->grupo->option("","Seleccione una L&iacute;nea primero");
        		$filter->grupo->in="grupo2";
        		$linea=$filter->getval('linea2');
        		if($linea!==FALSE){
        			$filter->grupo->options("SELECT grupo, nom_grup FROM grup WHERE linea='$linea' ORDER BY nom_grup");
        		}else{
        			$filter->grupo->option("","Seleccione un Departamento primero");
        		}
        
        		$filter->marca = new dropdownField("Marca", "marca");
        		$filter->marca->option("","");
        		$filter->marca->options("SELECT TRIM(marca) AS clave, TRIM(marca) AS valor FROM marc ORDER BY marca");
        		$filter->marca -> style='width:220px;';
        		*/
        $filter->buttons("reset", "search");
        $filter->build();
        $uri = "inventario/sinv/dataedit/show/<#codigo#>";
        function minimos($param)
        {
            $data = func_get_args();
            $valor = array_sum($data) - min($data) - max($data);
            return ceil($valor / (count($data) - 2));
        }
        $tabla = '';
        if ($filter->is_valid()) {
            $udia = days_in_month(substr($filter->fechah->newValue, 4), substr($filter->fechah->newValue, 0, 4));
            $fechad = $filter->fechad->newValue . '01';
            $fechah = $filter->fechah->newValue . $udia;
            $filter->db->where('a.fecha >=', $fechad);
            $filter->db->where('a.fecha <=', $fechah);
            $datetime1 = new DateTime($fechad);
            $datetime2 = new DateTime($fechah);
            $interval = $datetime1->diff($datetime2);
            $ffechad = explode('-', $fechad);
            $grid = new DataGrid("Lista de Art&iacute;culos");
            $grid->order_by("codigo", "asc");
            $grid->use_function('minimos');
            $grid->per_page = 15;
            $grid->column("C&oacute;digo", 'codigo');
            $grid->column("Descripci&oacute;n", "descrip");
            $columncal = array();
            for ($i = 0; $i <= $interval->m + 1; $i++) {
                $mk = mktime(0, 0, 0, $ffechad[1] + $i, 1, $ffechad[0]);
                $udia = days_in_month(date('m', $mk), date('Y', $mk));
                $sqdesde = date("Y-m-d", $mk);
                $sqhasta = date("Y-m-", $mk) . $udia;
                $etiq = date("m/Y", $mk);
                $select = "SUM(cana*(fecha BETWEEN '{$sqdesde}' AND '{$sqhasta}')) AS '{$etiq}'";
                $filter->db->select($select);
                $grid->column($etiq, "<nformat><#{$etiq}#></nformat>", 'align=right');
                $columncal[] = "<#{$etiq}#>";
            }
            $grid->column('Promedio', '<nformat><minimos>' . implode('|', $columncal) . '</minimos></nformat>', 'align=right');
            $grid->column('Minimo', '<nformat><#exmin#></nformat>', 'align=right');
            $grid->column('&nbsp;', '<a href="javascript:actumin(\'<#id#>\',\'<minimos>' . implode('|', $columncal) . '</minimos>\')" >Actualizar</a>', 'align=right');
            $grid->build();
            $tabla = $grid->output;
        }
        $url = site_url('inventario/comparativo/actumin/') . '/';
        $data['script'] = '<script language="javascript" type="text/javascript">
		function actumin(id,val){
			$.get("' . $url . '"+id+"/"+val, function(data) {
				alert(data);
			});
		}
		</script>';
        $data['content'] = $filter->output . $tabla;
        $data['title'] = "<h1>Comparativo de M&iacute;nimos de Inventario</h1>";
        $data["head"] = script("jquery.pack.js") . script("plugins/jquery.numeric.pack.js") . script("plugins/jquery.floatnumber.js") . script("sinvmaes2.js") . $this->rapyd->get_head();
        $this->load->view('view_ventanas', $data);
    }
Exemple #19
0
 function resumen()
 {
     $this->rapyd->load('datagrid2', 'datafilter', 'datatable');
     $form = new DataForm("finanzas/resumendiario/resumen/process");
     $form->fecha = new dateonlyField("Fecha", "fecha");
     $form->fecha->insertValue = date("Y-m-d");
     $form->fecha->rule = "required|chfecha";
     $form->fecha->size = 12;
     $form->submit("btnsubmit", "Consultar");
     $form->build_form();
     if ($form->on_success()) {
         $this->fecha = $form->fecha->newValue;
     }
     $dbfecha = $this->db->escape($this->fecha);
     //***********************************
     //      RESUMEN DE CAJAS (RCAJ)
     //***********************************
     $grid = new DataGrid2("Resumen de Cajas");
     $grid->db->select(array("cajero", "ingreso AS venta", "recibido", "(ingreso - recibido) AS diferencia"));
     $grid->db->from("rcaj");
     $grid->db->where("fecha", $this->fecha);
     $grid->order_by("caja", "asc");
     //$grid->per_page = 15;
     $grid->column('Caja', 'cajero', "align='center'");
     $grid->column('Venta', '<nformat><#venta#></nformat>', "align='right'");
     $grid->column('Recibido', '<nformat><#recibido#></nformat>', "align='right'");
     $grid->column('Diferencia', '<nformat><#diferencia#></nformat>', "align='right'");
     $grid->totalizar("venta", "recibido", "diferencia");
     $grid->build();
     //***********************************
     //DISTRIBUCION DE LA COBRANZA (SFPA)
     //***********************************
     $grid2 = new DataGrid2('Distribuci&oacute;n de la cobranza');
     $grid2->db->select(array('a.tipo', 'b.nombre', 'sum(a.monto) AS monto', 'COUNT(*) AS cantidad'));
     $grid2->db->from('sfpa a');
     $grid2->db->join('tarjeta b', 'a.tipo=b.tipo');
     $grid2->db->where('f_factura', $this->fecha);
     $grid2->db->groupby('a.tipo');
     $grid2->order_by('a.tipo', 'asc');
     //$grid2->per_page = 15;
     $grid2->column('Tipo', '(<#tipo#>) <#nombre#>', "align='left'");
     $grid2->column('Cantidad', 'cantidad', "align='right'");
     $grid2->column('Monto', '<nformat><#monto#></nformat>', "align='right'");
     $grid2->totalizar('monto');
     $grid2->build();
     //***********************************
     //      VENTAS Y DEVOLUCIONES
     //***********************************
     function vdnom($tipo_doc, $referen)
     {
         $nombre = $tipo_doc == 'D' ? 'Devoluciones ' : 'Ventas ';
         $nombre .= $referen == 'E' ? 'al Contado' : 'a Credito';
         return $nombre;
     }
     $grid3 = new DataGrid2("Distribuci&oacute;n de la cobranza");
     $grid3->db->select(array('tipo_doc', 'referen', 'COUNT(*) AS cana', 'SUM(totals)*IF(tipo_doc = "D" ,-1,1) AS monto'));
     $grid3->db->from("sfac a");
     $grid3->db->where('referen <>', 'P');
     $grid3->db->where('fecha', $this->fecha);
     $grid3->db->groupby('tipo_doc');
     $grid3->db->groupby('referen');
     $grid3->use_function('vdnom');
     $grid3->column('Tipo', '<vdnom><#tipo_doc#>|<#referen#></vdnom>', "align='left'");
     $grid3->column('Cantidad', '<nformat><#cana#>|0</nformat>', "align='right'");
     $grid3->column('Monto', '<nformat><#monto#></nformat>', "align='right'");
     $grid3->totalizar('monto');
     $grid3->build();
     //***********************************
     //   RESUMEN DE VENTAS
     //***********************************
     $udia = days_in_month(substr($this->fecha, 4, 2), substr($this->fecha, 0, 4));
     $fdesde = substr($this->fecha, 0, 6) . '01';
     $fhasta = substr($this->fecha, 0, 6) . $udia;
     $ano = substr($this->fecha, 0, 4);
     $row1 = $this->datasis->damerow("SELECT COUNT(*) AS a,SUM(totals*(IF(tipo_doc = 'F',1,-1))) AS b FROM sfac WHERE tipo_doc <>'X' AND YEAR(fecha) = {$ano} AND fecha < {$dbfecha}");
     $row2 = $this->datasis->damerow("SELECT COUNT(*) AS a,SUM(totals*(IF(tipo_doc = 'F',1,-1))) AS b FROM sfac WHERE tipo_doc <>'X' AND fecha BETWEEN {$fdesde} AND {$fhasta}");
     $row3 = $this->datasis->damerow("SELECT COUNT(*) AS a,SUM(totals*(IF(tipo_doc = 'F',1,-1))) AS b FROM sfac WHERE tipo_doc <>'X' AND fecha = {$dbfecha}");
     $cost1 = $this->datasis->dameval("SELECT SUM(costo*cana*(IF(tipoa = 'F',1,-1))) AS a FROM sitems WHERE tipoa <>'X' AND YEAR(fecha) = {$ano} AND fecha < {$dbfecha}");
     $cost2 = $this->datasis->dameval("SELECT SUM(costo*cana*(IF(tipoa = 'F',1,-1))) AS a FROM sitems WHERE tipoa <>'X' AND fecha BETWEEN {$fdesde} AND {$dbfecha}");
     $cost3 = $this->datasis->dameval("SELECT SUM(costo*cana*(IF(tipoa = 'F',1,-1))) AS a FROM sitems WHERE tipoa <>'X' AND fecha = {$dbfecha}");
     if (empty($row1)) {
         $row1 = array('a' => 0, 'b' => 0);
     }
     if (empty($row2)) {
         $row2 = array('a' => 0, 'b' => 0);
     }
     if (empty($row3)) {
         $row3 = array('a' => 0, 'b' => 0);
     }
     $row1['c'] = $cost1;
     $row2['c'] = $cost2;
     $row3['c'] = $cost3;
     $rdata[0] = array('a' => $row1['a'], 'b' => $row1['b'], 'c' => $row1['c'], 'd' => $row1['b'] - $row1['c'], 'razon' => 'Ventas en lo que va de año');
     $rdata[1] = array('a' => $row2['a'], 'b' => $row2['b'], 'c' => $row2['c'], 'd' => $row2['b'] - $row2['c'], 'razon' => 'Ventas en lo que va de mes');
     $rdata[2] = array('a' => $row3['a'], 'b' => $row3['b'], 'c' => $row3['c'], 'd' => $row3['b'] - $row3['c'], 'razon' => 'Ventas de hoy');
     $grid8 = new DataGrid("Resumen de Ventas " . $this->fecha, $rdata);
     $grid8->column("Raz&oacute;n", "razon");
     $grid8->column("Cantidad", "a", "align='right'");
     $grid8->column("Costo", "<nformat><#c#></nformat>", "align='right'");
     $grid8->column("Monto", "<nformat><#b#></nformat>", "align='right'");
     $grid8->column("Margen", "<nformat><#d#></nformat>", "align='right'");
     $grid8->build();
     $rdata = array();
     //***********************************
     //   CUENTAS POR COBRAR (smov)
     //***********************************
     $grid4 = new DataGrid2('Cuentas por Cobrar');
     $grid4->db->select(array("c.gr_desc grupo", "SUM((a.monto-a.abonos)*IF(tipo_doc='AN',-1,1))saldo"));
     $grid4->db->from('smov a');
     $grid4->db->join('scli b', 'a.cod_cli = b.cliente');
     $grid4->db->join('grcl c', 'b.grupo = c.grupo');
     $grid4->db->where("a.tipo_doc IN ('FC','ND','GI','AN')");
     $grid4->db->groupby('c.gr_desc');
     $grid4->order_by("c.gr_desc", "asc");
     //$grid4->per_page = 15;
     $grid4->column('Grupo de Clientes', 'grupo', "align='left'");
     $grid4->column('Monto', '<nformat><#saldo#></nformat>', "align='right'");
     $grid4->totalizar('saldo');
     $grid4->build();
     //***********************************
     //            GASTOS
     //***********************************
     $row = $this->datasis->dameval("SELECT SUM(montotot) AS a FROM scst WHERE tipo_doc = 'FC' AND recep = {$dbfecha}");
     $row2 = $this->datasis->dameval("SELECT SUM(totbruto) AS a FROM gser WHERE tipo_doc = 'FC' AND fecha = {$dbfecha}");
     $rdata[0] = array('nombre' => 'Total de Compras', 'monto' => $row);
     $rdata[1] = array('nombre' => 'Total de Gastos', 'monto' => $row2);
     $grid7 = new DataGrid2('Total Compras y Gastos de Hoy', $rdata);
     $grid7->column('Raz&oacute;n', 'nombre');
     $grid7->column('Monto', '<nformat><#monto#></nformat>', "align='right'");
     $grid7->totalizar('monto');
     $grid7->build();
     //***********************************
     //   CUENTAS POR PAGAR (sprm)
     //***********************************
     $grid5 = new DataGrid2('Cuentas por Pagar');
     $grid5->db->select(array('c.gr_desc grupo', "SUM((a.monto-a.abonos)*IF(tipo_doc = 'AN',-1,1)) saldo"));
     $grid5->db->from('sprm a');
     $grid5->db->join('sprv b', 'a.cod_prv = b.proveed');
     $grid5->db->join('grpr c', 'b.grupo = c.grupo');
     $grid5->db->where("a.tipo_doc IN ('FC','ND','GI','AN')");
     $grid5->db->groupby('c.gr_desc');
     $grid5->order_by('c.gr_desc', 'asc');
     //$grid5->per_page = 15;
     $grid5->column('Grupo de Proveedoores', 'grupo', "align='left'");
     $grid5->column('Monto', '<nformat><#saldo#></nformat>', "align='right'");
     $grid5->totalizar('saldo');
     $grid5->build();
     //***********************************
     //   PROMEDIO INVENTARIO (sinv)
     //***********************************
     $grid6 = new DataGrid2('Total de Inventario');
     $grid6->db->select(array('d.descrip AS descrip', 'SUM(a.pond*a.existen) AS suma'));
     $grid6->db->from('sinv a');
     $grid6->db->join('grup b ', 'a.grupo = b.grupo');
     $grid6->db->join('line c ', 'b.linea = c.linea');
     $grid6->db->join('dpto d ', 'd.depto = c.depto');
     $grid6->db->groupby('c.depto');
     $grid6->db->order_by('d.descrip');
     //$grid6->per_page = 15;
     $grid6->column('Departamento', 'descrip', "align='left'");
     $grid6->column('Monto', '<nformat><#suma#></nformat>', "align='right'");
     $grid6->totalizar('suma');
     $grid6->build();
     $data['rcaj'] = $grid->output;
     $data['sfpa'] = $grid2->output;
     $data['tot'] = $grid3->output;
     $data['resven'] = $grid8->output;
     $data['smov'] = $grid4->output;
     $data['scstgser'] = $grid7->output;
     $data['sprm'] = $grid5->output;
     $data['sinv'] = $grid6->output;
     $data0['content'] = $form->output . $this->load->view('view_resumendiario', $data, TRUE);
     $data0['head'] = $this->rapyd->get_head();
     $data0['title'] = "<h1>" . $this->t**s . " para la fecha " . dbdate_to_human($this->fecha) . "</h1>";
     $this->load->view('view_ventanas', $data0);
 }
Exemple #20
0
function display_days($day_count, $week_of_month, $month, $year)
{
    global $db, $phpc_script, $config, $first_day_of_week;
    if ($day_count > 7) {
        return array();
    }
    $day_of_month = ($week_of_month - 1) * 7 + $day_count - (7 + day_of_first($month, $year) - $first_day_of_week) % 7;
    if ($day_of_month <= 0 || $day_of_month > days_in_month($month, $year)) {
        $html_day = tag('td', attributes('class="none"'));
    } else {
        $currentday = date('j');
        $currentmonth = date('n');
        $currentyear = date('Y');
        // set whether the date is in the past or future/present
        if ($currentyear > $year || $currentyear == $year && ($currentmonth > $month || $currentmonth == $month && $currentday > $day_of_month)) {
            $current_era = 'past';
        } else {
            $current_era = 'future';
        }
        if (can_add_event()) {
            $html_day = tag('td', attributes('valign="top"', "class=\"{$current_era}\""), create_date_link('+', 'event_form', $year, $month, $day_of_month, array('class="phpc-add"')), create_date_link($day_of_month, 'display', $year, $month, $day_of_month, array('class="date"')));
        } else {
            $html_day = tag('td', attributes('valign="top"', "class=\"{$current_era}\""), create_date_link($day_of_month, 'display', $year, $month, $day_of_month, array('class="date"')));
        }
        $result = get_events_by_date($day_of_month, $month, $year);
        /* Start off knowing we don't need to close the event
         *  list.  loop through each event for the day
         */
        $have_events = false;
        $html_events = tag('ul');
        while ($row = $result->FetchRow($result)) {
            $subject = htmlspecialchars(strip_tags(stripslashes($row['subject'])));
            $event_time = formatted_time_string($row['starttime'], $row['eventtype']);
            $event = tag('li', tag('a', attributes("href=\"{$phpc_script}" . "?action=display&amp;" . "id={$row['id']}\""), ($event_time ? "{$event_time} - " : '') . $subject));
            $html_events->add($event);
            $have_events = true;
        }
        if ($have_events) {
            $html_day->add($html_events);
        }
    }
    return array_merge(array($html_day), display_days($day_count + 1, $week_of_month, $month, $year));
}
 /** ----------------------------------------
 	/**  Profile Update
 	/** ----------------------------------------*/
 function update_profile()
 {
     ee()->load->model('member_model');
     /** -------------------------------------
     		/**  Safety....
     		/** -------------------------------------*/
     if (count($_POST) == 0) {
         return ee()->output->show_user_error('general', array(ee()->lang->line('invalid_action')));
     }
     // Are any required custom fields empty?
     ee()->db->select('m_field_id, m_field_label');
     ee()->db->where('m_field_required = "y"');
     $query = ee()->db->get('member_fields');
     $errors = array();
     if ($query->num_rows() > 0) {
         foreach ($query->result_array() as $row) {
             if (isset($_POST['m_field_id_' . $row['m_field_id']]) and $_POST['m_field_id_' . $row['m_field_id']] == '') {
                 $errors[] = ee()->lang->line('mbr_custom_field_empty') . '&nbsp;' . $row['m_field_label'];
             }
         }
     }
     /** ----------------------------------------
     		/**  Blacklist/Whitelist Check
     		/** ----------------------------------------*/
     if (ee()->blacklist->blacklisted == 'y' && ee()->blacklist->whitelisted == 'n') {
         return ee()->output->show_user_error('general', array(ee()->lang->line('not_authorized')));
     }
     /** -------------------------------------
     		/**  Show errors
     		/** -------------------------------------*/
     if (count($errors) > 0) {
         return ee()->output->show_user_error('submission', $errors);
     }
     /** -------------------------------------
     		/**  Build query
     		/** -------------------------------------*/
     if (isset($_POST['url']) and $_POST['url'] == 'http://') {
         $_POST['url'] = '';
     }
     $fields = array('bday_y', 'bday_m', 'bday_d', 'url', 'location', 'occupation', 'interests', 'aol_im', 'icq', 'yahoo_im', 'msn_im', 'bio');
     $data = array();
     foreach ($fields as $val) {
         $data[$val] = isset($_POST[$val]) ? ee()->security->xss_clean($_POST[$val]) : '';
         unset($_POST[$val]);
     }
     ee()->load->helper('url');
     $data['url'] = preg_replace('/[\'"]/is', '', $data['url']);
     $data['url'] = prep_url($data['url']);
     if (is_numeric($data['bday_d']) and is_numeric($data['bday_m'])) {
         ee()->load->helper('date');
         $year = $data['bday_y'] != '' ? $data['bday_y'] : date('Y');
         $mdays = days_in_month($data['bday_m'], $year);
         if ($data['bday_d'] > $mdays) {
             $data['bday_d'] = $mdays;
         }
     }
     unset($_POST['HTTP_REFERER']);
     if (count($data) > 0) {
         ee()->member_model->update_member(ee()->session->userdata('member_id'), $data);
     }
     /** -------------------------------------
     		/**  Update the custom fields
     		/** -------------------------------------*/
     $m_data = array();
     if (count($_POST) > 0) {
         foreach ($_POST as $key => $val) {
             if (strncmp($key, 'm_field_id_', 11) == 0) {
                 $m_data[$key] = ee()->security->xss_clean($val);
             }
         }
         if (count($m_data) > 0) {
             ee()->member_model->update_member_data(ee()->session->userdata('member_id'), $m_data);
         }
     }
     /** -------------------------------------
     		/**  Update comments
     		/** -------------------------------------*/
     if ($data['location'] != "" or $data['url'] != "") {
         if (ee()->db->table_exists('comments')) {
             $d = array('location' => $data['location'], 'url' => $data['url']);
             ee()->db->where('author_id', ee()->session->userdata('member_id'));
             ee()->db->update('comments', $d);
         }
     }
     /** -------------------------------------
     		/**  Success message
     		/** -------------------------------------*/
     return $this->_var_swap($this->_load_element('success'), array('lang:heading' => ee()->lang->line('profile_updated'), 'lang:message' => ee()->lang->line('mbr_profile_has_been_updated')));
 }
 /**
  * Test all the core functions that use the calendar type system.
  *
  * @param string $type the calendar type we want to test
  */
 private function core_functions_test($type)
 {
     $this->set_calendar_type($type);
     // Get the calendar.
     $calendar = \core_calendar\type_factory::get_calendar_instance();
     // Test the userdate function.
     $this->assertEquals($calendar->timestamp_to_date_string($this->user->timecreated, '', 99, true, true), userdate($this->user->timecreated));
     // Test the calendar/lib.php functions.
     $this->assertEquals($calendar->get_weekdays(), calendar_get_days());
     $this->assertEquals($calendar->get_starting_weekday(), calendar_get_starting_weekday());
     $this->assertEquals($calendar->get_num_days_in_month('1986', '9'), calendar_days_in_month('9', '1986'));
     $this->assertEquals($calendar->get_next_month('1986', '9'), calendar_add_month('9', '1986'));
     $this->assertEquals($calendar->get_prev_month('1986', '9'), calendar_sub_month('9', '1986'));
     // Test the lib/moodle.php functions.
     $this->assertEquals($calendar->get_num_days_in_month('1986', '9'), days_in_month('9', '1986'));
     $this->assertEquals($calendar->get_weekday('1986', '9', '16'), dayofweek('16', '9', '1986'));
 }
 /**
  * Update member profile
  */
 function update_profile()
 {
     // validate for unallowed blank values
     if (empty($_POST)) {
         show_error(lang('unauthorized_access'));
     }
     $id = $_POST['id'];
     unset($_POST['id']);
     unset($_POST['edit_profile']);
     $_POST['url'] = $_POST['url'] == 'http://' ? '' : $_POST['url'];
     $fields = array('bday_y', 'bday_m', 'bday_d', 'url', 'location', 'occupation', 'interests', 'aol_im', 'icq', 'yahoo_im', 'msn_im', 'bio');
     $data = array();
     foreach ($fields as $val) {
         if (isset($_POST[$val])) {
             $data[$val] = $_POST[$val];
         }
         unset($_POST[$val]);
     }
     if (is_numeric($data['bday_d']) && is_numeric($data['bday_m'])) {
         $this->load->helper('date');
         $year = $data['bday_y'] != '' ? $data['bday_y'] : date('Y');
         $mdays = days_in_month($data['bday_m'], $year);
         if ($data['bday_d'] > $mdays) {
             $data['bday_d'] = $mdays;
         }
     }
     if (count($data) > 0) {
         $this->member_model->update_member($this->id, $data);
     }
     if (count($_POST) > 0) {
         $this->member_model->update_member_data($this->id, $_POST);
     }
     if ($data['location'] != "" or $data['url'] != "") {
         if ($this->db->table_exists('comments')) {
             $d = array('location' => $data['location'], 'url' => $data['url']);
             $this->db->where('author_id', $this->id);
             $this->db->update('comments', $d);
         }
     }
     $id = $id == '' ? '' : AMP . 'id=' . $id;
     $this->session->set_flashdata('message_success', lang('profile_updated'));
     $this->functions->redirect(BASE . AMP . 'C=myaccount' . AMP . 'M=edit_profile' . $id);
 }
 /** ----------------------------------------
 	/**  Channel Calendar
 	/** ----------------------------------------*/
 function calendar()
 {
     // Rick is using some funky conditional stuff for the calendar, so
     // we have to reassign the var_cond array using the legacy conditional
     // parser.  Bummer, but whatcha going to do?
     ee()->TMPL->var_cond = ee()->functions->assign_conditional_variables(ee()->TMPL->tagdata, '/', LD, RD);
     /** ----------------------------------------
     		/**  Determine the Month and Year
     		/** ----------------------------------------*/
     $year = '';
     $month = '';
     // Hard-coded month/year via tag parameters
     if (ee()->TMPL->fetch_param('month') and ee()->TMPL->fetch_param('year')) {
         $year = ee()->TMPL->fetch_param('year');
         $month = ee()->TMPL->fetch_param('month');
         if (strlen($month) == 1) {
             $month = '0' . $month;
         }
     } else {
         // Month/year in query string
         if (preg_match("#(\\d{4}/\\d{2})#", ee()->uri->query_string, $match)) {
             $ex = explode('/', $match['1']);
             $time = gmmktime(0, 0, 0, $ex['1'], 01, $ex['0']);
             $year = ee()->localize->format_date('%Y', $time, FALSE);
             $month = ee()->localize->format_date('%m', $time, FALSE);
         } else {
             // Defaults to current month/year
             $year = ee()->localize->format_date('%Y');
             $month = ee()->localize->format_date('%m');
         }
     }
     /** ----------------------------------------
     		/**  Set Unix timestamp for the given month/year
     		/** ----------------------------------------*/
     $date = gmmktime(12, 0, 0, $month, 1, $year);
     /** ----------------------------------------
     		/**  Determine the total days in the month
     		/** ----------------------------------------*/
     ee()->load->library('calendar');
     $adjusted_date = ee()->calendar->adjust_date($month, $year);
     $month = $adjusted_date['month'];
     $year = $adjusted_date['year'];
     ee()->load->helper('date');
     $total_days = days_in_month($month, $year);
     $previous_date = mktime(12, 0, 0, $month - 1, 1, $year);
     $next_date = mktime(12, 0, 0, $month + 1, 1, $year);
     /** ---------------------------------------
     		/**  Determine the total days of the previous month
     		/** ---------------------------------------*/
     $adj_prev_date = ee()->calendar->adjust_date($month - 1, $year);
     $prev_month = $adj_prev_date['month'];
     $prev_year = $adj_prev_date['year'];
     $prev_total_days = days_in_month($prev_month, $prev_year);
     /** ----------------------------------------
     		/**  Set the starting day of the week
     		/** ----------------------------------------*/
     // This can be set using a parameter in the tag:  start_day="saturday"
     // By default the calendar starts on sunday
     $start_days = array('sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday' => 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6);
     $start_day = isset($start_days[ee()->TMPL->fetch_param('start_day')]) ? $start_days[ee()->TMPL->fetch_param('start_day')] : 0;
     $day = $start_day + 1 - ee()->localize->format_date('%w', $date, FALSE);
     while ($day > 1) {
         $day -= 7;
     }
     /** ----------------------------------------
     		/**  {previous_path="channel/index"}
     		/** ----------------------------------------*/
     // This variables points to the previous month
     if (preg_match_all("#" . LD . "previous_path=(.+?)" . RD . "#", ee()->TMPL->tagdata, $matches)) {
         $adjusted_date = ee()->calendar->adjust_date($month - 1, $year, TRUE);
         foreach ($matches['1'] as $match) {
             $path = ee()->functions->create_url($match) . '/' . $adjusted_date['year'] . '/' . $adjusted_date['month'];
             ee()->TMPL->tagdata = preg_replace("#" . LD . "previous_path=.+?" . RD . "#", $path, ee()->TMPL->tagdata, 1);
         }
     }
     /** ----------------------------------------
     		/**  {next_path="channel/index"}
     		/** ----------------------------------------*/
     // This variables points to the next month
     if (preg_match_all("#" . LD . "next_path=(.+?)" . RD . "#", ee()->TMPL->tagdata, $matches)) {
         $adjusted_date = ee()->calendar->adjust_date($month + 1, $year, TRUE);
         foreach ($matches['1'] as $match) {
             $path = ee()->functions->create_url($match) . '/' . $adjusted_date['year'] . '/' . $adjusted_date['month'];
             ee()->TMPL->tagdata = preg_replace("#" . LD . "next_path=.+?" . RD . "#", $path, ee()->TMPL->tagdata, 1);
         }
     }
     /** ----------------------------------------
     		/**  {date format="%m %Y"}
     		/** ----------------------------------------*/
     $dates = array();
     // This variable is used in the heading of the calendar
     // to show the month and year
     $dates['date'] = $date;
     /** ----------------------------------------
     		/**  {previous_date format="%m %Y"}
     		/** ----------------------------------------*/
     // This variable is used in the heading of the calendar
     // to show the month and year
     $dates['previous_date'] = $previous_date;
     /** ----------------------------------------
     		/**  {next_date format="%m %Y"}
     		/** ----------------------------------------*/
     // This variable is used in the heading of the calendar
     // to show the month and year
     $dates['next_date'] = $next_date;
     ee()->TMPL->tagdata = ee()->TMPL->parse_date_variables(ee()->TMPL->tagdata, $dates);
     /** ----------------------------------------
     		/**  Day Heading
     		/** ----------------------------------------*/
     /*
     			This code parses out the headings for each day of the week
     			Contained in the tag will be this variable pair:
     	{calendar_heading}
     			<td class="calendarDayHeading">{lang:weekday_abrev}</td>
     			{/calendar_heading}
     	There are three display options for the header:
     	{lang:weekday_abrev} = S M T W T F S
     			{lang:weekday_short} = Sun Mon Tues, etc.
     			{lang:weekday_long} = Sunday Monday Tuesday, etc.
     */
     foreach (array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa') as $val) {
         $day_names_a[] = !ee()->lang->line($val) ? $val : ee()->lang->line($val);
     }
     foreach (array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat') as $val) {
         $day_names_s[] = !ee()->lang->line($val) ? $val : ee()->lang->line($val);
     }
     foreach (array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday') as $val) {
         $day_names_l[] = !ee()->lang->line($val) ? $val : ee()->lang->line($val);
     }
     if (preg_match("/" . LD . "calendar_heading" . RD . "(.*?)" . LD . '\\/' . "calendar_heading" . RD . "/s", ee()->TMPL->tagdata, $match)) {
         $temp = '';
         for ($i = 0; $i < 7; $i++) {
             $temp .= str_replace(array(LD . 'lang:weekday_abrev' . RD, LD . 'lang:weekday_short' . RD, LD . 'lang:weekday_long' . RD), array($day_names_a[($start_day + $i) % 7], $day_names_s[($start_day + $i) % 7], $day_names_l[($start_day + $i) % 7]), trim($match['1']) . "\n");
         }
         ee()->TMPL->tagdata = preg_replace("/" . LD . "calendar_heading" . RD . ".*?" . LD . '\\/' . "calendar_heading" . RD . "/s", trim($temp), ee()->TMPL->tagdata);
     }
     /** ----------------------------------------
     		/**  Separate out cell data
     		/** ----------------------------------------*/
     // We need to strip out the various variable pairs
     // that allow us to render each calendar cell.
     // We'll do this up-front and assign temporary markers
     // in the template which we will replace with the final
     // data later
     $row_start = '';
     $row_end = '';
     $row_chunk = '';
     $row_chunk_m = '94838dkAJDei8azDKDKe01';
     $entries = '';
     $entries_m = 'Gm983TGxkedSPoe0912NNk';
     $if_today = '';
     $if_today_m = 'JJg8e383dkaadPo20qxEid';
     $if_entries = '';
     $if_entries_m = 'Rgh43K0L0Dff9003cmqQw1';
     $if_not_entries = '';
     $if_not_entries_m = 'yr83889910BvndkGei8ti3';
     $if_blank = '';
     $if_blank_m = '43HDueie4q7pa8dAAseit6';
     if (preg_match("/" . LD . "calendar_rows" . RD . "(.*?)" . LD . '\\/' . "calendar_rows" . RD . "/s", ee()->TMPL->tagdata, $match)) {
         $row_chunk = trim($match['1']);
         //  Fetch all the entry_date variable
         if (preg_match("/" . LD . "row_start" . RD . "(.*?)" . LD . '\\/' . "row_start" . RD . "/s", $row_chunk, $match)) {
             $row_start = trim($match['1']);
             $row_chunk = trim(str_replace($match['0'], "", $row_chunk));
         }
         if (preg_match("/" . LD . "row_end" . RD . "(.*?)" . LD . '\\/' . "row_end" . RD . "/s", $row_chunk, $match)) {
             $row_end = trim($match['1']);
             $row_chunk = trim(str_replace($match['0'], "", $row_chunk));
         }
         foreach (ee()->TMPL->var_cond as $key => $val) {
             if ($val['3'] == 'today') {
                 $if_today = trim($val['2']);
                 $row_chunk = str_replace($val['1'], $if_today_m, $row_chunk);
                 unset(ee()->TMPL->var_cond[$key]);
             }
             if ($val['3'] == 'entries') {
                 $if_entries = trim($val['2']);
                 $row_chunk = str_replace($val['1'], $if_entries_m, $row_chunk);
                 unset(ee()->TMPL->var_cond[$key]);
             }
             if ($val['3'] == 'not_entries') {
                 $if_not_entries = trim($val['2']);
                 $row_chunk = str_replace($val['1'], $if_not_entries_m, $row_chunk);
                 unset(ee()->TMPL->var_cond[$key]);
             }
             if ($val['3'] == 'blank') {
                 $if_blank = trim($val['2']);
                 $row_chunk = str_replace($val['1'], $if_blank_m, $row_chunk);
                 unset(ee()->TMPL->var_cond[$key]);
             }
             if (preg_match("/" . LD . "entries" . RD . "(.*?)" . LD . '\\/' . "entries" . RD . "/s", $if_entries, $match)) {
                 $entries = trim($match['1']);
                 $if_entries = trim(str_replace($match['0'], $entries_m, $if_entries));
             }
         }
         ee()->TMPL->tagdata = preg_replace("/" . LD . "calendar_rows" . RD . ".*?" . LD . '\\/' . "calendar_rows" . RD . "/s", $row_chunk_m, ee()->TMPL->tagdata);
     }
     /** ----------------------------------------
     		/**  Fetch {switch} variable
     		/** ----------------------------------------*/
     // This variable lets us use a different CSS class
     // for the current day
     $switch_t = '';
     $switch_c = '';
     if (ee()->TMPL->fetch_param('switch')) {
         $x = explode("|", ee()->TMPL->fetch_param('switch'));
         if (count($x) == 2) {
             $switch_t = $x['0'];
             $switch_c = $x['1'];
         }
     }
     /** ---------------------------------------
     		/**  Set the day number numeric format
     		/** ---------------------------------------*/
     $day_num_fmt = ee()->TMPL->fetch_param('leading_zeroes') == 'yes' ? "%02d" : "%d";
     /** ----------------------------------------
     		/**  Build the SQL query
     		/** ----------------------------------------*/
     $this->initialize();
     // Fetch custom channel fields if we have search fields
     if (!empty(ee()->TMPL->search_fields)) {
         $this->fetch_custom_channel_fields();
     }
     $this->build_sql_query('/' . $year . '/' . $month . '/');
     if ($this->sql != '') {
         $query = ee()->db->query($this->sql);
         $data = array();
         if ($query->num_rows() > 0) {
             // We'll need this later
             ee()->load->library('typography');
             ee()->typography->initialize(array('convert_curly' => FALSE));
             /** ----------------------------------------
             				/**  Fetch query results and build data array
             				/** ----------------------------------------*/
             foreach ($query->result_array() as $row) {
                 /** ----------------------------------------
                 				/**  Define empty arrays and strings
                 				/** ----------------------------------------*/
                 $defaults = array('entry_date' => 'a', 'permalink' => 'a', 'title_permalink' => 'a', 'author' => 's', 'profile_path' => 'a', 'id_path' => 'a', 'base_fields' => 'a', 'day_path' => 'a', 'comment_auto_path' => 's', 'comment_entry_id_auto_path' => 's', 'comment_url_title_auto_path' => 's');
                 foreach ($defaults as $key => $val) {
                     ${$key} = $val == 'a' ? array() : '';
                 }
                 /** ---------------------------
                 				/**  Single Variables
                 				/** ---------------------------*/
                 foreach (ee()->TMPL->var_single as $key => $val) {
                     $entry_date[$key] = $row['entry_date'];
                     /** ----------------------------------------
                     				/**  parse permalink
                     				/** ----------------------------------------*/
                     if (strncmp($key, 'permalink', 9) == 0) {
                         if (ee()->functions->extract_path($key) != '' and ee()->functions->extract_path($key) != 'SITE_INDEX') {
                             $path = ee()->functions->extract_path($key) . '/' . $row['entry_id'];
                         } else {
                             $path = $row['entry_id'];
                         }
                         $permalink[$key] = ee()->functions->create_url($path);
                     }
                     /** ----------------------------------------
                     				/**  parse title permalink
                     				/** ----------------------------------------*/
                     if (strncmp($key, 'title_permalink', 15) == 0 or strncmp($key, 'url_title_path', 14) == 0) {
                         if (ee()->functions->extract_path($key) != '' and ee()->functions->extract_path($key) != 'SITE_INDEX') {
                             $path = ee()->functions->extract_path($key) . '/' . $row['url_title'];
                         } else {
                             $path = $row['url_title'];
                         }
                         $title_permalink[$key] = ee()->functions->create_url($path);
                     }
                     /** ----------------------------------------
                     				/**  {comment_auto_path}
                     				/** ----------------------------------------*/
                     if ($key == "comment_auto_path") {
                         $comment_auto_path = $row['comment_url'] == '' ? $row['channel_url'] : $row['comment_url'];
                     }
                     /** ----------------------------------------
                     				/**  {comment_url_title_auto_path}
                     				/** ----------------------------------------*/
                     if ($key == "comment_url_title_auto_path") {
                         $path = $row['comment_url'] == '' ? $row['channel_url'] : $row['comment_url'];
                         $comment_url_title_auto_path = $path . $row['url_title'];
                     }
                     /** ----------------------------------------
                     				/**  {comment_entry_id_auto_path}
                     				/** ----------------------------------------*/
                     if ($key == "comment_entry_id_auto_path") {
                         $path = $row['comment_url'] == '' ? $row['channel_url'] : $row['comment_url'];
                         $comment_entry_id_auto_path = $path . $row['entry_id'];
                     }
                     /** ----------------------------------------
                     				/**  {author}
                     				/** ----------------------------------------*/
                     if ($key == "author") {
                         $author = $row['screen_name'] != '' ? $row['screen_name'] : $row['username'];
                     }
                     /** ----------------------------------------
                     				/**  profile path
                     				/** ----------------------------------------*/
                     if (strncmp($key, 'profile_path', 12) == 0) {
                         $profile_path[$key] = ee()->functions->create_url(ee()->functions->extract_path($key) . '/' . $row['member_id']);
                     }
                     /** ----------------------------------------
                     				/**  parse comment_path
                     				/** ----------------------------------------*/
                     if (strncmp($key, 'comment_path', 12) == 0 or strncmp($key, 'entry_id_path', 13) == 0) {
                         $id_path[$key] = ee()->functions->create_url(ee()->functions->extract_path($key) . '/' . $row['entry_id']);
                     }
                     /** ----------------------------------------
                     				/**  Basic fields (username, screen_name, etc.)
                     				/** ----------------------------------------*/
                     if (isset($row[$val])) {
                         $base_fields[$key] = $row[$val];
                     }
                     /** ----------------------------------------
                     				/**  {day_path}
                     				/** ----------------------------------------*/
                     if (strncmp($key, 'day_path', 8) == 0) {
                         $formatted_date_path = ee()->localize->format_date('%Y/%m/%d', $row['entry_date']);
                         if (ee()->functions->extract_path($key) != '' and ee()->functions->extract_path($key) != 'SITE_INDEX') {
                             $formatted_date_path = ee()->functions->extract_path($key) . '/' . $formatted_date_path;
                         }
                         $if_entries = str_replace(LD . $key . RD, LD . 'day_path' . $val . RD, $if_entries);
                         $day_path[$key] = ee()->functions->create_url($formatted_date_path);
                     }
                 }
                 // END FOREACH SINGLE VARIABLES
                 /** ----------------------------------------
                 				/**  Build Data Array
                 				/** ----------------------------------------*/
                 $d = ee()->localize->format_date('%d', $row['entry_date']);
                 if (substr($d, 0, 1) == '0') {
                     $d = substr($d, 1);
                 }
                 $data[$d][] = array(ee()->typography->parse_type($row['title'], array('text_format' => 'lite', 'html_format' => 'none', 'auto_links' => 'n', 'allow_img_url' => 'no')), $row['url_title'], $entry_date, $permalink, $title_permalink, $author, $profile_path, $id_path, $base_fields, $day_path, $comment_auto_path, $comment_url_title_auto_path, $comment_entry_id_auto_path);
             }
             // END FOREACH
         }
         // END if ($query->num_rows() > 0)
     }
     // END if ($this->query != '')
     /** ----------------------------------------
     		/**  Build Calendar Cells
     		/** ----------------------------------------*/
     $out = '';
     $today = array('mday' => ee()->localize->format_date('%j'), 'mon' => ee()->localize->format_date('%n'), 'year' => ee()->localize->format_date('%Y'));
     while ($day <= $total_days) {
         $out .= $row_start;
         for ($i = 0; $i < 7; $i++) {
             if ($day > 0 and $day <= $total_days) {
                 if ($if_entries != '' and isset($data[$day])) {
                     $out .= str_replace($if_entries_m, $this->var_replace($if_entries, $data[$day], $entries), $row_chunk);
                     foreach ($day_path as $k => $v) {
                         $out = str_replace(LD . 'day_path' . $k . RD, $data[$day]['0']['9'][$k], $out);
                     }
                 } else {
                     $out .= str_replace($if_not_entries_m, $if_not_entries, $row_chunk);
                 }
                 $out = str_replace(LD . 'day_number' . RD, sprintf($day_num_fmt, $day), $out);
                 if ($day == $today["mday"] and $month == $today["mon"] and $year == $today["year"]) {
                     $out = str_replace(LD . 'switch' . RD, $switch_t, $out);
                 } else {
                     $out = str_replace(LD . 'switch' . RD, $switch_c, $out);
                 }
             } else {
                 $out .= str_replace($if_blank_m, $if_blank, $row_chunk);
                 $out = str_replace(LD . 'day_number' . RD, $day <= 0 ? sprintf($day_num_fmt, $prev_total_days + $day) : sprintf($day_num_fmt, $day - $total_days), $out);
             }
             $day++;
         }
         $out .= $row_end;
     }
     // Garbage collection
     $out = str_replace(array($entries_m, $if_blank_m, $if_today_m, $if_entries_m, $if_not_entries_m), '', $out);
     return str_replace($row_chunk_m, $out, ee()->TMPL->tagdata);
 }
Exemple #25
0
 function geneventasfiscal($mes)
 {
     $udia = days_in_month(substr($mes, 4), substr($mes, 0, 4));
     $fdesde = $mes . '01';
     $fhasta = $mes . $udia;
     $this->db->simple_query("DELETE FROM siva WHERE fechal = {$fdesde} AND fuente='FP'");
     $tasas = $this->_tasas($mes);
     $mivag = $tasas['general'];
     $mivar = $tasas['reducida'];
     $mivaa = $tasas['adicional'];
     //UPDATE fiscalz SET hora=CONCAT_WS(':',MINUTE(hora),SECOND(hora),'00') WHERE caja='MAYO' AND HOUR(hora)=0;
     $mSQL = "SELECT caja,serial,numero,fecha,factura,fecha1,hora,exento,base,iva,base1,iva1,base2,iva2,ncexento,ncbase,nciva,ncbase1,nciva1,ncbase2,nciva2,ncnumero \n\t\t\tFROM fiscalz WHERE fecha BETWEEN {$fdesde}  AND {$fhasta} ";
     $query = $this->db->query($mSQL);
     if ($query->num_rows() > 0) {
         $data['libro'] = 'V';
         $data['fuente'] = 'FP';
         $data['sucursal'] = '00';
         $data['tipo'] = 'CZ';
         $data['nacional'] = 'S';
         $data['fechal'] = $fdesde;
         $cCaja = '';
         foreach ($query->result() as $row) {
             $data['fecha'] = $row->fecha;
             $data['caja'] = $row->caja;
             $data['numero'] = $row->numero;
             $data['hora'] = $row->hora;
             $hhasta = $row->hora;
             if ($cCaja != $row->caja) {
                 if ($row->fecha1 == $row->fecha) {
                     $hdesde = '0';
                 } else {
                     $hdesde = $this->datasis->dameval("SELECT MAX(hora) FROM fiscalz WHERE fecha='{$row->fecha1}' AND caja='{$row->caja}'");
                     if (empty($hora)) {
                         $hdesde = '0';
                     }
                 }
             }
             $mSQL_1 = "INSERT INTO siva\n\t\t\t\t\t(id, libro, tipo, fuente, sucursal, fecha, numero, numhasta,  caja, nfiscal,  nhfiscal, \n\t\t\t\t\treferen, planilla, clipro, nombre, contribu, rif, registro,\n\t\t\t\t\tnacional, exento, general, geneimpu, \n\t\t\t\t\tadicional, adicimpu,  reducida,  reduimpu, stotal, impuesto, \n\t\t\t\t\tgtotal, reiva, fechal, fafecta,hora) SELECT \n\t\t\t\t\t 0  AS id,\n\t\t\t\t\t'V' AS libro, \n\t\t\t\t\tIF(MID(a.numero,1,2)='NC','NC','FC') AS tipo_doc,\n\t\t\t\t\t'FP'                                 AS fuente, \n\t\t\t\t\tCONCAT('0',MID(b.caja,1,1))          AS sucursal, \n\t\t\t\t\ta.fecha  AS fecha,\n\t\t\t\t\ta.numero AS numa, \n\t\t\t\t\ta.numero AS final,\n\t\t\t\t\tb.caja,\n\t\t\t\t\t' '       AS nfiscal,\n\t\t\t\t\t' '       AS nhfiscal,\n\t\t\t\t\te.serial  AS referen, \n\t\t\t\t\t' '       AS planilla, \n\t\t\t\t\tb.cliente AS clipro, \n\t\t\t\t\tCONCAT(c.nombres,' ', c.apellidos) AS nombre, \n\t\t\t\t\t'CO'                               AS contribu, \n\t\t\t\t\tc.cedula                           AS rif, \n\t\t\t\t\t'01'                               AS registro, \n\t\t\t\t\t'S'                                AS nacional,\n\t\t\t\t\tSUM(a.monto*(a.impuesto=0)) exento, \n\t\t\t\t\tROUND(SUM(a.monto*(a.impuesto=" . $mivag . ")*100/(100+a.impuesto)),2) baseg,\n\t\t\t\t\tROUND(SUM(a.monto*(a.impuesto=" . $mivag . ")-a.monto*(a.impuesto=" . $mivag . ")*100/(100+a.impuesto)),2) AS impug, \n\t\t\t\t\tROUND(SUM(a.monto*(a.impuesto=" . $mivaa . ")*100/(100+a.impuesto)),2) AS basea, \n\t\t\t\t\tROUND(SUM(a.monto*(a.impuesto=" . $mivaa . ")-a.monto*(a.impuesto=" . $mivaa . ")*100/(100+a.impuesto)),2) AS impua, \n\t\t\t\t\tROUND(SUM(a.monto*(a.impuesto=" . $mivar . ")*100/(100+a.impuesto)),2) AS baser, \n\t\t\t\t\tROUND(SUM(a.monto*(a.impuesto=" . $mivar . ")-a.monto*(a.impuesto=" . $mivar . ")*100/(100+a.impuesto)),2) AS impur,\n\t\t\t\t\tROUND(SUM((a.monto*100)/(100+a.impuesto)),2)           AS stotal,\n\t\t\t\t\tROUND(SUM(a.monto-((a.monto*100)/(100+a.impuesto))),2) AS impuesto, \n\t\t\t\t\tSUM(a.monto) AS gtotal,\n\t\t\t\t\t0            AS reiva,\n\t\t\t\t\t{$mes}01     AS fechal,\n\t\t\t\t\t0            AS fafecta,\n\t\t\t\t\tb.hora\n\t\t\t\tFROM vieite AS a \n\t\t\t\tLEFT JOIN viefac AS b ON a.numero=b.numero and a.caja=b.caja \n\t\t\t\tLEFT JOIN fiscalz AS e ON a.caja=e.caja AND a.fecha=e.fecha\n\t\t\t\tLEFT JOIN club c ON b.cliente=c.cod_tar \n\t\t\t\tLEFT JOIN dine d ON a.fecha=d.fecha AND a.caja=d.caja AND a.cajero=d.cajero\n\t\t\t\tWHERE a.fecha BETWEEN '{$row->fecha1}' AND '{$row->fecha}' AND c.cedula REGEXP '^[VEJG][0-9]{9}\$' \n\t\t\t\t\tAND a.caja='{$row->caja}' AND b.hora>='{$hdesde}' AND b.hora<'{$hhasta}'\n\t\t\t\tGROUP BY a.fecha, a.caja, numa";
             $flag = $this->db->simple_query($mSQL);
             if (!$flag) {
                 memowrite($mSQL, 'geneventasfiscal');
                 return 0;
             }
             $mSQL_2 = "SELECT tipo,\n\t\t\t\t\tSUM(exento)    AS exento, \n\t\t\t\t\tSUM(general)   AS baseg, \n\t\t\t\t\tSUM(reducida)  AS baser, \n\t\t\t\t\tSUM(adicional) AS basea,\n\t\t\t\t\tSUM(geneimpu)  AS ivag, \n\t\t\t\t\tSUM(reduimpu)  AS ivar,\n\t\t\t\t\tSUM(adicimpu)  AS ivaa\n\t\t\t\tFROM siva WHERE caja='{$row->caja}' AND fechal={$mes}01\n\t\t\t\tGROUP BY tipo";
             $query_2 = $this->db->query($mSQL_2);
             $cant = $query_2->num_rows();
             $NC = $FC = FALSE;
             foreach ($query_2->result() as $rrow) {
                 if ($rrow->tipo == 'FC') {
                     $FC = TRUE;
                     $data['nombre'] = 'VENTAS A NO CONTRIBUYENTE';
                     $data['exento'] = $row->exento - $rrow->exento;
                     $data['general'] = $row->base - $rrow->baseg;
                     $data['reducida'] = $row->base1 - $rrow->baser;
                     $data['adicional'] = $row->base2 - $rrow->basea;
                     $data['geneimpu'] = $row->iva - $rrow->ivag;
                     $data['reduimpu'] = $row->iva1 - $rrow->ivar;
                     $data['adicimpu'] = $row->iva2 - $rrow->ivaa;
                 } elseif ($rrow->tipo == 'NC') {
                     $NC = TRUE;
                     $data['nombre'] = 'NOTAS DE CREDITO A NO CONTRIBUYENTE';
                     $data['exento'] = -1 * ($row->ncexento + $rrow->exento);
                     $data['general'] = -1 * ($row->ncbase + $rrow->baseg);
                     $data['reducida'] = -1 * ($row->ncbase1 + $rrow->baser);
                     $data['adicional'] = -1 * ($row->ncbase2 + $rrow->basea);
                     $data['geneimpu'] = -1 * ($row->nciva + $rrow->ivag);
                     $data['reduimpu'] = -1 * ($row->nciva1 + $rrow->ivar);
                     $data['adicimpu'] = -1 * ($row->nciva2 + $rrow->ivaa);
                 }
                 $data['stotal'] = $data['exento'] + $data['general'] + $data['reducida'] + $data['adicional'];
                 $data['impuesto'] = $data['geneimpu'] + $data['reduimpu'] + $data['adicimpu'];
                 $data['gtotal'] = $data['stotal'] + $data['impuesto'];
                 $mmSQL = $this->db->insert_string('siva', $data);
                 $flag = $this->db->simple_query($mmSQL);
                 if (!$flag) {
                     memowrite($mmSQL, 'geneventasfiscal');
                     return 0;
                 }
             }
             //Si no hay ventas a contribuyente
             if (!$NC) {
                 $data['nombre'] = 'nNOTAS DE CREDITO A NO CONTRIBUYENTE';
                 $data['exento'] = -1 * $row->ncexento;
                 $data['general'] = -1 * $row->ncbase;
                 $data['reducida'] = -1 * $row->ncbase1;
                 $data['adicional'] = -1 * $row->ncbase2;
                 $data['geneimpu'] = -1 * $row->nciva;
                 $data['reduimpu'] = -1 * $row->nciva1;
                 $data['adicimpu'] = -1 * $row->nciva2;
                 $data['stotal'] = $data['exento'] + $data['general'] + $data['reducida'] + $data['adicional'];
                 $data['impuesto'] = $data['geneimpu'] + $data['reduimpu'] + $data['adicimpu'];
                 $data['gtotal'] = $data['stotal'] + $data['impuesto'];
                 $mmSQL = $this->db->insert_string('siva', $data);
                 $flag = $this->db->simple_query($mmSQL);
                 if (!$flag) {
                     memowrite($mmSQL, 'geneventasfiscal');
                     return 0;
                 }
             }
             if (!$FC) {
                 $data['nombre'] = 'vVENTAS A NO CONTRIBUYENTE';
                 $data['exento'] = $row->exento;
                 $data['general'] = $row->base;
                 $data['reducida'] = $row->base1;
                 $data['adicional'] = $row->base2;
                 $data['geneimpu'] = $row->iva;
                 $data['reduimpu'] = $row->iva1;
                 $data['adicimpu'] = $row->iva2;
                 $data['stotal'] = $data['exento'] + $data['general'] + $data['reducida'] + $data['adicional'];
                 $data['impuesto'] = $data['geneimpu'] + $data['reduimpu'] + $data['adicimpu'];
                 $data['gtotal'] = $data['stotal'] + $data['impuesto'];
                 $mmSQL = $this->db->insert_string('siva', $data);
                 $flag = $this->db->simple_query($mmSQL);
                 if (!$flag) {
                     memowrite($mmSQL, 'geneventasfiscal');
                     return 0;
                 }
             }
             $hdesde = $row->hora;
         }
     }
 }
Exemple #26
0
 function _post_insert($do)
 {
     $primary = $do->get('id');
     $error = 0;
     $montan = 0;
     // Monto para anticipar
     $sobrante = 0;
     // Monto sobrante para anticipar, reitegrar o pagar
     $abonado = 0;
     // Abonado si alguna factura esta pagada
     $rp = false;
     // Bandera para indicar retencion pendiente
     $transac = $do->get('transac');
     $estampa = $do->get('estampa');
     $hora = $do->get('hora');
     $cod_cli = $do->get('cod_cli');
     $nombre = $do->get('nombre');
     $estampa = $do->get('estampa');
     $usuario = $do->get('usuario');
     $hora = $do->get('hora');
     $operacion = $do->get('operacion');
     $periodo = $do->get('periodo');
     $id = $do->get('id');
     $numero = $do->get('nrocomp');
     $comprob = $periodo . $numero;
     $dbcod_cli = $this->db->escape($cod_cli);
     $dbtransac = $this->db->escape($transac);
     $efecha = $do->get('emision');
     $fecha = $do->get('fecha');
     $ex_fecha = explode('-', $fecha);
     $vence = $ex_fecha[0] . $ex_fecha[1] . days_in_month($ex_fecha[1], $ex_fecha[0]);
     $mNUMERO = 'R' . str_pad($primary, $this->datasis->long - 1, '0', STR_PAD_LEFT);
     $mSQL = "DELETE FROM smov WHERE transac={$dbtransac}";
     $ban = $this->db->simple_query($mSQL);
     if ($ban == false) {
         memowrite($mSQL, 'RIVC');
     }
     $arr_dev = array();
     $cli_dev = 0;
     $rel = 'itrivc';
     $cana = $do->count_rel($rel);
     for ($i = 0; $i < $cana; $i++) {
         $ittipo_doc = $do->get_rel($rel, 'tipo_doc', $i);
         $itnumero = $do->get_rel($rel, 'numero', $i);
         $itfecha = $do->get_rel($rel, 'fecha', $i);
         $itmonto = floatval($do->get_rel($rel, 'reiva', $i));
         $dbitnumero = $this->db->escape($itnumero);
         $dbittipo_doc = $this->db->escape($ittipo_doc);
         //Chequea que su origen sea sfac
         if ($ittipo_doc == 'F' || $ittipo_doc == 'D') {
             $sql = "SELECT referen,reiva,factura,cod_cli,nombre FROM sfac WHERE numero={$dbitnumero} AND tipo_doc={$dbittipo_doc}";
             $query = $this->db->query($sql);
             if ($query->num_rows() > 0) {
                 $row = $query->row();
                 $anterior = $row->reiva;
                 $itreferen = $row->referen;
                 $itfactura = $row->factura;
             }
             if ($anterior == 0) {
                 $mSQL = "UPDATE sfac SET reiva={$itmonto}, creiva='{$periodo}{$numero}', freiva='{$fecha}', ereiva='{$efecha}' WHERE numero={$dbitnumero} AND tipo_doc={$dbittipo_doc}";
                 $ban = $this->db->simple_query($mSQL);
                 if ($ban == false) {
                     memowrite($mSQL, 'rivc');
                 }
             }
         } else {
             //En caso de provenir de smov
             if ($ittipo_doc == 'NC') {
                 $mSQL = "UPDATE smov SET reteiva={$itmonto}, nroriva='{$periodo}{$numero}', emiriva='{$efecha}' WHERE numero={$dbitnumero} AND tipo_doc={$dbittipo_doc} AND cod_cli={$dbcod_cli} LIMIT 1";
                 $ban = $this->db->simple_query($mSQL);
                 if ($ban == false) {
                     memowrite($mSQL, 'rivc');
                 }
                 $itreferen = 'E';
             } else {
                 $itreferen = 'C';
             }
         }
         //Chequea si es credito y si tiene saldo
         if ($itreferen == 'C') {
             $iittipo_doc = $ittipo_doc == 'F' ? 'FC' : $ittipo_doc;
             $dbiittipo_doc = $this->db->escape($iittipo_doc);
             $saldo = floatval($this->datasis->dameval("SELECT monto-abonos FROM smov WHERE tipo_doc={$dbiittipo_doc} AND numero={$dbitnumero}"));
         } else {
             if ($ittipo_doc == 'F') {
                 //Busca un tipo de pago RP
                 $sel = array('b.monto - b.abonos AS saldo', 'b.numero');
                 $this->db->select($sel);
                 $this->db->from('sfac AS a');
                 $this->db->join('smov AS b', 'a.cod_cli=b.cod_cli AND a.transac=b.transac AND a.fecha=b.fecha');
                 $this->db->where('a.tipo_doc', 'F');
                 $this->db->where('b.tipo_doc', 'ND');
                 $this->db->where('a.numero', $itnumero);
                 $query = $this->db->get();
                 if ($query->num_rows() > 0) {
                     $row = $query->row();
                     $ittipo_doc = 'ND';
                     $itnumero = $row->numero;
                     $saldo = floatval($row->saldo);
                     $rp = true;
                 } else {
                     $saldo = 0;
                 }
             } else {
                 $saldo = 0;
             }
         }
         //Si es una factura o una nota de debito por causa o no causa de una RP
         if ($ittipo_doc == 'F' || $ittipo_doc == 'ND') {
             //Si el saldo es 0  o menor que el monto retenido
             if ($saldo == 0) {
                 $sobrante += $itmonto;
             } else {
                 //Como tiene saldo pendiente crea una NC y la aplica a la FC
                 $aplmonto = $itmonto > $saldo ? $saldo : $itmonto;
                 $sobrante += $itmonto - $aplmonto;
                 $mnumnc = 'I' . $this->datasis->fprox_numero('ncint', -1);
                 //$this->datasis->fprox_numero('nccli');
                 $data = array();
                 $data['cod_cli'] = $cod_cli;
                 $data['nombre'] = $nombre;
                 $data['tipo_doc'] = 'NC';
                 $data['numero'] = $mnumnc;
                 $data['fecha'] = $fecha;
                 $data['monto'] = $aplmonto;
                 $data['impuesto'] = 0;
                 $data['abonos'] = $aplmonto;
                 $data['vence'] = $fecha;
                 $data['tipo_ref'] = $rp || $ittipo_doc == 'F' ? 'FC' : $ittipo_doc;
                 $data['num_ref'] = $do->get_rel($rel, 'numero', $i);
                 $data['observa1'] = 'APLICACION DE RET/IVA A FC' . $do->get_rel($rel, 'numero', $i);
                 $data['estampa'] = $estampa;
                 $data['hora'] = $hora;
                 $data['transac'] = $transac;
                 $data['usuario'] = $usuario;
                 $data['codigo'] = 'NOCON';
                 $data['descrip'] = 'NOTA DE CONTABILIDAD';
                 $data['fecdoc'] = $itfecha;
                 $data['nroriva'] = $comprob;
                 $data['emiriva'] = $efecha;
                 $mSQL = $this->db->insert_string('smov', $data);
                 $ban = $this->db->simple_query($mSQL);
                 if ($ban == false) {
                     memowrite($mSQL, 'rivc');
                 }
                 //Aplica la NC a la FC o ND segun sea el caso
                 $data = array();
                 $data['numccli'] = $itnumero;
                 $data['tipoccli'] = $ittipo_doc == 'F' ? 'FC' : 'ND';
                 $data['cod_cli'] = $cod_cli;
                 $data['tipo_doc'] = 'NC';
                 $data['numero'] = $mnumnc;
                 $data['fecha'] = $fecha;
                 $data['monto'] = $aplmonto;
                 $data['abono'] = $aplmonto;
                 $data['ppago'] = 0;
                 $data['reten'] = 0;
                 $data['cambio'] = 0;
                 $data['mora'] = 0;
                 $data['transac'] = $transac;
                 $data['estampa'] = $estampa;
                 $data['hora'] = $hora;
                 $data['usuario'] = $usuario;
                 $data['reteiva'] = 0;
                 $data['nroriva'] = '';
                 $data['emiriva'] = '';
                 $data['recriva'] = '';
                 $mSQL = $this->db->insert_string('itccli', $data);
                 $ban = $this->db->simple_query($mSQL);
                 if ($ban == false) {
                     memowrite($mSQL, 'rivc');
                 }
                 // Abona la factura
                 $tiposfac = $ittipo_doc == 'F' ? 'FC' : 'ND';
                 $mSQL = "UPDATE smov SET abonos=abonos+{$aplmonto} WHERE numero='{$itnumero}' AND cod_cli={$dbcod_cli} AND tipo_doc='{$tiposfac}'";
                 $ban = $this->db->simple_query($mSQL);
                 if ($ban == false) {
                     memowrite($mSQL, 'rivc');
                 }
             }
             $mnumnd = 'I' . $this->datasis->fprox_numero('ndint', -1);
             //$this->datasis->fprox_numero('ndcli');
             $data = array();
             $data['cod_cli'] = 'REIVA';
             $data['nombre'] = 'RETENCION DE I.V.A. POR COMPENSAR';
             $data['tipo_doc'] = 'ND';
             $data['numero'] = $mnumnd;
             $data['fecha'] = $fecha;
             $data['monto'] = $itmonto;
             $data['impuesto'] = 0;
             $data['abonos'] = 0;
             $data['vence'] = $vence;
             $data['tipo_ref'] = 'FC';
             $data['num_ref'] = $do->get_rel($rel, 'numero', $i);
             $data['observa1'] = 'RET/IVA DE ' . $cod_cli . ' A DOC. FC' . $do->get_rel($rel, 'numero', $i);
             $data['estampa'] = $estampa;
             $data['hora'] = $hora;
             $data['transac'] = $transac;
             $data['usuario'] = $usuario;
             $data['codigo'] = 'NOCON';
             $data['descrip'] = 'NOTA DE CONTABILIDAD';
             $data['nroriva'] = $comprob;
             $data['emiriva'] = $efecha;
             $mSQL = $this->db->insert_string('smov', $data);
             $ban = $this->db->simple_query($mSQL);
             if ($ban == false) {
                 memowrite($mSQL, 'RIVC');
             }
         } else {
             //Si es una devolucion
             // Devoluciones genera un ND al cliente
             $mnumnd = 'I' . $this->datasis->fprox_numero('ndint', -1);
             //$this->datasis->fprox_numero('ndcli');
             $data = array();
             $data['cod_cli'] = $cod_cli;
             $data['nombre'] = $nombre;
             $data['tipo_doc'] = 'ND';
             $data['numero'] = $mnumnd;
             $data['fecha'] = $fecha;
             $data['monto'] = $itmonto;
             $data['impuesto'] = 0;
             $data['abonos'] = 0;
             $data['vence'] = $fecha;
             $data['tipo_ref'] = $ittipo_doc == 'F' ? 'FC' : 'DV';
             $data['num_ref'] = $itnumero;
             $data['observa1'] = 'RET/IVA DE ' . $cod_cli . ' A DOC. ' . $ittipo_doc . $itnumero;
             $data['estampa'] = $estampa;
             $data['hora'] = $hora;
             $data['transac'] = $transac;
             $data['usuario'] = $usuario;
             $data['nroriva'] = $comprob;
             $data['emiriva'] = $efecha;
             $mSQL = $this->db->insert_string('smov', $data);
             $ban = $this->db->simple_query($mSQL);
             if ($ban == false) {
                 memowrite($mSQL, 'rivc');
             }
             $arr_dev[$mnumnd] = $itmonto;
             $cli_dev += $itmonto;
             //Devoluciones debe crear un NC si esta en el periodo
             $mnumnc = 'I' . $this->datasis->fprox_numero('ncint', -1);
             //$this->datasis->fprox_numero('nccli');
             $data = array();
             $data['cod_cli'] = 'REIVA';
             $data['nombre'] = 'RETENCION DE I.V.A. POR COMPENSAR';
             $data['tipo_doc'] = 'NC';
             $data['numero'] = $mnumnc;
             $data['fecha'] = $fecha;
             $data['monto'] = $itmonto;
             $data['impuesto'] = 0;
             $data['abonos'] = 0;
             $data['vence'] = $fecha;
             $data['tipo_ref'] = $ittipo_doc == 'F' ? 'FC' : $ittipo_doc == 'NC' ? 'NC' : 'DV';
             $data['num_ref'] = $itnumero;
             $data['observa1'] = 'RET/IVA DE ' . $cod_cli . ' A DOC.' . $ittipo_doc . $itnumero;
             $data['estampa'] = $estampa;
             $data['hora'] = $hora;
             $data['transac'] = $transac;
             $data['usuario'] = $usuario;
             $data['codigo'] = 'NOCON';
             $data['descrip'] = 'NOTA DE CONTABILIDAD';
             $data['nroriva'] = $comprob;
             $data['emiriva'] = $efecha;
             $mSQL = $this->db->insert_string('smov', $data);
             $ban = $this->db->simple_query($mSQL);
             if ($ban == false) {
                 memowrite($mSQL, 'rivc');
             }
             if ($ittipo_doc != 'NC') {
                 //Aplica la NC a la ND si es posible a REIVA
                 //$mnumnd; $fecha;
                 $this->db->select(array('a.numero', 'a.fecha', 'a.monto - a.abonos AS saldo'));
                 $this->db->from('smov   AS a');
                 $this->db->join('itrivc AS b', 'a.transac=b.transac AND a.fecha=b.fecha AND a.num_ref=b.numero');
                 $this->db->where('b.numero', $itfactura);
                 $this->db->where('b.tipo_doc', 'F');
                 $this->db->where('a.tipo_doc', 'ND');
                 $this->db->where('a.cod_cli', 'REIVA');
                 $qquery = $this->db->get();
                 if ($qquery->num_rows() == 1) {
                     $rrrow = $qquery->row();
                     if ($rrrow->saldo >= $itmonto) {
                         $data = array();
                         $data['numccli'] = $mnumnc;
                         $data['tipoccli'] = 'NC';
                         $data['cod_cli'] = 'REIVA';
                         $data['tipo_doc'] = 'ND';
                         $data['numero'] = $rrrow->numero;
                         $data['fecha'] = $rrrow->fecha;
                         $data['monto'] = $itmonto;
                         $data['abono'] = $itmonto;
                         $data['ppago'] = 0;
                         $data['reten'] = 0;
                         $data['cambio'] = 0;
                         $data['mora'] = 0;
                         $data['transac'] = $transac;
                         $data['estampa'] = $estampa;
                         $data['hora'] = $hora;
                         $data['usuario'] = $usuario;
                         $data['reteiva'] = 0;
                         $data['nroriva'] = '';
                         $data['emiriva'] = '';
                         $data['recriva'] = '';
                         $mSQL = $this->db->insert_string('itccli', $data);
                         $ban = $this->db->simple_query($mSQL);
                         if ($ban == false) {
                             memowrite($mSQL, 'rivc');
                         }
                         //Abona la ND
                         $dbfecha = $this->db->escape($rrrow->fecha);
                         $dbnumero = $this->db->escape($rrrow->numero);
                         $mSQL = "UPDATE smov SET abonos=abonos+{$itmonto}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tcod_cli ='REIVA' AND\n\t\t\t\t\t\t\ttipo_doc='ND' AND\n\t\t\t\t\t\t\tnumero  = {$dbnumero} AND\n\t\t\t\t\t\t\tfecha   = {$dbfecha}";
                         $ban = $this->db->simple_query($mSQL);
                         if ($ban == false) {
                             memowrite($mSQL, 'rivc');
                         }
                         //Abona la NC
                         $dbfecha = $this->db->escape($fecha);
                         $dbnumero = $this->db->escape($mnumnc);
                         $mSQL = "UPDATE smov SET abonos=monto\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tcod_cli ='REIVA' AND\n\t\t\t\t\t\t\ttipo_doc='NC' AND\n\t\t\t\t\t\t\tnumero  = {$dbnumero} AND\n\t\t\t\t\t\t\tfecha   = {$dbfecha}";
                         $ban = $this->db->simple_query($mSQL);
                         if ($ban == false) {
                             memowrite($mSQL, 'rivc');
                         }
                     }
                 }
             }
         }
     }
     //Chequea si es un reintegro para crear un solo egreso de caja
     if ($sobrante > 0) {
         //Revisa si tiene que cruzar sobrante
         if (count($arr_dev) > 0) {
             $aplmonto = $cli_dev > $sobrante ? $sobrante : $cli_dev;
             $mnumnc = 'I' . $this->datasis->fprox_numero('ncint', -1);
             //$this->datasis->fprox_numero('nccli');
             $data = array();
             $data['cod_cli'] = $cod_cli;
             $data['nombre'] = $nombre;
             $data['tipo_doc'] = 'NC';
             $data['numero'] = $mnumnc;
             $data['fecha'] = $fecha;
             $data['monto'] = $aplmonto;
             $data['impuesto'] = 0;
             $data['abonos'] = $aplmonto;
             $data['vence'] = $fecha;
             $data['tipo_ref'] = '';
             $data['num_ref'] = '';
             $data['observa1'] = 'SOBRANTE DE RET/IVA ' . $comprob;
             $data['estampa'] = $estampa;
             $data['hora'] = $hora;
             $data['transac'] = $transac;
             $data['usuario'] = $usuario;
             $data['codigo'] = 'NOCON';
             $data['descrip'] = 'NOTA DE CONTABILIDAD';
             $data['fecdoc'] = $fecha;
             $data['nroriva'] = $comprob;
             $data['emiriva'] = $efecha;
             $mSQL = $this->db->insert_string('smov', $data);
             $ban = $this->db->simple_query($mSQL);
             if ($ban == false) {
                 memowrite($mSQL, 'rivc');
             }
             foreach ($arr_dev as $num => $valor) {
                 if ($sobrante == 0) {
                     break;
                 }
                 if ($sobrante >= $valor) {
                     $sobrante -= $valor;
                 } else {
                     $valor = $sobrante;
                     $sobrante = 0;
                 }
                 $data = array();
                 $data['numccli'] = $mnumnc;
                 $data['tipoccli'] = 'NC';
                 $data['cod_cli'] = $cod_cli;
                 $data['tipo_doc'] = 'ND';
                 $data['numero'] = $num;
                 $data['fecha'] = $fecha;
                 $data['monto'] = $valor;
                 $data['abono'] = $valor;
                 $data['ppago'] = 0;
                 $data['reten'] = 0;
                 $data['cambio'] = 0;
                 $data['mora'] = 0;
                 $data['transac'] = $transac;
                 $data['estampa'] = $estampa;
                 $data['hora'] = $hora;
                 $data['usuario'] = $usuario;
                 $data['reteiva'] = 0;
                 $data['nroriva'] = '';
                 $data['emiriva'] = '';
                 $data['recriva'] = '';
                 $mSQL = $this->db->insert_string('itccli', $data);
                 $ban = $this->db->simple_query($mSQL);
                 if ($ban == false) {
                     memowrite($mSQL, 'rivc');
                 }
                 //Abona la ND
                 $dbfecha = $this->db->escape($fecha);
                 $dbnumero = $this->db->escape($num);
                 $mSQL = "UPDATE smov SET abonos=monto\n\t\t\t\t\tWHERE\n\t\t\t\t\tcod_cli ={$dbcod_cli} AND\n\t\t\t\t\ttipo_doc='ND' AND\n\t\t\t\t\tnumero  = {$dbnumero} AND\n\t\t\t\t\ttransac = {$dbtransac}";
                 $ban = $this->db->simple_query($mSQL);
                 if ($ban == false) {
                     memowrite($mSQL, 'rivc');
                 }
             }
         }
         //Fin del cruce del sobrante
         if ($operacion == 'A' && $sobrante > 0) {
             $mnumant = $this->datasis->fprox_numero('nancli');
             $data = array();
             $data['cod_cli'] = $cod_cli;
             $data['nombre'] = $nombre;
             $data['tipo_doc'] = 'AN';
             $data['numero'] = $mnumant;
             $data['fecha'] = $fecha;
             $data['monto'] = $sobrante;
             $data['impuesto'] = 0;
             $data['vence'] = $fecha;
             $data['tipo_ref'] = 'CR';
             $data['num_ref'] = $numero;
             $data['observa1'] = 'RET/IVA DE ' . $cod_cli . ' A CR' . $comprob;
             $data['usuario'] = $usuario;
             $data['estampa'] = $estampa;
             $data['hora'] = $hora;
             $data['transac'] = $transac;
             $data['fecdoc'] = $fecha;
             $data['nroriva'] = $comprob;
             $data['emiriva'] = $efecha;
             $mSQL = $this->db->insert_string('smov', $data);
             $ban = $this->db->simple_query($mSQL);
             if ($ban == false) {
                 memowrite($mSQL, 'RIVC');
             }
         } elseif ($operacion == 'R' && $sobrante > 0) {
             $codbanc = $do->get('codbanc');
             $datacar = common::_traebandata($codbanc);
             $sp_fecha = date('Ymd');
             $ttipo = $datacar['tbanco'];
             $moneda = $datacar['moneda'];
             $negreso = $this->datasis->fprox_numero('negreso');
             if ($ttipo == 'CAJ') {
                 $numeroch = $this->datasis->fprox_numero('ncaja' . $codbanc);
                 $tipo_op = 'ND';
                 $tipo1 = 'D';
             } else {
                 //Pago con banco, falta implementar
                 $numeroch = 'NUMERO CHEQUE';
                 $tipo_op = 'CH';
                 $tipo1 = 'C';
             }
             $data = array();
             $data['codbanc'] = $codbanc;
             $data['moneda'] = $moneda;
             $data['numcuent'] = $datacar['numcuent'];
             $data['banco'] = $datacar['banco'];
             $data['saldo'] = $datacar['saldo'];
             $data['tipo_op'] = $tipo_op;
             $data['numero'] = $numeroch;
             $data['fecha'] = date('Y-m-d');
             $data['clipro'] = 'C';
             $data['codcp'] = $cod_cli;
             $data['nombre'] = $nombre;
             $data['monto'] = $sobrante;
             $data['concepto'] = 'REINTEGRO RET/IVA DE ' . $cod_cli;
             $data['concep2'] = ' CR' . $comprob;
             $data['benefi'] = '';
             $data['posdata'] = '';
             $data['abanco'] = '';
             $data['liable'] = $ttipo == 'CAJ' ? 'S' : 'N';
             $data['transac'] = $transac;
             $data['usuario'] = $usuario;
             $data['estampa'] = $estampa;
             $data['hora'] = $hora;
             $data['anulado'] = 'N';
             $data['susti'] = '';
             $data['negreso'] = $negreso;
             $sql = $this->db->insert_string('bmov', $data);
             $ban = $this->db->simple_query($sql);
             if ($ban == false) {
                 memowrite($sql, 'rivc');
                 $error++;
             }
             $this->datasis->actusal($codbanc, $sp_fecha, -1 * $sobrante);
         } elseif ($operacion == 'P' && $sobrante > 0) {
             //Lo manda a cuenta por pagar
             $causado = $this->datasis->fprox_numero('ncausado');
             $mnsprm = $mNUMERO;
             //$this->datasis->fprox_numero('num_nd');
             $data = array();
             $data['cod_prv'] = 'REINT';
             $data['nombre'] = 'REINTEGROS CLIENTES';
             $data['tipo_doc'] = 'ND';
             $data['numero'] = $mnsprm;
             $data['fecha'] = $fecha;
             $data['monto'] = $sobrante;
             $data['impuesto'] = 0;
             $data['abonos'] = 0;
             $data['vence'] = $fecha;
             $data['observa1'] = 'CARGO A CXC RET/IVA CR ' . $comprob;
             $data['observa2'] = 'DEL CLIENTE ' . $cod_cli;
             $data['tipo_ref'] = 'CR';
             $data['num_ref'] = $numero;
             $data['transac'] = $transac;
             $data['estampa'] = $estampa;
             $data['hora'] = $hora;
             $data['usuario'] = $usuario;
             $data['reteiva'] = 0;
             $data['montasa'] = 0;
             $data['monredu'] = 0;
             $data['monadic'] = 0;
             $data['tasa'] = 0;
             $data['reducida'] = 0;
             $data['sobretasa'] = 0;
             $data['exento'] = 0;
             $data['causado'] = $causado;
             $data['codigo'] = 'NOCON';
             $data['descrip'] = 'NOTA DE CONTABILIDAD';
             $sql = $this->db->insert_string('sprm', $data);
             $ban = $this->db->simple_query($sql);
             if ($ban == false) {
                 memowrite($sql, 'rivc');
                 $error++;
             }
             $sql = 'UPDATE rivc SET sprmreinte=' . $this->db->escape($mnsprm) . ' WHERE id=' . $this->db->escape($id);
             $ban = $this->db->simple_query($sql);
             if ($ban == false) {
                 memowrite($sql, 'rivc');
                 $error++;
             }
         }
     }
     $periodo = $do->get('periodo');
     $nrocomp = $do->get('nrocomp');
     $primary = implode(',', $do->pk);
     logusu($do->table, "Creo {$this->t**s} ID {$primary} {$periodo}{$nrocomp}");
     return true;
 }
 /**
  * Add a month to a UNIX time_t timestamp
  */
 function add_month($time)
 {
     $year = date('Y', $time);
     $month = date('n', $time);
     // 1 to 12
     $month_days = days_in_month($month, $year);
     return $time + $month_days * SECS_PER_DAY;
 }
Exemple #28
0
} else {
    $categ = 'SELECT disTINCT l.categ_id,c.name FROM crm_lead l,crm_case_categ c where l.categ_id = c.id and l.categ_id is not null order by l.categ_id';
    $r1 = retrieve($categ);
    $acateg = [];
    foreach ($r1 as $v) {
        $acateg[] = $v['name'];
    }
    /*
    for($i = count($r1) ; $i > 0 ; $i--) {
      $acateg[] = $r1[$i-1]['name'];
    }
    */
    $jsonb = [];
    foreach ($em as $k => $v) {
        $mnum = name_to_nmonth($mn, $v);
        $num = days_in_month($mnum, $year);
        $nn = name_to_n2($m2, $mnum);
        $q3 = '';
        if ($nn != '00') {
            $q2 = "\n      SELECT  a.categ_id , \n          COALESCE(b.count, 0) AS Count,sum_rev\n    FROM \n      (\n          SELECT 21 AS categ_id\n          UNION\n          SELECT 22 AS categ_id\n          UNION\n          SELECT 23 AS categ_id\n          UNION\n          SELECT 24 AS categ_id\n          UNION\n          SELECT 25 AS categ_id\n          UNION\n          SELECT 26 AS categ_id\n          UNION\n          SELECT 27 AS categ_id\n          UNION\n          SELECT 28 AS categ_id\n          UNION\n          SELECT 29 AS categ_id\n  \tUNION\n          SELECT 30 AS categ_id\n  \tUNION\n          SELECT 31 AS categ_id\n      ) a LEFT JOIN \n      (\n          SELECT l.categ_id,c.name,COALESCE(sum(l.planned_revenue) , 0) as sum_rev,count(*) FROM crm_lead l,crm_case_categ c \n          WHERE (l.create_date, l.create_date) OVERLAPS ('{$year}-{$nn}-01'::DATE, '{$year}-{$nn}-{$num}'::DATE) AND l.categ_id = c.id group by l.categ_id,c.name order by c.name desc\n      ) b \n\n  ON a.categ_id = b.categ_id order by categ_id\n      ";
            //echo $q2 . "<br/><br/>";
            $q = "\n  \t\tSELECT c.name,COALESCE(sum(l.planned_revenue) , 0) as sum_rev,count(*) FROM crm_lead l,crm_case_categ c WHERE (l.create_date, l.create_date) OVERLAPS ('{$year}-{$nn}-01'::DATE, '{$year}-{$nn}-{$num}'::DATE) AND l.categ_id = c.id group by c.name\n  \t\t";
            $result = retrieve($q2);
            $jsona = [];
            $values = [];
            $ev = [];
            foreach ($result as $key => $val) {
                $ev[] = $val['count'];
            }
            $jsonb[] = ['label' => $v, 'values' => $ev];
        }
Exemple #29
0
 /**
  * Total days in a given month
  *
  * @param	int	the month
  * @param	int	the year
  * @return	int
  */
 public function get_total_days($month, $year)
 {
     $this->CI->load->helper('date');
     return days_in_month($month, $year);
 }
 public function test_days_in_month()
 {
     $this->assertEquals(30, days_in_month(06, 2005));
     $this->assertEquals(28, days_in_month(02, 2011));
     $this->assertEquals(29, days_in_month(02, 2012));
 }