Moving 2.0 development version to main trunk.
[fa-stable.git] / purchasing / includes / db / invoice_db.inc
1 <?php
2
3 include_once($path_to_root . "/purchasing/includes/db/invoice_items_db.inc");
4
5 //--------------------------------------------------------------------------------------------------
6
7 function read_supplier_details_to_trans(&$supp_trans, $supplier_id)
8 {
9         $sql = "SELECT ".TB_PREF."suppliers.supp_name, ".TB_PREF."payment_terms.terms, ".TB_PREF."payment_terms.days_before_due,
10                 ".TB_PREF."payment_terms.day_in_following_month,
11                 ".TB_PREF."suppliers.tax_group_id, ".TB_PREF."tax_groups.name As tax_group_name
12                 From ".TB_PREF."suppliers, ".TB_PREF."payment_terms, ".TB_PREF."tax_groups
13                 WHERE ".TB_PREF."suppliers.tax_group_id = ".TB_PREF."tax_groups.id
14                 AND ".TB_PREF."suppliers.payment_terms=".TB_PREF."payment_terms.terms_indicator
15                 AND ".TB_PREF."suppliers.supplier_id = '" . $supplier_id . "'";
16
17         $result = db_query($sql, "The supplier record selected: " . $supplier_id . " cannot be retrieved");
18
19         $myrow = db_fetch($result);
20
21     $supp_trans->supplier_id = $supplier_id;
22     $supp_trans->supplier_name = $myrow['supp_name'];
23         $supp_trans->terms_description = $myrow['terms'];
24
25         if ($myrow['days_before_due'] == 0)
26         {
27                 $supp_trans->terms = "1" . $myrow['day_in_following_month'];
28         }
29         else
30         {
31                 $supp_trans->terms = "0" . $myrow['days_before_due'];
32         }
33         $supp_trans->tax_description = $myrow['tax_group_name'];
34         $supp_trans->tax_group_id = $myrow['tax_group_id'];
35
36     if ($supp_trans->tran_date == "")
37     {
38                 $supp_trans->tran_date = Today();
39                 if (!is_date_in_fiscalyear($supp_trans->tran_date))
40                         $supp_trans->tran_date = end_fiscalyear();
41         }
42     //if ($supp_trans->due_date=="") {
43     //  get_duedate_from_terms($supp_trans);
44     //}
45     get_duedate_from_terms($supp_trans);
46 }
47
48 //--------------------------------------------------------------------------------------------------
49
50 function update_supp_received_items_for_invoice($id, $po_detail_item, $qty_invoiced, $chg_price=null)
51 {
52         if ($chg_price != null)
53         {
54                 $sql = "SELECT act_price FROM ".TB_PREF."purch_order_details WHERE
55                         po_detail_item = $po_detail_item";
56                 $result = db_query($sql, "The old actual price of the purchase order line could not be retrieved");
57                 $row = db_fetch_row($result);
58                 $ret = $row[0];
59                 $sql = "SELECT delivery_date FROM ".TB_PREF."grn_batch,".TB_PREF."grn_items WHERE
60                         ".TB_PREF."grn_batch.id = ".TB_PREF."grn_items.grn_batch_id AND ".TB_PREF."grn_items.id=$id";
61                 $result = db_query($sql, "The old delivery date from the received record cout not be retrieved");
62                 $row = db_fetch_row($result);
63                 $date = $row[0];
64         }
65         else
66         {
67                 $ret = 0;
68                 $date = "";
69         }
70     $sql = "UPDATE ".TB_PREF."purch_order_details
71                 SET qty_invoiced = qty_invoiced + $qty_invoiced ";
72
73         if ($chg_price != null)
74                 $sql .= " , act_price = $chg_price ";
75
76         $sql .= " WHERE po_detail_item = $po_detail_item";
77     db_query($sql, "The quantity invoiced of the purchase order line could not be updated");
78
79     $sql = "UPDATE ".TB_PREF."grn_items
80         SET quantity_inv = quantity_inv + $qty_invoiced
81         WHERE id = $id";
82         db_query($sql, "The quantity invoiced off the items received record could not be updated");
83         return array($ret, $date);
84 }
85
86 function get_deliveries_between($stock_id, $from, $to)
87 {
88         $from = date2sql($from);
89         $to = date2sql($to);
90         $sql = "SELECT SUM(-qty), AVG(standard_cost) FROM ".TB_PREF."stock_moves
91                 WHERE type=13 AND stock_id='$stock_id' AND
92                         tran_date>='$from' AND tran_date<='$to' GROUP BY stock_id";
93         $result = db_query($sql, "The deliveries could not be updated");
94         return db_fetch_row($result);
95 }
96 //----------------------------------------------------------------------------------------
97
98 function add_supp_invoice($supp_trans) // do not receive as ref because we change locally
99 {
100         //$company_currency = get_company_currency();
101         /*Start an sql transaction */
102         begin_transaction();
103
104         $tax_total = 0;
105     $taxes = $supp_trans->get_taxes($supp_trans->tax_group_id);
106
107     foreach ($taxes as $taxitem)
108     {
109         $tax_total += $taxitem['Value'];
110     }
111
112     $invoice_items_total = $supp_trans->get_total_charged($supp_trans->tax_group_id);
113
114         if ($supp_trans->is_invoice)
115                 $trans_type = 20;
116         else
117         {
118                 $trans_type = 21;
119                 // let's negate everything because it's a credit note
120                 $invoice_items_total = -$invoice_items_total;
121                 $tax_total = -$tax_total;
122                 $supp_trans->ov_discount = -$supp_trans->ov_discount; // this isn't used at all...
123         }
124
125     $date_ = $supp_trans->tran_date;
126
127     /*First insert the invoice into the supp_trans table*/
128         $invoice_id = add_supp_trans($trans_type, $supp_trans->supplier_id, $date_, $supp_trans->due_date,
129                 $supp_trans->reference, $supp_trans->supp_reference,
130                 $invoice_items_total, $tax_total, $supp_trans->ov_discount);
131
132     /* Now the control account */
133     $supplier_accounts = get_supplier_accounts($supp_trans->supplier_id);
134     add_gl_trans_supplier($trans_type, $invoice_id, $date_, $supplier_accounts["payable_account"], 0, 0,
135                 -($invoice_items_total +  $tax_total + $supp_trans->ov_discount),
136                 $supp_trans->supplier_id,
137                 "The general ledger transaction for the control total could not be added");
138
139     /*Loop through the GL Entries and create a debit posting for each of the accounts entered */
140
141     /*the postings here are a little tricky, the logic goes like this:
142     if its a general ledger amount it goes straight to the account specified
143
144     if its a GRN amount invoiced then :
145
146     The cost as originally credited to GRN suspense on arrival of items is debited to GRN suspense. Any difference
147     between the std cost and the currency cost charged as converted at the ex rate of of the invoice is written off
148     to the purchase price variance account applicable to the item being invoiced.
149     */
150
151     foreach ($supp_trans->gl_codes as $entered_gl_code)
152     {
153
154             /*GL Items are straight forward - just do the debit postings to the GL accounts specified -
155             the credit is to creditors control act  done later for the total invoice value + tax*/
156
157                 if (!$supp_trans->is_invoice)
158                         $entered_gl_code->amount = -$entered_gl_code->amount;
159
160                 $memo_ = $entered_gl_code->memo_;
161                 add_gl_trans_supplier($trans_type, $invoice_id, $date_, $entered_gl_code->gl_code,
162                         $entered_gl_code->gl_dim, $entered_gl_code->gl_dim2, $entered_gl_code->amount, $supp_trans->supplier_id);
163
164                 add_supp_invoice_gl_item($trans_type, $invoice_id, $entered_gl_code->gl_code,
165                         $entered_gl_code->amount, $memo_);
166     }
167     foreach ($supp_trans->grn_items as $entered_grn)
168     {
169
170         if (!$supp_trans->is_invoice)
171         {
172                         $entered_grn->this_quantity_inv = -$entered_grn->this_quantity_inv;
173         }
174
175                 $line_taxfree = $entered_grn->taxfree_charge_price($supp_trans->tax_group_id);
176                 $line_tax = $entered_grn->full_charge_price($supp_trans->tax_group_id) - $line_taxfree;
177
178         $old = update_supp_received_items_for_invoice($entered_grn->id, $entered_grn->po_detail_item,
179                 $entered_grn->this_quantity_inv, $entered_grn->chg_price);
180                 $stock_gl_code = get_stock_gl_code($entered_grn->item_code);
181
182                 add_gl_trans_supplier($trans_type, $invoice_id, $date_, $stock_gl_code["inventory_account"],
183                         $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
184                         $entered_grn->this_quantity_inv * $line_taxfree, $supp_trans->supplier_id);
185         // -------------- if price changed since po received. 16 Aug 2008 Joe Hunt
186                 $old_price = $old[0];
187         if ($old_price != $entered_grn->chg_price) // price-change, so update
188         {
189                 $diff = $entered_grn->chg_price - $old_price;
190                         $old_date = sql2date($old[1]);
191                         // only update the diff (last parameter, adj_only is set to true).
192                 $mat_cost = update_average_material_cost($supp_trans->supplier_id, $entered_grn->item_code,
193                         $diff, $entered_grn->this_quantity_inv, $old_date, true);
194                 // function just above this
195                 $deliveries = get_deliveries_between($entered_grn->item_code, $old_date, $date_);
196                         if ($deliveries[0] != 0) // have deliveries been done during the period?
197                 {
198
199                         $amt = ($mat_cost - $deliveries[1]) * $deliveries[0]; // $amt in home currency
200
201                                 add_gl_trans($trans_type, $invoice_id, $date_,  $stock_gl_code["cogs_account"],
202                                         $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], _("Cost diff."),
203                                 $amt, null, null, null,
204                                 "The general ledger transaction could not be added for the price variance of the inventory item");
205                                 add_gl_trans($trans_type, $invoice_id, $date_,  $stock_gl_code["inventory_account"],
206                                         0, 0, _("Cost diff."), -$amt, null, null, null,
207                                 "The general ledger transaction could not be added for the price variance of the inventory item");
208                                 update_stock_move_pid(13, $entered_grn->item_code, $old_date, $date_, 0, $mat_cost);
209                 }
210                         update_stock_move_pid(25, $entered_grn->item_code, $old_date, $old_date, $supp_trans->supplier_id, $mat_cost);
211         }
212         // ----------------------------------------------------------------------
213
214                 add_supp_invoice_item($trans_type, $invoice_id, $entered_grn->item_code,
215                         $entered_grn->item_description, 0,      $line_taxfree, $line_tax,
216                         $entered_grn->this_quantity_inv, $entered_grn->id, $entered_grn->po_detail_item, "");
217     } /* end of GRN postings */
218     /* Now the TAX account */
219     foreach ($taxes as $taxitem)
220     {
221         if ($taxitem['Value'] != 0)
222         {
223
224                 if (!$supp_trans->is_invoice)
225                         $taxitem['Value'] = -$taxitem['Value'];
226                 // here we suppose that tax is never included in price (we are company customer).
227                         add_supp_invoice_tax_item($trans_type, $invoice_id, $taxitem['tax_type_id'],
228                                 $taxitem['rate'], 0, $taxitem['Value']);
229
230                 add_gl_trans_supplier($trans_type, $invoice_id, $date_,
231                         $taxitem['purchasing_gl_code'], 0, 0, $taxitem['Value'],
232                         $supp_trans->supplier_id,
233                         "A general ledger transaction for the tax amount could not be added");
234         }
235     }
236         add_comments($trans_type, $invoice_id, $date_, $supp_trans->Comments);
237
238         references::save_last($supp_trans->reference, $trans_type);
239
240     commit_transaction();
241
242     return $invoice_id;
243 }
244
245 //----------------------------------------------------------------------------------------
246
247 // get all the invoices/credits for a given PO - quite long route to get there !
248
249 function get_po_invoices_credits($po_number)
250 {
251         $sql = "SELECT DISTINCT ".TB_PREF."supp_trans.trans_no, ".TB_PREF."supp_trans.type,
252                 ov_amount+ov_discount+ov_gst AS Total,
253                 ".TB_PREF."supp_trans.tran_date
254                 FROM ".TB_PREF."supp_trans, ".TB_PREF."supp_invoice_items, ".TB_PREF."purch_order_details
255                 WHERE ".TB_PREF."supp_invoice_items.supp_trans_no = ".TB_PREF."supp_trans.trans_no
256                 AND ".TB_PREF."supp_invoice_items.po_detail_item_id = ".TB_PREF."purch_order_details.po_detail_item
257                 AND ".TB_PREF."purch_order_details.order_no = $po_number";
258
259         return db_query($sql, "The invoices/credits for the po $po_number could not be retreived");
260 }
261
262 //----------------------------------------------------------------------------------------
263
264 function read_supp_invoice($trans_no, $trans_type, &$supp_trans)
265 {
266         $sql = "SELECT ".TB_PREF."supp_trans.*, supp_name FROM ".TB_PREF."supp_trans,".TB_PREF."suppliers
267                 WHERE trans_no = $trans_no AND type = $trans_type
268                 AND ".TB_PREF."suppliers.supplier_id=".TB_PREF."supp_trans.supplier_id";
269         $result = db_query($sql, "Cannot retreive a supplier transaction");
270
271         if (db_num_rows($result) == 1)
272         {
273                 $trans_row = db_fetch($result);
274
275                 $supp_trans->supplier_id = $trans_row["supplier_id"];
276                 $supp_trans->supplier_name = $trans_row["supp_name"];
277                 $supp_trans->tran_date = sql2date($trans_row["tran_date"]);
278                 $supp_trans->due_date = sql2date($trans_row["due_date"]);
279                 //$supp_trans->Comments = $trans_row["TransText"];
280                 $supp_trans->Comments = "";
281                 $supp_trans->reference = $trans_row["reference"];
282                 $supp_trans->supp_reference = $trans_row["supp_reference"];
283                 $supp_trans->ov_amount = $trans_row["ov_amount"];
284                 $supp_trans->ov_discount = $trans_row["ov_discount"];
285                 $supp_trans->ov_gst = $trans_row["ov_gst"];
286
287                 $id = $trans_row["trans_no"];
288
289                 $result = get_supp_invoice_items($trans_type, $id);
290
291                 if (db_num_rows($result) > 0)
292                 {
293
294             while ($details_row = db_fetch($result))
295             {
296
297                 if ($details_row["gl_code"] == 0)
298                 {
299                         $supp_trans->add_grn_to_trans($details_row["grn_item_id"], $details_row["po_detail_item_id"], $details_row["stock_id"],
300                                         $details_row["description"], 0, 0, $details_row["quantity"], 0, $details_row["FullUnitPrice"],
301                                         false, 0, 0);
302                 }
303                 else
304                 {
305                         $supp_trans->add_gl_codes_to_trans($details_row["gl_code"], get_gl_account_name($details_row["gl_code"]), 0, 0,
306                                         $details_row["FullUnitPrice"], $details_row["memo_"]);
307                 }
308             }
309         }
310         else
311         {
312                         return display_db_error("Invalid supptrans details for supptrans number : $trans_no and type : $trans_type", $sql, true);
313                 }
314
315         }
316         else
317         {
318                 return display_db_error("Invalid supptrans number : $trans_no and type : $trans_type", $sql, true);
319         }
320 }
321
322 //----------------------------------------------------------------------------------------
323
324 function void_supp_invoice($type, $type_no)
325 {
326         begin_transaction();
327
328         void_bank_trans($type, $type_no, true);
329
330         void_gl_trans($type, $type_no, true);
331
332         void_supp_allocations($type, $type_no);
333
334         void_supp_trans($type, $type_no);
335
336         $result = get_supp_invoice_items($type, $type_no);
337
338         // now remove this invoice/credit from any GRNs/POs that it's related to
339         if (db_num_rows($result) > 0)
340         {
341         while ($details_row = db_fetch($result))
342         {
343                 if (strlen($details_row["grn_item_id"]) > 0) // it can be empty for GL items
344                 {
345                                 update_supp_received_items_for_invoice($details_row["grn_item_id"],
346                                         $details_row["po_detail_item_id"], -$details_row["quantity"]);
347                 }
348         }
349         }
350
351         void_supp_invoice_items($type, $type_no);
352         void_supp_invoice_tax_items($type, $type_no);
353
354         commit_transaction();
355 }
356
357 //----------------------------------------------------------------------------------------
358
359
360 ?>