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