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
15 function write_sales_invoice(&$invoice)
19 $trans_no = $invoice->trans_no;
20 if (is_array($trans_no))
21 $trans_no = key($trans_no);
23 $date_ = $invoice->document_date;
24 $charge_shipping =$invoice->freight_cost;
28 hook_db_prewrite($invoice, ST_SALESINVOICE);
29 $company_data = get_company_prefs();
31 $branch_data = get_branch_accounts($invoice->Branch);
33 $customer = get_customer($invoice->customer_id);
35 add_new_exchange_rate($customer['curr_code'], $date_, $invoice->ex_rate);
37 // offer price values without freight costs
38 $items_total = $invoice->get_items_total_dispatch();
39 $freight_tax = $invoice->get_shipping_tax();
41 if (!$invoice->is_prepaid())
42 update_customer_trans_version(get_parent_type(ST_SALESINVOICE), $invoice->src_docs);
43 elseif (count($invoice->prepayments)) { // partial invoice
44 $last_payment = end($invoice->prepayments);
45 $gl_date = sql2date($last_payment['tran_date']);
46 } else { // final invoice
47 $gl_date = $invoice->document_date;
51 $taxes = $invoice->get_taxes(); // all taxes with freight_tax
52 $dec = user_price_dec();
53 foreach ($taxes as $taxitem) {
54 $taxitem['Value'] = round2($taxitem['Value'], $dec);
55 $ov_gst += $taxitem['Value'];
58 if($invoice->tax_included==0) {
59 $items_added_tax = $ov_gst-$freight_tax;
60 $freight_added_tax = $freight_tax;
63 $freight_added_tax = 0;
66 /* Insert/update the debtor_trans */
67 $sales_order = $invoice->order_no;
68 if (is_array($sales_order))
69 $sales_order = $sales_order[0]; // assume all crucial SO data are same for every delivery
72 $allocs = get_payments_for($trans_no, ST_SALESINVOICE, $invoice->customer_id);
73 delete_comments(ST_SALESINVOICE, $trans_no);
74 void_gl_trans(ST_SALESINVOICE, $trans_no, true);
75 void_trans_tax_details(ST_SALESINVOICE, $trans_no);
77 $allocs = get_payments_for($invoice->order_no, ST_SALESORDER, $invoice->customer_id);
79 if ($invoice->is_prepaid()) // selected prepayment is already in cart
81 $allocs = $invoice->prepayments;
82 // values posted are reduced by prepaid_factor
83 $prepaid_factor = $invoice->prep_amount/$invoice->get_trans_total();
87 // write_customer_trans have to be called after optional void_cust_allocations above
88 $invoice_no = write_customer_trans(ST_SALESINVOICE, $trans_no, $invoice->customer_id,
89 $invoice->Branch, $date_, $invoice->reference, $items_total, 0,
90 $items_added_tax, $invoice->freight_cost, $freight_added_tax,
91 $invoice->sales_type, $sales_order, $invoice->ship_via,
92 $invoice->due_date, 0, 0, $invoice->dimension_id,
93 $invoice->dimension2_id, $invoice->payment, $invoice->tax_included, $invoice->prep_amount);
96 $invoice->trans_no = array($invoice_no=>0);
98 move_trans_attachments(ST_SALESINVOICE, $trans_no, $invoice_no);
101 // for prepayments use deferred income account if set
102 $sales_account = $invoice->is_prepaid() ? get_company_pref('deferred_income_act') : 0;
104 foreach ($invoice->line_items as $line_no => $invoice_line) {
105 $qty = $invoice_line->qty_dispatched;
106 $line_taxfree_price = get_tax_free_price_for_item($invoice_line->stock_id,
107 $invoice_line->price * $qty, 0, $invoice->tax_included,
108 $invoice->tax_group_array);
110 $line_tax = get_full_price_for_item($invoice_line->stock_id,
111 $invoice_line->price * $qty, 0, $invoice->tax_included,
112 $invoice->tax_group_array) - $line_taxfree_price;
114 write_customer_trans_detail_item(ST_SALESINVOICE, $invoice_no, $invoice_line->stock_id,
115 $invoice_line->item_description, $invoice_line->qty_dispatched,
116 $invoice_line->line_price(), $qty ? $line_tax/$qty : 0, $invoice_line->discount_percent,
117 $invoice_line->standard_cost, $invoice_line->src_id,
118 $trans_no ? $invoice_line->id : 0);
120 // Update delivery items for the quantity invoiced
121 if ($invoice_line->qty_old != $invoice_line->qty_dispatched)
123 if ($invoice->is_prepaid())
124 update_prepaid_so_line($invoice_line->src_id, $invoice_line->qty_dispatched-$invoice_line->qty_old);
126 update_parent_line(ST_SALESINVOICE, $invoice_line->src_id, ($invoice_line->qty_dispatched-$invoice_line->qty_old));
128 if ($invoice_line->qty_dispatched != 0) {
129 $stock_gl_code = get_stock_gl_code($invoice_line->stock_id);
131 if ($invoice_line->line_price() != 0) {
132 //Post sales transaction to GL credit sales
134 // If there is a Branch Sales Account, then override with this,
135 // else take the Item Sales Account
136 if (!$invoice->is_prepaid())
137 $sales_account = ($branch_data['sales_account'] != "" ? $branch_data['sales_account'] : $stock_gl_code['sales_account']);
138 // If there is a Customer Dimension, then override with this,
139 // else take the Item Dimension (if any)
140 $dim = ($invoice->dimension_id != $customer['dimension_id'] ? $invoice->dimension_id :
141 ($customer['dimension_id'] != 0 ? $customer["dimension_id"] : $stock_gl_code["dimension_id"]));
142 $dim2 = ($invoice->dimension2_id != $customer['dimension2_id'] ? $invoice->dimension2_id :
143 ($customer['dimension2_id'] != 0 ? $customer["dimension2_id"] : $stock_gl_code["dimension2_id"]));
144 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $sales_account, $dim, $dim2,
145 -$line_taxfree_price*$prepaid_factor,
146 $invoice->customer_id, "The sales price GL posting could not be inserted");
148 if ($invoice_line->discount_percent != 0) {
150 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_,
151 $branch_data["sales_discount_account"], $dim, $dim2,
152 ($line_taxfree_price * $invoice_line->discount_percent)*$prepaid_factor,
153 $invoice->customer_id, "The sales discount GL posting could not be inserted");
154 } /*end of if discount !=0 */
156 } /*quantity dispatched is more than 0 */
157 } /*end of delivery_line loop */
159 if (($items_total + $charge_shipping) != 0) {
160 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $branch_data["receivables_account"], $invoice->dimension_id, $invoice->dimension2_id,
161 ($items_total + $charge_shipping + $items_added_tax + $freight_added_tax)*$prepaid_factor,
162 $invoice->customer_id, "The total debtor GL posting could not be inserted");
164 $to_allocate = ($items_total + $charge_shipping + $items_added_tax + $freight_added_tax);
166 if ($charge_shipping != 0) {
167 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $company_data["freight_act"], $invoice->dimension_id, $invoice->dimension2_id,
168 -$invoice->get_tax_free_shipping()*$prepaid_factor, $invoice->customer_id,
169 "The freight GL posting could not be inserted");
172 foreach ($taxes as $taxitem) {
173 if ($taxitem['Net'] != 0) {
174 $ex_rate = get_exchange_rate_from_home_currency(get_customer_currency($invoice->customer_id), $date_);
175 add_trans_tax_details(ST_SALESINVOICE, $invoice_no, $taxitem['tax_type_id'],
176 $taxitem['rate'], $invoice->tax_included, $prepaid_factor*$taxitem['Value'],
177 $taxitem['Net'], $ex_rate, $date_, $invoice->reference, TR_OUTPUT);
178 if (isset($taxitem['sales_gl_code']) && !empty($taxitem['sales_gl_code']) && $taxitem['Value'] != 0)
179 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $taxitem['sales_gl_code'], $invoice->dimension_id, $invoice->dimension2_id,
180 (-$taxitem['Value'])*$prepaid_factor, $invoice->customer_id,
181 "A tax GL posting could not be inserted");
185 /*Post a balance post if $total != 0 */
186 add_gl_balance(ST_SALESINVOICE, $invoice_no, $date_, -$total, PT_CUSTOMER, $invoice->customer_id);
188 add_comments(ST_SALESINVOICE, $invoice_no, $date_, $invoice->Comments);
190 if ($trans_no == 0) {
191 $Refs->save(ST_SALESINVOICE, $invoice_no, $invoice->reference, null, $invoice->fixed_asset);
192 if ($invoice->payment_terms['cash_sale'] && $invoice->pos['pos_account']) {
193 $amount = $items_total + $items_added_tax + $invoice->freight_cost
194 + $freight_added_tax;
196 // to use debtors.pmt_discount on cash sale:
197 // extend invoice entry page with final amount after discount
198 // and change line below.
199 $discount = 0; // $invoice->cash_discount*$amount;
200 $payment_info = $invoice->pos['pos_name'].' #'.$invoice_no;
201 if (!empty($invoice->payment_info))
202 $payment_info .= ' ' . $invoice->payment_info;
203 $pmtno = write_customer_payment(0, $invoice->customer_id,
204 $invoice->Branch, $invoice->pos['pos_account'], $date_,
205 $Refs->get_next(ST_CUSTPAYMENT, null, array('customer' => $invoice->customer_id,
206 'branch' => $invoice->Branch, 'date' => $date_)),
207 $amount-$discount, $discount, $payment_info,
208 0,0,0,$invoice->dimension_id, $invoice->dimension2_id);
209 add_cust_allocation($amount, ST_CUSTPAYMENT, $pmtno, ST_SALESINVOICE, $invoice_no, $invoice->customer_id, $date_);
211 update_debtor_trans_allocation(ST_SALESINVOICE, $invoice_no, $invoice->customer_id);
212 update_debtor_trans_allocation(ST_CUSTPAYMENT, $pmtno, $invoice->customer_id);
216 reallocate_payments($invoice_no, ST_SALESINVOICE, $date_, $to_allocate, $allocs, $invoice->customer_id);
217 hook_db_postwrite($invoice, ST_SALESINVOICE);
219 commit_transaction();
224 //--------------------------------------------------------------------------------------------------
226 function void_sales_invoice($type, $type_no)
230 hook_db_prevoid($type, $type_no);
231 void_bank_trans($type, $type_no, true);
232 void_gl_trans($type, $type_no, true);
234 // reverse all the changes in parent document(s)
235 $factor = get_cust_prepayment_invoice_factor($type_no);
238 $lines = get_customer_trans_details($type, $type_no);
239 while($line = db_fetch($lines))
241 update_prepaid_so_line($line['src_id'], -$factor*$line['quantity']);
246 $deliveries = get_sales_parent_numbers($type, $type_no);
248 if ($deliveries !== 0) {
249 if ($type == ST_SALESINVOICE && count($deliveries) == 1 && get_reference(ST_CUSTDELIVERY, $deliveries[0]) == "auto")
251 $trans = get_customer_trans($deliveries[0], ST_CUSTDELIVERY);
252 void_sales_delivery(ST_CUSTDELIVERY, $deliveries[0], false);
253 $date_ = sql2date($trans['tran_date']);
254 add_audit_trail(ST_CUSTDELIVERY, $deliveries[0], $date_, _("Voided."));
255 add_voided_entry(ST_CUSTDELIVERY, $deliveries[0], $date_, "");
259 $srcdetails = get_sales_parent_lines($type, $type_no);
260 while ($row = db_fetch($srcdetails)) {
261 update_parent_line($type, $row['id'], -$row['qty_done']);
266 // clear details after they've been reversed in the sales order
267 void_customer_trans_details($type, $type_no);
269 void_stock_move($type, $type_no); // in case of credit note with return
271 void_trans_tax_details($type, $type_no);
273 void_cust_allocations($type, $type_no);
275 // do this last because other voidings can depend on it - especially voiding
276 // DO NOT MOVE THIS ABOVE VOIDING or we can end up with trans with alloc < 0
277 void_customer_trans($type, $type_no);
279 commit_transaction();
282 function is_cust_invoice_credited($trans_no)
284 return db_num_rows(get_sales_child_lines(ST_SALESINVOICE, $trans_no));
287 function get_cust_prepayment_invoice_factor($trans_no)
289 $sql = "SELECT IF(dt.prep_amount>0, dt.prep_amount/so.total ,0)
290 FROM ".TB_PREF."debtor_trans dt
291 LEFT JOIN ".TB_PREF."sales_orders so ON so.trans_type=".ST_SALESORDER." AND so.order_no=dt.order_
292 WHERE dt.type=".ST_SALESINVOICE." AND trans_no=".db_escape($trans_no);
293 $row = db_fetch(db_query($sql, 'cannot retrieve prepaid invoice factor'));
294 return is_array($row) ? $row[0] : false;
298 Return yet not invoiced amount of prepayment invoice (or 0 if normal invoice)
300 function prepaid_invoice_remainder($order)
302 $sql = "SELECT so.total - SUM(IFNULL(inv.prep_amount,0)) FROM "
303 .TB_PREF."sales_orders so
304 LEFT JOIN ".TB_PREF."payment_terms pt ON so.payment_terms=pt.terms_indicator AND pt.days_before_due = -1
305 LEFT JOIN ".TB_PREF."debtor_trans inv ON inv.type=".ST_SALESINVOICE ." AND inv.order_=so.order_no
306 WHERE so.order_no=".db_escape($order)
307 ." AND so.trans_type=".ST_SALESORDER
308 ." AND so.payment_terms=pt.terms_indicator";
310 $result = db_fetch(db_query($sql, "cannot find final invoice value"));
311 return $result[0] ? $result[0] : 0;
316 Find oldest delivery date for sales invoice
318 function get_oldest_delivery_date($invoice_no)
320 $sql = "SELECT MIN(trans.tran_date)
322 ".TB_PREF."debtor_trans_details del
323 LEFT JOIN ".TB_PREF."debtor_trans_details inv
325 LEFT JOIN ".TB_PREF."debtor_trans trans
326 ON trans.type=".ST_CUSTDELIVERY." AND trans.trans_no = del.debtor_trans_no
328 inv.debtor_trans_type=".ST_SALESINVOICE
329 ." AND inv.debtor_trans_no=".db_escape($invoice_no);
330 $res = db_query($sql, 'cannot find oldest delivery date');
331 $date = db_fetch($res);
336 Find oldest payment date for sales invoice
338 function get_oldest_payment_date($invoice_no)
340 $sql = "SELECT MIN(payment.tran_date)
342 ".TB_PREF."cust_allocations alloc,
343 ".TB_PREF."debtor_trans payment
345 alloc.trans_type_to=".ST_SALESINVOICE." AND alloc.trans_no_to=".db_escape($invoice_no)
346 ." AND alloc.trans_type_from=payment.type AND alloc.trans_no_from=payment.trans_no";
347 $res = db_query($sql, 'cannot find oldest delivery date');
348 $date = db_fetch($res);