Added fixed assets module
[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 material_cost + labour_cost + overhead_cost AS standard_cost, units, decimals
90                 FROM ".TB_PREF."stock_master,".TB_PREF."item_units
91                 WHERE stock_id=".db_escape($stock_id)
92                 ." AND ".TB_PREF."stock_master.units=".TB_PREF."item_units.abbr";
93         $result = db_query($sql, "The standard cost cannot be retrieved");
94
95         return db_fetch($result);
96 }
97
98 //--------------------------------------------------------------------------------------
99
100 function get_standard_cost($stock_id)
101 {
102         $sql = "SELECT (material_cost + labour_cost + overhead_cost) AS std_cost
103                 FROM ".TB_PREF."stock_master s WHERE stock_id=".db_escape($stock_id);
104         $result = db_query($sql, "The standard cost cannot be retrieved");
105
106         $myrow = db_fetch_row($result);
107
108         return $myrow[0];
109 }
110
111 //--------------------------------------------------------------------------------------
112
113 function is_inventory_item($stock_id)
114 {
115         $sql = "SELECT stock_id FROM ".TB_PREF."stock_master
116                 WHERE stock_id=".db_escape($stock_id)." AND mb_flag <> 'D'";
117         $result = db_query($sql, "Cannot query is inventory item or not");
118
119         return db_num_rows($result) > 0;
120 }
121
122 //-------------------------------------------------------------------
123
124 function last_negative_stock_begin_date($stock_id, $to)
125 {
126         $to = date2sql($to);
127         $sql ="SET @q = 0";
128         db_query($sql);
129         $sql = "SET @flag = 0";
130         db_query($sql);
131         $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 
132                 FROM ".TB_PREF."stock_moves
133                 WHERE stock_id=".db_escape($stock_id)." AND tran_date<='$to' 
134                 AND qty <> 0
135                 GROUP BY stock_id ORDER BY tran_date";
136
137         $result = db_query($sql, "The dstock moves could not be retrieved");
138         $row = db_fetch_row($result);
139         return $row[3];
140 }
141
142 //-------------------------------------------------------------------
143
144 function get_already_delivered($stock_id, $location, $trans_no)
145 {
146         $sql = "SELECT qty
147                 FROM ".TB_PREF."stock_moves
148                 WHERE stock_id = ".db_escape($stock_id)."
149                 AND loc_code = ".db_escape($location)."
150                 AND type=".ST_CUSTDELIVERY." AND trans_no=".db_escape($trans_no);
151         $result = db_query($sql, "Could not get stock moves");
152         $row = db_fetch_row($result);
153         return $row[0];
154 }
155
156 function last_negative_stock_trans_id($stock_id, $to)
157 {
158         $sql = "SELECT * from ".TB_PREF."stock_moves
159                 WHERE stock_id=".db_escape($stock_id)." 
160                 AND qty <> 0 order by trans_id asc";
161         
162         $result = db_query($sql, "The query on stock moves failed.");
163         
164         $qty = 0;
165         $flag = 0;
166         $negative_trans_id = -1;
167         
168         while ($myrow = db_fetch($result))
169         {
170                 $qty += $myrow['qty'];
171                 if ($qty < 0 && $flag == 0)
172                 {
173                         $flag = 1;
174                         $negative_trans_id = $myrow['trans_id'];
175                 }
176                 if ($qty >= 0)
177                         $flag = 0;
178         }
179
180         if ($flag == 1)
181                 return $negative_trans_id;
182         else 
183                 return false;
184 }
185
186 //-------------------------------------------------------------------
187
188 function get_deliveries_between($stock_id, $from, $to)
189 {
190         $from = date2sql($from);
191         $to = date2sql($to);
192         $sql = "SELECT SUM(-qty), SUM(-qty*standard_cost) FROM ".TB_PREF."stock_moves
193                 WHERE type=".ST_CUSTDELIVERY." AND stock_id=".db_escape($stock_id)." AND
194                         tran_date>='$from' AND tran_date<='$to' GROUP BY stock_id";
195
196         $result = db_query($sql, "The deliveries could not be updated");
197         return db_fetch_row($result);
198 }
199
200 function get_deliveries_from_trans($stock_id, $from)
201 {
202         // -ve qty is delivery either by ST_CUSTDELIVERY or inventory adjustment
203     //Price for GRN and SUPPCREDIT and std_cost for other trans_types
204     $sql = "SELECT SUM(-qty), SUM(-qty*IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost))
205         FROM ".TB_PREF."stock_moves
206         WHERE stock_id=".db_escape($stock_id)." AND qty < 0 AND
207             trans_id>='$from' GROUP BY stock_id";
208         $result = db_query($sql, "The deliveries could not be updated");
209         $row = db_fetch_row($result);
210         
211     $sql = "SELECT IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost)
212         FROM ".TB_PREF."stock_moves
213         WHERE stock_id=".db_escape($stock_id)
214             ." AND trans_id ='$from'";
215     $result = db_query($sql, "The deliveries could not be updated");
216     $cost = db_fetch_row($result);
217
218         // Adjusting QOH valuation 
219         $sql = "SELECT SUM(qty)
220                 FROM ".TB_PREF."stock_moves
221                 WHERE stock_id=".db_escape($stock_id)." AND
222                         trans_id<'$from' GROUP BY stock_id";
223         $result = db_query($sql, "The deliveries could not be updated");
224         $qoh = db_fetch_row($result);
225
226         $qty = $row[0] - $qoh[0]; //QOH prior to -ve stock is subtracted
227         $final_cost = $row[1] - $qoh[0]*$cost[0];
228         
229         return array($qty,$final_cost); 
230 }
231
232 function get_purchases_from_trans($stock_id, $from)
233 {
234         // Calculate All inward stock moves i.e. qty > 0
235         $sql = "SELECT SUM(qty), SUM(qty*standard_cost)
236                 FROM ".TB_PREF."stock_moves
237                 WHERE stock_id=".db_escape($stock_id)." AND qty > 0 AND 
238                         trans_id>'$from' GROUP BY stock_id";
239         $result = db_query($sql, "Could not get get_purchases_from_trans");
240         $row = db_fetch_row($result);
241         
242         return $row;
243 }
244
245 //-------------------------------------------------------------------
246
247 function adjust_deliveries($stock_id, $material_cost, $to)
248 {
249         global $Refs;
250
251         if (!is_inventory_item($stock_id))
252                 return;
253         
254         $from = last_negative_stock_trans_id($stock_id, $to);
255         if ($from == false || $from == -1)
256                 return;
257
258         $row = get_deliveries_from_trans($stock_id, $from);
259                 
260         if ($row == false)
261                 return; 
262         $old_sales_cost = $row[1];
263         $new_sales_cost = $row[0] * $material_cost;
264         $sales_diff = $new_sales_cost - $old_sales_cost;
265         
266         $row = get_purchases_from_trans($stock_id, $from);
267         $purchase_diff = 0;
268         $old_purchase_cost = $new_purchase_cost = 0;
269         if ($row != false)
270         {
271                 $old_purchase_cost = $row[1];
272                 $new_purchase_cost = $row[0] * $material_cost;
273                 $purchase_diff = $new_purchase_cost - $old_purchase_cost;
274         }
275
276         $diff =  $sales_diff - $purchase_diff;
277
278         if ($diff != 0)
279         {
280                 $stock_gl_code = get_stock_gl_code($stock_id);
281
282                 $dec = user_price_dec();
283                 $old_cost = -round2($old_sales_cost-$old_purchase_cost,$dec);
284                 $new_cost = -round2($new_sales_cost-$new_purchase_cost,$dec);
285
286                 $cart = new items_cart(ST_COSTUPDATE);
287                 $cart->tran_date = $cart->doc_date = $cart->event_date = $to;
288                 if (!is_date_in_fiscalyear($cart->tran_date))
289                         $cart->tran_date = end_fiscalyear();
290                 $cart->reference = $Refs->get_next(ST_COSTUPDATE, null, $cart->tran_date, $to);
291
292                 $cart->memo_ = _("Cost was ") . $old_cost. _(" changed to ") . $new_cost . _(" for item ")."'$stock_id'";
293
294                 $cart->add_gl_item($stock_gl_code["cogs_account"], $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"], $diff);
295                 $cart->add_gl_item($stock_gl_code["inventory_account"], 0, 0, -$diff);
296
297                 write_journal_entries($cart);
298         }
299 }
300
301 function get_stock_gl_code($stock_id)
302 {
303         /*Gets the GL Codes relevant to the item account  */
304         $sql = "SELECT mb_flag, inventory_account, cogs_account,
305                 adjustment_account, sales_account, assembly_account, dimension_id, dimension2_id FROM
306                 ".TB_PREF."stock_master WHERE stock_id = ".db_escape($stock_id);
307
308         $get = db_query($sql,"retreive stock gl code");
309         return db_fetch($get);
310 }
311
312 //-----------------------------------------------------------------------------------------
313
314 function handle_negative_inventory($stock_id, $quantity, $standard_cost, $date_)
315 {
316         //If negative adjustment result in negative or zero inventory
317         //then difference should be adjusted
318         $qoh = get_qoh_on_date($stock_id);
319
320         if ($qoh + $quantity <= 0 && $qoh > 0) //Positive inventory turning zero/negative
321         {
322                 global $Refs;
323
324                 $id = get_next_trans_no(ST_JOURNAL);
325                 $ref = $Refs->get_next(ST_JOURNAL, null, $date_);
326                 $diff = round($qoh*get_standard_cost($stock_id) + $quantity*$standard_cost, user_price_dec());
327
328                 if ($diff != 0)
329                 {
330                         begin_transaction();
331                         add_journal(ST_JOURNAL, $id, $diff, $date_, get_company_currency(), $ref);
332                         $Refs->save(ST_JOURNAL, $id, $ref);
333
334                         $stock_gl_code = get_stock_gl_code($stock_id);
335                         $memo = _("Zero/negative inventory handling");
336                         //Reverse the inventory effect if $qoh <=0
337                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
338                                 $stock_gl_code["inventory_account"],
339                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo, 
340                                 -$diff);
341                         //GL Posting to inventory adjustment account
342                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
343                                 $stock_gl_code["adjustment_account"],
344                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
345                                 $diff);
346
347                         add_audit_trail(ST_JOURNAL, $id, $date_);
348                         add_comments(ST_JOURNAL, $id, $date_, $memo);
349                         $Refs->save(ST_JOURNAL, $id, $ref);     
350                         commit_transaction();
351                 }
352         }
353 }
354
355 //--------------------------------------------------------------------------------------
356
357 // $date_ - display / non-sql date
358 // $std_cost - in HOME currency
359 // $price - in transaction currency
360
361 function add_stock_move($type, $stock_id, $trans_no, $location,
362     $date_, $reference, $quantity, $std_cost, $price=0)
363 {
364         $date = date2sql($date_);
365
366         $sql = "INSERT INTO ".TB_PREF."stock_moves (stock_id, trans_no, type, loc_code,
367                 tran_date, reference, qty, standard_cost, price) VALUES ("
368                 .db_escape($stock_id).", ".db_escape($trans_no).", "
369                 .db_escape($type).", ".db_escape($location).", '$date', "
370                 .db_escape($reference).", "
371                 .db_escape($quantity).", ".db_escape($std_cost)."," .db_escape($price).")";
372
373         db_query($sql, "The stock movement record cannot be inserted");
374
375         return db_insert_id();
376 }
377
378 function update_stock_move($type, $trans_no, $stock_id, $cost)
379 {
380         $sql = "UPDATE ".TB_PREF."stock_moves SET standard_cost=".db_escape($cost)
381                         ." WHERE type=".db_escape($type)
382                         ."      AND trans_no=".db_escape($trans_no)
383                         ."      AND stock_id=".db_escape($stock_id);
384         db_query($sql, "The stock movement standard_cost cannot be updated");
385 }
386
387 //--------------------------------------------------------------------------------------------------
388
389 function get_stock_moves($type, $type_no)
390 {
391         $sql = "SELECT move.*, item.description, item.mb_flag, item.units, stock.location_name,
392                 item.material_cost + item.labour_cost + item.overhead_cost AS FixedStandardCost
393                 FROM ".TB_PREF."stock_moves move,"
394                         .TB_PREF."locations stock,"
395                         .TB_PREF."stock_master item
396                 WHERE move.stock_id = item.stock_id
397                 AND stock.loc_code=move.loc_code
398                 AND type=".db_escape($type)
399                 ." AND trans_no=".db_escape($type_no)
400                 ." ORDER BY trans_id";
401
402         return db_query($sql, "Could not get stock moves");
403 }
404
405 //--------------------------------------------------------------------------------------------------
406
407 function void_stock_move($type, $type_no)
408 {
409     $sql = "SELECT move.*, supplier.supplier_id
410                 FROM ".TB_PREF."stock_moves move
411                                 LEFT JOIN ".TB_PREF."supp_trans credit ON credit.trans_no=move.trans_no AND credit.type=move.type
412                                 LEFT JOIN ".TB_PREF."grn_batch grn ON grn.id=move.trans_no AND 25=move.type
413                                 LEFT JOIN ".TB_PREF."suppliers supplier ON IFNULL(grn.supplier_id, credit.supplier_id)=supplier.supplier_id
414                         WHERE move.type=".db_escape($type)." AND move.trans_no=".db_escape($type_no);
415
416     $result = db_query($sql, "Could not void stock moves");
417     while ($row = db_fetch($result))
418     {
419                 //Skip cost averaging of service items
420                 if (is_inventory_item($row["stock_id"]))
421                 {
422                         // The cost has to be adjusted.
423                         // Transaction rates are stored either as price or standard_cost depending on types
424                         $types = array(ST_SUPPCREDIT, ST_SUPPRECEIVE);
425                         if (in_array($type, $types))
426                                 $unit_cost = $row["price"];
427                         else
428                                 $unit_cost = $row["standard_cost"];
429
430                         update_average_material_cost($row["supplier_id"], $row["stock_id"],
431                                 $unit_cost, -$row["qty"], sql2date($row["tran_date"]));
432                 }
433     }
434         $sql = "DELETE FROM ".TB_PREF."stock_moves
435                         WHERE type=".db_escape($type)
436                         ."      AND trans_no=".db_escape($type_no);
437         db_query($sql, "The stock movement cannot be delated");
438 }
439
440 //--------------------------------------------------------------------------------------------------
441
442 function get_location_name($loc_code)
443 {
444         $sql = "SELECT location_name FROM ".TB_PREF."locations
445                 WHERE loc_code=".db_escape($loc_code);
446
447         $result = db_query($sql, "could not retreive the location name for $loc_code");
448
449         if (db_num_rows($result) == 1)
450         {
451                 $row = db_fetch_row($result);
452                 return $row[0];
453         }
454
455         display_db_error("could not retreive the location name for $loc_code", $sql, true);
456 }
457
458 function get_mb_flag($stock_id)
459 {
460         $sql = "SELECT mb_flag FROM ".TB_PREF."stock_master
461                 WHERE stock_id = ".db_escape($stock_id);
462         $result = db_query($sql, "retreive mb_flag from item");
463         
464         if (db_num_rows($result) == 0)
465                 return -1;
466
467         $myrow = db_fetch_row($result);
468         return $myrow[0];
469 }
470