Ejemplo n.º 1
0
 public function gera_relatorio()
 {
     echo "index carregada";
     $this->load->helper('mpdf');
     $html = "<html>";
     $html .= "<head></head>";
     $html .= "<body>Meu arquivo de teste</body>";
     $html .= "</html>";
     // Opcional: Também é possivel carregar uma view inteira...
     //$html = $this->load->view('uma_view_qualquer', null, true);
     pdf($html);
 }
Ejemplo n.º 2
0
				$releve_HTML_table_body .= affich_score_html($score,$tableau_tri_mode);
			}
			$valeur1 = $tab_moyenne_scores_item[$item_id];
			$valeur2 = $tab_pourcentage_acquis_item[$item_id];
			$releve_PDF->bilan_periode_synthese_pourcentages($valeur1,$valeur2,FALSE,TRUE);
			$checkbox = ($affichage_checkbox) ? '<td class="nu"><input type="checkbox" name="id_item[]" value="'.$item_id.'" /></td>' : '' ;
			$releve_HTML_table_body .= '<td class="nu">&nbsp;</td>'.affich_score_html($valeur1,$tableau_tri_mode,'%').affich_score_html($valeur2,$tableau_tri_mode,'%').$checkbox.'</tr>'."\r\n";
		}
	}
	$releve_HTML_table_body = '<tbody>'.$releve_HTML_table_body.'</tbody>'."\r\n";
	// dernière ligne (doublée)
	$memo_y = $releve_PDF->GetY()+2;
	$releve_PDF->SetY( $memo_y );
	$releve_PDF->choisir_couleur_fond('gris_moyen');
	$releve_PDF->Cell($releve_PDF->intitule_largeur , $releve_PDF->cases_hauteur , pdf('moy. scores '.$info_ponderation_courte.' [*]') , 1 , 2 , 'C' , true , '');
	$releve_PDF->Cell($releve_PDF->intitule_largeur , $releve_PDF->cases_hauteur , pdf('% validations [**]') , 1 , 0 , 'C' , true , '');
	$releve_HTML_table_foot1 = '<tr><th>moy. scores '.$info_ponderation_courte.' [*]</th>';
	$releve_HTML_table_foot2 = '<tr><th>% validations [**]</th>';
	$checkbox = ($affichage_checkbox) ? '<tr><th class="nu">&nbsp;</th>' : '' ;
	$memo_x = $releve_PDF->GetX();
	$releve_PDF->SetXY($memo_x,$memo_y);
	if($tableau_tri_objet=='eleve')
	{
		foreach($tab_liste_item as $item_id)	// Pour chaque item...
		{
			$valeur1 = $tab_moyenne_scores_item[$item_id];
			$valeur2 = $tab_pourcentage_acquis_item[$item_id];
			$releve_PDF->bilan_periode_synthese_pourcentages($valeur1,$valeur2,TRUE,FALSE);
			$releve_HTML_table_foot1 .= affich_score_html($valeur1,'score','%');
			$releve_HTML_table_foot2 .= affich_score_html($valeur2,'score','%');
			$checkbox .= ($affichage_checkbox) ? '<td class="nu"><input type="checkbox" name="id_item[]" value="'.$item_id.'" /></td>' : '' ;
function write($_POST)
{
    # Set max execution time to 12 hours
    ini_set("max_execution_time", 43200);
    # Get vars
    foreach ($_POST as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
    }
    $VATP = TAX_VAT;
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        return $err;
    }
    pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
    $i = 0;
    foreach ($invids as $key => $invid) {
        db_connect();
        $sql = "SELECT * FROM nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
        $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
        if (pg_numrows($invRslt) < 1) {
            return "<i class=err>Not Found</i>";
        }
        $inv = pg_fetch_array($invRslt);
        $ctyp = $inv['ctyp'];
        //$td=$inv['sdate'];
        $td = $inv['odate'];
        //$cus['surname']=$inv['cusname'];
        if ($ctyp == 's') {
            $cusnum = $inv['tval'];
            $sql = "SELECT * FROM customers WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $custRslt = db_exec($sql) or errDie("Unable to view customer");
            $cus = pg_fetch_array($custRslt);
            $na = $cus['surname'];
        } elseif ($ctyp == 'c') {
            $deptid = $inv['tval'];
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$deptid}'";
            $deptRslt = db_exec($sql) or errDie("Unable to view customers");
            $dept = pg_fetch_array($deptRslt);
            $na = $inv['cusname'];
        }
        db_connect();
        $sql = "SELECT * FROM nons_inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql) or errDie("Unable to get data.");
        unset($totstkamt);
        $refnum = getrefnum();
        /*refnum*/
        /* - Start Hooks - */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "NO VAT");
        $varacc = gethook("accnum", "salesacc", "name", "sales_variance");
        /* - End Hooks - */
        db_conn("cubit");
        $real_invid = divlastid('inv', USER_DIV);
        db_conn("cubit");
        # Put in product
        $totstkamt = array();
        while ($stk = pg_fetch_array($stkdRslt)) {
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stk['vatex']}'";
            $Ri = db_exec($Sl) or errDie("Unable to get data.");
            $vd = pg_fetch_array($Ri);
            if ($vd['zero'] == "Yes") {
                $stk['vatex'] = "y";
            }
            $t = $inv['chrgvat'];
            $stkacc = $stk['accid'];
            if (isset($totstkamt[$stkacc])) {
                if ($stk['vatex'] == "y") {
                    $totstkamt[$stkacc] += vats($stk['amt'], 'novat', $vd['vat_amount']);
                    $va = 0;
                    $inv['chrgvat'] = "";
                } else {
                    $totstkamt[$stkacc] += vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                    $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                    if ($inv['chrgvat'] == "no") {
                        $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                    }
                }
            } else {
                if ($stk['vatex'] == "y") {
                    $totstkamt[$stkacc] = vats($stk['amt'], 'novat', $vd['vat_amount']);
                    $inv['chrgvat'] = "";
                    $va = 0;
                } else {
                    $totstkamt[$stkacc] = vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']);
                    $va = sprint($stk['amt'] - vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']));
                    if ($inv['chrgvat'] == "no") {
                        $va = sprint($stk['amt'] * $vd['vat_amount'] / 100);
                    }
                }
            }
            vatr($vd['id'], $td, "OUTPUT", $vd['code'], $refnum, "Non-Stock Sales, invoice No.{$real_invid}", vats($stk['amt'], $inv['chrgvat'], $vd['vat_amount']) + $va, $va);
            //print vats($stk['amt'],$inv['chrgvat'], $vd['vat_amount']);
            $inv['chrgvat'] = $t;
            //$sql = "UPDATE nons_inv_items SET accid = '$stk[account]' WHERE id = '$stk[id]'";
            //$sRslt = db_exec($sql);
        }
        /* --- Start Some calculations --- */
        # Subtotal
        $SUBTOT = sprint($inv['subtot']);
        $VAT = sprint($inv['vat']);
        $TOTAL = sprint($inv['total']);
        /* --- End Some calculations --- */
        /* - Start Hooks - */
        //$vatacc = gethook("accnum", "salesacc", "name", "VAT");
        /* - End Hooks - */
        # todays date
        $date = date("d-m-Y");
        $sdate = date("Y-m-d");
        db_conn("cubit");
        if (isset($bankid)) {
            $bankid += 0;
            db_conn("cubit");
            $sql = "SELECT * FROM bankacct WHERE bankid = '{$inv['accid']}'";
            $deptRslt = db_exec($sql) or errDie("Unable to view customers");
            if (pg_numrows($deptRslt) < 1) {
                $error = "<li class=err> Bank not Found.";
                $confirm .= "{$error}<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
                return $confirm;
            } else {
                $deptd = pg_fetch_array($deptRslt);
            }
            db_conn('core');
            $Sl = "SELECT * FROM bankacc WHERE accid='{$bankid}'";
            $rd = db_exec($Sl) or errDie("Unable to get data.");
            $data = pg_fetch_array($rd);
            $BA = $data['accnum'];
        }
        $tot_post = 0;
        # bank  % cust
        if ($ctyp == 's') {
            # Get department
            db_conn("exten");
            $sql = "SELECT * FROM departments WHERE deptid = '{$cus['deptid']}' AND div = '" . USER_DIV . "'";
            $deptRslt = db_exec($sql);
            if (pg_numrows($deptRslt) < 1) {
                $dept['deptname'] = "<li class=err>Department not Found.";
            } else {
                $dept = pg_fetch_array($deptRslt);
            }
            $tpp = 0;
            //$sql = "SELECT * FROM nons_inv_items  WHERE invid = '$invid' AND div = '".USER_DIV."'";
            //$stkdRslt = db_exec($sql);
            // 			# Put in product
            // 			while($stk = pg_fetch_array($stkdRslt)){
            // 				$wamt=$stk['amt'];
            //
            // 				$tot_post+=$wamt;
            // 				writetrans($dept['debtacc'], $stk['account'], $td, $refnum, $wamt, "Non-Stock Sales on invoice No.$real_invid customer $cus[surname].");
            // 			}
            # record transaction  from data
            foreach ($totstkamt as $stkacc => $wamt) {
                # Debit Customer and Credit stock
                $tot_post += $wamt;
                writetrans($dept['debtacc'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            # Debit bank and credit the account involved
            if ($VAT != 0) {
                $tot_post += $VAT;
                writetrans($dept['debtacc'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            $sdate = date("Y-m-d");
        } else {
            if (!isset($accountc)) {
                $accountc = 0;
            }
            if (!isset($dept['pca'])) {
                $accountc += 0;
                $dept['pca'] = $accountc;
                $dept['debtacc'] = $accountc;
            }
            if (isset($bankid)) {
                $dept['pca'] = $BA;
            }
            if ($ctyp == "ac") {
                $dept['pca'] = $inv['tval'];
            }
            $tpp = 0;
            # record transaction  from data
            foreach ($totstkamt as $stkacc => $wamt) {
                if (!isset($cust['surname'])) {
                    $cust['surname'] = $inv['cusname'];
                    $cust['addr1'] = $inv['cusaddr'];
                }
                # Debit Customer and Credit stock
                $tot_post += $wamt;
                writetrans($dept['pca'], $stkacc, $td, $refnum, $wamt, "Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            if (isset($bankid)) {
                db_connect();
                $bankid += 0;
                $sql = "INSERT INTO cashbook(bankid, trantype, date, name, descript, cheqnum, amount, vat, chrgvat, banked, accinv, div) VALUES ('{$bankid}', 'deposit', '{$td}', '{$inv['cusname']}', 'Non-Stock Sales on invoice No.{$real_invid} customer {$inv['cusname']}', '0', '{$TOTAL}', '{$VAT}', '{$inv['chrgvat']}', 'no', '{$stkacc}', '" . USER_DIV . "')";
                $Rslt = db_exec($sql) or errDie("Unable to add bank payment to database.", SELF);
                $sql = "UPDATE nons_invoices SET jobid='{$bankid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
                $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            }
            # Debit bank and credit the account involved
            if ($VAT != 0) {
                $tot_post += $VAT;
                writetrans($dept['pca'], $vatacc, $td, $refnum, $VAT, "Non-Stock Sales VAT received on invoice No.{$real_invid} customer {$inv['cusname']}.");
            }
            $sdate = date("Y-m-d");
        }
        $tot_post = sprint($tot_post);
        db_connect();
        if ($ctyp == 's') {
            $sql = "UPDATE nons_invoices SET balance = total, cusid = '{$cusnum}', ctyp = '{$ctyp}', cusaddr = '{$cus['addr1']}', cusvatno = '{$cus['vatnum']}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            # Record the payment on the statement
            $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}','{$inv['odate']}', 'Non-Stock Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            # Record the payment on the statement
            $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$cusnum}', '{$real_invid}', '{$inv['docref']}', '{$TOTAL}', '{$TOTAL}','{$inv['sdate']}', 'Non-Stock Invoice', '" . USER_DIV . "')";
            $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
            # Update the customer (make balance more)
            $sql = "UPDATE customers SET balance = (balance + '{$TOTAL}'::numeric(13,2)) WHERE cusnum = '{$cusnum}' AND div = '" . USER_DIV . "'";
            $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
            # Make ledge record
            custledger($cusnum, $stkacc, $td, $real_invid, "Non Stock Invoice No. {$real_invid}", $TOTAL, "d");
            custDT($TOTAL, $cusnum, $td, $invid, "nons");
            //print $tot_post;exit;
            $tot_dif = sprint($tot_post - $TOTAL);
            if ($tot_dif > 0) {
                writetrans($varacc, $dept['debtacc'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            } elseif ($tot_dif < 0) {
                $tot_dif = $tot_dif * -1;
                writetrans($dept['debtacc'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            }
        } else {
            $date = date("Y-m-d");
            $sql = "UPDATE nons_invoices SET balance=total, accid = '{$dept['pca']}', ctyp = '{$ctyp}', done = 'y', invnum = '{$real_invid}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
            $upRslt = db_exec($sql) or errDie("Unable to update invoice information");
            $tot_dif = sprint($tot_post - $TOTAL);
            if ($tot_dif > 0) {
                writetrans($varacc, $dept['pca'], $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            } elseif ($tot_dif < 0) {
                $tot_dif = $tot_dif * -1;
                writetrans($dept['pca'], $varacc, $td, $refnum, $tot_dif, "Sales Variance on invoice {$real_invid}");
            }
            if ($ctyp == "c") {
                $cusnum = "0";
            } elseif ($ctyp == "ac") {
                $cusnum = "0";
                $na = "";
            }
        }
        db_connect();
        $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\tVALUES('{$inv['sdate']}', '{$invid}', '{$real_invid}', '{$dept['debtacc']}', '{$VAT}', '{$TOTAL}', 'non', '" . USER_DIV . "')";
        $recRslt = db_exec($sql);
        db_conn('cubit');
        $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t\t('{$cusnum}','{$na}','Non-stock Invoice {$real_invid}','{$inv['sdate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
        $Ri = db_exec($Sl);
        $ecost = sprint($TOTAL - $VAT);
        db_conn('cubit');
        $inv['jobid'] += 0;
        $Sl = "SELECT * FROM ninvc WHERE inv='{$inv['jobid']}'";
        $Ri = db_exec($Sl);
        if (CC_USE == "use") {
            if (pg_num_rows($Ri) > 0) {
                while ($data = pg_fetch_array($Ri)) {
                    db_conn('cubit');
                    $sql = "SELECT * FROM costcenters WHERE ccid = '{$data['cid']}'";
                    $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
                    $cc = pg_fetch_array($ccRslt);
                    $amount = sprint($ecost * $data['amount'] / 100);
                    db_conn(PRD_DB);
                    $sql = "INSERT INTO cctran(ccid, trantype, typename, edate, description, amount, username, div)\n\t\t\t\t\tVALUES('{$cc['ccid']}', 'dt', 'Invoice', '{$inv['sdate']}', 'Invoice No.{$real_invid}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "')";
                    $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
                }
            }
        }
        $i++;
    }
    pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
    // Retrieve template settings
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        pdf($_POST);
    } else {
        templatePdf($_POST);
    }
    // Final Laytout
    $write = "\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t\t<tr><th>{$i} Invoices Proccesed</th></tr>\n\t\t<tr class='bg-even'><td>Invoices have been successfully printed.</td></tr>\n\t</table>\n\t<p>\n\t<table border=0 cellpadding='" . TMPL_tblCellPadding . "' cellspacing='" . TMPL_tblCellSpacing . "'>\n\t<tr><th>Quick Links</th></tr>\n\t<tr class='bg-odd'><td><a href='invoice-view.php'>View Invoices</a></td></tr>\n\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
Ejemplo n.º 4
0
	$sacoche_pdf->tableau_devoir_repartition_nominative_initialiser($somme);
	foreach($tab_item_id as $item_id=>$tab_infos_item)
	{
		// 1ère ligne : nouvelle page si besoin + référence du devoir et des codes si besoin
		$sacoche_pdf->tableau_devoir_repartition_nominative_entete($groupe_nom,$date_fr,$description,$tab_init_quantitatif,$tab_repartition_quantitatif[$item_id]);
		// ligne de répartition pour 1 item : référence item
		$sacoche_pdf->tableau_saisie_reference_item($tab_infos_item[0],$tab_infos_item[1]);
		// ligne de répartition pour 1 item : cases répartition nominative
		foreach($tab_repartition_nominatif[$item_id] as $code=>$tab_eleves)
		{
			// Ecrire les noms ; plus court avec MultiCell() mais pb des retours à la ligne pour les noms trop longs
			$memo_X = $sacoche_pdf->GetX();
			$memo_Y = $sacoche_pdf->GetY();
			foreach($tab_eleves as $key => $eleve_texte)
			{
				$sacoche_pdf->CellFit($sacoche_pdf->cases_largeur , $sacoche_pdf->lignes_hauteur , pdf($eleve_texte) , 0 , 2 , 'L' , false , '');
			}
			// Ajouter la bordure
			$sacoche_pdf->SetXY($memo_X , $memo_Y);
			$sacoche_pdf->Cell($sacoche_pdf->cases_largeur , $sacoche_pdf->cases_hauteur , '' , 1 , 0 , 'C' , false , '');
		}
		$sacoche_pdf->SetXY($sacoche_pdf->marge_gauche , $sacoche_pdf->GetY()+$sacoche_pdf->cases_hauteur);
	}
	$sacoche_pdf->Output($dossier_export.$fnom_export.'_repartition_nominative.pdf','F');
	//
	// c'est fini...
	//
	exit();
}

//	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Ejemplo n.º 5
0
 public function pdf($html, $name = null, $orientation = null, $disposition = null)
 {
     return pdf($html, $name, $orientation, $disposition);
 }
Ejemplo n.º 6
0
 static function generate($form)
 {
     $config = Config::read();
     $weightArray = array();
     $headerArray = array();
     $selectedFields = "";
     $tables = "";
     $whereCondition = "";
     $maxCondition = "";
     $n = 0;
     $db = db::raw_connect();
     if (isset($form['dataFilter']) && $form['dataFilter']) {
         if (strpos($form['dataFilter'], '@')) {
             ereg("[\\@][A-Za-z0-9_]+", $form['dataFilter'], $regs);
             foreach ($regs as $reg) {
                 $form['dataFilter'] = str_replace($reg, $_REQUEST["fl_" . str_replace("@", "", $reg)], $form['dataFilter']);
             }
         }
     }
     if ($form['type'] == 'standard') {
         if (isset($form['joinTables']) && $form['joinTables']) {
             $tables = $form['joinTables'];
         }
         if (isset($form['joinConditions']) && $form['joinConditions']) {
             $whereCondition = " " . $form['joinConditions'];
         }
         foreach ($form['components'] as $name => $com) {
             if (!isset($com['attributes']['value'])) {
                 $com['attributes']['value'] = "";
             }
             if ($_REQUEST['fl_' . $name] == $com['attributes']['value']) {
                 $_REQUEST['fl_' . $name] = "";
             }
             if (trim($_REQUEST["fl_" . $name]) && $_REQUEST["fl_" . $name] != '@') {
                 if ($form['components'][$name]['valueType'] == 'date') {
                     $whereCondition .= " and " . $form['source'] . ".{$name} = '" . $_REQUEST["fl_" . $name] . "'";
                 } else {
                     if ($form['components'][$name]['valueType'] == 'numeric') {
                         $whereCondition .= " and " . $form['source'] . ".{$name} = '" . $_REQUEST["fl_" . $name] . "'";
                     } else {
                         if ($form['components'][$name]['type'] == 'hidden') {
                             $whereCondition .= " and " . $form['source'] . ".{$name} = '" . $_REQUEST["fl_" . $name] . "'";
                         } else {
                             if ($com['type'] == 'check') {
                                 if ($_REQUEST["fl_" . $name] == $form['components'][$name]['checkedValue']) {
                                     $whereCondition .= " and " . $form['source'] . ".{$name} = '" . $_REQUEST["fl_" . $name] . "'";
                                 }
                             } else {
                                 if ($com['type'] == 'time') {
                                     if ($_REQUEST["fl_" . $name] != '00:00') {
                                         $whereCondition .= " and {$form['source']}.{$name} = '" . $_REQUEST["fl_" . $name] . "'";
                                     }
                                 } else {
                                     if ($com['primary'] || $com['type'] == 'combo') {
                                         $whereCondition .= " and " . $form['source'] . ".{$name} = '" . $_REQUEST["fl_" . $name] . "'";
                                     } else {
                                         $whereCondition .= " and " . $form['source'] . ".{$name} like '%" . $_REQUEST["fl_" . $name] . "%'";
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     //Modificaciones para seleccion de la ordenacion del report, si esta acabado en _id, quiere decir foreignkey
     //Cojeremos el texto sin el id, tendremos la tabla
     ActiveRecord::sql_item_sanizite($_REQUEST['reportTypeField']);
     if (substr($_REQUEST['reportTypeField'], strlen($_REQUEST['reportTypeField']) - 3, strlen($_REQUEST['reportTypeField'])) == "_id") {
         $OrderFields = substr($_REQUEST['reportTypeField'], 0, strlen($_REQUEST['reportTypeField']) - 3);
     } else {
         $OrderFields = $_REQUEST['reportTypeField'];
     }
     $maxCondition = $whereCondition;
     $n = 0;
     foreach ($form['components'] as $name => $com) {
         if (!isset($com['notReport'])) {
             $com['notReport'] = false;
         }
         if (!isset($com['class'])) {
             $com['class'] = false;
         }
         if (!$com['notReport']) {
             if (isset($com['caption']) && $com['caption']) {
                 $headerArray[$n] = str_replace("&oacute;", "ó", $com['caption']);
                 $headerArray[$n] = str_replace("&aacute;", "á", $headerArray[$n]);
                 $headerArray[$n] = str_replace("&eacute;", "é", $headerArray[$n]);
                 $headerArray[$n] = str_replace("&iacute;", "í", $headerArray[$n]);
                 $headerArray[$n] = str_replace("&uacute;", "ú", $headerArray[$n]);
                 $headerArray[$n] = str_replace("<br/>", " ", $headerArray[$n]);
             } else {
                 $com['caption'] = "";
             }
             if ($com['type'] == 'combo' && $com['class'] == 'dynamic') {
                 if (isset($com['extraTables']) && $com['extraTables']) {
                     $tables .= "{$com['extraTables']},";
                 }
                 if (isset($com['whereConditionOnQuery']) && $com['whereConditionOnQuery']) {
                     $whereCondition .= " and {$com['whereConditionOnQuery']}";
                 }
                 if (strpos(" " . $com['detailField'], "concat(")) {
                     $selectedFields .= $com['detailField'] . ",";
                 } else {
                     $selectedFields .= $com['foreignTable'] . "." . $com['detailField'] . ",";
                     //Comparamos la Tabla foranea que tenemos, y cuando sea igual, suponiendo no hay
                     //mas de una clave foranea por tabla, sabremos a que tabla pertenece
                     if ($com['foreignTable'] == $OrderFields) {
                         $OrderFields = $com['foreignTable'] . "." . $com['detailField'];
                     }
                 }
                 $tables .= $com['foreignTable'] . ",";
                 if ($com['column_relation']) {
                     $whereCondition .= " and " . $com['foreignTable'] . "." . $com['column_relation'] . " = " . $form['source'] . "." . $name;
                 } else {
                     $whereCondition .= " and " . $com['foreignTable'] . "." . $name . " = " . $form['source'] . "." . $name;
                 }
                 $weightArray[$n] = strlen($headerArray[$n]) + 2;
                 $n++;
             } else {
                 if ($com['type'] != 'hidden') {
                     if ($com['class'] == 'static' && isset($com['type']) && $com['type'] == 'combo') {
                         $weightArray[$n] = strlen($headerArray[$n]) + 2;
                         if ($config->type == 'pgsql') {
                             $selectedFields .= "case ";
                         }
                         if ($config->type == 'mysql') {
                             for ($i = 0; $i <= count($com['items']) - 2; $i++) {
                                 $selectedFields .= "if(" . $form['source'] . "." . $name . "='" . $com['items'][$i][0] . "', '" . $com['items'][$i][1] . "', ";
                                 if ($weightArray[$n] < strlen($com['items'][$i][1])) {
                                     $weightArray[$n] = strlen($com['items'][$i][1]) + 1;
                                 }
                             }
                         }
                         if ($config->type == 'pgsql') {
                             for ($i = 0; $i <= count($com['items']) - 1; $i++) {
                                 $selectedFields .= " when " . $form['source'] . "." . $name . "='" . $com['items'][$i][0] . "' THEN '" . $com['items'][$i][1] . "' ";
                                 if ($weightArray[$n] < strlen($com['items'][$i][1])) {
                                     $weightArray[$n] = strlen($com['items'][$i][1]) + 1;
                                 }
                             }
                         }
                         $n++;
                         if ($config->type == 'mysql') {
                             $selectedFields .= "'" . $com['items'][$i][1] . "')";
                             for ($j = 0; $j <= $i - 2; $j++) {
                                 $selectedFields .= ")";
                             }
                         }
                         if ($config->type == 'pgsql') {
                             $selectedFields .= " end ";
                         }
                         $selectedFields .= ",";
                     } else {
                         $selectedFields .= $form['source'] . "." . $name . ",";
                         //Aqui seguro que no es foranea, entonces tenemos que poner la tabla principal 							//
                         //antes para evitar repeticiones
                         if ($name == $OrderFields) {
                             $OrderFields = $form['source'] . "." . $OrderFields;
                         }
                         $weightArray[$n] = strlen($headerArray[$n]) + 2;
                         $n++;
                     }
                 }
             }
         }
     }
     $tables .= $form['source'];
     $selectedFields = substr($selectedFields, 0, strlen($selectedFields) - 1);
     if (isset($form['dataRequisite']) && $form['dataRequisite']) {
         $whereCondition .= " and {$form['dataFilter']}";
     }
     //Modificacion del order
     if ($OrderFields) {
         $OrderCondition = "Order By " . $OrderFields;
     } else {
         $OrderCondition = "";
     }
     $query = "select {$selectedFields} from {$tables} where 1 = 1 " . $whereCondition . " " . $OrderCondition;
     $q = $db->query($query);
     if (!is_bool($q)) {
         if (!$db->num_rows($q)) {
             Flash::notice("No hay informaci&oacute;n para listar");
             return;
         }
     } else {
         Flash::error($db->error());
         return;
     }
     $result = array();
     $n = 0;
     while ($row = $db->fetch_array($q, db::DB_NUM)) {
         $result[$n++] = $row;
     }
     foreach ($result as $row) {
         for ($i = 0; $i <= count($row) - 1; $i++) {
             if ($weightArray[$i] < strlen(trim($row[$i]))) {
                 $weightArray[$i] = strlen(trim($row[$i]));
             }
         }
     }
     for ($i = 0; $i <= count($weightArray) - 1; $i++) {
         $weightArray[$i] *= 1.8;
     }
     $sumArray = array_sum($weightArray);
     if (!$_REQUEST['reportType']) {
         $_REQUEST['reportType'] = 'pdf';
     }
     if ($_REQUEST['reportType'] != 'html') {
         $title = str_replace("&oacute;", "ó", $form['caption']);
         $title = str_replace("&aacute;", "á", $title);
         $title = str_replace("&eacute;", "é", $title);
         $title = str_replace("&iacute;", "í", $title);
         $title = str_replace("&uacute;", "ú", $title);
     } else {
         $title = $form['caption'];
     }
     switch ($_REQUEST['reportType']) {
         case 'pdf':
             require_once CORE_PATH . 'extensions/report/format/pdf.php';
             pdf($result, $sumArray, $title, $weightArray, $headerArray);
             break;
         case 'xls':
             require_once CORE_PATH . 'extensions/report/format/xls.php';
             xls($result, $sumArray, $title, $weightArray, $headerArray);
             break;
         case 'html':
             require_once CORE_PATH . 'extensions/report/format/htm.php';
             htm($result, $sumArray, $title, $weightArray, $headerArray);
             break;
         case 'doc':
             require_once CORE_PATH . 'extensions/report/format/doc.php';
             doc($result, $sumArray, $title, $weightArray, $headerArray);
             break;
         default:
             require_once CORE_PATH . 'extensions/report/format/pdf.php';
             pdf($result, $sumArray, $title, $weightArray, $headerArray);
             break;
     }
 }
Ejemplo n.º 7
0
		$releve_html_table_head .= '<th title="'.html($tab_item[$item_id][0]['item_nom']).'">'.html($tab_item[$item_id][0]['item_ref']).'</th>';
	}
	$releve_pdf->SetX( $releve_pdf->GetX()+2 );
	$releve_pdf->choisir_couleur_fond('gris_fonce');
	$releve_pdf->Cell($releve_pdf->cases_largeur , $releve_pdf->cases_hauteur , '[ * ]'  , 1 , 0 , 'C' , true , '');
	$releve_pdf->Cell($releve_pdf->cases_largeur , $releve_pdf->cases_hauteur , '[ ** ]' , 1 , 1 , 'C' , true , '');
	$releve_html_table_head .= '<th class="nu">&nbsp;</th><th>[ * ]</th><th>[ ** ]</th></tr></thead>'."\r\n";
	// lignes suivantes
	$releve_html_table_body1 = '';
	$releve_html_table_body2 = '';
	// Pour chaque élève...
	foreach($tab_eleve as $tab)
	{
		extract($tab);	// $eleve_id $eleve_nom $eleve_prenom $eleve_id_gepi
		$releve_pdf->choisir_couleur_fond('gris_clair');
		$releve_pdf->Cell($releve_pdf->eleve_largeur , $releve_pdf->cases_hauteur , pdf($eleve_nom.' '.$eleve_prenom) , 1 , 0 , 'L' , true , '');
		$releve_html_table_body1 .= '<tr><td>'.html($eleve_nom.' '.$eleve_prenom).'</td>';
		$releve_html_table_body2 .= '<tr><td>'.html($eleve_nom.' '.$eleve_prenom).'</td>';
		// Pour chaque item...
		foreach($tab_liste_item as $item_id)
		{
			$score = (isset($tab_score_eleve_item[$eleve_id][$matiere_id][$item_id])) ? $tab_score_eleve_item[$eleve_id][$matiere_id][$item_id] : false ;
			$releve_pdf->afficher_score_bilan($score,$br=0);
			$releve_html_table_body1 .= affich_score_html($score,'score');
			$releve_html_table_body2 .= affich_score_html($score,'etat');
		}
		$releve_pdf->bilan_periode_synthese_pourcentages($tab_moyenne_scores_eleve[$matiere_id][$eleve_id],$tab_pourcentage_acquis_eleve[$matiere_id][$eleve_id],false,true);
		$releve_html_table_body1 .= '<td class="nu">&nbsp;</td>'.affich_score_html($tab_moyenne_scores_eleve[$matiere_id][$eleve_id],'score','%').affich_score_html($tab_pourcentage_acquis_eleve[$matiere_id][$eleve_id],'score','%').'</tr>'."\r\n";
		$releve_html_table_body2 .= '<td class="nu">&nbsp;</td>'.affich_score_html($tab_moyenne_scores_eleve[$matiere_id][$eleve_id],'etat','%').affich_score_html($tab_pourcentage_acquis_eleve[$matiere_id][$eleve_id],'etat','%').'</tr>'."\r\n";
	}
	$releve_html_table_body1 = '<tbody>'.$releve_html_table_body1.'</tbody>'."\r\n";
Ejemplo n.º 8
0
 public function imprimir()
 {
     setlocale(LC_ALL, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
     date_default_timezone_set('America/Sao_Paulo');
     $dadosResult = $this->contrato_model->listar($this->id, 'nome, cpf, idade, endereco, bairro, cidade, curso, dias, data, horario, meses, valor_matricula, mensalidades, valor_mensalidade, carga_horaria, boleto_nome, boleto_cpf');
     $dados = $dadosResult[0];
     $html = "<html>";
     $html .= "<head><title>Contrato | " . $dados['nome'] . "</title></head>";
     $html .= "<body>";
     if ($dados['idade'] < 18) {
         $menor = ' responsável <strong>' . $dados['boleto_nome'] . '</strong>, CPF <strong>' . $dados['boleto_cpf'] . '</strong>';
     } else {
         $menor = '';
     }
     $valor_matricula = $dados['valor_matricula'] == '00,00' ? 'Isento' : 'R$ ' . $dados['valor_matricula'];
     $html .= '<p style="text-align: center;"><strong>CONTRATO DE PRESTAÇÃO DE SERVIÇOS</strong></p>
     <p style="font-size:10px; text-align: justify;">Pelo presente instrumento particular de serviços, Escola de Dança Aline Rosa com sede nesta capital na Av. Assis Brasil 2100, 2° andar, bairro Passo D\'Areia, Porto Alegre/RS, CNPJ 00714970/0001-59 neste ato representado por sua diretora abaixo firmado doravante denominada simplesmente <strong>CONTRATADO</strong>, e do outro lado, doravante denominado <strong>CONTRATANTE</strong> Sr(a) <strong>' . $dados['nome'] . '</strong>, CPF <strong>' . $dados['boleto_cpf'] . '</strong>' . $menor . ' residente no endereço <strong>' . $dados['endereco'] . '</strong>, no bairro <strong>' . $dados['bairro'] . '</strong> na cidade de <strong>' . $dados['cidade'] . '</strong>/RS tem justo e contratado:</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 1°:</strong> O presente contrato é estabelecido sob os preceitos da Lei de Diretrizes e Bases da Educação e regimento dos cursos livre, tem por finalidade a prestação de serviços educacionais em Dança. O contratado colocará a disposição do contratante aulas de: <strong>' . $dados['curso'] . '</strong> no(s) dia(s) <strong>' . $dados['dias'] . '</strong> no horário <strong>' . $dados['horario'] . '</strong> nas dependências da Escola de Dança Aline Rosa. A duração do presente contrato é de <strong>' . $dados['meses'] . '</strong> meses à contar da data de assinatura do mesmo até dezembro do corrente ano.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 2°:</strong> O contratante pagará ao contratado pelos serviços prestados o seguinte: taxa de matrícula no valor de <strong>' . $valor_matricula . '</strong>, e mais <strong>' . $dados['mensalidades'] . '</strong> mensalidades no valor de R$ <strong>' . $dados['valor_mensalidade'] . '</strong>. O valor é antecipado no dia 10 de cada mês. Sendo a Escola da iniciativa privada, as mensalidades são pagas integralmente do período de entrada a dezembro, sem descontos. A quantidade de aulas do ano letivo é de <strong>' . $dados['carga_horaria'] . '</strong> aulas. A mensalidade de dezembro deverá ser paga integralmente, pois a carga horária deste mês foi completada durante o ano levito através de aulas extras, ensaios. <strong>No caso de inadimplência no período de dois meses o aluno não poderá frequentar as aulas até quitar as mensalidades pendentes</strong>.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 3°:</strong> A cobrança de mensalidades será realizada através de boleto bancário fornecido pelo Contratado. O contratante deverá pagar `custa dos encargos, juros e demais taxas em caso de atraso. Não será aceito pagamento na secretaria da Escola por motivo de segurança. A assuidade as aulas é responsabilidade do contratante. Em caso de falta a recuperação será realizada nos horários e turmas compatíveis que o contratado dispõe. Em caso de falta o aluno não haverá desconto na mensalidade. O material das aulas teóricas não está incluso na mensalidade sendo cobrado separadamente de acordo com o andamento do curso e o nível técnico dos alunos.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 4°:</strong> O aluno que desistir no decorrer do ano letivo deverá assinar o termo de cancelamento na secretaria da Escola, estar com as mensalidades dos meses anteriores em dia para cancelar o presente contrato. Haverá uma taxa de R$ 60,00 para o cancelamento, pois as turmas têm números de vagas limitado. Caso não seja assinado o termo de cancelamento as mensalidades estarão correndo por conta do COntratante até o final do presente contrato, e sujeitos a cobrança judicial.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 5°:</strong> O ingresso do estudante na Escola pressupõe que tenha condições de saúde para frequentar as aulas e realizar esforço físico, sendo de sua inteira responsablilidade informar a Escola eventuais lesões, uso contínuo de medicamentos, doenças ou sequelas de tratamentos realizados.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 6°:</strong> Passeios extras, amostras de arte, festivais de dança deverão ter a autorização por escrito e será responsabilidade dos pais o custeio dos mesmos quando menor de idade. Toda a atividade, ensaio, apresentação compõem a carga horária e são consideradas como aula dada.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 7°:</strong> O contratante reconhece a competência da Escola de Dança e aceita os programas de ensino adotados, acatando ao seu regimento interno, normas diciplinares, agrupamento de estudantes em turmas conforme nível técnico, com a inclusão - ou não - nas diversas danças, apresentações ocasionais ou festivais competitivos. Comprometendo-se oferecer aulas ministradas por profissionais qualificados, procurar contribuir para o desenvolvimento físico e intelectual do estudante; promover objetivamente o progresso técnico e artístico do estudante com suas aptidões e possibilidades individuais. O contratado se reserva o direito de mudanças técnicas e de professor ao seu critério. Os professores muito embora se comprometam a despender a todos os estudantes a mesma atenção e ensinamentos, não garantem os mesmos resultados e promoções iguais a todos. É do conhecimento do contratante que as condições físicas são individuais e distintas, e que o tempo para atingir cada nível de progresso varia de aluno para aluno.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 8°:</strong> As apresentações realizadas pela Escola serão organizadas pela mesma, ficando aos pais ou responsável o compromisso de pagar o figurino e a taxa de participação para a inclusão do aluno na atividade. Será assinado um contrato especial para participação neste evento.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 9°:</strong> Todos são responsáveis pela conservação da Escola em todos os seus aspectos, devendo pagar os danos como fator de justiça, todo aquele que os causar. O aluno é responsável pelo seu material, mochila, bolsa, roupa, carteira, celular ou objetos de valor. A Escola dispõe de armários rotativos ou fixos para guardar os pertences com segurança.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 10°:</strong> O aluno, ou seus pais, caso seja menor, desde já cedem a Escola o direito de imagem, autorizando a veiculação de sua imagem em todos os meios de publicação e difusão que interessem aos fins artísticos e/ou comerciais da Escola de Dança Aline Rosa como entidades voltadas a fins educacionais e culturais.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 11°:</strong> O contratado deverá comunicar ao contratante toda e qualquer modificação técnica ou atividade realizada na Escola. Todas as infomações que constam na ficha de cadastro são de responsabilidade do contratante. Em caso de alteração nos dados deve o contratante informar a secretaria da Escola para evitar falhas na comunicação.</p>
     <p style="font-size:10px; text-align: justify;"><strong>Cláusula 12°:</strong> Fica claramente entendido que tanto os serviços que o contratado presta, bem como o presente contrato, não serão em nenhum momento considerados experimentais.</p>
     <p style="font-size:12px;">Assim por estarem justas e contratadas, as partes assinam o presente em duas vias de igual teor e forma.</p>
     <br/>
     <p style="width:300px; float:left;  border-top:2px solid #000000; text-align: center; font-weight: bold;">Contratado</p>
     <p style="width:300px; float:right; margin-top: 0px; border-top:2px solid #000000; text-align: center; font-weight: bold;">Contratante</p>
     <br/>
     <p style="clear:both; text-align:right;">Porto Alegre, _______ de _____________________ de 2016.</p>
     ';
     $html .= "</body>";
     $html .= "</html>";
     $nomeArquivo = str_replace(" ", "-", strtolower($dados['nome']));
     pdf($html, 'contrato-' . $nomeArquivo, 'Contrato ' . $dados['nome'], 'Visite nosso site: www.escoladancaalinerosa.com.br');
 }
Ejemplo n.º 9
0
    $pdf->MultiCell(50, 1, 'Ad Soyad:', 0, 'L', 0, 1, '120', '', true);
    $pdf->MultiCell(50, 1, 'İmza:', 0, 'L', 0, 1, '120', '', true);
    $pdf->Output();
}
function strtolower_turkish($string)
{
    $lower = array('İ' => 'i', 'I' => 'ı', 'Ğ' => 'ğ', 'Ü' => 'ü', 'Ş' => 'ş', 'Ö' => 'ö', 'Ç' => 'ç');
    return strtolower(strtr($string, $lower));
}
function streq_turkish($string1, $string2)
{
    return strtolower_turkish($string1) == strtolower_turkish($string2);
}
// FIXME production kodda derin değişiklikler yapmak istemiyorum.
// Bu yüzden SESSION.tc yerine SESSION.sorgutc şeklinde kaydet
// eyleminin atadığı değerlerden farklı değerler atandı.  Arada
// bir state kaçırırsak sızma olmasın.
$tc = F3::get('SESSION.sorgutc');
$kizliksoyad = F3::get('SESSION.sorgukizliksoyad');
if (!empty($kizliksoyad) && preg_match('/^\\d{11}$/', $tc)) {
    $kul = new Axon('kul');
    $kul->load("tc={$tc}");
    if (!$kul->dry() && streq_turkish($kul->kizliksoyad, $kizliksoyad)) {
        pdf($kul);
    } else {
        F3::set('error', "Böyle bir kayıt bulunamadı.");
        F3::call(':sorgual');
    }
} else {
    echo "hatali istek";
}
Ejemplo n.º 10
0
 function laporan($var)
 {
     cek_keamanan(array("admin", "user"));
     $this->model("model_user");
     $this->layout = "laporan";
     // untuk layout laporan biasanya tanpa menu
     $data['judul'] = "Laporan User";
     $data['data'] = $this->model_user->ambil_data();
     $out = $this->view("user/daftar", $data, false);
     if (key_exists("ekspor", $var)) {
         switch ($var['ekspor']) {
             case "xls":
                 xls($out);
                 break;
             case "pdf":
                 pdf($out);
                 break;
             default:
                 echo $out;
         }
     } else {
         echo $out;
     }
 }
function write($_POST)
{
    # Set max execution time to 12 hours
    ini_set("max_execution_time", 43200);
    # Get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    foreach ($invids as $key => $invid) {
        $v->isOk($invid, "num", 1, 20, "Invalid recuring invoice number.");
    }
    # display errors, if any
    $err = "";
    if ($v->isError()) {
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return $err;
    }
    $i = 0;
    foreach ($invids as $key => $invid) {
        # Get recuring invoice info
        db_connect();
        $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $invRslt = db_exec($sql) or errDie("Unable to get recuring invoice information");
        if (pg_numrows($invRslt) < 1) {
            return "<i class='err'>Not Found</i>";
        }
        $inv = pg_fetch_array($invRslt);
        # check if invoice has been printed
        if ($inv['printed'] == "y") {
            $error = "<li class='err'> Error : Invoice number <b>{$inv['invnum']}</b> has already been printed.";
            $error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $error;
        }
        # check if invoice has been serialised
        if ($inv['serd'] == "n") {
            $error = "<li class='err'> Error : You must select serial numbers for some Items on Invoice No. <b>T {$invid}</b> before you can print it.";
            $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
            return $error;
        }
        # Begin Updates
        pglib_transaction("BEGIN") or errDie("Unable to start a database transaction.", SELF);
        $invnum = divlastid('inv', USER_DIV);
        $Sl = "INSERT INTO ncsrec (oldnum, newnum, div) VALUES ('{$invid}', '{$invnum}', '" . USER_DIV . "')";
        $Rs = db_exec($Sl) or errDie("Unable to insert into db");
        # Get department
        db_conn("exten");
        $sql = "SELECT * FROM departments WHERE deptid = '{$inv['deptid']}' AND div = '" . USER_DIV . "'";
        $deptRslt = db_exec($sql);
        if (pg_numrows($deptRslt) < 1) {
            $dept['deptname'] = "<i class='err'>Not Found</i>";
        } else {
            $dept = pg_fetch_array($deptRslt);
        }
        /* --- Start Products Display --- */
        # Products layout
        $commision = 0;
        $products = "";
        $disc = 0;
        # get selected stock in this invoice
        db_connect();
        $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        if (pg_numrows($stkdRslt) < 1) {
            $error = "<li class='err'> Error : Invoice number <b>{$invid}</b> has no items.</li>";
            if (($r2sid = r2sListCheck("invoice_stk_view")) !== false) {
                $error .= "<p><input type='button' onClick='document.location.href=\"r2srestore.php?r2sid={$r2sid}\";' value='List Invoices'>";
            } else {
                $error .= "<p><input type='button' onClick='document.location.href=\"invoice-view.php\";' value='List Invoices'>";
            }
            $OUTPUT = $error;
            pglib_transaction("ROLLBACK");
            require "template.php";
        }
        $taxex = 0;
        while ($stkd = pg_fetch_array($stkdRslt)) {
            # get warehouse name
            db_conn("exten");
            $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
            $whRslt = db_exec($sql);
            $wh = pg_fetch_array($whRslt);
            # get selected stock in this warehouse
            db_connect();
            $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
            $stkRslt = db_exec($sql);
            $stk = pg_fetch_array($stkRslt);
            $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
            # Check Tax Excempt
            if ($stk['exvat'] == 'yes') {
                $taxex += $stkd['amt'];
            }
            # Keep track of discounts
            $disc += $stkd['disc'] * $stkd['qty'];
            # Insert stock record
            $sdate = date("Y-m-d");
            $csprice = sprint($stk['csprice'] * $stkd['qty']);
            # Get amount exluding vat if including and not exempted
            //			$VATP = TAX_VAT;
            #get the actual vat perc of this item
            $get_vat = "SELECT vat_amount FROM vatcodes WHERE id = '{$stkd['vatcode']}' LIMIT 1";
            $run_vat = db_exec($get_vat) or errDie("Unable to get vat percentage information");
            if (pg_numrows($run_vat) < 1) {
                $VATP = 0;
            } else {
                $varr = pg_fetch_array($run_vat);
                $VATP = $varr['vat_amount'];
            }
            $amtexvat = sprint($stkd['amt']);
            if ($inv['chrgvat'] == "inc" && $stk['exvat'] != 'yes') {
                $amtexvat = sprint($stkd['amt'] * 100 / (100 + $VATP));
            }
            if ($stkd['account'] == 0) {
                db_connect();
                $sql = "\n\t\t\t\t\tINSERT INTO stockrec (\n\t\t\t\t\t\tedate, stkid, stkcod, stkdes, trantype, qty, \n\t\t\t\t\t\tcsprice, csamt, details, div\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t'{$sdate}', '{$stkd['stkid']}', '{$stk['stkcod']}', '{$stk['stkdes']}', 'invoice', '{$stkd['qty']}', \n\t\t\t\t\t\t'{$amtexvat}', '{$csprice}', 'Stock sold - Invoice No. {$invnum}', '" . USER_DIV . "'\n\t\t\t\t\t)";
                $recRslt = db_exec($sql);
                # Sales rep commission
                //				$commision = $commision + coms($inv['salespn'], $stkd['amt'], $stk['com']);
                $commision = $commision + coms($inv['salespn'], $amtexvat, $stk['com']);
            }
        }
        /* --- Start Some calculations --- */
        # Subtotal
        $SUBTOT = sprint($inv['subtot']);
        # Calculate tradediscm
        if (strlen($inv['traddisc']) > 0) {
            $traddiscm = sprint($inv['traddisc'] / 100 * $SUBTOT);
        } else {
            $traddiscm = "0.00";
        }
        # Calculate subtotal
        $VATP = TAX_VAT;
        $SUBTOTAL = sprint($inv['subtot']);
        $VAT = sprint($inv['vat']);
        $TOTAL = sprint($inv['total']);
        $inv['delchrg'] = sprint($inv['delchrg']);
        com_invoice($inv['salespn'], $TOTAL - $VAT, $commision, $invnum, $inv["odate"]);
        /* --- End Some calculations --- */
        /* - Start Hooks - */
        $vatacc = gethook("accnum", "salesacc", "name", "VAT", "out");
        /* - End Hooks - */
        # Todays date
        $date = date("d-m-Y");
        $sdate = date("Y-m-d");
        $refnum = getrefnum();
        /* --- Updates ---- */
        db_connect();
        $Sql = "UPDATE invoices SET printed ='y', done ='y', invnum='{$invnum}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $upRslt = db_exec($Sql) or errDie("Unable to update invoice information");
        # Record the payment on the statement
        $sql = "\n\t\t\t\tINSERT INTO stmnt \n\t\t\t\t\t(cusnum, invid, docref, amount, date, type, div, allocation_date) \n\t\t\t\tVALUES \n\t\t\t\t\t('{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "', '{$inv['odate']}')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Record the payment on the statement
        $sql = "INSERT INTO open_stmnt(cusnum, invid, docref, amount, balance, date, type, div) VALUES('{$inv['cusnum']}', '{$invnum}', '{$inv['docref']}', '{$inv['total']}','{$inv['total']}', '{$inv['odate']}', 'Invoice', '" . USER_DIV . "')";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Save invoice discount
        $sql = "INSERT INTO inv_discs(cusnum, invid, traddisc, itemdisc, inv_date, delchrg, div,total) VALUES('{$inv['cusnum']}', '{$invnum}', '{$traddiscm}', '{$disc}', '{$inv['odate']}', '{$inv['delchrg']}', '" . USER_DIV . "', ({$SUBTOT}+{$inv['delchrg']}))";
        $stmntRslt = db_exec($sql) or errDie("Unable to insert statement record in Cubit.", SELF);
        # Update the customer (make balance more)
        $sql = "UPDATE customers SET balance = (balance + '{$inv['total']}') WHERE cusnum = '{$inv['cusnum']}' AND div = '" . USER_DIV . "'";
        $rslt = db_exec($sql) or errDie("Unable to update invoice in Cubit.", SELF);
        # Make ledge record
        custledger($inv['cusnum'], $dept['incacc'], $inv["odate"], $invnum, "Invoice No. {$invnum}", $inv['total'], "d");
        $nsp = 0;
        db_connect();
        # get selected stock in this invoice
        $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
        $stkdRslt = db_exec($sql);
        $tcosamt = 0;
        while ($stkd = pg_fetch_array($stkdRslt)) {
            $stkd['account'] += 0;
            if ($stkd['account'] == 0) {
                db_connect();
                # get selamt from selected stock
                $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
                $stkRslt = db_exec($sql);
                $stk = pg_fetch_array($stkRslt);
                if ($stk['units'] - $stkd['qty'] < 0) {
                    if ($stk['units'] <= 0) {
                        $cosamt = 0;
                    } else {
                        $cosamt = round($stk['units'] * $stk['csprice'], 2);
                    }
                } else {
                    $cosamt = round($stkd['qty'] * $stk['csprice'], 2);
                }
                $uc = sprint($cosamt / $stkd['qty']);
                if ($stk['csprice'] > 0) {
                    $Sl = "INSERT INTO scr(inv,stkid,amount) VALUES ('{$invnum}','{$stkd['stkid']}','{$uc}')";
                    $Rg = db_exec($Sl);
                }
                # update stock(alloc - qty)
                $sql = "UPDATE stock SET csamt = (csamt - '{$cosamt}'),units = (units - '{$stkd['qty']}'),alloc = (alloc - '{$stkd['qty']}')  WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
                $rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.", SELF);
                if ($stk['serd'] == 'yes') {
                    ext_invSer($stkd['serno'], $stkd['stkid'], "{$inv['cusname']} {$inv['surname']}", $invnum);
                }
                # stkid, stkcod, stkdes, trantype, edate, qty, csamt, details
                $sdate = date("Y-m-d");
                if ($stkd['account'] == 0) {
                    stockrec($stk['stkid'], $stk['stkcod'], $stk['stkdes'], 'ct', $sdate, $stkd['qty'], $cosamt, "Sold to Customer : {$inv['surname']} - Invoice No. {$invnum}");
                }
            }
            ###################VAT CALCS#######################
            db_connect();
            $stkd['vatcode'] += 0;
            $Sl = "SELECT * FROM vatcodes WHERE id='{$stkd['vatcode']}'";
            $Ri = db_exec($Sl);
            if (pg_num_rows($Ri) < 1) {
                return "Please select the vatcode for all your stock.";
            }
            $vd = pg_fetch_array($Ri);
            if ($stk['exvat'] == 'yes' || $vd['zero'] == "Yes") {
                $excluding = "y";
            } else {
                $excluding = "";
            }
            $vr = vatcalc($stkd['amt'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
            $vrs = explode("|", $vr);
            $ivat = $vrs[0];
            $iamount = $vrs[1];
            vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
            ####################################################
            if ($stkd['account'] == 0) {
                # get accounts
                db_conn("exten");
                $sql = "SELECT stkacc,cosacc FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
                $whRslt = db_exec($sql);
                $wh = pg_fetch_array($whRslt);
                $stockacc = $wh['stkacc'];
                $cosacc = $wh['cosacc'];
                if ($cosamt > 0) {
                    # dt(cos) ct(stock)
                    //						writetrans($cosacc, $stockacc, $date, $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
                    writetrans($cosacc, $stockacc, $inv['odate'], $refnum, $cosamt, "Cost Of Sales for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
                }
                $tcosamt += $cosamt;
                db_connect();
                $date = date("Y-m-d");
                $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\t\t\tVALUES('{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'stk', '" . USER_DIV . "')";
                $recRslt = db_exec($sql);
            } else {
                $amtexvat = sprint($stkd['amt']);
                db_connect();
                $sdate = date("Y-m-d");
                $nsp += sprint($iamount - $ivat);
                //writetrans($cosacc, $stockacc,$inv['odate'] , $refnum, $cosamt, "Cost Of Sales for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
                writetrans($dept['debtacc'], $stkd['account'], $inv['odate'], $refnum, $iamount - $ivat, "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
                db_connect();
                $date = date("Y-m-d");
                $sql = "INSERT INTO salesrec(edate, invid, invnum, debtacc, vat, total, typ, div)\n\t\t\t\t\tVALUES('{$inv['odate']}', '{$invid}', '{$invnum}', '{$dept['debtacc']}', '{$ivat}', '{$iamount}', 'non', '" . USER_DIV . "')";
                $recRslt = db_exec($sql);
            }
        }
        /* - Start Transactoins - */
        # dt(debtors) ct(income/sales)
        //			writetrans($dept['debtacc'], $dept['incacc'], $date, $refnum, sprint($TOTAL-$VAT-$nsp), "Debtors Control for Invoice No.$invnum for Customer : $inv[cusname] $inv[surname]");
        writetrans($dept['debtacc'], $dept['incacc'], $inv['odate'], $refnum, sprint($TOTAL - $VAT - $nsp), "Debtors Control for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
        # dt(debtors) ct(vat account)
        writetrans($dept['debtacc'], $vatacc, $inv['odate'], $refnum, $VAT, "VAT Received on Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}");
        db_conn('cubit');
        $Sl = "INSERT INTO sj(cid,name,des,date,exl,vat,inc,div) VALUES\n\t\t\t('{$inv['cusnum']}','{$inv['surname']}','Invoice {$invnum}','{$inv['odate']}','" . sprint($TOTAL - $VAT) . "','{$VAT}','" . sprint($TOTAL) . "','" . USER_DIV . "')";
        $Ri = db_exec($Sl);
        $ecost = sprint($TOTAL - $VAT);
        db_conn('cubit');
        $inv['jobid'] += 0;
        $Sl = "SELECT * FROM invc WHERE inv='{$inv['jobid']}'";
        $Ri = db_exec($Sl);
        if (CC_USE == "use") {
            if (pg_num_rows($Ri) > 0) {
                while ($data = pg_fetch_array($Ri)) {
                    db_conn('cubit');
                    $sql = "SELECT * FROM costcenters WHERE ccid = '{$data['cid']}'";
                    $ccRslt = db_exec($sql) or errDie("Unable to retrieve Cost centers from database.");
                    $cc = pg_fetch_array($ccRslt);
                    $amount = sprint($ecost * $data['amount'] / 100);
                    db_conn(PRD_DB);
                    $sql = "INSERT INTO cctran(ccid, trantype, typename, edate, description, amount, username, div)\n\t\t\t\t\t\tVALUES('{$cc['ccid']}', 'dt', 'Invoice', '{$inv['odate']}', 'Invoice No.{$invnum}', '{$amount}', '" . USER_NAME . "', '" . USER_DIV . "')";
                    $insRslt = db_exec($sql) or errDie("Unable to retrieve insert Cost center amounts into database.");
                }
            }
        }
        ####/*###*/############VAT CALCS#######################
        $inv['delvat'] += 0;
        db_conn('cubit');
        $Sl = "SELECT * FROM vatcodes WHERE id='{$inv['delvat']}'";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            $Sl = "SELECT * FROM vatcodes";
            $Ri = db_exec($Sl);
        }
        $vd = pg_fetch_array($Ri);
        if ($vd['zero'] == "Yes") {
            $excluding = "y";
        } else {
            $excluding = "";
        }
        $vr = vatcalc($inv['delchrg'], $inv['chrgvat'], $excluding, $inv['traddisc'], $vd['vat_amount']);
        $vrs = explode("|", $vr);
        $ivat = $vrs[0];
        $iamount = $vrs[1];
        vatr($vd['id'], $inv['odate'], "OUTPUT", $vd['code'], $refnum, "VAT for Invoice No.{$invnum} for Customer : {$inv['cusname']} {$inv['surname']}", $iamount, $ivat);
        ####################################################
        # Commit updates
        pglib_transaction("COMMIT") or errDie("Unable to commit a database transaction.", SELF);
        $i++;
    }
    // Retrieve template settings
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='invoices'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if ($template == "invoice-print.php") {
        pdf($_POST);
    } else {
        templatePdf($_POST);
    }
    // Final Laytout
    $write = "\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>{$i} Invoices Proccesed</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>Invoices has been successfully printed.</td>\n\t\t</tr>\n\t</table>\n\t<p>\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Quick Links</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td><a href='invoice-view.php'>View Invoices</a></td>\n\t\t</tr>\n\t\t<script>document.write(getQuicklinkSpecial());</script>\n\t</table>";
    return $write;
}
Ejemplo n.º 12
0
 public function invoice()
 {
     $this->language->load('sale/order');
     $this->data['title'] = $this->language->get('heading_title');
     if (isset($this->request->server['HTTPS']) && ($this->request->server['HTTPS'] == 'on' || $this->request->server['HTTPS'] == '1') || $this->request->server['HTTPS'] == '443') {
         $this->data['base'] = HTTPS_SERVER;
     } elseif (isset($this->request->server['HTTP_X_FORWARDED_PROTO']) && $this->request->server['HTTP_X_FORWARDED_PROTO'] == 'https') {
         $this->data['base'] = HTTPS_SERVER;
     } else {
         $this->data['base'] = HTTP_SERVER;
     }
     if ($this->config->get('config_logo') && file_exists(DIR_IMAGE . $this->config->get('config_logo'))) {
         $this->data['logo'] = HTTP_CATALOG . 'image/' . $this->config->get('config_logo');
     } else {
         $this->data['logo'] = '';
     }
     $this->data['direction'] = $this->language->get('direction');
     $this->data['language'] = $this->language->get('code');
     $this->data['text_invoice'] = $this->language->get('text_invoice');
     $this->data['text_order_id'] = $this->language->get('text_order_id');
     $this->data['text_invoice_no'] = $this->language->get('text_invoice_no');
     $this->data['text_invoice_date'] = $this->language->get('text_invoice_date');
     $this->data['text_date_added'] = $this->language->get('text_date_added');
     $this->data['text_telephone'] = $this->language->get('text_telephone');
     $this->data['text_fax'] = $this->language->get('text_fax');
     $this->data['text_to'] = $this->language->get('text_to');
     $this->data['text_company_id'] = $this->language->get('text_company_id');
     $this->data['text_tax_id'] = $this->language->get('text_tax_id');
     $this->data['text_ship_to'] = $this->language->get('text_ship_to');
     $this->data['text_payment_method'] = $this->language->get('text_payment_method');
     $this->data['text_shipping_method'] = $this->language->get('text_shipping_method');
     $this->data['column_product'] = $this->language->get('column_product');
     $this->data['column_model'] = $this->language->get('column_model');
     $this->data['column_quantity'] = $this->language->get('column_quantity');
     $this->data['column_price'] = $this->language->get('column_price');
     $this->data['column_tax_value'] = $this->language->get('column_tax_value');
     $this->data['column_tax_percent'] = $this->language->get('column_tax_percent');
     $this->data['column_total'] = $this->language->get('column_total');
     $this->data['column_comment'] = $this->language->get('column_comment');
     $this->load->model('sale/order');
     $this->load->model('setting/setting');
     $pdf = false;
     $this->data['orders'] = array();
     $orders = array();
     if (isset($this->request->post['selected'])) {
         $orders = $this->request->post['selected'];
         $pdf = isset($this->request->get['pdf']) ? true : false;
     } elseif (isset($this->request->get['order_id'])) {
         $orders[] = $this->request->get['order_id'];
         $pdf = isset($this->request->get['pdf']) ? true : false;
     }
     foreach ($orders as $order_id) {
         $order_info = $this->model_sale_order->getOrder($order_id);
         if ($order_info) {
             $store_info = $this->model_setting_setting->getSetting('config', $order_info['store_id']);
             if ($store_info) {
                 $store_address = $store_info['config_address'];
                 $store_email = $store_info['config_email'];
                 $store_telephone = $store_info['config_telephone'];
                 $store_fax = $store_info['config_fax'];
             } else {
                 $store_address = $this->config->get('config_address');
                 $store_email = $this->config->get('config_email');
                 $store_telephone = $this->config->get('config_telephone');
                 $store_fax = $this->config->get('config_fax');
             }
             $store_company_id = $this->config->get('config_company_id') ? $this->config->get('config_company_id') : '';
             $store_company_tax_id = $this->config->get('config_company_tax_id') ? $this->config->get('config_company_tax_id') : '';
             if ($order_info['invoice_no']) {
                 $invoice_no = $order_info['invoice_prefix'] . $order_info['invoice_no'];
             } else {
                 $invoice_no = '';
             }
             if ($order_info['shipping_address_format']) {
                 $format = $order_info['shipping_address_format'];
             } else {
                 $format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
             }
             $find = array('{firstname}', '{lastname}', '{company}', '{address_1}', '{address_2}', '{city}', '{postcode}', '{zone}', '{zone_code}', '{country}');
             $replace = array('firstname' => $order_info['shipping_firstname'], 'lastname' => $order_info['shipping_lastname'], 'company' => $order_info['shipping_company'], 'address_1' => $order_info['shipping_address_1'], 'address_2' => $order_info['shipping_address_2'], 'city' => $order_info['shipping_city'], 'postcode' => $order_info['shipping_postcode'], 'zone' => $order_info['shipping_zone'], 'zone_code' => $order_info['shipping_zone_code'], 'country' => $order_info['shipping_country']);
             $shipping_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\\s\\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
             if ($order_info['payment_address_format']) {
                 $format = $order_info['payment_address_format'];
             } else {
                 $format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
             }
             $find = array('{firstname}', '{lastname}', '{company}', '{address_1}', '{address_2}', '{city}', '{postcode}', '{zone}', '{zone_code}', '{country}');
             $replace = array('firstname' => $order_info['payment_firstname'], 'lastname' => $order_info['payment_lastname'], 'company' => $order_info['payment_company'], 'address_1' => $order_info['payment_address_1'], 'address_2' => $order_info['payment_address_2'], 'city' => $order_info['payment_city'], 'postcode' => $order_info['payment_postcode'], 'zone' => $order_info['payment_zone'], 'zone_code' => $order_info['payment_zone_code'], 'country' => $order_info['payment_country']);
             $payment_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\\s\\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
             if (!empty($payment_address)) {
                 $similar_address = similar_text(strtoupper($payment_address), strtoupper($shipping_address), $similarity);
                 if (number_format($similarity, 0) > 90) {
                     $same_address = true;
                 } else {
                     $same_address = false;
                 }
             } else {
                 $same_address = true;
             }
             $product_data = array();
             $products = $this->model_sale_order->getOrderProducts($order_id);
             foreach ($products as $product) {
                 $option_data = array();
                 $options = $this->model_sale_order->getOrderOptions($order_id, $product['order_product_id']);
                 foreach ($options as $option) {
                     if ($option['type'] != 'file') {
                         $value = $option['value'];
                     } else {
                         $value = utf8_substr($option['value'], 0, utf8_strrpos($option['value'], '.'));
                     }
                     $option_data[] = array('name' => $option['name'], 'value' => $value);
                 }
                 $product_data[] = array('name' => $product['name'], 'model' => $product['model'], 'option' => $option_data, 'quantity' => $product['quantity'], 'price' => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']), 'tax_value' => $this->currency->format($this->config->get('config_tax') ? $product['tax'] * $product['quantity'] : 0, $order_info['currency_code'], $order_info['currency_value']), 'tax_percent' => number_format(($this->config->get('config_tax') ? $product['tax'] * $product['quantity'] : 0) * 100 / ($product['price'] * $product['quantity']), 2, '.', ''), 'total' => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? $product['tax'] * $product['quantity'] : 0), $order_info['currency_code'], $order_info['currency_value']));
             }
             $voucher_data = array();
             $vouchers = $this->model_sale_order->getOrderVouchers($order_id);
             foreach ($vouchers as $voucher) {
                 $voucher_data[] = array('description' => $voucher['description'], 'amount' => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']));
             }
             $total_data = $this->model_sale_order->getOrderTotals($order_id);
             $this->data['orders'][] = array('order_id' => $order_id, 'invoice_no' => $invoice_no, 'date_added' => date($this->language->get('date_format_time'), strtotime($order_info['date_added'])), 'store_name' => $order_info['store_name'], 'store_url' => rtrim($order_info['store_url'], '/'), 'store_address' => nl2br($store_address), 'store_email' => $store_email, 'store_telephone' => $store_telephone, 'store_fax' => $store_fax, 'store_company_id' => $store_company_id, 'store_company_tax_id' => $store_company_tax_id, 'email' => $order_info['email'], 'telephone' => $order_info['telephone'], 'shipping_address' => $same_address ? '' : $shipping_address, 'shipping_method' => $order_info['shipping_method'], 'payment_address' => $same_address ? $shipping_address : $payment_address, 'payment_company_id' => $order_info['payment_company_id'], 'payment_tax_id' => $order_info['payment_tax_id'], 'payment_method' => $order_info['payment_method'], 'product' => $product_data, 'voucher' => $voucher_data, 'total' => $total_data, 'comment' => nl2br($order_info['comment']));
         }
     }
     $this->template = 'sale/order_invoice.tpl';
     if ($pdf) {
         $document_type = $this->language->get('text_invoice');
         $this->response->setOutput(pdf($this->render(), $document_type, $this->request->get['order_id']));
     } else {
         $this->response->setOutput($this->render());
     }
 }
Ejemplo n.º 13
0
 public function render($pagina, $dados)
 {
     $view = 'relatorios/' . $pagina;
     $html = $this->load->view($view, $dados, true);
     pdf($html);
 }