Changes up to 2.3.7 merged into unstable branch.
[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, $exclude=0)
13 {
14     if ($date_ == null)
15     {
16         $sql = "SELECT SUM(qty) FROM ".TB_PREF."stock_moves
17             WHERE stock_id=".db_escape($stock_id);
18         $date_ = Today();
19         $date = date2sql($date_);
20     }
21     else
22     {
23         $date = date2sql($date_);
24         $sql = "SELECT SUM(qty) FROM ".TB_PREF."stock_moves
25             WHERE stock_id=".db_escape($stock_id)."
26             AND tran_date <= '$date'"; 
27     }
28         
29     if ($location != null)
30         $sql .= " AND loc_code = ".db_escape($location);
31
32     $result = db_query($sql, "QOH calulcation failed");
33
34     $myrow = db_fetch_row($result);
35     if ($exclude > 0)
36     {
37         $sql = "SELECT SUM(qty) FROM ".TB_PREF."stock_moves
38             WHERE stock_id=".db_escape($stock_id)
39             ." AND type=".db_escape($exclude)
40             ." AND tran_date = '$date'";
41
42         $result = db_query($sql, "QOH calulcation failed");
43         $myrow2 = db_fetch_row($result);
44         if ($myrow2 !== false)
45             $myrow[0] -= $myrow2[0];
46     }
47
48     return $myrow[0];
49 }
50
51 //--------------------------------------------------------------------------------------
52
53 function get_item_edit_info($stock_id)
54 {
55         $sql = "SELECT material_cost + labour_cost + overhead_cost AS standard_cost, units, decimals
56                 FROM ".TB_PREF."stock_master,".TB_PREF."item_units
57                 WHERE stock_id=".db_escape($stock_id)
58                 ." AND ".TB_PREF."stock_master.units=".TB_PREF."item_units.abbr";
59         $result = db_query($sql, "The standard cost cannot be retrieved");
60
61         return db_fetch($result);
62 }
63
64 //--------------------------------------------------------------------------------------
65
66 function get_standard_cost($stock_id)
67 {
68         $sql = "SELECT (material_cost + labour_cost + overhead_cost) AS std_cost
69                 FROM ".TB_PREF."stock_master s WHERE stock_id=".db_escape($stock_id);
70         $result = db_query($sql, "The standard cost cannot be retrieved");
71
72         $myrow = db_fetch_row($result);
73
74         return $myrow[0];
75 }
76
77 //--------------------------------------------------------------------------------------
78
79 function is_inventory_item($stock_id)
80 {
81         $sql = "SELECT stock_id FROM ".TB_PREF."stock_master
82                 WHERE stock_id=".db_escape($stock_id)." AND mb_flag <> 'D'";
83         $result = db_query($sql, "Cannot query is inventory item or not");
84
85         return db_num_rows($result) > 0;
86 }
87
88 //-------------------------------------------------------------------
89
90 function last_negative_stock_begin_date($stock_id, $to)
91 {
92         $to = date2sql($to);
93         $sql ="SET @q = 0";
94         db_query($sql);
95         $sql = "SET @flag = 0";
96         db_query($sql);
97         $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 
98                 FROM ".TB_PREF."stock_moves
99                 WHERE stock_id=".db_escape($stock_id)." AND tran_date<='$to' 
100                 AND qty <> 0
101                 GROUP BY stock_id ORDER BY tran_date";
102
103         $result = db_query($sql, "The dstock moves could not be retrieved");
104         $row = db_fetch_row($result);
105         return $row[3];
106 }
107
108 //-------------------------------------------------------------------
109
110 function get_already_delivered($stock_id, $location, $trans_no)
111 {
112         $sql = "SELECT ".TB_PREF."stock_moves.qty
113                 FROM ".TB_PREF."stock_moves
114                 WHERE ".TB_PREF."stock_moves.stock_id = ".db_escape($stock_id)."
115                 AND ".TB_PREF."stock_moves.loc_code = ".db_escape($location)."
116                 AND type=".ST_CUSTDELIVERY." AND trans_no=".db_escape($trans_no);
117         $result = db_query($sql, "Could not get stock moves");
118         $row = db_fetch_row($result);
119         return $row[0];
120 }
121
122 function last_negative_stock_trans_id($stock_id, $to)
123 {
124         $sql = "SELECT * from ".TB_PREF."stock_moves
125                 WHERE stock_id=".db_escape($stock_id)." 
126                 AND qty <> 0 order by trans_id asc";
127         
128         $result = db_query($sql, "The query on stock moves failed.");
129         
130         $qty = 0;
131         $flag = 0;
132         $negative_trans_id = -1;
133         
134         while ($myrow = db_fetch($result))
135         {
136                 $qty += $myrow['qty'];
137                 if ($qty < 0 && $flag == 0)
138                 {
139                         $flag = 1;
140                         $negative_trans_id = $myrow['trans_id'];
141                 }
142                 if ($qty >= 0)
143                         $flag = 0;
144         }
145
146         if ($flag == 1)
147                 return $negative_trans_id;
148         else 
149                 return false;
150 }
151
152 //-------------------------------------------------------------------
153
154 function get_deliveries_between($stock_id, $from, $to)
155 {
156         $from = date2sql($from);
157         $to = date2sql($to);
158         $sql = "SELECT SUM(-qty), SUM(-qty*standard_cost) FROM ".TB_PREF."stock_moves
159                 WHERE type=".ST_CUSTDELIVERY." AND stock_id=".db_escape($stock_id)." AND
160                         tran_date>='$from' AND tran_date<='$to' GROUP BY stock_id";
161
162         $result = db_query($sql, "The deliveries could not be updated");
163         return db_fetch_row($result);
164 }
165
166 function get_deliveries_from_trans($stock_id, $from)
167 {
168         // -ve qty is delivery either by ST_CUSTDELIVERY or inventory adjustment
169         $sql = "SELECT SUM(-qty), SUM(-qty*standard_cost) FROM ".TB_PREF."stock_moves
170                 WHERE stock_id=".db_escape($stock_id)." AND qty < 0 AND
171                         trans_id>='$from' GROUP BY stock_id";
172         $result = db_query($sql, "The deliveries could not be updated");
173         $row = db_fetch_row($result);
174         
175         $sql = "SELECT standard_cost FROM ".TB_PREF."stock_moves
176                 WHERE stock_id=".db_escape($stock_id)
177                         ." AND trans_id ='$from'";
178         $result = db_query($sql, "The deliveries could not be updated");
179         $cost = db_fetch_row($result);  
180         
181         // Adjusting QOH valuation 
182         $sql = "SELECT SUM(qty) FROM ".TB_PREF."stock_moves
183                 WHERE stock_id=".db_escape($stock_id)." AND
184                         trans_id<'$from' GROUP BY stock_id";
185         $result = db_query($sql, "The deliveries could not be updated");
186         $qoh = db_fetch_row($result);
187         
188         $qty = $row[0] - $qoh[0]; //QOH prior to -ve stock is subtracted\r
189         $final_cost = $row[1] - $qoh[0]*$cost[0];
190         
191         return array($qty,$final_cost); 
192 }
193
194 function get_purchases_from_trans($stock_id, $from)
195 {
196         // Calculate All inward stock moves i.e. qty > 0
197         $sql = "SELECT SUM(qty), SUM(qty*standard_cost) FROM ".TB_PREF."stock_moves
198                 WHERE stock_id=".db_escape($stock_id)." AND qty > 0 AND 
199                         trans_id>'$from' GROUP BY stock_id";
200         $result = db_query($sql, "Could not get get_purchases_from_trans");
201         $row = db_fetch_row($result);
202         
203         return $row;
204 }
205
206 //-------------------------------------------------------------------
207
208 function adjust_deliveries($stock_id, $material_cost, $to)
209 {
210         if (!is_inventory_item($stock_id))
211                 return;
212         
213         $from = last_negative_stock_trans_id($stock_id, $to);
214         if ($from == false || $from == -1)
215                 return;
216
217         $row = get_deliveries_from_trans($stock_id, $from);
218                 
219         if ($row == false)
220                 return; 
221         $old_sales_cost = $row[1];
222         $new_sales_cost = $row[0] * $material_cost;
223         $sales_diff = $new_sales_cost - $old_sales_cost;
224         
225         $row = get_purchases_from_trans($stock_id, $from);
226         $purchase_diff = 0;
227         $old_purchase_cost = 0;
228         if ($row != false)
229         {
230                 $old_purchase_cost = $row[1];
231                 $new_purchase_cost = $row[0] * $material_cost;
232                 $purchase_diff = $new_purchase_cost - $old_purchase_cost;
233         }
234
235         $diff =  $sales_diff - $purchase_diff;
236         
237         if ($diff != 0)
238         {
239                 $update_no = get_next_trans_no(ST_COSTUPDATE);
240                 if (!is_date_in_fiscalyear($to))
241                         $to = end_fiscalyear();
242            
243                 $stock_gl_code = get_stock_gl_code($stock_id);
244
245                 $dec = user_price_dec();
246                 $old_cost = -round2($old_sales_cost-$old_purchase_cost,$dec);
247                 $new_cost = -round2($new_sales_cost-$new_purchase_cost,$dec);
248                 
249                 $memo_ = _("Cost was ") . $old_cost. _(" changed to ") . $new_cost . _(" for item ")."'$stock_id'";
250                 add_gl_trans_std_cost(ST_COSTUPDATE, $update_no, $to, $stock_gl_code["cogs_account"], 
251                         $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"], $memo_, $diff);           
252
253                 add_gl_trans_std_cost(ST_COSTUPDATE, $update_no, $to, $stock_gl_code["inventory_account"], 0, 0, $memo_, 
254                         -$diff);
255                 add_audit_trail(ST_COSTUPDATE, $update_no, $to);
256         }
257 }
258
259 function get_stock_gl_code($stock_id)
260 {
261         /*Gets the GL Codes relevant to the item account  */
262         $sql = "SELECT mb_flag, inventory_account, cogs_account,
263                 adjustment_account, sales_account, assembly_account, dimension_id, dimension2_id FROM
264                 ".TB_PREF."stock_master WHERE stock_id = ".db_escape($stock_id);
265
266         $get = db_query($sql,"retreive stock gl code");
267         return db_fetch($get);
268 }
269
270 //-----------------------------------------------------------------------------------------
271
272 function handle_negative_inventory($stock_id, $quantity, $standard_cost, $date_)
273 {
274         //If negative adjustment result in negative or zero inventory \r
275         //then difference should be adjusted
276         $qoh = get_qoh_on_date($stock_id);
277
278         if ($qoh + $quantity <= 0 && $qoh > 0) //Positive inventory turning zero/negative
279         {
280                 global $Refs;
281
282                 $id = get_next_trans_no(ST_JOURNAL);
283                 $ref = $Refs->get_next(ST_JOURNAL);
284                 $diff = get_standard_cost($stock_id) - $standard_cost;
285                 
286                 if ($diff !=0)
287                 {
288                         $stock_gl_code = get_stock_gl_code($stock_id);
289                         $memo = _("Zero/negative inventory handling");
290                         //Reverse the inventory effect if $qoh <=0
291                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
292                                 $stock_gl_code["inventory_account"],
293                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo, 
294                                 -$qoh * $diff);
295                         //GL Posting to inventory adjustment account
296                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
297                                 $stock_gl_code["adjustment_account"],
298                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
299                                 $qoh * $diff);
300                                 
301                         add_audit_trail(ST_JOURNAL, $id, $date_);
302                         add_comments(ST_JOURNAL, $id, $date_, $memo);
303                         $Refs->save(ST_JOURNAL, $id, $ref);     
304                 }
305         }
306 }
307
308 //--------------------------------------------------------------------------------------
309
310 // $date_ - display / non-sql date
311 // $std_cost - in HOME currency
312 // $show_or_hide - wil this move be visible in reports, etc
313 // $price - in $person_id's currency
314
315 function add_stock_move($type, $stock_id, $trans_no, $location,
316     $date_, $reference, $quantity, $std_cost, $person_id=0, $show_or_hide=1,
317     $price=0, $discount_percent=0, $error_msg="")
318 {
319         $date = date2sql($date_);
320
321         $sql = "INSERT INTO ".TB_PREF."stock_moves (stock_id, trans_no, type, loc_code,
322                 tran_date, person_id, reference, qty, standard_cost, visible, price,
323                 discount_percent) VALUES (".db_escape($stock_id)
324                 .", ".db_escape($trans_no).", ".db_escape($type)
325                 .",     ".db_escape($location).", '$date', "
326                 .db_escape($person_id).", ".db_escape($reference).", "
327                 .db_escape($quantity).", ".db_escape($std_cost).","
328                 .db_escape($show_or_hide).", "
329                 .db_escape($price).", ".db_escape($discount_percent).")";
330
331         if ($error_msg == "")
332                 $error_msg = "The stock movement record cannot be inserted";
333
334         db_query($sql, $error_msg);
335
336         return db_insert_id();
337 }
338
339 function update_stock_move($type, $trans_no, $stock_id, $cost)
340 {
341         $sql = "UPDATE ".TB_PREF."stock_moves SET standard_cost=".db_escape($cost)
342                         ." WHERE type=".db_escape($type)
343                         ."      AND trans_no=".db_escape($trans_no)
344                         ."      AND stock_id=".db_escape($stock_id);
345         db_query($sql, "The stock movement standard_cost cannot be updated");
346 }
347
348 function update_stock_move_pid($type, $type_no, $stock_id, $pid, $cost)
349 {
350         $sql = "UPDATE ".TB_PREF."stock_moves SET standard_cost=".db_escape($cost)
351                 ." WHERE type=".db_escape($type)
352                 ."      AND trans_no=".db_escape($type_no)
353                 ."      AND stock_id=".db_escape($stock_id)
354                 ."  AND person_id = ".db_escape($pid);
355         db_query($sql, "The stock movement standard_cost cannot be updated");
356 }
357
358 //--------------------------------------------------------------------------------------------------
359
360 function get_stock_moves($type, $type_no, $visible=false)
361 {
362         $sql = "SELECT ".TB_PREF."stock_moves.*, ".TB_PREF."stock_master.description, "
363                 .TB_PREF."stock_master.units,".TB_PREF."locations.location_name,"
364                 .TB_PREF."stock_master.material_cost + "
365                         .TB_PREF."stock_master.labour_cost + "
366                         .TB_PREF."stock_master.overhead_cost AS FixedStandardCost
367                 FROM ".TB_PREF."stock_moves,".TB_PREF."locations,".TB_PREF."stock_master
368                 WHERE ".TB_PREF."stock_moves.stock_id = ".TB_PREF."stock_master.stock_id
369                 AND ".TB_PREF."locations.loc_code=".TB_PREF."stock_moves.loc_code
370                 AND type=".db_escape($type)." AND trans_no=".db_escape($type_no)." ORDER BY trans_id";
371         if ($visible)
372                 $sql .= " AND ".TB_PREF."stock_moves.visible=1";
373
374         return db_query($sql, "Could not get stock moves");
375 }
376
377 //--------------------------------------------------------------------------------------------------
378
379 function void_stock_move($type, $type_no)
380 {
381
382     $sql = "SELECT * from ".TB_PREF."stock_moves WHERE type=".db_escape($type)." AND trans_no=".db_escape($type_no);
383     $result = db_query($sql, "Could not void stock moves");
384     while ($row = db_fetch($result))
385     {
386                 //Skip cost averaging of service items
387                 if (is_inventory_item($row["stock_id"]))
388                 {
389                         // The cost has to be adjusted.
390                         // Transaction rates are stored either as price or standard_cost depending on types
391                         $types = array(ST_SUPPCREDIT);
392                         if (in_array($type,$types))
393                                 $trans_rate = $row["price"];
394                         else
395                                 $trans_rate = $row["standard_cost"];
396
397                         update_average_material_cost(0, $row["stock_id"],
398                                 $trans_rate, -$row["qty"], sql2date($row["tran_date"]));
399                 }
400                 
401                 //Post stock move for service items also
402         add_stock_move($type, $row["stock_id"], $type_no, $row["loc_code"],
403                 sql2date($row["tran_date"]), $row["reference"], -$row["qty"]
404                         , $row["standard_cost"], $row["person_id"], $row["visible"],
405                 $row["price"], $row["discount_percent"]);
406     }
407 }
408
409 //--------------------------------------------------------------------------------------------------
410
411 function get_location_name($loc_code)
412 {
413         $sql = "SELECT location_name FROM ".TB_PREF."locations WHERE loc_code="
414                 .db_escape($loc_code);
415
416         $result = db_query($sql, "could not retreive the location name for $loc_code");
417
418         if (db_num_rows($result) == 1)
419         {
420                 $row = db_fetch_row($result);
421                 return $row[0];
422         }
423
424         display_db_error("could not retreive the location name for $loc_code", $sql, true);
425 }
426
427 //--------------------------------------------------------------------------------------------------
428
429
430 ?>