Incorrect Journal Balance (sales invoice) when many decimals in tax and price.
[fa-stable.git] / reporting / rep107.php
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 $page_security = $_POST['PARAM_0'] == $_POST['PARAM_1'] ?
13         'SA_SALESTRANSVIEW' : 'SA_SALESBULKREP';
14 // ----------------------------------------------------------------
15 // $ Revision:  2.0 $
16 // Creator:     Joe Hunt
17 // date_:       2005-05-19
18 // Title:       Print Invoices
19 // ----------------------------------------------------------------
20 $path_to_root="..";
21
22 include_once($path_to_root . "/includes/session.inc");
23 include_once($path_to_root . "/includes/date_functions.inc");
24 include_once($path_to_root . "/includes/data_checks.inc");
25 include_once($path_to_root . "/sales/includes/sales_db.inc");
26
27 //----------------------------------------------------------------------------------------------------
28 function get_invoice_range($from, $to, $currency=false)
29 {
30         global $SysPrefs;
31
32         $ref = ($SysPrefs->print_invoice_no() == 1 ? "trans_no" : "reference");
33
34         $sql = "SELECT trans.trans_no, trans.reference";
35
36 //  if($currency !== false)
37 //              $sql .= ", cust.curr_code";
38
39         $sql .= " FROM ".TB_PREF."debtor_trans trans 
40                         LEFT JOIN ".TB_PREF."voided voided ON trans.type=voided.type AND trans.trans_no=voided.id";
41
42         if ($currency !== false)
43                 $sql .= " LEFT JOIN ".TB_PREF."debtors_master cust ON trans.debtor_no=cust.debtor_no";
44
45         $sql .= " WHERE trans.type=".ST_SALESINVOICE
46                 ." AND ISNULL(voided.id)"
47                 ." AND trans.trans_no BETWEEN ".db_escape($from)." AND ".db_escape($to);                        
48
49         if ($currency !== false)
50                 $sql .= " AND cust.curr_code=".db_escape($currency);
51
52         $sql .= " ORDER BY trans.tran_date, trans.$ref";
53
54         return db_query($sql, "Cant retrieve invoice range");
55 }
56
57 print_invoices();
58
59 //----------------------------------------------------------------------------------------------------
60
61 function print_invoices()
62 {
63         global $path_to_root, $SysPrefs;
64
65         include_once($path_to_root . "/reporting/includes/pdf_report.inc");
66
67         $from = $_POST['PARAM_0'];
68         $to = $_POST['PARAM_1'];
69         $currency = $_POST['PARAM_2'];
70         $email = $_POST['PARAM_3'];
71         $pay_service = $_POST['PARAM_4'];
72         $comments = $_POST['PARAM_5'];
73         $customer = $_POST['PARAM_6'];
74         $orientation = $_POST['PARAM_7'];
75
76         if (!$from || !$to) return;
77
78         $orientation = ($orientation ? 'L' : 'P');
79         $dec = user_price_dec();
80
81         $fno = explode("-", $from);
82         $tno = explode("-", $to);
83         $from = min($fno[0], $tno[0]);
84         $to = max($fno[0], $tno[0]);
85
86         //-------------code-Descr-Qty--uom--tax--prc--Disc-Tot--//
87         $cols = array(4, 60, 225, 300, 325, 385, 450, 515);
88
89         // $headers in doctext.inc
90         $aligns = array('left', 'left', 'right', 'center', 'right', 'right', 'right');
91
92         $params = array('comments' => $comments);
93
94         $cur = get_company_Pref('curr_default');
95
96         if ($email == 0)
97                 $rep = new FrontReport(_('INVOICE'), "InvoiceBulk", user_pagesize(), 9, $orientation);
98         if ($orientation == 'L')
99                 recalculate_cols($cols);
100
101         $range = Array();
102         if ($currency == ALL_TEXT)
103                 $range = get_invoice_range($from, $to);
104         else
105                 $range = get_invoice_range($from, $to, $currency);
106
107         while($row = db_fetch($range))
108         {
109                         if (!exists_customer_trans(ST_SALESINVOICE, $row['trans_no']))
110                                 continue;
111                         $sign = 1;
112                         $myrow = get_customer_trans($row['trans_no'], ST_SALESINVOICE);
113
114                         if ($customer && $myrow['debtor_no'] != $customer) {
115                                 continue;
116                         }
117 //                      if ($currency != ALL_TEXT && $myrow['curr_code'] != $currency) {
118 //                              continue;
119 //                      }
120                         
121                         $baccount = get_default_bank_account($myrow['curr_code']);
122                         $params['bankaccount'] = $baccount['id'];
123
124                         $branch = get_branch($myrow["branch_code"]);
125                         $sales_order = get_sales_order_header($myrow["order_"], ST_SALESORDER);
126                         if ($email == 1)
127                         {
128                                 $rep = new FrontReport("", "", user_pagesize(), 9, $orientation);
129                                 $rep->title = _('INVOICE');
130                                 $rep->filename = "Invoice" . $myrow['reference'] . ".pdf";
131                         }       
132                         $rep->currency = $cur;
133                         $rep->Font();
134                         $rep->Info($params, $cols, null, $aligns);
135
136                         $contacts = get_branch_contacts($branch['branch_code'], 'invoice', $branch['debtor_no'], true);
137                         $baccount['payment_service'] = $pay_service;
138                         $rep->SetCommonData($myrow, $branch, $sales_order, $baccount, ST_SALESINVOICE, $contacts);
139                         $rep->SetHeaderType('Header2');
140                         $rep->NewPage();
141                         // calculate summary start row for later use
142                         $summary_start_row = $rep->bottomMargin + (15 * $rep->lineHeight);
143
144                         $show_this_payment = $rep->formData['prepaid'] == 'partial'; // include payments invoiced here in summary
145
146                         if ($rep->formData['prepaid'])
147                         {
148                                 
149                                 $result = get_sales_order_invoices($myrow['order_']);
150                                 $prepayments = array();
151                                 while($inv = db_fetch($result))
152                                 {
153                                         $prepayments[] = $inv;
154                                         if ($inv['trans_no'] == $row['trans_no'])
155                                         break;
156                                 }
157
158                                 if (count($prepayments) > ($show_this_payment ? 0 : 1))
159                                         $summary_start_row += (count($prepayments)) * $rep->lineHeight;
160                                 else
161                                         unset($prepayments);
162                         }
163
164                         $result = get_customer_trans_details(ST_SALESINVOICE, $row['trans_no']);
165                         $SubTotal = 0;
166                         while ($myrow2=db_fetch($result))
167                         {
168                                 if ($myrow2["quantity"] == 0)
169                                         continue;
170
171                                 $Net = round2($sign * ((1 - $myrow2["discount_percent"]) * $myrow2["unit_price"] * $myrow2["quantity"]),
172                                    user_price_dec());
173                                 $SubTotal += $Net;
174                         $DisplayPrice = number_format2($myrow2["unit_price"],$dec);
175                         $DisplayQty = number_format2($sign*$myrow2["quantity"],get_qty_dec($myrow2['stock_id']));
176                         $DisplayNet = number_format2($Net,$dec);
177                         if ($myrow2["discount_percent"]==0)
178                                         $DisplayDiscount ="";
179                         else
180                                         $DisplayDiscount = number_format2($myrow2["discount_percent"]*100,user_percent_dec()) . "%";
181                                 $c=0;
182                                 $rep->TextCol($c++, $c, $myrow2['stock_id'], -2);
183                                 $oldrow = $rep->row;
184                                 $rep->TextColLines($c++, $c, $myrow2['StockDescription'], -2);
185                                 if (!empty($SysPrefs->prefs['long_description_invoice']) && !empty($myrow2['StockLongDescription']))
186                                 {
187                                         $c--;
188                                         $rep->TextColLines($c++, $c, $myrow2['StockLongDescription'], -2);
189                                 }
190                                 $newrow = $rep->row;
191                                 $rep->row = $oldrow;
192                                 if ($Net != 0.0 || !is_service($myrow2['mb_flag']) || !$SysPrefs->no_zero_lines_amount())
193                                 {
194                                         $rep->TextCol($c++, $c, $DisplayQty, -2);
195                                         $rep->TextCol($c++, $c, $myrow2['units'], -2);
196                                         $rep->TextCol($c++, $c, $DisplayPrice, -2);
197                                         $rep->TextCol($c++, $c, $DisplayDiscount, -2);
198                                         $rep->TextCol($c++, $c, $DisplayNet, -2);
199                                 }
200                                 $rep->row = $newrow;
201                                 //$rep->NewLine(1);
202                                 if ($rep->row < $summary_start_row)
203                                         $rep->NewPage();
204                         }
205
206                         $memo = get_comments_string(ST_SALESINVOICE, $row['trans_no']);
207                         if ($memo != "")
208                         {
209                                 $rep->NewLine();
210                                 $rep->TextColLines(1, 3, $memo, -2);
211                         }
212
213                         $DisplaySubTot = number_format2($SubTotal,$dec);
214
215                         // set to start of summary line:
216                 $rep->row = $summary_start_row;
217                         if (isset($prepayments))
218                         {
219                                 // Partial invoices table
220                                 $rep->TextCol(0, 3,_("Prepayments invoiced to this order up to day:"));
221                                 $rep->TextCol(0, 3,     str_pad('', 150, '_'));
222                                 $rep->cols[2] -= 20;
223                                 $rep->aligns[2] = 'right';
224                                 $rep->NewLine(); $c = 0; $tot_pym=0;
225                                 $rep->TextCol(0, 3,     str_pad('', 150, '_'));
226                                 $rep->TextCol($c++, $c, _("Date"));
227                                 $rep->TextCol($c++, $c, _("Invoice reference"));
228                                 $rep->TextCol($c++, $c, _("Amount"));
229
230                                 foreach ($prepayments as $invoice)
231                                 {
232                                         if ($show_this_payment || ($invoice['reference'] != $myrow['reference']))
233                                         {
234                                                 $rep->NewLine();
235                                                 $c = 0; $tot_pym += $invoice['prep_amount'];
236                                                 $rep->TextCol($c++, $c, sql2date($invoice['tran_date']));
237                                                 $rep->TextCol($c++, $c, $invoice['reference']);
238                                                 $rep->TextCol($c++, $c, number_format2($invoice['prep_amount'], $dec));
239                                         }
240                                         if ($invoice['reference']==$myrow['reference']) break;
241                                 }
242                                 $rep->TextCol(0, 3,     str_pad('', 150, '_'));
243                                 $rep->NewLine();
244                                 $rep->TextCol(1, 2,     _("Total payments:"));
245                                 $rep->TextCol(2, 3,     number_format2($tot_pym, $dec));
246                         }
247
248
249                         $doctype = ST_SALESINVOICE;
250                 $rep->row = $summary_start_row;
251                         $rep->cols[2] += 20;
252                         $rep->cols[3] += 20;
253                         $rep->aligns[3] = 'left';
254
255                         $rep->TextCol(3, 6, _("Sub-total"), -2);
256                         $rep->TextCol(6, 7,     $DisplaySubTot, -2);
257                         $rep->NewLine();
258                         if ($myrow['ov_freight'] != 0.0)
259                         {
260                                 $DisplayFreight = number_format2($sign*$myrow["ov_freight"],$dec);
261                                 $rep->TextCol(3, 6, _("Shipping"), -2);
262                                 $rep->TextCol(6, 7,     $DisplayFreight, -2);
263                                 $rep->NewLine();
264                         }       
265                         $tax_items = get_trans_tax_details(ST_SALESINVOICE, $row['trans_no']);
266                         $first = true;
267                 while ($tax_item = db_fetch($tax_items))
268                 {
269                         if ($tax_item['amount'] == 0)
270                                 continue;
271                         $DisplayTax = number_format2($sign*$tax_item['amount'], $dec);
272
273                         if ($SysPrefs->suppress_tax_rates() == 1)
274                                 $tax_type_name = $tax_item['tax_type_name'];
275                         else
276                                 $tax_type_name = $tax_item['tax_type_name']." (".$tax_item['rate']."%) ";
277
278                         if ($myrow['tax_included'])
279                         {
280                                 if ($SysPrefs->alternative_tax_include_on_docs() == 1)
281                                 {
282                                         if ($first)
283                                         {
284                                                         $rep->TextCol(3, 6, _("Total Tax Excluded"), -2);
285                                                         $rep->TextCol(6, 7,     number_format2($sign*$tax_item['net_amount'], $dec), -2);
286                                                         $rep->NewLine();
287                                         }
288                                                 $rep->TextCol(3, 6, $tax_type_name, -2);
289                                                 $rep->TextCol(6, 7,     $DisplayTax, -2);
290                                                 $first = false;
291                                 }
292                                 else
293                                                 $rep->TextCol(3, 6, _("Included") . " " . $tax_type_name . _("Amount") . ": " . $DisplayTax, -2);
294                                 }
295                         else
296                         {
297                                         $rep->TextCol(3, 6, $tax_type_name, -2);
298                                         $rep->TextCol(6, 7,     $DisplayTax, -2);
299                                 }
300                                 $rep->NewLine();
301                 }
302
303                 $rep->NewLine();
304                         $DisplayTotal = number_format2($sign*($myrow["ov_freight"] + $myrow["ov_gst"] +
305                                 $myrow["ov_amount"]+$myrow["ov_freight_tax"]),$dec);
306                         $rep->Font('bold');
307                         if (!$myrow['prepaid']) $rep->Font('bold');
308                                 $rep->TextCol(3, 6, $rep->formData['prepaid'] ? _("TOTAL ORDER VAT INCL.") : _("TOTAL INVOICE"), - 2);
309                         $rep->TextCol(6, 7, $DisplayTotal, -2);
310                         if ($rep->formData['prepaid'])
311                         {
312                                 $rep->NewLine();
313                                 $rep->Font('bold');
314                                 $rep->TextCol(3, 6, $rep->formData['prepaid']=='final' ? _("THIS INVOICE") : _("TOTAL INVOICE"), - 2);
315                                 $rep->TextCol(6, 7, number_format2($myrow['prep_amount'], $dec), -2);
316                         }
317                         $words = price_in_words($rep->formData['prepaid'] ? $myrow['prep_amount'] : $myrow['Total']
318                                 , array( 'type' => ST_SALESINVOICE, 'currency' => $myrow['curr_code']));
319                         if ($words != "")
320                         {
321                                 $rep->NewLine(1);
322                                 $rep->TextCol(1, 7, $myrow['curr_code'] . ": " . $words, - 2);
323                         }
324                         $rep->Font();
325                         if ($email == 1)
326                         {
327                                 $rep->End($email, sprintf(_("Invoice %s from %s"), $myrow['reference'], get_company_pref('coy_name')));
328                         }
329         }
330         if ($email == 0)
331                 $rep->End();
332 }
333