Merged changes form stable branch up to 2.3.13
[fa-stable.git] / sales / includes / db / sales_invoice_db.inc
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 //-----------------------------------------------------------------------------
13 //      Add or update Sales Invoice
14 //
15 function write_sales_invoice(&$invoice)
16 {
17         global $Refs;
18
19         $trans_no = $invoice->trans_no;
20         if (is_array($trans_no))
21                 $trans_no = key($trans_no);
22
23         $date_ = $invoice->document_date;
24         $charge_shipping =$invoice->freight_cost;
25
26         begin_transaction();
27
28         hook_db_prewrite($invoice, ST_SALESINVOICE);
29         $company_data = get_company_prefs();
30
31         $branch_data = get_branch_accounts($invoice->Branch);
32
33         $customer = get_customer($invoice->customer_id);
34
35         // offer price values without freight costs
36         $items_total = $invoice->get_items_total_dispatch();
37         $freight_tax = $invoice->get_shipping_tax();
38
39         if (!$invoice->is_prepaid())
40                 update_customer_trans_version(get_parent_type(ST_SALESINVOICE), $invoice->src_docs);
41
42         $ov_gst = 0;
43         $taxes = $invoice->get_taxes(); // all taxes with freight_tax
44         $dec = user_price_dec();
45         foreach ($taxes as $taxitem) {
46                 $taxitem['Value'] =  round2($taxitem['Value'], $dec);
47                 $ov_gst +=  $taxitem['Value'];
48         }
49
50         if($invoice->tax_included==0) {
51             $items_added_tax = $ov_gst-$freight_tax;
52             $freight_added_tax = $freight_tax;
53         } else {
54             $items_added_tax = 0;
55             $freight_added_tax = 0;
56         }
57
58         /* Insert/update the debtor_trans */
59         $sales_order = $invoice->order_no;
60         if (is_array($sales_order))
61                         $sales_order = $sales_order[0]; // assume all crucial SO data are same for every delivery
62
63         if ($trans_no) {
64                 $allocs = get_payments_for($trans_no, ST_SALESINVOICE);
65                 delete_comments(ST_SALESINVOICE, $trans_no);
66                 void_gl_trans(ST_SALESINVOICE, $trans_no, true);
67                 void_trans_tax_details(ST_SALESINVOICE, $trans_no);
68         } else
69                 $allocs = get_payments_for($invoice->order_no, ST_SALESORDER);
70
71         if ($invoice->is_prepaid()) // selected prepayment is already in cart
72         {
73                 $allocs = $invoice->prepayments;
74                 // values posted are reduced by prepaid_factor
75                 $prepaid_factor = $invoice->prep_amount/$invoice->get_trans_total();
76         } else {
77                 $prepaid_factor = 1;
78         }
79
80          // write_customer_trans have to be called after optional void_cust_allocations above
81         $invoice_no = write_customer_trans(ST_SALESINVOICE, $trans_no, $invoice->customer_id,
82                 $invoice->Branch, $date_, $invoice->reference, $items_total, 0,
83                 $items_added_tax, $invoice->freight_cost, $freight_added_tax,
84                 $invoice->sales_type, $sales_order, $invoice->ship_via, 
85                 $invoice->due_date, 0, 0, $invoice->dimension_id, 
86                 $invoice->dimension2_id, $invoice->payment, $invoice->tax_included, $invoice->prep_amount); 
87                 // 2008-06-14 extra $alloc, 2008-11-12 added dimension_id Joe Hunt
88
89         if ($trans_no == 0) {
90                 $invoice->trans_no = array($invoice_no=>0);
91         }
92
93         $total = 0;
94         // for prepayments use deferred income account if set
95         $sales_account = $invoice->is_prepaid() ? get_company_pref('deferred_income_act') : 0;
96
97         foreach ($invoice->line_items as $line_no => $invoice_line) {
98                 $qty = $invoice_line->qty_dispatched;
99                 $line_taxfree_price = get_tax_free_price_for_item($invoice_line->stock_id,
100                         $invoice_line->price * $qty, 0, $invoice->tax_included,
101                         $invoice->tax_group_array);
102
103                 $line_tax = get_full_price_for_item($invoice_line->stock_id,
104                         $invoice_line->price * $qty, 0, $invoice->tax_included,
105                         $invoice->tax_group_array) - $line_taxfree_price;
106
107                 write_customer_trans_detail_item(ST_SALESINVOICE, $invoice_no, $invoice_line->stock_id,
108                         $invoice_line->item_description, $invoice_line->qty_dispatched,
109                         $invoice_line->line_price(), $qty ? $line_tax/$qty : 0, $invoice_line->discount_percent,
110                         $invoice_line->standard_cost, $invoice_line->src_id,
111                         $trans_no ? $invoice_line->id : 0);
112
113                 // Update delivery items for the quantity invoiced
114                 if ($invoice_line->qty_old != $invoice_line->qty_dispatched)
115                 {
116                         if ($invoice->is_prepaid())
117                                 update_prepaid_so_line($invoice_line->src_id, $invoice_line->qty_dispatched-$invoice_line->qty_old);
118                         else
119                                 update_parent_line(ST_SALESINVOICE, $invoice_line->src_id, ($invoice_line->qty_dispatched-$invoice_line->qty_old));
120                 }
121                 if ($invoice_line->qty_dispatched != 0) {
122                         $stock_gl_code = get_stock_gl_code($invoice_line->stock_id);
123
124                         if ($invoice_line->line_price() != 0) {
125                                 //Post sales transaction to GL credit sales
126
127                                 // 2008-06-14. If there is a Branch Sales Account, then override with this,
128                                 // else take the Item Sales Account
129                                 if (!$invoice->is_prepaid())
130                                         $sales_account = ($branch_data['sales_account'] != "" ? $branch_data['sales_account'] : $stock_gl_code['sales_account']);
131                                 // 2008-08-01. If there is a Customer Dimension, then override with this,
132                                 // else take the Item Dimension (if any)
133                                 $dim = ($invoice->dimension_id != $customer['dimension_id'] ? $invoice->dimension_id : 
134                                         ($customer['dimension_id'] != 0 ? $customer["dimension_id"] : $stock_gl_code["dimension_id"]));
135                                 $dim2 = ($invoice->dimension2_id != $customer['dimension2_id'] ? $invoice->dimension2_id : 
136                                         ($customer['dimension2_id'] != 0 ? $customer["dimension2_id"] : $stock_gl_code["dimension2_id"]));
137                                 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $sales_account, $dim, $dim2,
138                                         -$line_taxfree_price*$prepaid_factor,
139                                         $invoice->customer_id, "The sales price GL posting could not be inserted");
140
141                                 if ($invoice_line->discount_percent != 0) {
142
143                                         $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_,
144                                                 $branch_data["sales_discount_account"], $dim, $dim2,
145                                                 ($line_taxfree_price * $invoice_line->discount_percent)*$prepaid_factor,
146                                                 $invoice->customer_id, "The sales discount GL posting could not be inserted");
147                                 } /*end of if discount !=0 */
148                         }
149                 } /*quantity dispatched is more than 0 */
150         } /*end of delivery_line loop */
151
152         if (($items_total + $charge_shipping) != 0) {
153                 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $branch_data["receivables_account"], 0, 0,
154                         ($items_total + $charge_shipping + $items_added_tax + $freight_added_tax)*$prepaid_factor,
155                         $invoice->customer_id, "The total debtor GL posting could not be inserted");
156         }
157         $to_allocate = ($items_total + $charge_shipping + $items_added_tax + $freight_added_tax);
158
159         if ($charge_shipping != 0) {
160                 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $company_data["freight_act"], 0, 0,
161                         -$invoice->get_tax_free_shipping()*$prepaid_factor, $invoice->customer_id,
162                         "The freight GL posting could not be inserted");
163         }
164         // post all taxes
165         foreach ($taxes as $taxitem) {
166                 if ($taxitem['Net'] != 0) {
167                         $ex_rate = get_exchange_rate_from_home_currency(get_customer_currency($invoice->customer_id), $date_);
168                         add_trans_tax_details(ST_SALESINVOICE, $invoice_no, $taxitem['tax_type_id'],
169                                 $taxitem['rate'], $invoice->tax_included, $taxitem['Value'],
170                                  $taxitem['Net'], $ex_rate, $date_, $invoice->reference, $date_, $prepaid_factor*$taxitem['Value']);
171                         if (isset($taxitem['sales_gl_code']))
172                                 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $taxitem['sales_gl_code'], 0, 0,
173                                         (-$taxitem['Value'])*$prepaid_factor, $invoice->customer_id,
174                                         "A tax GL posting could not be inserted");
175                 }
176         }
177
178         /*Post a balance post if $total != 0 */
179         add_gl_balance(ST_SALESINVOICE, $invoice_no, $date_, -$total, PT_CUSTOMER, $invoice->customer_id);      
180
181         add_comments(ST_SALESINVOICE, $invoice_no, $date_, $invoice->Comments);
182
183         if ($trans_no == 0) {
184                 $Refs->save(ST_SALESINVOICE, $invoice_no, $invoice->reference);
185                 if ($invoice->payment_terms['cash_sale'] && $invoice->pos['pos_account']) {
186                         $amount = $items_total + $items_added_tax + $invoice->freight_cost 
187                                 + $freight_added_tax;
188
189                         // to use debtors.pmt_discount on cash sale:
190                         // extend invoice entry page with final amount after discount 
191                         // and change line below.
192                         $discount = 0; // $invoice->cash_discount*$amount;
193                         $pmtno = write_customer_payment(0, $invoice->customer_id, 
194                                 $invoice->Branch, $invoice->pos['pos_account'], $date_,
195                                 $Refs->get_next(ST_CUSTPAYMENT), $amount-$discount, $discount,
196                                 _('Cash invoice').' '.$invoice_no);
197                         add_cust_allocation($amount, ST_CUSTPAYMENT, $pmtno, ST_SALESINVOICE, $invoice_no);
198
199                         update_debtor_trans_allocation(ST_SALESINVOICE, $invoice_no, $amount);
200                         update_debtor_trans_allocation(ST_CUSTPAYMENT, $pmtno, $amount);
201                 }
202         }
203 //_vd($allocs);
204         reallocate_payments($invoice_no, ST_SALESINVOICE, $date_, $to_allocate, $allocs);
205 //_vd(get_payments_for($sales_order, ST_SALESORDER));
206 //_vd(get_payments_for($invoice_no, ST_SALESINVOICE));
207 //_vd(get_gl(ST_SALESINVOICE, $invoice_no));
208 //_vd(get_customer_trans($invoice_no, ST_SALESINVOICE));
209 //_vd(get_sales_order_header($sales_order, ST_SALESORDER));
210         hook_db_postwrite($invoice, ST_SALESINVOICE);
211 //$result = get_trans_tax_details(ST_SALESINVOICE, $invoice_no);
212 //while($row=db_fetch($result))
213 //      _vd($row);
214 //exit;
215         commit_transaction();
216
217         return $invoice_no;
218 }
219
220 //--------------------------------------------------------------------------------------------------
221
222 function void_sales_invoice($type, $type_no)
223 {
224         begin_transaction();
225
226         hook_db_prevoid($type, $type_no);
227         void_bank_trans($type, $type_no, true);
228         void_gl_trans($type, $type_no, true);
229
230         // reverse all the changes in parent document(s)
231         $factor = get_cust_prepayment_invoice_factor($type_no);
232         if ($factor != 0)
233         {
234                 $lines = get_customer_trans_details($type, $type_no);
235                 while($line = db_fetch($lines))
236                 {
237                         update_prepaid_so_line($line['src_id'], -$factor*$line['quantity']);
238                 }
239         }
240         else
241         {
242                 $deliveries = get_sales_parent_numbers($type, $type_no);
243
244                 if ($deliveries !== 0) {
245                         if (count($deliveries) == 1 && get_reference(ST_CUSTDELIVERY, $deliveries[0]) == "auto")
246                         {
247                                 void_sales_delivery(ST_CUSTDELIVERY, $deliveries[0], false);
248                                 $date_ = Today();
249                                 add_audit_trail(ST_CUSTDELIVERY, $deliveries[0], $date_, _("Voided."));
250                                 add_voided_entry(ST_CUSTDELIVERY, $deliveries[0], $date_, "");
251                         }
252                         else
253                         {
254                                 $srcdetails = get_sales_parent_lines($type, $type_no);
255                                         while ($row = db_fetch($srcdetails)) {
256                                         update_parent_line($type, $row['id'], -$row['quantity']);
257                                 }
258                         }
259                 }
260         }
261         // clear details after they've been reversed in the sales order
262         void_customer_trans_details($type, $type_no);
263
264         void_trans_tax_details($type, $type_no);
265
266         void_cust_allocations($type, $type_no);
267
268         // do this last because other voidings can depend on it - especially voiding
269         // DO NOT MOVE THIS ABOVE VOIDING or we can end up with trans with alloc < 0
270         void_customer_trans($type, $type_no);
271
272         commit_transaction();
273 }
274
275 function get_cust_prepayment_invoice_factor($trans_no)
276 {
277         $sql = "SELECT IF(dt.prep_amount>0, dt.prep_amount/so.total ,0) 
278                 FROM ".TB_PREF."debtor_trans dt
279                 LEFT JOIN ".TB_PREF."sales_orders so ON so.trans_type=".ST_SALESORDER." AND so.order_no=dt.order_
280                  WHERE dt.type=".ST_SALESINVOICE." AND trans_no=".db_escape($trans_no);
281         $row = db_fetch(db_query($sql, 'cannot retrieve prepaid invoice factor'));
282         return $row[0];
283 }
284
285 function prepaid_invoice_remainder($order)
286 {
287         $sql = "SELECT so.total - IFNULL(SUM(inv.prep_amount),0) FROM "
288                 .TB_PREF."sales_orders so,
289                 ".TB_PREF."debtor_trans inv
290                 LEFT JOIN ".TB_PREF."payment_terms pt ON inv.payment_terms=pt.terms_indicator
291                 WHERE  so.order_no=".db_escape($order)
292                         ." AND so.trans_type=".ST_SALESORDER
293                         ." AND inv.type=".ST_SALESINVOICE
294                         ." AND inv.order_=so.order_no"
295                         ." AND pt.days_before_due<0";
296
297         $result = db_fetch(db_query($sql, "cannot find final invoice value"));
298         return $result[0];
299 }
300
301 /*
302         Find oldest delivery date for sales invoice
303 */
304 function get_oldest_delivery_date($invoice_no)
305 {
306         $sql = "SELECT MIN(trans.tran_date)
307                         FROM
308                                 ".TB_PREF."debtor_trans_details del
309                         LEFT JOIN ".TB_PREF."debtor_trans_details inv
310                                 ON inv.src_id=del.id
311                         LEFT JOIN ".TB_PREF."debtor_trans trans 
312                                 ON trans.type=".ST_CUSTDELIVERY." AND trans.trans_no = del.debtor_trans_no
313                         WHERE
314                                 inv.debtor_trans_type=".ST_SALESINVOICE
315                                 ." AND inv.debtor_trans_no=".db_escape($invoice_no);
316         $res = db_query($sql, 'cannot find oldest delivery date');
317         $date = db_fetch($res);
318         return $date[0];
319 }
320
321 /*
322         Find oldest payment date for sales invoice
323 */
324 function get_oldest_payment_date($invoice_no)
325 {
326         $sql = "SELECT MIN(payment.tran_date)
327                         FROM
328                         ".TB_PREF."cust_allocations alloc,
329                         ".TB_PREF."debtor_trans payment
330                         WHERE
331                                 alloc.trans_type_to=".ST_SALESINVOICE." AND alloc.trans_no_to=".db_escape($invoice_no)
332                         ." AND alloc.trans_type_from=payment.type AND alloc.trans_no_from=payment.trans_no";
333         $res = db_query($sql, 'cannot find oldest delivery date');
334         $date = db_fetch($res);
335         return $date[0];
336 }