Added credit info in supplier invoice and supplier credit note.
[fa-stable.git] / purchasing / includes / db / 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 include_once($path_to_root . "/purchasing/includes/db/invoice_items_db.inc");
13
14 //--------------------------------------------------------------------------------------------------
15
16 function read_supplier_details_to_trans(&$supp_trans, $supplier_id)
17 {
18         $sql = "SELECT supp.supp_name, terms.terms, terms.days_before_due,
19                 terms.day_in_following_month, supp.tax_included,
20                 supp.tax_group_id, tax_group.name AS tax_group_name,
21                 supp.credit_limit - Sum(IFNULL(IF(trans.type=".ST_SUPPCREDIT.", -1, 1) 
22                         * (ov_amount + ov_gst + ov_discount),0)) as cur_credit
23                 FROM ".TB_PREF."suppliers supp LEFT JOIN ".TB_PREF."supp_trans trans ON supp.supplier_id = trans.supplier_id, ".TB_PREF."payment_terms terms, ".TB_PREF."tax_groups tax_group
24                 WHERE supp.tax_group_id = tax_group.id
25                 AND supp.payment_terms=terms.terms_indicator
26                 AND supp.supplier_id = ".db_escape($supplier_id)." GROUP BY supp.supp_name";
27
28         $result = db_query($sql, "The supplier record selected: " . $supplier_id . " cannot be retrieved");
29
30         $myrow = db_fetch($result);
31
32     $supp_trans->supplier_id = $supplier_id;
33     $supp_trans->tax_included = $myrow['tax_included'];
34     $supp_trans->supplier_name = $myrow['supp_name'];
35         $supp_trans->terms_description = $myrow['terms'];
36         $supp_trans->credit = $myrow['cur_credit'];
37
38         if ($myrow['days_before_due'] == 0)
39         {
40                 $supp_trans->terms = "1" . $myrow['day_in_following_month'];
41         }
42         else
43         {
44                 $supp_trans->terms = "0" . $myrow['days_before_due'];
45         }
46         $supp_trans->tax_description = $myrow['tax_group_name'];
47         $supp_trans->tax_group_id = $myrow['tax_group_id'];
48
49     if ($supp_trans->tran_date == "")
50     {
51                 $supp_trans->tran_date = Today();
52                 if (!is_date_in_fiscalyear($supp_trans->tran_date))
53                         $supp_trans->tran_date = end_fiscalyear();
54         }
55     //if ($supp_trans->due_date=="") {
56     //  get_duedate_from_terms($supp_trans);
57     //}
58     get_duedate_from_terms($supp_trans);
59 }
60
61 //--------------------------------------------------------------------------------------------------
62
63 function update_supp_received_items_for_invoice($id, $po_detail_item, $qty_invoiced, $chg_price=null)
64 {
65         if ($chg_price != null)
66         {
67                 $sql = "SELECT act_price, unit_price FROM ".TB_PREF."purch_order_details WHERE
68                         po_detail_item = ".db_escape($po_detail_item);
69                 $result = db_query($sql, "The old actual price of the purchase order line could not be retrieved");
70                 $row = db_fetch_row($result);
71                 $ret = $row[0];
72
73                 $unit_price = $row[1]; //Added by Rasmus
74
75                 $sql = "SELECT delivery_date FROM ".TB_PREF."grn_batch,".TB_PREF."grn_items WHERE
76                         ".TB_PREF."grn_batch.id = ".TB_PREF."grn_items.grn_batch_id AND "
77                         .TB_PREF."grn_items.id=".db_escape($id);
78                 $result = db_query($sql, "The old delivery date from the received record cout not be retrieved");
79                 $row = db_fetch_row($result);
80                 $date = $row[0];
81         }
82         else
83         {
84                 $ret = 0;
85                 $date = "";
86                 $unit_price = 0; // Added by Rasmus
87         }
88     $sql = "UPDATE ".TB_PREF."purch_order_details
89                 SET qty_invoiced = qty_invoiced + ".db_escape($qty_invoiced);
90
91         if ($chg_price != null)
92                 $sql .= " , act_price = ".db_escape($chg_price);
93
94         $sql .= " WHERE po_detail_item = ".db_escape($po_detail_item);
95     db_query($sql, "The quantity invoiced of the purchase order line could not be updated");
96
97     $sql = "UPDATE ".TB_PREF."grn_items
98         SET quantity_inv = quantity_inv + ".db_escape($qty_invoiced)."
99         WHERE id = ".db_escape($id);
100         db_query($sql, "The quantity invoiced off the items received record could not be updated");
101         return array($ret, $date, $unit_price);
102 }
103
104 function get_diff_in_home_currency($supplier, $old_date, $date, $amount1, $amount2)
105 {
106         $dec = user_price_dec();
107         price_decimal_format($amount2, $dec);
108         $currency = get_supplier_currency($supplier);
109         $ex_rate = get_exchange_rate_to_home_currency($currency, $old_date);
110         $amount1 = $amount1 / $ex_rate;
111         $ex_rate = get_exchange_rate_to_home_currency($currency, $date);
112         $amount2 = $amount2 / $ex_rate;
113         $diff = $amount2 - $amount1;
114         //return round2($diff, $dec);
115         return $diff;
116 }
117 //----------------------------------------------------------------------------------------
118
119 function add_supp_invoice($supp_trans, $invoice_no=0) // do not receive as ref because we change locally
120 {
121         global $Refs;
122
123         //$company_currency = get_company_currency();
124         /*Start an sql transaction */
125         begin_transaction();
126
127         $tax_total = 0;
128     $taxes = $supp_trans->get_taxes($supp_trans->tax_group_id);
129
130     foreach ($taxes as $n => $taxitem)
131     {
132                 $taxes[$n]['Value'] =  round2($taxitem['Value'], user_price_dec());
133         $tax_total += $taxes[$n]['Value'];
134     }
135
136         $invoice_items_total = $supp_trans->get_items_total();
137 //      $invoice_items_total = $supp_trans->get_total_taxfree($supp_trans->tax_group_id);
138
139         if($supp_trans->tax_included==0) {
140                 $item_added_tax = $tax_total;
141         } else {
142                 $item_added_tax = 0;
143                 
144         }
145
146         $trans_type = $supp_trans->trans_type;
147         
148         if ($trans_type == ST_SUPPCREDIT)
149         {
150                 // let's negate everything because it's a credit note
151                 $invoice_items_total = -$invoice_items_total;
152                 $tax_total = -$tax_total;
153                 $supp_trans->ov_discount = -$supp_trans->ov_discount; // this isn't used at all...
154                 $item_added_tax = -$item_added_tax;
155         }
156
157     $date_ = $supp_trans->tran_date;
158         $ex_rate = get_exchange_rate_from_home_currency(get_supplier_currency($supp_trans->supplier_id), $date_);
159
160     /*First insert the invoice into the supp_trans table*/
161         $invoice_id = write_supp_trans($trans_type, 0, $supp_trans->supplier_id, $date_, $supp_trans->due_date,
162                 $supp_trans->reference, $supp_trans->supp_reference,
163                 $invoice_items_total, $item_added_tax, $supp_trans->ov_discount, "", 0, $supp_trans->tax_included);
164
165         $total = 0;
166     /* Now the control account */
167     $supplier_accounts = get_supplier_accounts($supp_trans->supplier_id);
168     $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_, $supplier_accounts["payable_account"], 0, 0,
169                 -($invoice_items_total +  $item_added_tax + $supp_trans->ov_discount),
170                 $supp_trans->supplier_id,
171                 "The general ledger transaction for the control total could not be added");
172
173     foreach ($supp_trans->gl_codes as $entered_gl_code)
174     {
175
176             /*GL Items are straight forward - just do the debit postings to the GL accounts specified -
177             the credit is to creditors control act  done later for the total invoice value + tax*/
178
179                 if ($trans_type == ST_SUPPCREDIT)
180                         $entered_gl_code->amount = -$entered_gl_code->amount;
181
182                 $memo_ = $entered_gl_code->memo_;
183                 $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_, $entered_gl_code->gl_code,
184                         $entered_gl_code->gl_dim, $entered_gl_code->gl_dim2, $entered_gl_code->amount, $supp_trans->supplier_id, "", 0, $memo_);
185
186                 add_supp_invoice_gl_item($trans_type, $invoice_id, $entered_gl_code->gl_code,
187                         $entered_gl_code->amount, $memo_);
188
189                 // store tax details if the gl account is a tax account
190                 if ($trans_type == ST_SUPPCREDIT)
191                         $entered_gl_code->amount = -$entered_gl_code->amount;
192                 add_gl_tax_details($entered_gl_code->gl_code, 
193                         $trans_type, $invoice_id, $entered_gl_code->amount,
194                         $ex_rate, $date_, $supp_trans->supp_reference, $supp_trans->tax_included);
195     }
196     foreach ($supp_trans->grn_items as $line_no => $entered_grn)
197     {
198
199         if ($trans_type == ST_SUPPCREDIT)
200         {
201                         $entered_grn->this_quantity_inv = -$entered_grn->this_quantity_inv;
202                         set_grn_item_credited($entered_grn, $supp_trans->supplier_id, $invoice_id, $date_);
203         }
204                 $line_taxfree = $entered_grn->taxfree_charge_price($supp_trans->tax_group_id);
205                 $line_tax = $entered_grn->full_charge_price($supp_trans->tax_group_id) - $line_taxfree;
206                 $stock_gl_code = get_stock_gl_code($entered_grn->item_code);
207                 $iv_act = (is_inventory_item($entered_grn->item_code) ? $stock_gl_code["inventory_account"] : 
208                         ($supplier_accounts["purchase_account"] ? $supplier_accounts["purchase_account"] : $stock_gl_code["cogs_account"]));
209                 $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_, $iv_act,
210                         $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
211                         $entered_grn->this_quantity_inv * $line_taxfree, $supp_trans->supplier_id);
212                 /*$total += add_gl_trans_supplier($trans_type, $invoice_id, $date_, $iv_act,
213                         $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'],
214                         $entered_grn->this_quantity_inv * $line_taxfree, $supp_trans->supplier_id);*/
215         // -------------- if price changed since po received. 16 Aug 2008 Joe Hunt
216         if ($trans_type == ST_SUPPINVOICE)
217         {
218                 $old = update_supp_received_items_for_invoice($entered_grn->id, $entered_grn->po_detail_item,
219                         $entered_grn->this_quantity_inv, $entered_grn->chg_price);
220                         // Since the standard cost is always calculated on basis of the po unit_price,
221                         // this is also the price that should be the base of calculating the price diff.
222                         // In cases where there is two different po invoices on the same delivery with different unit prices this will not work either
223
224                         //$old_price = $old[0];
225                          
226                         $old_price = $old[2];
227
228                         /*
229                         If statement is removed. Should always check for deliveries nomatter if there has been a price change. 
230                         */
231                         //if ($old_price != $entered_grn->chg_price) // price-change, so update
232                         //{
233                         //$diff = $entered_grn->chg_price - $old_price;
234                         $old_date = sql2date($old[1]);
235                         if (is_inventory_item($entered_grn->item_code))
236                         {
237                                 $diff = get_diff_in_home_currency($supp_trans->supplier_id, $old_date, $date_, $old_price, 
238                                         $entered_grn->chg_price);       
239                         
240                                 // always return due to change in currency.
241                                 /*$mat_cost = update_average_material_cost(null, $entered_grn->item_code,
242                                         $diff, $entered_grn->this_quantity_inv, $old_date, true); */
243                                 $mat_cost = update_average_material_cost(null, $entered_grn->item_code,
244                                         $diff, $entered_grn->this_quantity_inv, null, true);
245                                 
246                                 //Add GL transaction for GRN Provision in case of difference
247                                 if (($diff * $entered_grn->this_quantity_inv) != 0 )
248                                 {
249                                         $diff_amt = $diff * $entered_grn->this_quantity_inv;
250                                         add_gl_trans($trans_type, $invoice_id, $date_,  $iv_act,
251                                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], 'GRN Provision',
252                                                 $diff_amt, null, null, null,
253                                                 "The general ledger transaction could not be added for the GRN of the inventory item"); 
254                                         
255                                         add_gl_trans($trans_type, $invoice_id, $date_,  $stock_gl_code["cogs_account"],
256                                                 0, 0, 'GRN Provision', -$diff_amt, null, null, null,
257                                                 "The general ledger transaction could not be added for the GRN of the inventory item");                         
258                                 }
259                         }       
260                         // added 2008-12-08 Joe Hunt. Update the purchase data table
261                         add_or_update_purchase_data($supp_trans->supplier_id, $entered_grn->item_code, $entered_grn->chg_price); 
262                         /*$deliveries = get_deliveries_between($entered_grn->item_code, $old_date, Today()); // extend the period, if invoice is before any deliveries.
263                         if ($deliveries[0] != 0) // have deliveries been done during the period?
264                         {
265                                 $deliveries[1] /= $deliveries[0];
266                                 $amt = ($mat_cost - $deliveries[1]) * $deliveries[0]; // $amt in home currency
267                                 if ($amt != 0.0)
268                                 {
269                                         $_s = $entered_grn->item_code;
270                                         $_d = $deliveries[0];
271                                         $_od = $old_date;
272                                         $_cd = $mat_cost - $deliveries[1];
273                                         $memo = _("Cost difference adjustment for $_s. $_d items delivered since $_od. The cost difference is $_cd");
274                                         add_gl_trans($trans_type, $invoice_id, $date_,  $stock_gl_code["cogs_account"],
275                                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
276                                                 $amt, null, null, null,
277                                                 "The general ledger transaction could not be added for the price variance of the inventory item");
278                                         add_gl_trans($trans_type, $invoice_id, $date_,  $iv_act,
279                                                 0, 0, $memo, -$amt, null, null, null,
280                                                 "The general ledger transaction could not be added for the price variance of the inventory item");
281                                 }               
282                                 update_stock_move_pid(ST_CUSTDELIVERY, $entered_grn->item_code, $old_date, $date_, 0, $mat_cost);
283                         } */
284                         if (is_inventory_item($entered_grn->item_code))
285                                 update_stock_move_pid(ST_SUPPRECEIVE, $entered_grn->item_code, $old_date, $old_date, $supp_trans->supplier_id, $mat_cost);
286                 //}
287                 }
288         // ----------------------------------------------------------------------
289
290                 add_supp_invoice_item($trans_type, $invoice_id, $entered_grn->item_code,
291                         $entered_grn->item_description, 0,      $entered_grn->chg_price, $line_tax,
292                         $entered_grn->this_quantity_inv, $entered_grn->id, $entered_grn->po_detail_item, "");
293     } /* end of GRN postings */
294     /* Now the TAX account */
295     $taxes = $supp_trans->get_taxes($supp_trans->tax_group_id, 0, false); // 2009.08-18 Joe Hunt. We have already got the gl lines
296     foreach ($taxes as $taxitem)
297     {
298         if ($taxitem['Net'] != 0)
299         {
300
301                 if ($trans_type == ST_SUPPCREDIT)
302                 {
303                         $taxitem['Net'] = -$taxitem['Net'];
304                         $taxitem['Value'] = -$taxitem['Value'];
305                 }       
306                         add_trans_tax_details($trans_type, $invoice_id, 
307                                 $taxitem['tax_type_id'], $taxitem['rate'], $supp_trans->tax_included, $taxitem['Value'],
308                                 $taxitem['Net'], $ex_rate, $date_, $supp_trans->supp_reference);
309
310                 if ($trans_type == ST_SUPPCREDIT)
311                         $taxitem['Value'] = -$taxitem['Value'];
312                 $total += add_gl_trans_supplier($trans_type, $invoice_id, $date_,
313                         $taxitem['purchasing_gl_code'], 0, 0, $taxitem['Value'],
314                         $supp_trans->supplier_id,
315                         "A general ledger transaction for the tax amount could not be added");
316         }
317     }
318         
319         /*Post a balance post if $total != 0 */
320         add_gl_balance($trans_type, $invoice_id, $date_, -$total, PT_SUPPLIER, $supp_trans->supplier_id);       
321
322         add_comments($trans_type, $invoice_id, $date_, $supp_trans->Comments);
323
324         $Refs->save($trans_type, $invoice_id, $supp_trans->reference);
325
326         if ($invoice_no != 0)
327         {
328                 $invoice_alloc_balance = get_supp_trans_allocation_balance(ST_SUPPINVOICE, $invoice_no);
329                 if ($invoice_alloc_balance > 0) 
330                 {       //the invoice is not already fully allocated 
331
332                         $trans = get_supp_trans($invoice_no, ST_SUPPINVOICE);
333                         $total = $trans['Total'];
334
335                         $allocate_amount = ($invoice_alloc_balance > $total) ? $total : $invoice_alloc_balance;
336                         /*Now insert the allocation record if > 0 */
337                         if ($allocate_amount != 0) 
338                         {
339                                 update_supp_trans_allocation(ST_SUPPINVOICE, $invoice_no, $allocate_amount);
340                                 update_supp_trans_allocation(ST_SUPPCREDIT, $invoice_id, $allocate_amount); // ***
341                                 add_supp_allocation($allocate_amount, ST_SUPPCREDIT, $invoice_id, ST_SUPPINVOICE, $invoice_no,
342                                         $date_);
343                                 // Exchange Variations Joe Hunt 2008-09-20 ////////////////////////////////////////
344
345                                 exchange_variation(ST_SUPPCREDIT, $invoice_id, ST_SUPPINVOICE, $invoice_no, $date_,
346                                         $allocate_amount, PT_SUPPLIER);
347
348                                 ///////////////////////////////////////////////////////////////////////////
349                         }
350                 }
351         }
352         
353
354     commit_transaction();
355
356     return $invoice_id;
357 }
358
359 //----------------------------------------------------------------------------------------
360
361 // get all the invoices/credits for a given PO - quite long route to get there !
362
363 function get_po_invoices_credits($po_number)
364 {
365         $sql = "SELECT DISTINCT ".TB_PREF."supp_trans.trans_no, ".TB_PREF."supp_trans.type,
366                 ov_amount+ov_discount+ov_gst AS Total,
367                 ".TB_PREF."supp_trans.tran_date
368                 FROM ".TB_PREF."supp_trans, ".TB_PREF."supp_invoice_items, "
369                 .TB_PREF."purch_order_details, ".TB_PREF."purch_orders
370                 WHERE ".TB_PREF."supp_invoice_items.supp_trans_no = ".TB_PREF."supp_trans.trans_no
371                 AND ".TB_PREF."supp_invoice_items.po_detail_item_id = ".TB_PREF."purch_order_details.po_detail_item
372                 AND ".TB_PREF."purch_orders.supplier_id = ".TB_PREF."supp_trans.supplier_id
373                 AND ".TB_PREF."purch_order_details.order_no = ".db_escape($po_number);
374
375         return db_query($sql, "The invoices/credits for the po $po_number could not be retreived");
376 }
377
378 //----------------------------------------------------------------------------------------
379
380 function read_supp_invoice($trans_no, $trans_type, &$supp_trans)
381 {
382         $sql = "SELECT ".TB_PREF."supp_trans.*, supp_name FROM ".TB_PREF."supp_trans,".TB_PREF."suppliers
383                 WHERE trans_no = ".db_escape($trans_no)." AND type = ".db_escape($trans_type)."
384                 AND ".TB_PREF."suppliers.supplier_id=".TB_PREF."supp_trans.supplier_id";
385         $result = db_query($sql, "Cannot retreive a supplier transaction");
386
387         if (db_num_rows($result) == 1)
388         {
389                 $trans_row = db_fetch($result);
390
391                 $supp_trans->supplier_id = $trans_row["supplier_id"];
392                 $supp_trans->supplier_name = $trans_row["supp_name"];
393                 $supp_trans->tran_date = sql2date($trans_row["tran_date"]);
394                 $supp_trans->due_date = sql2date($trans_row["due_date"]);
395                 //$supp_trans->Comments = $trans_row["TransText"];
396                 $supp_trans->Comments = get_comments_string($trans_type, $trans_no);
397                 $supp_trans->reference = $trans_row["reference"];
398                 $supp_trans->supp_reference = $trans_row["supp_reference"];
399                 $supp_trans->ov_amount = $trans_row["ov_amount"];
400                 $supp_trans->ov_discount = $trans_row["ov_discount"];
401                 $supp_trans->ov_gst = $trans_row["ov_gst"];
402                 $supp_trans->tax_included = $trans_row["tax_included"];
403
404                 $id = $trans_row["trans_no"];
405
406                 $result = get_supp_invoice_items($trans_type, $id);
407
408                 if (db_num_rows($result) > 0)
409                 {
410
411             while ($details_row = db_fetch($result))
412             {
413
414                 if ($details_row["gl_code"] == 0)
415                 {
416                         $supp_trans->add_grn_to_trans($details_row["grn_item_id"], $details_row["po_detail_item_id"], $details_row["stock_id"],
417                                         $details_row["description"], 0, 0, $details_row["quantity"], 0, $details_row["FullUnitPrice"],
418                                         0, 0);
419                 }
420                 else
421                 {
422                         $supp_trans->add_gl_codes_to_trans($details_row["gl_code"], get_gl_account_name($details_row["gl_code"]), 0, 0,
423                                         $details_row["FullUnitPrice"], $details_row["memo_"]);
424                 }
425             }
426         }
427         else
428         {
429                         return display_db_error("Invalid supptrans details for supptrans number : $trans_no and type : $trans_type", $sql, true);
430                 }
431
432         }
433         else
434         {
435                 return display_db_error("Invalid supptrans number : $trans_no and type : $trans_type", $sql, true);
436         }
437 }
438
439 //----------------------------------------------------------------------------------------
440
441 function get_matching_invoice_item($stock_id, $po_item_id)
442 {
443         $sql = "SELECT *, tran_date FROM ".TB_PREF."supp_invoice_items, ".TB_PREF."supp_trans
444                 WHERE supp_trans_type = ".ST_SUPPINVOICE." AND stock_id = "
445                 .db_escape($stock_id)." AND po_detail_item_id = ".db_escape($po_item_id)."
446                 AND supp_trans_no = trans_no";
447         $result = db_query($sql, "Cannot retreive supplier transaction detail records");
448         return db_fetch($result);  
449 }
450
451 function void_supp_invoice($type, $type_no)
452 {
453         begin_transaction();
454
455         $trans = get_supp_trans($type_no, $type);
456
457         void_bank_trans($type, $type_no, true);
458
459         void_gl_trans($type, $type_no, true);
460
461         void_supp_allocations($type, $type_no);
462
463         void_supp_trans($type, $type_no);
464
465         $result = get_supp_invoice_items($type, $type_no);
466
467         // now remove this invoice/credit from any GRNs/POs that it's related to
468         if (db_num_rows($result) > 0)
469         {
470                 $date_ = Today();
471         while ($details_row = db_fetch($result))
472         {
473                 if ((int)$details_row["grn_item_id"] > 0) // it can be empty for GL items
474                 {
475                         // Changed 2008-10-17 by Joe Hunt to get the avg. material cost updated
476                                 $old = update_supp_received_items_for_invoice($details_row["grn_item_id"],
477                                         $details_row["po_detail_item_id"], -$details_row["quantity"], $details_row["FullUnitPrice"]); 
478                                 
479                                 //$diff = $details_row["FullUnitPrice"] - $old[2];
480                                 $old_date = sql2date($old[1]);
481                                 
482                                 $batch = get_grn_batch_from_item($details_row["grn_item_id"]);  
483                                 $grn = get_grn_batch($batch);
484                         if ($type == ST_SUPPCREDIT) // credit note 2009-06-14 Joe Hunt Must restore the po and grn
485                         {       // We must get the corresponding invoice item to check for price chg.
486                                         $match = get_matching_invoice_item($details_row["stock_id"], $details_row["po_detail_item_id"]);
487                                         if ($match !== false)
488                                                 $mat_cost = update_average_material_cost($grn["supplier_id"], $details_row["stock_id"],  
489                                                         $match["unit_price"], -$details_row["quantity"], sql2date($match['tran_date']), $match['tran_date'] !== $trans['tran_date']);
490                                         else            
491                                                 $mat_cost = update_average_material_cost($grn["supplier_id"], $details_row["stock_id"],  
492                                                         $details_row["FullUnitPrice"], -$details_row["quantity"], $old_date, $old[1] !== $trans['tran_date']);
493                                         $sql = "UPDATE ".TB_PREF."purch_order_details
494                                         SET quantity_ordered = quantity_ordered + ".-$details_row["quantity"].", ";
495                                 if ($match !== false)
496                                         $sql .= "act_price=".$match['unit_price'].", ";
497                                 $sql .= "quantity_received = quantity_received + ".-$details_row["quantity"]."
498                                     WHERE po_detail_item = ".$details_row["po_detail_item_id"];
499                                         db_query($sql, "a purchase order details record could not be updated. This receipt of goods has not been processed ");
500                                         $sql = "UPDATE ".TB_PREF."grn_items SET qty_recd=qty_recd+".-$details_row["quantity"]."
501                                                 WHERE id=".$details_row["grn_item_id"];
502                                         db_query($sql);
503                         }
504                         else
505                         {
506                                         $diff = get_diff_in_home_currency($grn["supplier_id"], $old_date, sql2date($trans['tran_date']), $old[2], 
507                                                 $details_row["FullUnitPrice"]);
508                                         // Only adjust the avg for the diff
509                                         $mat_cost = update_average_material_cost(null, $details_row["stock_id"],
510                                                 $diff, -$details_row["quantity"], $old_date, true);
511                                 }
512                                 $deliveries = get_deliveries_between($details_row["stock_id"], $old_date, $date_);
513                                 if ($deliveries[0] != 0) // have deliveries been done during the period?
514                                 {
515                                         update_stock_move_pid(ST_CUSTDELIVERY, $details_row["stock_id"], $old_date, $date_, 0, $mat_cost);
516                                 }
517                                 update_stock_move_pid(ST_SUPPRECEIVE, $details_row["stock_id"], $old_date, $old_date, $grn['supplier_id'], $mat_cost);
518                 }
519         }
520         }
521
522         if ($type == ST_SUPPCREDIT) // void the credits in stock moves
523                 void_stock_move($type, $type_no); 
524         void_supp_invoice_items($type, $type_no);
525         void_trans_tax_details($type, $type_no);
526
527         commit_transaction();
528 }
529
530 //----------------------------------------------------------------------------------------
531 function get_gl_account_info($acc)
532 {
533         $sql = "SELECT account_code, account_name FROM ".TB_PREF."chart_master WHERE account_code=".db_escape($acc);
534         return db_query($sql,"get account information");
535 }
536
537 function is_reference_already_there($supplier_id, $supp_reference)
538 {
539         $sql = "SELECT Count(*) FROM ".TB_PREF."supp_trans WHERE supplier_id="
540                 .db_escape($supplier_id) . " AND supp_reference=" 
541                 .db_escape($supp_reference) 
542                 . " AND ov_amount!=0"; // ignore voided invoice references
543
544         $result=db_query($sql,"The sql to check for the previous entry of the same invoice failed");
545
546         $myrow = db_fetch_row($result);
547         return ($myrow[0] == 1);
548 }
549
550 function remove_not_invoice_item($id)
551 {
552         begin_transaction();
553
554         $myrow = get_grn_item_detail($id);
555
556         $grn = get_grn_batch($myrow['grn_batch_id']);
557
558         $sql = "UPDATE ".TB_PREF."purch_order_details
559                 SET quantity_received = qty_invoiced, quantity_ordered = qty_invoiced WHERE po_detail_item = ".$myrow["po_detail_item"];
560         db_query($sql, "The quantity invoiced of the purchase order line could not be updated");
561
562         $sql = "UPDATE ".TB_PREF."grn_items
563                 SET qty_recd = quantity_inv WHERE id = ".$myrow["id"];
564         db_query($sql, "The quantity invoiced off the items received record could not be updated");
565
566         update_average_material_cost($grn["supplier_id"], $myrow["item_code"],
567                 $myrow["unit_price"], -$myrow["QtyOstdg"], Today());
568
569         add_stock_move(ST_SUPPRECEIVE, $myrow["item_code"], $myrow['grn_batch_id'], $grn['loc_code'], sql2date($grn["delivery_date"]), "",
570                 -$myrow["QtyOstdg"], $myrow['std_cost_unit'], $grn["supplier_id"], 1, $myrow['unit_price']);
571
572         commit_transaction();
573 }
574 ?>