Forgot the immediate allocations.
[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, unit_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
60                 $unit_price = $row[1]; //Added by Rasmus
61
62                 $sql = "SELECT delivery_date FROM ".TB_PREF."grn_batch,".TB_PREF."grn_items WHERE
63                         ".TB_PREF."grn_batch.id = ".TB_PREF."grn_items.grn_batch_id AND ".TB_PREF."grn_items.id=$id";
64                 $result = db_query($sql, "The old delivery date from the received record cout not be retrieved");
65                 $row = db_fetch_row($result);
66                 $date = $row[0];
67         }
68         else
69         {
70                 $ret = 0;
71                 $date = "";
72                 $unit_price = 0; // Added by Rasmus
73         }
74     $sql = "UPDATE ".TB_PREF."purch_order_details
75                 SET qty_invoiced = qty_invoiced + $qty_invoiced ";
76
77         if ($chg_price != null)
78                 $sql .= " , act_price = $chg_price ";
79
80         $sql .= " WHERE po_detail_item = $po_detail_item";
81     db_query($sql, "The quantity invoiced of the purchase order line could not be updated");
82
83     $sql = "UPDATE ".TB_PREF."grn_items
84         SET quantity_inv = quantity_inv + $qty_invoiced
85         WHERE id = $id";
86         db_query($sql, "The quantity invoiced off the items received record could not be updated");
87         return array($ret, $date, $unit_price);
88 }
89
90 function get_deliveries_between($stock_id, $from, $to)
91 {
92         $from = date2sql($from);
93         $to = date2sql($to);
94         $sql = "SELECT SUM(-qty), SUM(-qty*standard_cost) FROM ".TB_PREF."stock_moves
95                 WHERE type=13 AND stock_id='$stock_id' AND
96                         tran_date>='$from' AND tran_date<='$to' GROUP BY stock_id";
97         $result = db_query($sql, "The deliveries could not be updated");
98         return db_fetch_row($result);
99 }
100
101 function get_diff_in_home_currency($supplier, $old_date, $date, $amount1, $amount2)
102 {
103         $currency = get_supplier_currency($supplier);
104         $amount1 = to_home_currency($amount1, $currency, $old_date);
105         $amount2 = to_home_currency($amount2, $currency, $date);
106         return $amount2 - $amount1;
107 }
108 //----------------------------------------------------------------------------------------
109
110 function add_supp_invoice($supp_trans, $invoice_no=0) // do not receive as ref because we change locally
111 {
112         //$company_currency = get_company_currency();
113         /*Start an sql transaction */
114         begin_transaction();
115
116         $tax_total = 0;
117     $taxes = $supp_trans->get_taxes($supp_trans->tax_group_id);
118
119     foreach ($taxes as $taxitem)
120     {
121         $tax_total += $taxitem['Value'];
122     }
123
124     $invoice_items_total = $supp_trans->get_total_charged($supp_trans->tax_group_id);
125
126         if ($supp_trans->is_invoice)
127                 $trans_type = 20;
128         else
129         {
130                 $trans_type = 21;
131                 // let's negate everything because it's a credit note
132                 $invoice_items_total = -$invoice_items_total;
133                 $tax_total = -$tax_total;
134                 $supp_trans->ov_discount = -$supp_trans->ov_discount; // this isn't used at all...
135         }
136
137     $date_ = $supp_trans->tran_date;
138
139     /*First insert the invoice into the supp_trans table*/
140         $invoice_id = add_supp_trans($trans_type, $supp_trans->supplier_id, $date_, $supp_trans->due_date,
141                 $supp_trans->reference, $supp_trans->supp_reference,
142                 $invoice_items_total, $tax_total, $supp_trans->ov_discount);
143
144         $total = 0;
145     /* Now the control account */
146     $supplier_accounts = get_supplier_accounts($supp_trans->supplier_id);
147     $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_, $supplier_accounts["payable_account"], 0, 0,
148                 -($invoice_items_total +  $tax_total + $supp_trans->ov_discount),
149                 $supp_trans->supplier_id,
150                 "The general ledger transaction for the control total could not be added");
151
152     /*Loop through the GL Entries and create a debit posting for each of the accounts entered */
153
154     /*the postings here are a little tricky, the logic goes like this:
155     if its a general ledger amount it goes straight to the account specified
156
157     if its a GRN amount invoiced then :
158
159     The cost as originally credited to GRN suspense on arrival of items is debited to GRN suspense. Any difference
160     between the std cost and the currency cost charged as converted at the ex rate of of the invoice is written off
161     to the purchase price variance account applicable to the item being invoiced.
162     */
163     foreach ($supp_trans->gl_codes as $entered_gl_code)
164     {
165
166             /*GL Items are straight forward - just do the debit postings to the GL accounts specified -
167             the credit is to creditors control act  done later for the total invoice value + tax*/
168
169                 if (!$supp_trans->is_invoice)
170                         $entered_gl_code->amount = -$entered_gl_code->amount;
171
172                 $memo_ = $entered_gl_code->memo_;
173                 $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_, $entered_gl_code->gl_code,
174                         $entered_gl_code->gl_dim, $entered_gl_code->gl_dim2, $entered_gl_code->amount, $supp_trans->supplier_id);
175
176                 add_supp_invoice_gl_item($trans_type, $invoice_id, $entered_gl_code->gl_code,
177                         $entered_gl_code->amount, $memo_);
178     }
179     foreach ($supp_trans->grn_items as $entered_grn)
180     {
181
182         if (!$supp_trans->is_invoice)
183         {
184                         $entered_grn->this_quantity_inv = -$entered_grn->this_quantity_inv;
185                         set_grn_item_credited($entered_grn, $supp_trans->supplier_id, $invoice_id, $date_);
186         }
187
188                 $line_taxfree = $entered_grn->taxfree_charge_price($supp_trans->tax_group_id);
189                 $line_tax = $entered_grn->full_charge_price($supp_trans->tax_group_id) - $line_taxfree;
190                 $stock_gl_code = get_stock_gl_code($entered_grn->item_code);
191
192                 $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_, $stock_gl_code["inventory_account"],
193                         $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
194                         $entered_grn->this_quantity_inv * $line_taxfree, $supp_trans->supplier_id);
195         // -------------- if price changed since po received. 16 Aug 2008 Joe Hunt
196         if($supp_trans->is_invoice)
197         {
198                 $old = update_supp_received_items_for_invoice($entered_grn->id, $entered_grn->po_detail_item,
199                         $entered_grn->this_quantity_inv, $entered_grn->chg_price);
200                         // Since the standard cost is always calculated on basis of the po unit_price,
201                         // this is also the price that should be the base of calculating the price diff.
202                         // In cases where there is two different po invoices on the same delivery with different unit prices this will not work either
203
204                         //$old_price = $old[0];
205                          
206                         $old_price = $old[2];
207
208                         /*
209                         If statement is removed. Should always check for deliveries nomatter if there has been a price change. 
210                         */
211                         //if ($old_price != $entered_grn->chg_price) // price-change, so update
212                         //{
213                         //$diff = $entered_grn->chg_price - $old_price;
214                         $old_date = sql2date($old[1]);
215                         $diff = get_diff_in_home_currency($supp_trans->supplier_id, $old_date, $date_, $old_price, 
216                                 $entered_grn->chg_price);
217                         // always return due to change in currency.
218                         $mat_cost = update_average_material_cost(null, $entered_grn->item_code,
219                                 $diff, $entered_grn->this_quantity_inv, $old_date, true);
220                         // added 2008-12-08 Joe Hunt. Update the purchase data table
221                         add_or_update_purchase_data($supp_trans->supplier_id, $entered_grn->item_code, $entered_grn->chg_price); 
222                         $deliveries = get_deliveries_between($entered_grn->item_code, $old_date, Today()); // extend the period, if invoice is before any deliveries.
223                         if ($deliveries[0] != 0) // have deliveries been done during the period?
224                         {
225                                 $deliveries[1] /= $deliveries[0];
226                                 $amt = ($mat_cost - $deliveries[1]) * $deliveries[0]; // $amt in home currency
227                                 if ($amt != 0.0)
228                                 {
229                                         add_gl_trans($trans_type, $invoice_id, $date_,  $stock_gl_code["cogs_account"],
230                                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], _("Cost diff."),
231                                                 $amt, null, null, null,
232                                                 "The general ledger transaction could not be added for the price variance of the inventory item");
233                                         add_gl_trans($trans_type, $invoice_id, $date_,  $stock_gl_code["inventory_account"],
234                                                 0, 0, _("Cost diff."), -$amt, null, null, null,
235                                                 "The general ledger transaction could not be added for the price variance of the inventory item");
236                                 }               
237                                 update_stock_move_pid(13, $entered_grn->item_code, $old_date, $date_, 0, $mat_cost);
238                         }
239                         update_stock_move_pid(25, $entered_grn->item_code, $old_date, $old_date, $supp_trans->supplier_id, $mat_cost);
240                 //}
241                 }
242         // ----------------------------------------------------------------------
243
244                 add_supp_invoice_item($trans_type, $invoice_id, $entered_grn->item_code,
245                         $entered_grn->item_description, 0,      $line_taxfree, $line_tax,
246                         $entered_grn->this_quantity_inv, $entered_grn->id, $entered_grn->po_detail_item, "");
247     } /* end of GRN postings */
248     /* Now the TAX account */
249     foreach ($taxes as $taxitem)
250     {
251         if ($taxitem['Value'] != 0)
252         {
253
254                 if (!$supp_trans->is_invoice)
255                         $taxitem['Value'] = -$taxitem['Value'];
256                 // here we suppose that tax is never included in price (we are company customer).
257                         add_supp_invoice_tax_item($trans_type, $invoice_id, $taxitem['tax_type_id'],
258                                 $taxitem['rate'], 0, $taxitem['Value']);
259
260                 $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_,
261                         $taxitem['purchasing_gl_code'], 0, 0, $taxitem['Value'],
262                         $supp_trans->supplier_id,
263                         "A general ledger transaction for the tax amount could not be added");
264         }
265     }
266         
267         /*Post a balance post if $total != 0 */
268         add_gl_balance($trans_type, $invoice_id, $date_, -$total, payment_person_types::supplier(), $supp_trans->supplier_id);  
269
270         add_comments($trans_type, $invoice_id, $date_, $supp_trans->Comments);
271
272         references::save_last($supp_trans->reference, $trans_type);
273
274         if ($invoice_no != 0)
275         {
276                 $invoice_alloc_balance = get_supp_trans_allocation_balance(20, $invoice_no);
277                 if ($invoice_alloc_balance > 0) 
278                 {       //the invoice is not already fully allocated 
279
280                         $trans = get_supp_trans($invoice_no, 20);
281                         $total = $trans['Total'];
282
283                         $allocate_amount = ($invoice_alloc_balance > $total) ? $total : $invoice_alloc_balance;
284                         /*Now insert the allocation record if > 0 */
285                         if ($allocate_amount != 0) 
286                         {
287                                 update_supp_trans_allocation(20, $invoice_no, $allocate_amount);
288                                 update_supp_trans_allocation(21, $invoice_id, $allocate_amount); // ***
289                                 add_supp_allocation($allocate_amount, 21, $invoice_id, 20, $invoice_no,
290                                         $date_);
291                                 // Exchange Variations Joe Hunt 2008-09-20 ////////////////////////////////////////
292
293                                 exchange_variation(21, $invoice_id, 20, $invoice_no, $date_,
294                                         $allocate_amount, payment_person_types::supplier());
295
296                                 ///////////////////////////////////////////////////////////////////////////
297                         }
298                 }
299         }
300         
301
302     commit_transaction();
303
304     return $invoice_id;
305 }
306
307 //----------------------------------------------------------------------------------------
308
309 // get all the invoices/credits for a given PO - quite long route to get there !
310
311 function get_po_invoices_credits($po_number)
312 {
313         $sql = "SELECT DISTINCT ".TB_PREF."supp_trans.trans_no, ".TB_PREF."supp_trans.type,
314                 ov_amount+ov_discount+ov_gst AS Total,
315                 ".TB_PREF."supp_trans.tran_date
316                 FROM ".TB_PREF."supp_trans, ".TB_PREF."supp_invoice_items, ".TB_PREF."purch_order_details
317                 WHERE ".TB_PREF."supp_invoice_items.supp_trans_no = ".TB_PREF."supp_trans.trans_no
318                 AND ".TB_PREF."supp_invoice_items.po_detail_item_id = ".TB_PREF."purch_order_details.po_detail_item
319                 AND ".TB_PREF."purch_order_details.order_no = $po_number";
320
321         return db_query($sql, "The invoices/credits for the po $po_number could not be retreived");
322 }
323
324 //----------------------------------------------------------------------------------------
325
326 function read_supp_invoice($trans_no, $trans_type, &$supp_trans)
327 {
328         $sql = "SELECT ".TB_PREF."supp_trans.*, supp_name FROM ".TB_PREF."supp_trans,".TB_PREF."suppliers
329                 WHERE trans_no = $trans_no AND type = $trans_type
330                 AND ".TB_PREF."suppliers.supplier_id=".TB_PREF."supp_trans.supplier_id";
331         $result = db_query($sql, "Cannot retreive a supplier transaction");
332
333         if (db_num_rows($result) == 1)
334         {
335                 $trans_row = db_fetch($result);
336
337                 $supp_trans->supplier_id = $trans_row["supplier_id"];
338                 $supp_trans->supplier_name = $trans_row["supp_name"];
339                 $supp_trans->tran_date = sql2date($trans_row["tran_date"]);
340                 $supp_trans->due_date = sql2date($trans_row["due_date"]);
341                 //$supp_trans->Comments = $trans_row["TransText"];
342                 $supp_trans->Comments = "";
343                 $supp_trans->reference = $trans_row["reference"];
344                 $supp_trans->supp_reference = $trans_row["supp_reference"];
345                 $supp_trans->ov_amount = $trans_row["ov_amount"];
346                 $supp_trans->ov_discount = $trans_row["ov_discount"];
347                 $supp_trans->ov_gst = $trans_row["ov_gst"];
348
349                 $id = $trans_row["trans_no"];
350
351                 $result = get_supp_invoice_items($trans_type, $id);
352
353                 if (db_num_rows($result) > 0)
354                 {
355
356             while ($details_row = db_fetch($result))
357             {
358
359                 if ($details_row["gl_code"] == 0)
360                 {
361                         $supp_trans->add_grn_to_trans($details_row["grn_item_id"], $details_row["po_detail_item_id"], $details_row["stock_id"],
362                                         $details_row["description"], 0, 0, $details_row["quantity"], 0, $details_row["FullUnitPrice"],
363                                         false, 0, 0);
364                 }
365                 else
366                 {
367                         $supp_trans->add_gl_codes_to_trans($details_row["gl_code"], get_gl_account_name($details_row["gl_code"]), 0, 0,
368                                         $details_row["FullUnitPrice"], $details_row["memo_"]);
369                 }
370             }
371         }
372         else
373         {
374                         return display_db_error("Invalid supptrans details for supptrans number : $trans_no and type : $trans_type", $sql, true);
375                 }
376
377         }
378         else
379         {
380                 return display_db_error("Invalid supptrans number : $trans_no and type : $trans_type", $sql, true);
381         }
382 }
383
384 //----------------------------------------------------------------------------------------
385
386 function void_supp_invoice($type, $type_no)
387 {
388         begin_transaction();
389
390         void_bank_trans($type, $type_no, true);
391
392         void_gl_trans($type, $type_no, true);
393
394         void_supp_allocations($type, $type_no);
395
396         void_supp_trans($type, $type_no);
397
398         $result = get_supp_invoice_items($type, $type_no);
399
400         // now remove this invoice/credit from any GRNs/POs that it's related to
401         if (db_num_rows($result) > 0)
402         {
403                 $date_ = Today();
404         while ($details_row = db_fetch($result))
405         {
406                 if ((int)$details_row["grn_item_id"] > 0) // it can be empty for GL items
407                 {
408                         // Changed 2008-10-17 by Joe Hunt to get the avg. material cost updated
409                                 $old = update_supp_received_items_for_invoice($details_row["grn_item_id"],
410                                         $details_row["po_detail_item_id"], -$details_row["quantity"], $details_row["FullUnitPrice"]); 
411                                 
412                                 //$diff = $details_row["FullUnitPrice"] - $old[2];
413                                 $old_date = sql2date($old[1]);
414                                 
415                                 $batch = get_grn_batch_from_item($details_row["grn_item_id"]);  
416                                 $grn = get_grn_batch($batch);
417                                 
418                                 $diff = get_diff_in_home_currency($grn["supplier_id"], $old_date, $date_, $old[2], 
419                                         $details_row["FullUnitPrice"]);
420                                 // Only adjust the avg for the diff
421                                 $mat_cost = update_average_material_cost(null, $details_row["stock_id"],
422                                         $diff, -$details_row["quantity"], $date_, true);
423
424                                 $deliveries = get_deliveries_between($details_row["stock_id"], $old_date, $date_);
425                                 if ($deliveries[0] != 0) // have deliveries been done during the period?
426                                 {
427                                         $deliveries[1] /= $deliveries[0];
428                                         $amt = ($mat_cost - $deliveries[1]) * $deliveries[0]; // $amt in home currency
429                                         if ($amt != 0.0)
430                                         {
431                                                 $stock_gl_code = get_stock_gl_code($details_row["stock_id"]);
432                                                 add_gl_trans($type, $type_no, $date_,   $stock_gl_code["cogs_account"],
433                                                         $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], _("Cost diff."),
434                                                         -$amt, null, null, null,
435                                                         "The general ledger transaction could not be added for the price variance of the inventory item");
436                                                 add_gl_trans($type, $type_no, $date_, $stock_gl_code["inventory_account"],
437                                                         0, 0, _("Cost diff."), $amt, null, null, null,
438                                                         "The general ledger transaction could not be added for the price variance of the inventory item");
439                                         }               
440                                         update_stock_move_pid(13, $details_row["stock_id"], $old_date, $date_, 0, $mat_cost);
441                                 }
442                                 update_stock_move_pid(25, $details_row["stock_id"], $old_date, $old_date, $grn['supplier_id'], $mat_cost);
443
444                 }
445         }
446         }
447
448         void_supp_invoice_items($type, $type_no);
449         void_supp_invoice_tax_items($type, $type_no);
450
451         commit_transaction();
452 }
453
454 //----------------------------------------------------------------------------------------
455
456
457 ?>