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)
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
22 AND stock_id=".db_escape($stock_id)."
23 AND tran_date <= '$date'";
25 if ($location != null)
26 $sql .= " AND loc_code = ".db_escape($location);
28 $result = db_query($sql, "QOH calculation failed");
30 $myrow = db_fetch_row($result);
33 return $qoh ? $qoh : 0;
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.
41 * $delta_qty - tested change in stock qty at $date.
42 * $date - check date; when set to null checks all the stock history.
45 function check_negative_stock($stock_id, $delta_qty, $location=null, $date=null)
49 return null; // qty increese is always safe
54 $date = date2sql($date);
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'";
62 $sql .= " AND loc_code = ".db_escape($location);
64 $result = db_query($sql, "QOH calculation failed");
65 $qos = db_fetch_assoc($result);
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'";
71 $sql .= " AND loc_code=".db_escape($location);
73 $rt = running_total_sql($sql, 'qty', 'tran_date');
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);
79 if ($min_qos && ($min_qos['qty'] < $qos['qty']))
82 return -$delta_qty > $qos['qty'] ? $qos : null;
85 //--------------------------------------------------------------------------------------
87 function get_item_edit_info($stock_id)
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");
95 return db_fetch($result);
98 //--------------------------------------------------------------------------------------
100 function get_standard_cost($stock_id)
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");
106 $myrow = db_fetch_row($result);
111 //--------------------------------------------------------------------------------------
113 function is_inventory_item($stock_id)
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");
119 return db_num_rows($result) > 0;
122 //-------------------------------------------------------------------
124 function last_negative_stock_begin_date($stock_id, $to)
129 $sql = "SET @flag = 0";
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'
135 GROUP BY stock_id ORDER BY tran_date";
137 $result = db_query($sql, "The dstock moves could not be retrieved");
138 $row = db_fetch_row($result);
142 //-------------------------------------------------------------------
144 function get_already_delivered($stock_id, $location, $trans_no)
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);
157 Returns start move_id in latest negative status period for $stock_id
159 function last_negative_stock_trans_id($stock_id, $to)
161 $sql = "SELECT * from ".TB_PREF."stock_moves
162 WHERE stock_id=".db_escape($stock_id)."
163 AND qty <> 0 order by trans_id asc";
165 $result = db_query($sql, "The query on stock moves failed.");
169 $negative_trans_id = -1;
171 while ($myrow = db_fetch($result))
173 $qty += $myrow['qty'];
174 if ($qty < 0 && $flag == 0)
177 $negative_trans_id = $myrow['trans_id'];
184 return $negative_trans_id;
189 //-------------------------------------------------------------------
191 function get_deliveries_between($stock_id, $from, $to)
193 $from = date2sql($from);
195 $sql = "SELECT SUM(-qty), SUM(-qty*standard_cost) FROM ".TB_PREF."stock_moves
196 WHERE type=".ST_CUSTDELIVERY." AND stock_id=".db_escape($stock_id)." AND
197 tran_date>='$from' AND tran_date<='$to' GROUP BY stock_id";
199 $result = db_query($sql, "The deliveries could not be updated");
200 return db_fetch_row($result);
204 Returns quantity and total cost of $stock_id sales, entered after record with $move_id
206 function get_deliveries_from_trans($stock_id, $move_id)
208 // -ve qty is delivery either by ST_CUSTDELIVERY or inventory adjustment
209 //Price for GRN and SUPPCREDIT and std_cost for other trans_types
210 $sql = "SELECT SUM(-qty), SUM(-qty*IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost))
211 FROM ".TB_PREF."stock_moves
212 WHERE stock_id=".db_escape($stock_id)." AND qty < 0 AND
213 trans_id>='$move_id' GROUP BY stock_id";
214 $result = db_query($sql, "The deliveries could not be updated");
215 $row = db_fetch_row($result);
217 $sql = "SELECT IF(type=".ST_SUPPRECEIVE." OR type=".ST_SUPPCREDIT.", price, standard_cost)
218 FROM ".TB_PREF."stock_moves
219 WHERE stock_id=".db_escape($stock_id)
220 ." AND trans_id ='$move_id'";
221 $result = db_query($sql, "The deliveries could not be updated");
222 $cost = db_fetch_row($result);
224 // Adjusting QOH valuation
225 $sql = "SELECT SUM(qty)
226 FROM ".TB_PREF."stock_moves
227 WHERE stock_id=".db_escape($stock_id)." AND
228 trans_id<'$move_id' GROUP BY stock_id";
229 $result = db_query($sql, "The deliveries could not be updated");
230 $qoh = db_fetch_row($result);
232 $qty = $row[0] - $qoh[0]; //QOH prior to -ve stock is subtracted
233 $final_cost = $row[1] - $qoh[0]*$cost[0];
235 return array($qty,$final_cost);
239 Returns quantity and total cost of $stock_id purchases, entered after record with $move_id
241 function get_purchases_from_trans($stock_id, $move_id)
243 // Calculate All inward stock moves i.e. qty > 0
244 $sql = "SELECT SUM(qty), SUM(qty*standard_cost)
245 FROM ".TB_PREF."stock_moves
246 WHERE stock_id=".db_escape($stock_id)." AND qty > 0 AND
247 trans_id>'$move_id' GROUP BY stock_id";
248 $result = db_query($sql, "Could not get get_purchases_from_trans");
249 $row = db_fetch_row($result);
254 //-------------------------------------------------------------------
256 This routine fixes stock and COGS balances for all $stock_id sales made during negative inventory status.
257 This is called when delivery is received causing inventory status to be positive again.
259 function adjust_deliveries($stock_id, $material_cost, $to)
263 if (!is_inventory_item($stock_id))
266 $move_id = last_negative_stock_trans_id($stock_id, $to);
267 if ($move_id == false || $move_id == -1)
270 $row = get_deliveries_from_trans($stock_id, $move_id);
274 $old_sales_cost = $row[1];
275 $new_sales_cost = $row[0] * $material_cost;
276 $sales_diff = $new_sales_cost - $old_sales_cost;
278 $row = get_purchases_from_trans($stock_id, $move_id);
280 $old_purchase_cost = $new_purchase_cost = 0;
283 $old_purchase_cost = $row[1];
284 $new_purchase_cost = $row[0] * $material_cost;
285 $purchase_diff = $new_purchase_cost - $old_purchase_cost;
288 $diff = $sales_diff - $purchase_diff;
292 $stock_gl_code = get_stock_gl_code($stock_id);
294 $dec = user_price_dec();
295 $old_cost = -round2($old_sales_cost-$old_purchase_cost,$dec);
296 $new_cost = -round2($new_sales_cost-$new_purchase_cost,$dec);
298 $cart = new items_cart(ST_COSTUPDATE);
299 $cart->tran_date = $cart->doc_date = $cart->event_date = $to;
300 if (!is_date_in_fiscalyear($cart->tran_date))
301 $cart->tran_date = end_fiscalyear();
302 $cart->reference = $Refs->get_next(ST_COSTUPDATE, null, $cart->tran_date, $to);
304 $cart->memo_ = _("Cost was ") . $old_cost. _(" changed to ") . $new_cost . _(" for item ")."'$stock_id'";
306 $cart->add_gl_item($stock_gl_code["cogs_account"], $stock_gl_code["dimension_id"], $stock_gl_code["dimension2_id"], $diff);
307 $cart->add_gl_item($stock_gl_code["inventory_account"], 0, 0, -$diff);
309 write_journal_entries($cart);
313 function get_stock_gl_code($stock_id)
315 /*Gets the GL Codes relevant to the item account */
316 $sql = "SELECT mb_flag, inventory_account, cogs_account,
317 adjustment_account, sales_account, assembly_account, dimension_id, dimension2_id FROM
318 ".TB_PREF."stock_master WHERE stock_id = ".db_escape($stock_id);
320 $get = db_query($sql,"retreive stock gl code");
321 return db_fetch($get);
324 function get_purchase_value($stock_id)
326 $sql = "SELECT purchase_cost FROM
327 ".TB_PREF."stock_master WHERE stock_id = ".db_escape($stock_id);
329 $result = db_query($sql,"retreive stock purchase price");
330 $row = db_fetch_row($result);
334 function update_purchase_value($stock_id, $price)
336 $price = round2($price, user_price_dec());
337 $sql = "UPDATE ".TB_PREF."stock_master SET purchase_cost=".db_escape($price)
338 ." WHERE stock_id=".db_escape($stock_id);
339 db_query($sql, "The stock master purchase_cost cannot be updated");
341 //-----------------------------------------------------------------------------------------
343 function handle_negative_inventory($stock_id, $quantity, $standard_cost, $date_)
345 //If negative adjustment result in negative or zero inventory
346 //then difference should be adjusted
347 $qoh = get_qoh_on_date($stock_id);
349 if ($qoh + $quantity <= 0 && $qoh > 0) //Positive inventory turning zero/negative
353 $id = get_next_trans_no(ST_JOURNAL);
354 $ref = $Refs->get_next(ST_JOURNAL, null, $date_);
355 $diff = round($qoh*get_standard_cost($stock_id) + $quantity*$standard_cost, user_price_dec());
360 add_journal(ST_JOURNAL, $id, $diff, $date_, get_company_currency(), $ref);
361 $Refs->save(ST_JOURNAL, $id, $ref);
363 $stock_gl_code = get_stock_gl_code($stock_id);
364 $memo = _("Zero/negative inventory handling");
365 //Reverse the inventory effect if $qoh <=0
366 add_gl_trans_std_cost(ST_JOURNAL, $id, $date_,
367 $stock_gl_code["inventory_account"],
368 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
370 //GL Posting to inventory adjustment account
371 add_gl_trans_std_cost(ST_JOURNAL, $id, $date_,
372 $stock_gl_code["adjustment_account"],
373 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
376 add_audit_trail(ST_JOURNAL, $id, $date_);
377 add_comments(ST_JOURNAL, $id, $date_, $memo);
378 $Refs->save(ST_JOURNAL, $id, $ref);
379 commit_transaction();
384 //--------------------------------------------------------------------------------------
386 // $date_ - display / non-sql date
387 // $std_cost - in HOME currency
388 // $price - in transaction currency
390 function add_stock_move($type, $stock_id, $trans_no, $location,
391 $date_, $reference, $quantity, $std_cost, $price=0)
393 $date = date2sql($date_);
395 $sql = "INSERT INTO ".TB_PREF."stock_moves (stock_id, trans_no, type, loc_code,
396 tran_date, reference, qty, standard_cost, price) VALUES ("
397 .db_escape($stock_id).", ".db_escape($trans_no).", "
398 .db_escape($type).", ".db_escape($location).", '$date', "
399 .db_escape($reference).", "
400 .db_escape($quantity).", ".db_escape($std_cost)."," .db_escape($price).")";
402 db_query($sql, "The stock movement record cannot be inserted");
404 return db_insert_id();
407 function update_stock_move($type, $trans_no, $stock_id, $cost)
409 $sql = "UPDATE ".TB_PREF."stock_moves SET standard_cost=".db_escape($cost)
410 ." WHERE type=".db_escape($type)
411 ." AND trans_no=".db_escape($trans_no)
412 ." AND stock_id=".db_escape($stock_id);
413 db_query($sql, "The stock movement standard_cost cannot be updated");
416 //--------------------------------------------------------------------------------------------------
418 function get_stock_moves($type, $type_no)
420 $sql = "SELECT move.*, item.description, item.mb_flag, item.units, stock.location_name,
421 item.material_cost + item.labour_cost + item.overhead_cost AS FixedStandardCost
422 FROM ".TB_PREF."stock_moves move,"
423 .TB_PREF."locations stock,"
424 .TB_PREF."stock_master item
425 WHERE move.stock_id = item.stock_id
426 AND stock.loc_code=move.loc_code
427 AND type=".db_escape($type)
428 ." AND trans_no=".db_escape($type_no)
429 ." ORDER BY trans_id";
431 return db_query($sql, "Could not get stock moves");
434 //--------------------------------------------------------------------------------------------------
436 function void_stock_move($type, $type_no)
438 $sql = "SELECT move.*, supplier.supplier_id
439 FROM ".TB_PREF."stock_moves move
440 LEFT JOIN ".TB_PREF."supp_trans credit ON credit.trans_no=move.trans_no AND credit.type=move.type
441 LEFT JOIN ".TB_PREF."grn_batch grn ON grn.id=move.trans_no AND 25=move.type
442 LEFT JOIN ".TB_PREF."suppliers supplier ON IFNULL(grn.supplier_id, credit.supplier_id)=supplier.supplier_id
443 WHERE move.type=".db_escape($type)." AND move.trans_no=".db_escape($type_no);
445 $result = db_query($sql, "Could not void stock moves");
446 while ($row = db_fetch($result))
448 //Skip cost averaging of service items
449 if (is_inventory_item($row["stock_id"]))
451 // The cost has to be adjusted.
452 // Transaction rates are stored either as price or standard_cost depending on types
453 $types = array(ST_SUPPCREDIT, ST_SUPPRECEIVE);
454 if (in_array($type, $types))
455 $unit_cost = $row["price"];
457 $unit_cost = $row["standard_cost"];
459 update_average_material_cost($row["supplier_id"], $row["stock_id"],
460 $unit_cost, -$row["qty"], sql2date($row["tran_date"]));
463 $sql = "DELETE FROM ".TB_PREF."stock_moves
464 WHERE type=".db_escape($type)
465 ." AND trans_no=".db_escape($type_no);
466 db_query($sql, "The stock movement cannot be delated");
469 //--------------------------------------------------------------------------------------------------
471 function get_location_name($loc_code)
473 $sql = "SELECT location_name FROM ".TB_PREF."locations
474 WHERE loc_code=".db_escape($loc_code);
476 $result = db_query($sql, "could not retreive the location name for $loc_code");
478 if (db_num_rows($result) == 1)
480 $row = db_fetch_row($result);
484 display_db_error("could not retreive the location name for $loc_code", $sql, true);
487 function get_mb_flag($stock_id)
489 $sql = "SELECT mb_flag FROM ".TB_PREF."stock_master
490 WHERE stock_id = ".db_escape($stock_id);
491 $result = db_query($sql, "retreive mb_flag from item");
493 if (db_num_rows($result) == 0)
496 $myrow = db_fetch_row($result);