Fixed sales database design to ensure document relations consistency on line level.
[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         $company_data = get_company_prefs();
29
30         $branch_data = get_branch_accounts($invoice->Branch);
31
32         $customer = get_customer($invoice->customer_id);
33
34         // offer price values without freight costs
35         $items_total = $invoice->get_items_total_dispatch();
36         $freight_tax = $invoice->get_shipping_tax();
37
38         update_customer_trans_version(get_parent_type(ST_SALESINVOICE), $invoice->src_docs);
39
40         $ov_gst = 0;
41         $taxes = $invoice->get_taxes(); // all taxes with freight_tax
42
43         foreach ($taxes as $taxitem) {
44                 $taxitem['Value'] =  round2($taxitem['Value'], user_price_dec());
45                 $ov_gst +=  $taxitem['Value'];
46         }
47
48         if($invoice->tax_included==0) {
49             $items_added_tax = $ov_gst-$freight_tax;
50             $freight_added_tax = $freight_tax;
51         } else {
52             $items_added_tax = 0;
53             $freight_added_tax = 0;
54         }
55         // 2006-06-14. If the Customer Branch AR Account is set to a Bank Account,
56         // the transaction will be settled at once.
57         if (is_bank_account($branch_data['receivables_account']))
58                 $alloc = $items_total + $items_added_tax + $invoice->freight_cost + $freight_added_tax;
59         else
60                 $alloc = 0;
61
62         /* Insert/update the debtor_trans */
63         $sales_order = $invoice->order_no;
64         if (is_array($sales_order))
65                         $sales_order = $sales_order[0]; // assume all crucial SO data are same for every delivery
66
67         $invoice_no = write_customer_trans(ST_SALESINVOICE, $trans_no, $invoice->customer_id,
68                 $invoice->Branch, $date_, $invoice->reference, $items_total, 0,
69                 $items_added_tax, $invoice->freight_cost, $freight_added_tax,
70                 $invoice->sales_type, $sales_order, $invoice->ship_via, 
71                 $invoice->due_date, $alloc, 0, $invoice->dimension_id, 
72                 $invoice->dimension2_id, $invoice->payment); 
73                 // 2008-06-14 extra $alloc, 2008-11-12 added dimension_id Joe Hunt
74
75         if ($trans_no == 0) {
76                 $invoice->trans_no = array($invoice_no=>0);
77         } else {
78                 delete_comments(ST_SALESINVOICE, $invoice_no);
79                 void_gl_trans(ST_SALESINVOICE, $invoice_no, true);
80                 void_cust_allocations(ST_SALESINVOICE, $invoice_no); // ?
81                 void_trans_tax_details(ST_SALESINVOICE, $invoice_no);
82         }
83         $total = 0;
84         foreach ($invoice->line_items as $line_no => $invoice_line) {
85
86                 $line_taxfree_price = get_tax_free_price_for_item($invoice_line->stock_id,
87                         $invoice_line->price, 0, $invoice->tax_included,
88                         $invoice->tax_group_array);
89
90                 $line_tax = get_full_price_for_item($invoice_line->stock_id,
91                         $invoice_line->price, 0, $invoice->tax_included,
92                         $invoice->tax_group_array) - $line_taxfree_price;
93
94                 write_customer_trans_detail_item(ST_SALESINVOICE, $invoice_no, $invoice_line->stock_id,
95                         $invoice_line->item_description, $invoice_line->qty_dispatched,
96                         $invoice_line->line_price(), $line_tax, $invoice_line->discount_percent,
97                         $invoice_line->standard_cost, $invoice_line->src_id,
98                         $trans_no ? $invoice_line->id : 0);
99
100                 // Update delivery items for the quantity invoiced
101                 if ($invoice_line->qty_old != $invoice_line->qty_dispatched)
102                         update_parent_line(ST_SALESINVOICE, $invoice_line->src_id, ($invoice_line->qty_dispatched-$invoice_line->qty_old));
103
104                 if ($invoice_line->qty_dispatched != 0) {
105                         $stock_gl_code = get_stock_gl_code($invoice_line->stock_id);
106
107                         if ($invoice_line->line_price() != 0) {
108                                 //Post sales transaction to GL credit sales
109
110                                 // 2008-06-14. If there is a Branch Sales Account, then override with this,
111                                 // else take the Item Sales Account
112                                 $sales_account = ($branch_data['sales_account'] != "" ? $branch_data['sales_account'] : $stock_gl_code['sales_account']);
113                                 // 2008-08-01. If there is a Customer Dimension, then override with this,
114                                 // else take the Item Dimension (if any)
115                                 $dim = ($invoice->dimension_id != $customer['dimension_id'] ? $invoice->dimension_id : 
116                                         ($customer['dimension_id'] != 0 ? $customer["dimension_id"] : $stock_gl_code["dimension_id"]));
117                                 $dim2 = ($invoice->dimension2_id != $customer['dimension2_id'] ? $invoice->dimension2_id : 
118                                         ($customer['dimension2_id'] != 0 ? $customer["dimension2_id"] : $stock_gl_code["dimension2_id"]));
119                                 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $sales_account, $dim, $dim2,
120                                         (-$line_taxfree_price * $invoice_line->qty_dispatched),
121                                         $invoice->customer_id, "The sales price GL posting could not be inserted");
122
123                                 if ($invoice_line->discount_percent != 0) {
124
125                                         $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_,
126                                                 $branch_data["sales_discount_account"], $dim, $dim2,
127                                                 ($line_taxfree_price * $invoice_line->qty_dispatched * $invoice_line->discount_percent),
128                                                 $invoice->customer_id, "The sales discount GL posting could not be inserted");
129                                 } /*end of if discount !=0 */
130                         }
131                 } /*quantity dispatched is more than 0 */
132         } /*end of delivery_line loop */
133
134         if (($items_total + $charge_shipping) != 0) {
135                 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $branch_data["receivables_account"], 0, 0,
136                         ($items_total + $charge_shipping + $items_added_tax + $freight_added_tax),
137                         $invoice->customer_id, "The total debtor GL posting could not be inserted");
138         }
139
140         if ($charge_shipping != 0) {
141                 $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $company_data["freight_act"], 0, 0,
142                         -$invoice->get_tax_free_shipping(), $invoice->customer_id,
143                         "The freight GL posting could not be inserted");
144         }
145         // post all taxes
146         foreach ($taxes as $taxitem) {
147
148                 if ($taxitem['Net'] != 0) {
149                         $ex_rate = get_exchange_rate_from_home_currency(get_customer_currency($invoice->customer_id), $date_);
150                         add_trans_tax_details(ST_SALESINVOICE, $invoice_no, $taxitem['tax_type_id'],
151                                 $taxitem['rate'], $invoice->tax_included, $taxitem['Value'],
152                                  $taxitem['Net'], $ex_rate, $date_, $invoice->reference);
153
154                         $total += add_gl_trans_customer(ST_SALESINVOICE, $invoice_no, $date_, $taxitem['sales_gl_code'], 0, 0,
155                                 (-$taxitem['Value']), $invoice->customer_id,
156                                 "A tax GL posting could not be inserted");
157                 }
158         }
159
160         /*Post a balance post if $total != 0 */
161         add_gl_balance(ST_SALESINVOICE, $invoice_no, $date_, -$total, PT_CUSTOMER, $invoice->customer_id);      
162
163         add_comments(10, $invoice_no, $date_, $invoice->Comments);
164
165         if ($trans_no == 0) {
166                 $Refs->save(ST_SALESINVOICE, $invoice_no, $invoice->reference);
167                 if ($invoice->cash) {
168                         $amount = $items_total + $items_added_tax + $invoice->freight_cost 
169                                 + $freight_added_tax;
170
171                         // to use debtors.pmt_discount on cash sale:
172                         // extend invoice entry page with final amount after discount 
173                         // and change line below.
174                         $discount = 0; // $invoice->cash_discount*$amount;
175                         $pmtno = write_customer_payment(0, $invoice->customer_id, 
176                                 $invoice->Branch, $invoice->cash_account, $date_,
177                                 $Refs->get_next(ST_CUSTPAYMENT), $amount-$discount, $discount,
178                                 _('Cash invoice').' '.$invoice_no);
179                         add_cust_allocation($amount, ST_CUSTPAYMENT, $pmtno, ST_SALESINVOICE, $invoice_no);
180
181                         update_debtor_trans_allocation(ST_SALESINVOICE, $invoice_no, $amount);
182                         update_debtor_trans_allocation(ST_CUSTPAYMENT, $pmtno, $amount);
183                 }
184         }
185         commit_transaction();
186
187         return $invoice_no;
188 }
189
190 //--------------------------------------------------------------------------------------------------
191
192 function void_sales_invoice($type, $type_no)
193 {
194         begin_transaction();
195
196         void_bank_trans($type, $type_no, true);
197         void_gl_trans($type, $type_no, true);
198
199         // reverse all the changes in parent document(s)
200
201         $deliveries = get_sales_parent_numbers($type, $type_no);
202
203         if ($deliveries !== 0) {
204                 if (count($deliveries) == 1 && get_reference(ST_CUSTDELIVERY, $deliveries[0]) == "auto")
205                 {
206                         void_sales_delivery(ST_CUSTDELIVERY, $deliveries[0], false);
207                         $date_ = Today();
208                         add_audit_trail(ST_CUSTDELIVERY, $deliveries[0], $date_, _("Voided."));
209                         add_voided_entry(ST_CUSTDELIVERY, $deliveries[0], $date_, "");
210                 }
211                 else
212                 {
213                         
214                         $srcdetails = get_sales_parent_lines($type, $type_no);
215                         while ($row = db_fetch($src_details)) {
216                                 update_parent_line($type, $row['id'], -$row['quantity']);
217                         }
218                 }
219         }
220         // clear details after they've been reversed in the sales order
221         void_customer_trans_details($type, $type_no);
222
223         void_trans_tax_details($type, $type_no);
224
225         void_cust_allocations($type, $type_no);
226
227         // do this last because other voidings can depend on it - especially voiding
228         // DO NOT MOVE THIS ABOVE VOIDING or we can end up with trans with alloc < 0
229         void_customer_trans($type, $type_no);
230
231         commit_transaction();
232 }
233
234 ?>