4ffda2e7abe2a1ff0497b71d7b2c691ab7e63766
[fa-stable.git] / includes / db / inventory_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 function get_qoh_on_date($stock_id, $location=null, $date_=null)
13 {
14     if ($date_ == null)
15         $date_ = Today();
16
17      $date = date2sql($date_);
18      $sql = "SELECT SUM(qty)
19         FROM ".TB_PREF."stock_moves st
20                 LEFT JOIN ".TB_PREF."voided v ON st.type=v.type AND st.trans_no=v.id
21           WHERE ISNULL(v.id)
22           AND stock_id=".db_escape($stock_id)."
23           AND tran_date <= '$date'"; 
24
25     if ($location != null)
26         $sql .= " AND loc_code = ".db_escape($location);
27
28     $result = db_query($sql, "QOH calculation failed");
29
30     $myrow = db_fetch_row($result);
31
32     $qoh =  $myrow[0];
33                 return $qoh ? $qoh : 0;
34 }
35
36 /**
37 *       Check whether change in stock on date would not cause negative qoh in stock history.
38 *       Returns null on success or max. available quantity with respective date otherwise.
39 *   Running balance is checked on daily basis only, as we do not control time of transaction.
40 *
41 *       $delta_qty - tested change in stock qty at $date.
42 *       $date - check date; when set to null checks all the stock history.
43 **/
44
45 function check_negative_stock($stock_id, $delta_qty, $location=null, $date=null)
46 {
47
48         if ($delta_qty >= 0)
49                  return null;   // qty increese is always safe
50
51         if (!isset($date))
52                 $date = Today();
53
54         $date = date2sql($date);
55
56         // check stock status on date
57     $sql = "SELECT SUM(qty) qty, '$date' tran_date FROM ".TB_PREF."stock_moves
58             WHERE stock_id=".db_escape($stock_id)."
59             AND tran_date <= '$date'"; 
60
61     if ($location)
62         $sql .= " AND loc_code = ".db_escape($location);
63
64     $result = db_query($sql, "QOH calculation failed");
65     $qos = db_fetch_assoc($result);
66
67         // check also all stock changes after the date to avoid negative stock in future
68         $sql = TB_PREF."stock_moves WHERE stock_id=".db_escape($stock_id) . " AND tran_date > '$date'";
69
70         if ($location)
71                 $sql .= " AND loc_code=".db_escape($location);
72
73         $rt = running_total_sql($sql, 'qty', 'tran_date');
74
75         $sql = "SELECT  {$qos['qty']}+total qty, tran_date FROM ($rt) stock_status ORDER by total, tran_date";
76         $history = db_query($sql, 'cannot check stock history');
77         $min_qos = db_fetch($history);
78
79         if ($min_qos && ($min_qos['qty'] < $qos['qty']))
80                 $qos = $min_qos;
81
82         return  -$delta_qty > $qos['qty'] ? $qos : null;
83 }
84
85 //--------------------------------------------------------------------------------------
86
87 function get_item_edit_info($stock_id)
88 {
89         $sql = "SELECT item.material_cost, item.units, unit.decimals
90                 FROM ".TB_PREF."stock_master item,"
91                         .TB_PREF."item_units unit
92                 WHERE stock_id=".db_escape($stock_id)
93                 ." AND item.units=unit.abbr";
94         $result = db_query($sql, "The standard cost cannot be retrieved");
95
96         $row = db_fetch($result);
97         if ($row['decimals'] == -1)
98                 $row['decimals'] = user_qty_dec();
99         return $row;
100 }
101
102 //--------------------------------------------------------------------------------------
103
104 function get_unit_cost($stock_id)
105 {
106         $sql = "SELECT material_cost
107                 FROM ".TB_PREF."stock_master
108                 WHERE stock_id=".db_escape($stock_id);
109         $result = db_query($sql, "The standard cost cannot be retrieved");
110
111         $myrow = db_fetch_row($result);
112
113         return $myrow[0];
114 }
115
116 //--------------------------------------------------------------------------------------
117  
118 function get_purchase_cost($stock_id)
119 {
120         $sql = "SELECT purchase_cost
121                 FROM ".TB_PREF."stock_master
122                 WHERE stock_id=".db_escape($stock_id);
123         $result = db_query($sql, "The purchase cost cannot be retrieved");
124
125         $myrow = db_fetch_row($result);
126
127         return $myrow[0];
128 }
129
130 //--------------------------------------------------------------------------------------
131
132 function is_inventory_item($stock_id)
133 {
134         $sql = "SELECT stock_id FROM "
135                 .TB_PREF."stock_master
136                 WHERE stock_id=".db_escape($stock_id)." AND mb_flag <> 'D'";
137         $result = db_query($sql, "Cannot query is inventory item or not");
138
139         return db_num_rows($result) > 0;
140 }
141
142 //-------------------------------------------------------------------
143
144 function last_negative_stock_begin_date($stock_id, $to)
145 {
146         $to = date2sql($to);
147         $sql ="SET @q = 0";
148         db_query($sql);
149         $sql = "SET @flag = 0";
150         db_query($sql);
151         $sql = "SELECT SUM(qty), @q:= @q + qty, IF(@q < 0 AND @flag=0, @flag:=1,@flag:=0), IF(@q < 0 AND @flag=1, tran_date,'') AS begin_date 
152                 FROM ".TB_PREF."stock_moves
153                 WHERE stock_id=".db_escape($stock_id)." AND tran_date<='$to' 
154                 AND qty <> 0
155                 GROUP BY stock_id ORDER BY tran_date";
156
157         $result = db_query($sql, "The dstock moves could not be retrieved");
158         $row = db_fetch_row($result);
159         return $row[3];
160 }
161
162 //-------------------------------------------------------------------
163
164 function get_already_delivered($stock_id, $location, $trans_no)
165 {
166         $sql = "SELECT qty
167                 FROM ".TB_PREF."stock_moves
168                 WHERE stock_id = ".db_escape($stock_id)."
169                 AND loc_code = ".db_escape($location)."
170                 AND type=".ST_CUSTDELIVERY." AND trans_no=".db_escape($trans_no);
171         $result = db_query($sql, "Could not get stock moves");
172         $row = db_fetch_row($result);
173         return $row[0];
174 }
175 /*
176         Returns start move_id in latest negative status period for $stock_id
177         FIXME: $to ? 
178 */
179 function last_negative_stock_trans_id($stock_id, $to)
180 {
181         $sql = "SELECT * from ".TB_PREF."stock_moves
182                 WHERE stock_id=".db_escape($stock_id)." 
183                 AND qty <> 0 order by trans_id asc";
184         
185         $result = db_query($sql, "The query on stock moves failed.");
186         
187         $qty = 0;
188         $flag = 0;
189         $negative_trans_id = -1;
190         
191         while ($myrow = db_fetch($result))
192         {
193                 $qty += $myrow['qty'];
194                 if ($qty < 0 && $flag == 0)
195                 {
196                         $flag = 1;
197                         $negative_trans_id = $myrow['trans_id'];
198                 }
199                 if ($qty >= 0)
200                         $flag = 0;
201         }
202
203         if ($flag == 1)
204                 return $negative_trans_id;
205         else 
206                 return false;
207 }
208
209 //-------------------------------------------------------------------
210
211 function get_deliveries_between($stock_id, $from, $to)
212 {
213         $from = date2sql($from);
214         $to = date2sql($to);
215         $sql = "SELECT SUM(-qty), SUM(-qty*standard_cost) FROM ".TB_PREF."stock_moves
216                 WHERE type=".ST_CUSTDELIVERY." AND stock_id=".db_escape($stock_id)." AND
217                         tran_date>='$from' AND tran_date<='$to' GROUP BY stock_id";
218
219         $result = db_query($sql, "The deliveries could not be updated");
220         return db_fetch_row($result);
221 }
222
223 /*
224         Returns quantity and total cost of $stock_id sales, entered after record with $move_id
225 */
226 function get_deliveries_from_trans($stock_id, $move_id)
227 {
228         // -ve qty is delivery either by ST_CUSTDELIVERY or inventory adjustment
229     //Price for GRN and SUPPCREDIT and std_cost for other trans_types
230     $sql = "SELECT SUM(-qty), SUM(-qty*IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost))
231         FROM ".TB_PREF."stock_moves
232         WHERE stock_id=".db_escape($stock_id)." AND qty < 0 AND
233             trans_id>='$move_id' GROUP BY stock_id";
234         $result = db_query($sql, "The deliveries could not be updated");
235         $row = db_fetch_row($result);
236         
237     $sql = "SELECT IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost)
238         FROM ".TB_PREF."stock_moves
239         WHERE stock_id=".db_escape($stock_id)
240             ." AND trans_id ='$move_id'";
241     $result = db_query($sql, "The deliveries could not be updated");
242     $cost = db_fetch_row($result);
243
244         // Adjusting QOH valuation 
245         $sql = "SELECT SUM(qty)
246                 FROM ".TB_PREF."stock_moves
247                 WHERE stock_id=".db_escape($stock_id)." AND
248                         trans_id<'$move_id' GROUP BY stock_id";
249         $result = db_query($sql, "The deliveries could not be updated");
250         $qoh = db_fetch_row($result);
251
252         $qty = $row[0] - $qoh[0]; //QOH prior to -ve stock is subtracted
253         $final_cost = $row[1] - $qoh[0]*$cost[0];
254         
255         return array($qty,$final_cost); 
256 }
257
258 /*
259         Returns quantity and total cost of $stock_id purchases, entered after record with $move_id
260 */
261 function get_purchases_from_trans($stock_id, $move_id)
262 {
263         // Calculate All inward stock moves i.e. qty > 0
264         $sql = "SELECT SUM(qty), SUM(qty*standard_cost)
265                 FROM ".TB_PREF."stock_moves
266                 WHERE stock_id=".db_escape($stock_id)." AND qty > 0 AND 
267                         trans_id>'$move_id' GROUP BY stock_id";
268         $result = db_query($sql, "Could not get get_purchases_from_trans");
269         $row = db_fetch_row($result);
270         
271         return $row;
272 }
273
274 //-------------------------------------------------------------------
275 /*
276         This routine fixes stock and COGS balances for all $stock_id sales made during negative inventory status.
277         This is called when delivery is received causing inventory status to be positive again.
278 */
279 function adjust_deliveries($stock_id, $material_cost, $to)
280 {
281         global $Refs;
282
283         if (!is_inventory_item($stock_id))
284                 return;
285         
286         $move_id = last_negative_stock_trans_id($stock_id, $to);
287         if ($move_id == false || $move_id == -1)
288                 return;
289
290         $row = get_deliveries_from_trans($stock_id, $move_id);
291
292         if ($row == false)
293                 return; 
294         $old_sales_cost = $row[1];
295         $new_sales_cost = $row[0] * $material_cost;
296         $sales_diff = $new_sales_cost - $old_sales_cost;
297         
298         $row = get_purchases_from_trans($stock_id, $move_id);
299         $purchase_diff = 0;
300         $old_purchase_cost = $new_purchase_cost = 0;
301         if ($row != false)
302         {
303                 $old_purchase_cost = $row[1];
304                 $new_purchase_cost = $row[0] * $material_cost;
305                 $purchase_diff = $new_purchase_cost - $old_purchase_cost;
306         }
307
308         $diff =  $sales_diff - $purchase_diff;
309
310         if ($diff != 0)
311         {
312                 $stock_gl_code = get_stock_gl_code($stock_id);
313
314                 $dec = user_price_dec();
315                 $old_cost = -round2($old_sales_cost-$old_purchase_cost,$dec);
316                 $new_cost = -round2($new_sales_cost-$new_purchase_cost,$dec);
317
318                 $cart = new items_cart(ST_COSTUPDATE);
319                 $cart->tran_date = $cart->doc_date = $cart->event_date = $to;
320                 if (!is_date_in_fiscalyear($cart->tran_date))
321                         $cart->tran_date = end_fiscalyear();
322                 $cart->reference = $Refs->get_next(ST_COSTUPDATE, null, $cart->tran_date, $to);
323
324                 $cart->memo_ = _("Cost was ") . $old_cost. _(" changed to ") . $new_cost . _(" for item ")."'$stock_id'";
325
326                 $cart->add_gl_item($stock_gl_code["cogs_account"], $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"], $diff);
327                 $cart->add_gl_item($stock_gl_code["inventory_account"], 0, 0, -$diff);
328
329                 write_journal_entries($cart);
330         }
331 }
332
333 function get_stock_gl_code($stock_id)
334 {
335         /*Gets the GL Codes relevant to the item account  */
336         $sql = "SELECT mb_flag, inventory_account, cogs_account,
337                 adjustment_account, sales_account, wip_account, dimension_id, dimension2_id FROM
338                 ".TB_PREF."stock_master WHERE stock_id = ".db_escape($stock_id);
339
340         $get = db_query($sql,"retreive stock gl code");
341         return db_fetch($get);
342 }
343
344 function get_purchase_value($stock_id)
345 {
346         $sql = "SELECT purchase_cost FROM
347                 ".TB_PREF."stock_master WHERE stock_id = ".db_escape($stock_id);
348
349         $result = db_query($sql,"retreive stock purchase price");
350         $row = db_fetch_row($result);
351         return $row[0];
352 }
353
354 function update_purchase_value($stock_id, $price)
355 {
356         $price = round2($price, user_price_dec());
357         $sql = "UPDATE ".TB_PREF."stock_master SET purchase_cost=".db_escape($price)
358                         ." WHERE stock_id=".db_escape($stock_id);
359         db_query($sql, "The stock master purchase_cost cannot be updated");
360 }       
361 //-----------------------------------------------------------------------------------------
362
363 function handle_negative_inventory($stock_id, $quantity, $standard_cost, $date_)
364 {
365         //If negative adjustment result in negative or zero inventory
366         //then difference should be adjusted
367         $qoh = get_qoh_on_date($stock_id);
368
369         if ($qoh + $quantity <= 0 && $qoh > 0) //Positive inventory turning zero/negative
370         {
371                 global $Refs;
372
373                 $id = get_next_trans_no(ST_JOURNAL);
374                 $ref = $Refs->get_next(ST_JOURNAL, null, $date_);
375                 $diff = round($qoh*get_unit_cost($stock_id) + $quantity*$standard_cost, user_price_dec());
376
377                 if ($diff != 0)
378                 {
379                         begin_transaction();
380                         add_journal(ST_JOURNAL, $id, $diff, $date_, get_company_currency(), $ref);
381                         $Refs->save(ST_JOURNAL, $id, $ref);
382
383                         $stock_gl_code = get_stock_gl_code($stock_id);
384                         $memo = _("Zero/negative inventory handling");
385                         //Reverse the inventory effect if $qoh <=0
386                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
387                                 $stock_gl_code["inventory_account"],
388                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo, 
389                                 -$diff);
390                         //GL Posting to inventory adjustment account
391                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
392                                 $stock_gl_code["adjustment_account"],
393                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
394                                 $diff);
395
396                         add_audit_trail(ST_JOURNAL, $id, $date_);
397                         add_comments(ST_JOURNAL, $id, $date_, $memo);
398                         $Refs->save(ST_JOURNAL, $id, $ref);     
399                         commit_transaction();
400                 }
401         }
402 }
403
404 //--------------------------------------------------------------------------------------
405
406 // $date_ - display / non-sql date
407 // $std_cost - in HOME currency
408 // $price - in transaction currency
409
410 function add_stock_move($type, $stock_id, $trans_no, $location,
411     $date_, $reference, $quantity, $std_cost, $price=0)
412 {
413         $date = date2sql($date_);
414
415         $sql = "INSERT INTO ".TB_PREF."stock_moves (stock_id, trans_no, type, loc_code,
416                 tran_date, reference, qty, standard_cost, price) VALUES ("
417                 .db_escape($stock_id).", ".db_escape($trans_no).", "
418                 .db_escape($type).", ".db_escape($location).", '$date', "
419                 .db_escape($reference).", "
420                 .db_escape($quantity).", ".db_escape($std_cost)."," .db_escape($price).")";
421
422         db_query($sql, "The stock movement record cannot be inserted");
423
424         return db_insert_id();
425 }
426
427 function update_stock_move($type, $trans_no, $stock_id, $cost)
428 {
429         $sql = "UPDATE ".TB_PREF."stock_moves SET standard_cost=".db_escape($cost)
430                         ." WHERE type=".db_escape($type)
431                         ."      AND trans_no=".db_escape($trans_no)
432                         ."      AND stock_id=".db_escape($stock_id);
433         db_query($sql, "The stock movement standard_cost cannot be updated");
434 }
435
436 //--------------------------------------------------------------------------------------------------
437
438 function get_stock_moves($type, $type_no)
439 {
440         $sql = "SELECT move.*, item.description, item.mb_flag, item.units, stock.location_name
441                 FROM ".TB_PREF."stock_moves move,"
442                         .TB_PREF."locations stock,"
443                         .TB_PREF."stock_master item
444                 WHERE move.stock_id = item.stock_id
445                 AND stock.loc_code=move.loc_code
446                 AND type=".db_escape($type)
447                 ." AND trans_no=".db_escape($type_no)
448                 ." ORDER BY trans_id";
449
450         return db_query($sql, "Could not get stock moves");
451 }
452
453 //--------------------------------------------------------------------------------------------------
454
455 function void_stock_move($type, $type_no)
456 {
457     $sql = "SELECT move.*, supplier.supplier_id
458                 FROM ".TB_PREF."stock_moves move
459                                 LEFT JOIN ".TB_PREF."supp_trans credit ON credit.trans_no=move.trans_no AND credit.type=move.type
460                                 LEFT JOIN ".TB_PREF."grn_batch grn ON grn.id=move.trans_no AND 25=move.type
461                                 LEFT JOIN ".TB_PREF."suppliers supplier ON IFNULL(grn.supplier_id, credit.supplier_id)=supplier.supplier_id
462                         WHERE move.type=".db_escape($type)." AND move.trans_no=".db_escape($type_no);
463
464     $result = db_query($sql, "Could not void stock moves");
465     while ($row = db_fetch($result))
466     {
467                 //Skip cost averaging of service items
468                 if (is_inventory_item($row["stock_id"]))
469                 {
470                         // The cost has to be adjusted.
471                         // Transaction rates are stored either as price or standard_cost depending on types
472                         $types = array(ST_SUPPCREDIT, ST_SUPPRECEIVE);
473                         if (in_array($type, $types))
474                                 $unit_cost = $row["price"];
475                         else
476                                 $unit_cost = $row["standard_cost"];
477
478                         update_average_material_cost($row["supplier_id"], $row["stock_id"],
479                                 $unit_cost, -$row["qty"], sql2date($row["tran_date"]));
480                 }
481     }
482         $sql = "DELETE FROM ".TB_PREF."stock_moves
483                         WHERE type=".db_escape($type)
484                         ."      AND trans_no=".db_escape($type_no);
485         db_query($sql, "The stock movement cannot be delated");
486 }
487
488 //--------------------------------------------------------------------------------------------------
489
490 function get_location_name($loc_code)
491 {
492         $sql = "SELECT location_name FROM ".TB_PREF."locations
493                 WHERE loc_code=".db_escape($loc_code);
494
495         $result = db_query($sql, "could not retreive the location name for $loc_code");
496
497         if (db_num_rows($result) == 1)
498         {
499                 $row = db_fetch_row($result);
500                 return $row[0];
501         }
502
503         display_db_error("could not retreive the location name for $loc_code", $sql, true);
504 }
505
506 function get_mb_flag($stock_id)
507 {
508         $sql = "SELECT mb_flag FROM ".TB_PREF."stock_master
509                 WHERE stock_id = ".db_escape($stock_id);
510         $result = db_query($sql, "retreive mb_flag from item");
511         
512         if (db_num_rows($result) == 0)
513                 return -1;
514
515         $myrow = db_fetch_row($result);
516         return $myrow[0];
517 }
518