Old ineffective sql_trail superseded by new improved db_trail logging only calls...
[fa-stable.git] / purchasing / includes / db / grn_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     Update average inventory item cost.
14 */
15 function update_average_material_cost($supplier, $stock_id, $price, $qty, $date, $adj_only=false)
16 {
17         // probably this function should be optimized
18         // passing transaction cart as argument. This would
19         // save a couple of db calls like get_supplier()
20         
21         $supp = get_supplier($supplier);
22         if ($supplier != null)
23                 $currency = $supp['curr_code'];
24         else
25                 $currency = null;
26
27         if ($supp['tax_included'])
28                 $price = get_tax_free_price_for_item(ST_SUPPINVOICE, // ?
29                 $stock_id, $price, $supp['tax_group_id'],
30                         $supp['tax_included']);
31
32         if ($currency != null)
33         {
34                 $ex_rate = get_exchange_rate_to_home_currency($currency, $date);
35                 $price_in_home_currency = $price / $ex_rate;
36         }       
37         else
38                 $price_in_home_currency = $price;
39
40         $price_in_home_currency_ = $price_in_home_currency;
41
42         // Handle if inventory will become negative
43     // Skip negative inventory adjustment for case of adjust_only
44     if (is_inventory_item($stock_id) && !$adj_only) 
45         handle_negative_inventory($stock_id, $qty, $price_in_home_currency, $date);
46
47         $item = get_item($stock_id);
48         $avg_cost =  $item['material_cost'];
49
50         $qoh = get_qoh_on_date($stock_id);
51
52         $cost_adjust = false;
53
54         if ($adj_only)
55         {
56                 if ($qoh > 0)
57                         $avg_cost = ($qoh * $avg_cost + $qty * $price_in_home_currency) / $qoh;
58         }
59         else
60         {
61                 if ($qoh < 0)
62                 {
63                         if ($qoh + $qty >= 0)
64                                 $cost_adjust = true;
65                         $qoh = 0;
66                 }
67                 if ($qoh + $qty > 0)
68                         $avg_cost = ($qoh * $avg_cost + $qty * $price_in_home_currency) / ($qoh + $qty);
69         }
70
71         if ($cost_adjust) // Material_cost replaced with price
72                 adjust_deliveries($stock_id, $price_in_home_currency_, $date);
73
74         $sql = "UPDATE ".TB_PREF."stock_master SET material_cost=".db_escape($avg_cost)."
75                 WHERE stock_id=".db_escape($stock_id);
76
77         db_query($sql,"The cost details for the inventory item could not be updated");
78         return $avg_cost;
79 }
80
81 //-------------------------------------------------------------------------------------------------------------
82 //
83 //      Add or update GRN transaction.
84 //
85 function write_grn(&$po)
86 {
87         global $Refs;
88
89         $date_ = $po->tran_date;
90         $grn = $po->grn_id;
91
92         begin_transaction(__FUNCTION__, func_get_args());
93         hook_db_prewrite($po, ST_SUPPRECEIVE);
94
95         if (!is_company_currency($po->curr_code))
96         {
97                 if (!$po->ex_rate)
98                         $po->ex_rate = get_date_exchange_rate($po->curr_code, $date_);
99                 else
100                         add_new_exchange_rate($po->curr_code, $date_, $po->ex_rate);
101         } else
102                 $po->ex_rate = 1;
103
104         if(!$grn)
105                 $grn = add_grn_batch($po->order_no, $po->supplier_id, $po->reference, $po->Location, $date_, $po->ex_rate);
106         else {
107
108                 update_grn_batch($grn, $po->reference, $po->Location, $date_);
109
110                 void_gl_trans(ST_SUPPRECEIVE, $grn, true);
111                 void_stock_move(ST_SUPPRECEIVE, $grn);
112                 void_trans_tax_details(ST_SUPPRECEIVE, $grn);
113                 delete_comments(ST_SUPPRECEIVE, $grn);
114         }
115
116     $clearing_act = get_company_pref('grn_clearing_act');
117     $total = 0;
118         foreach ($po->line_items as $line_no => $order_line)
119         {
120                 if ($order_line->quantity != 0)
121                 {
122                         $stock_gl_code = get_stock_gl_code($order_line->stock_id);
123
124                         //------------------------------------------------------------------------------------------------------
125                         if ($order_line->qty_received == 0)
126                         {
127                                 /* This must be the first receipt of goods against this PO line. */
128                                 /* Store provisional cost used in GL posting - inventory is updated to actual cost later when invoice is received */
129                                 $order_line->unit_cost = round2($order_line->taxfree_charge_value() / $po->ex_rate / $order_line->quantity, user_price_dec());
130                         }
131
132                         //------------------- update average material cost and clearing account --------------------------------
133                         if (is_inventory_item($order_line->stock_id))
134                         {
135                                 if ($clearing_act)
136                                         $total += add_gl_trans_std_cost(ST_SUPPRECEIVE, $grn, $date_, $stock_gl_code["inventory_account"],
137                                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $order_line->stock_id,
138                                             $order_line->unit_cost*$order_line->quantity, PT_SUPPLIER, $po->supplier_id);
139
140                                 update_average_material_cost($po->supplier_id, $order_line->stock_id, $order_line->price,
141                                         $order_line->quantity, $date_);
142                         }
143
144                         /* Need to insert a grn item */ // also need to check for over-receive.(within allowance)
145                         if ($order_line->quantity + $order_line->qty_received > $order_line->qty_ordered)
146                                 $order_line->qty_ordered = $order_line->quantity + $order_line->qty_received;
147
148                         /* Store line details and update po_line */
149                         $grn_item = write_grn_item($grn, $order_line->po_item_id,
150                                 $order_line->stock_id, $order_line->item_description, $order_line->quantity, $order_line->grn_item_id, $order_line->unit_cost);
151
152                         $po->line_items[$line_no]->grn_item_id = $grn_item;
153                         /* Update location stock records - NB  a po cannot be entered for a service/kit parts done automatically */
154                         add_stock_move(ST_SUPPRECEIVE, $order_line->stock_id, $grn, $po->Location, $date_, "",
155                                 $order_line->quantity, $order_line->unit_cost, $order_line->taxfree_charge_value()/$order_line->quantity);
156
157                 } /* quantity received is != 0 */
158         }
159
160         if ($clearing_act && $total != 0.0) {
161                 $accs = get_supplier_accounts($po->supplier_id);
162                 $total += add_gl_trans_supplier(ST_SUPPRECEIVE, $grn, $date_, $clearing_act,
163                         $accs['dimension_id'], $accs['dimension2_id'], -$total, null);
164         }
165         $Refs->save(ST_SUPPRECEIVE, $grn, $po->reference);
166
167         add_audit_trail(ST_SUPPRECEIVE, $grn, $date_);
168
169         $po->trans_no = $grn;
170         hook_db_postwrite($po, ST_SUPPRECEIVE);
171
172         commit_transaction();
173
174         return $grn;
175 }
176
177 //----------------------------------------------------------------------------------------
178
179 function add_grn_batch($po_number, $supplier_id, $reference, $location, $date_, $rate)
180 {
181         $date = date2sql($date_);
182
183         $sql = "INSERT INTO ".TB_PREF."grn_batch (purch_order_no, delivery_date, supplier_id, reference, loc_code, rate)
184                         VALUES (".db_escape($po_number).", ".db_escape($date).", "
185                         .db_escape($supplier_id).", ".db_escape($reference).", ".db_escape($location).", ".db_escape($rate).")";
186
187         db_query($sql, "A grn batch record could not be inserted.");
188
189         return db_insert_id();
190 }
191
192 //----------------------------------------------------------------------------------------
193
194 function update_grn_batch($grn, $reference, $location, $date_)
195 {
196         $date = date2sql($date_);
197
198         $sql = "UPDATE ".TB_PREF."grn_batch SET 
199                         delivery_date=".db_escape($date).",
200                         reference=".db_escape($reference).", 
201                         loc_code=".db_escape($location)."
202                         WHERE id=".db_escape($grn);
203
204         db_query($sql, "A grn batch record could not be updated.");
205
206         return db_insert_id();
207 }
208 //-------------------------------------------------------------------------------------------------------------
209
210 function write_grn_item($grn_batch_id, $po_detail_item, $item_code, $description, $quantity_received, $grn_item_id, $unit_cost)
211 {
212         if ($grn_item_id)
213                 $sql = "UPDATE ".TB_PREF."grn_items SET qty_recd=".db_escape($quantity_received)
214                         ." WHERE id=".db_escape($grn_item_id);
215         else
216                 $sql = "INSERT INTO ".TB_PREF."grn_items (grn_batch_id, po_detail_item, item_code, description, qty_recd)
217                         VALUES (".db_escape($grn_batch_id).", "
218                         .db_escape($po_detail_item).", ".db_escape($item_code).", ".db_escape($description)
219                         .", ".db_escape($quantity_received).")";
220
221         db_query($sql, "A GRN detail item could not be stored.");
222
223         $sql = "UPDATE ".TB_PREF."purch_order_details po,
224                         (SELECT SUM(qty_recd) received FROM ".TB_PREF."grn_items grn WHERE po_detail_item=".db_escape($po_detail_item).") grn
225         SET po.quantity_received = grn.received,
226             po.std_cost_unit =".db_escape($unit_cost)."
227         WHERE po_detail_item = ".db_escape($po_detail_item);
228         db_query($sql, "a purchase order details record could not be updated. This receipt of goods has not been processed ");
229
230         return db_insert_id();
231 }
232
233 //----------------------------------------------------------------------------------------
234 function get_grn_batch_from_item($item)
235 {
236         $sql = "SELECT grn_batch_id FROM ".TB_PREF."grn_items WHERE id=".db_escape($item);
237         $result = db_query($sql, "Could not retreive GRN batch id");
238         $row = db_fetch_row($result);
239         return $row[0];
240 }
241
242 function get_grn_batch($grn)
243 {
244         $sql = "SELECT * FROM ".TB_PREF."grn_batch WHERE id=".db_escape($grn);
245         $result = db_query($sql, "Could not retreive GRN batch id");
246         return db_fetch($result);
247 }
248
249 function set_grn_item_credited(&$entered_grn, $supplier, $transno, $date)
250 {
251         $mcost = update_average_material_cost($supplier, $entered_grn->item_code,
252                 $entered_grn->chg_price, $entered_grn->this_quantity_inv, $date);
253
254         $sql = "SELECT grn.*, item.*
255         FROM ".TB_PREF."grn_batch grn,"
256                 .TB_PREF."grn_items item
257         WHERE item.grn_batch_id=grn.id
258                 AND item.id=".db_escape($entered_grn->id)."
259         AND item.item_code=".db_escape($entered_grn->item_code);
260
261         $result = db_query($sql, "Could not retreive GRNS");
262         $myrow = db_fetch($result);
263
264         $sql = "UPDATE ".TB_PREF."purch_order_details
265         SET quantity_received = quantity_received - "
266                 .db_escape($entered_grn->this_quantity_inv).",
267         quantity_ordered = quantity_ordered - "
268         .db_escape($entered_grn->this_quantity_inv).",
269         qty_invoiced = qty_invoiced - ".db_escape($entered_grn->this_quantity_inv).",
270         act_price=".db_escape($entered_grn->chg_price)."
271         WHERE po_detail_item = ".$myrow["po_detail_item"];
272         db_query($sql, "a purchase order details record could not be updated. This receipt of goods has not been processed ");
273
274         //$sql = "UPDATE ".TB_PREF."grn_items SET qty_recd=0, quantity_inv=0 WHERE id=$entered_grn->id";
275         $sql = "UPDATE ".TB_PREF."grn_items SET qty_recd=qty_recd-".db_escape($entered_grn->this_quantity_inv)
276         .",quantity_inv=quantity_inv-".db_escape($entered_grn->this_quantity_inv)
277         ." WHERE id=".db_escape($entered_grn->id);
278         db_query($sql);
279
280     add_stock_move(ST_SUPPCREDIT, $entered_grn->item_code, $transno, $myrow['loc_code'], $date, "",
281        -$entered_grn->this_quantity_inv, $mcost, $entered_grn->chg_price);
282 }
283
284 function get_grn_items($grn_batch_id=0, $supplier_id="", $outstanding_only=false,
285         $is_invoiced_only=false, $invoice_no=0, $begin="", $end="")
286 {
287     $sql = "SELECT grn.*, grn_item.*, po_item.delivery_date as req_del_date,
288                 grn_item.quantity_inv".($invoice_no ? "-invoice_item.quantity" : '')."  quantity_inv,
289         po_item.unit_price,
290         po_item.act_price,
291         po_item.quantity_ordered,
292         po_item.quantity_received,
293         po_item.std_cost_unit, units
294         FROM    ".TB_PREF."grn_batch grn"
295                                 ." INNER JOIN ".TB_PREF."grn_items grn_item ON grn_item.grn_batch_id=grn.id"
296                         ." INNER JOIN ".TB_PREF."purch_order_details po_item ON grn_item.po_detail_item=po_item.po_detail_item"
297                         ." INNER JOIN ".TB_PREF."stock_master stock_item ON stock_item.stock_id=grn_item.item_code";
298  
299     if ($invoice_no != 0) {
300         $sql .= " LEFT JOIN ".TB_PREF."supp_invoice_items invoice_item ON ";
301
302                 $inv_cond = "invoice_item.supp_trans_type=".ST_SUPPINVOICE." AND invoice_item.supp_trans_no ";
303                 if (is_array($invoice_no))
304                         $inv_cond .= " IN (".implode(',' , $invoice_no) . ")";
305                 else
306                         $inv_cond .= " = $invoice_no";
307                 $sql .= "($inv_cond) AND grn_item.id=invoice_item.grn_item_id";
308         }
309
310     $sql .= " WHERE grn_item.qty_recd != 0";
311
312         if ($outstanding_only)
313         $sql .= " AND (".($invoice_no ? "$inv_cond OR ":'')."grn_item.qty_recd - grn_item.quantity_inv > 0)";
314
315         $sql .= " AND stock_item.stock_id=grn_item.item_code ";
316
317         if ($begin != "")
318                 $sql .= " AND grn.delivery_date>='".date2sql($begin)."'";
319         if ($end != "")
320                 $sql .= " AND grn.delivery_date<='".date2sql($end)."'";
321         if ($grn_batch_id != 0)
322                 $sql .= " AND grn.id=".db_escape($grn_batch_id)
323                         ." AND grn_item.grn_batch_id=".db_escape($grn_batch_id);
324
325         if ($is_invoiced_only)
326                 $sql .= " AND grn_item.quantity_inv > 0";
327
328         if ($supplier_id != "")
329                 $sql .= " AND grn.supplier_id =".db_escape($supplier_id);
330
331         $sql .= " ORDER BY grn.delivery_date, grn.id, grn_item.id";
332
333         return db_query($sql, "Could not retreive GRNS");
334 }
335
336 //----------------------------------------------------------------------------------------
337
338 // get the details for a given grn item
339
340 function get_grn_item($grn_item_no)
341 {
342         $sql = "SELECT grn.*, po.unit_price, grn.qty_recd - grn.quantity_inv AS QtyOstdg,
343                 po.std_cost_unit
344                 FROM ".TB_PREF."grn_items grn,"
345                         .TB_PREF."purch_order_details po,"
346                         .TB_PREF."stock_master item
347                 WHERE grn.po_detail_item=po.po_detail_item
348                         AND item.stock_id=grn.item_code
349                         AND grn.id=".db_escape($grn_item_no);
350
351         $result = db_query($sql, "could not retreive grn item details");
352         return db_fetch($result);
353 }
354
355 //----------------------------------------------------------------------------------------
356
357 function read_grn_items_to_order($grn_batch, &$order)
358 {
359         $result = get_grn_items($grn_batch);
360
361         if (db_num_rows($result) > 0)
362         {
363
364                 while ($myrow = db_fetch_assoc($result))
365                 {
366                         if ($myrow['qty_recd'] == 0 && $myrow['quantity_inv'] == 0)
367                                 continue; // We will not have empty credited rows.
368
369                         $order->add_to_order($myrow["item_code"],
370                                 $myrow["qty_recd"],$myrow["description"], $myrow["unit_price"],
371                                 sql2date($myrow["req_del_date"]), $myrow["quantity_inv"],
372                                 $myrow["quantity_received"], $myrow["quantity_ordered"], $myrow["id"], $myrow["po_detail_item"], $myrow["std_cost_unit"]);
373                 } /* line po from purchase order details */
374         } //end of checks on returned data set
375 }
376
377 //----------------------------------------------------------------------------------------
378
379 // read a grn into an order class
380
381 function read_grn($grn_batch, &$order)
382 {
383         $sql= "SELECT * FROM ".TB_PREF."grn_batch WHERE id=".db_escape($grn_batch);
384
385         $result = db_query($sql, "The grn sent is not valid");
386
387         $row = db_fetch($result);
388         $po_number = $row["purch_order_no"];
389         $order->ex_rate = $row["rate"];
390
391         $result = read_po_header($po_number, $order);
392
393         if ($result)
394         {
395
396                 $order->trans_type = ST_SUPPRECEIVE;
397                 $order->tran_date = sql2date($row["delivery_date"]);
398                 $order->Location = $row["loc_code"];
399                 $order->reference = $row["reference"];
400                 $order->grn_id = $grn_batch;
401
402                 read_grn_items_to_order($grn_batch, $order);
403         }
404 }
405
406 //----------------------------------------------------------------------------------------------------------
407
408 // get the GRNs (batch info not details) for a given po number
409
410 function get_po_grns($po_number)
411 {
412     $sql = "SELECT * FROM ".TB_PREF."grn_batch WHERE purch_order_no=".db_escape($po_number);
413
414         return db_query($sql, "The grns for the po $po_number could not be retreived");
415 }
416
417 //----------------------------------------------------------------------------------------------------------
418
419 function exists_grn($grn_batch)
420 {
421         $sql = "SELECT id FROM ".TB_PREF."grn_batch WHERE id=".db_escape($grn_batch);
422         $result = db_query($sql, "Cannot retreive a grn");
423
424     return (db_num_rows($result) > 0);
425 }
426
427 //----------------------------------------------------------------------------------------------------------
428
429 function exists_grn_on_invoices($grn_batch)
430 {
431         $sql = "SELECT inv.id
432                 FROM ".TB_PREF."supp_invoice_items inv,"
433                         .TB_PREF."grn_items grn
434                 WHERE inv.grn_item_id=grn.id
435                 AND quantity != 0
436                 AND grn_batch_id=".db_escape($grn_batch);
437         $result = db_query($sql, "Cannot query GRNs");
438
439     return (db_num_rows($result) > 0);
440 }
441
442 //----------------------------------------------------------------------------------------------------------
443
444 function void_grn($grn_batch)
445 {
446         // if this grn is references on any invoices/credit notes, then it
447         // can't be voided
448         if (exists_grn_on_invoices($grn_batch))
449                 return false;
450
451         begin_transaction(__FUNCTION__, func_get_args());
452         hook_db_prevoid(ST_SUPPRECEIVE, $grn_batch);
453
454         void_bank_trans(ST_SUPPRECEIVE, $grn_batch, true);
455         void_gl_trans(ST_SUPPRECEIVE, $grn_batch, true);
456
457         // clear the quantities of the grn items in the POs and invoices
458         $result = get_grn_items($grn_batch);
459
460     if (db_num_rows($result) > 0)
461     {
462
463         while ($myrow = db_fetch($result))
464         {
465
466                 $sql = "UPDATE ".TB_PREF."purch_order_details
467                 SET quantity_received = quantity_received - " . $myrow["qty_recd"] . "
468                 WHERE po_detail_item = " . $myrow["po_detail_item"];
469
470                 db_query($sql, "a purchase order details record could not be voided.");
471         }
472     }
473
474         // clear the quantities in the grn items
475         $sql = "UPDATE ".TB_PREF."grn_items SET qty_recd=0, quantity_inv=0
476                 WHERE grn_batch_id=".db_escape($grn_batch);
477
478         db_query($sql, "A grn detail item could not be voided.");
479
480     // clear the stock move items
481     void_stock_move(ST_SUPPRECEIVE, $grn_batch);
482
483         commit_transaction();
484
485         return true;
486 }
487
488 //----------------------------------------------------------------------------------------------------------
489