a79c2574dab6e626556bc66d3ffb9a610fb71d3c
[fa-stable.git] / manufacturing / includes / db / work_orders_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
14 function add_material_cost($stock_id, $qty, $date_, $advanced=false)
15 {
16         $m_cost = 0;
17     $result = get_bom($stock_id);
18         while ($bom_item = db_fetch($result))
19         {
20                 $standard_cost = get_standard_cost($bom_item['component']);
21                 $m_cost += ($bom_item['quantity'] * $standard_cost);
22         }
23         $bom_cost = $m_cost;
24         
25         $sql = "SELECT material_cost, labour_cost, overhead_cost FROM ".TB_PREF."stock_master WHERE stock_id = "
26                 .db_escape($stock_id);
27         $result = db_query($sql);
28         $myrow = db_fetch($result);
29         $material_cost =  $myrow['material_cost'];
30         
31         if ($advanced)
32         {
33                 //reduce overhead_cost and labour_cost from price as those will remain as is
34                 $m_cost = $m_cost - $myrow['labour_cost'] - $myrow['overhead_cost'];
35         }
36         
37         $qoh = get_qoh_on_date($stock_id);
38         $cost_adjust = false;
39         if ($qoh < 0)
40         {
41                 if ($qoh + $qty >= 0)
42                         $cost_adjust = true;
43                 $qoh = 0;
44         }               
45         if ($qoh + $qty != 0)   
46                 $material_cost = ($qoh * $material_cost + $qty * $m_cost) /     ($qoh + $qty);
47         
48         if ($advanced && $cost_adjust) // new 2010-02-10
49                 adjust_deliveries($stock_id, $bom_cost, $date_);        
50         
51         $sql = "UPDATE ".TB_PREF."stock_master SET material_cost=".db_escape($material_cost)."
52                     WHERE stock_id=".db_escape($stock_id);
53         db_query($sql,"The cost details for the inventory item could not be updated");
54 }
55
56 function add_overhead_cost($stock_id, $qty, $date_, $costs, $adj_only=false)
57 {
58         if ($qty != 0)
59                 $costs /= $qty;
60         $sql = "SELECT overhead_cost FROM ".TB_PREF."stock_master WHERE stock_id = "
61                 .db_escape($stock_id);
62         $result = db_query($sql);
63         $myrow = db_fetch($result);
64         $overhead_cost =  $myrow['overhead_cost'];
65         $qoh = get_qoh_on_date($stock_id);
66         if ($qoh < 0)
67                 $qoh = 0;
68         if ($adj_only)
69         {
70                 if ($qty != 0)
71                         $costs = $qty * $costs;
72                 if ($qoh>0)
73                         $overhead_cost = ($qoh * $overhead_cost + $costs) / $qoh;
74                 else // Journal Entry if QOH is 0/negative 
75                 {
76                         global $Refs;
77
78                         $id = get_next_trans_no(ST_JOURNAL);
79                         $ref = $Refs->get_next(ST_JOURNAL);
80                         
81                         $stock_gl_code = get_stock_gl_code($stock_id);
82                         $memo = "WO Overhead cost settlement JV for zero/negative respository of ".$stock_id;
83                         //Reverse the inventory effect if $qoh <=0
84                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
85                                 $stock_gl_code["inventory_account"],
86                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo, 
87                                 -$costs);
88                         //GL Posting to inventory adjustment account
89                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
90                                 $stock_gl_code["adjustment_account"],
91                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
92                                 $costs);
93                                 
94                         add_audit_trail(ST_JOURNAL, $id, $date_);
95                         add_comments(ST_JOURNAL, $id, $date_, $memo);
96                         $Refs->save(ST_JOURNAL, $id, $ref);     
97                 }
98         }
99         else
100         {               
101                 if ($qoh + $qty != 0)   
102                         $overhead_cost = ($qoh * $overhead_cost + $qty * $costs) /      ($qoh + $qty);
103         }
104         $sql = "UPDATE ".TB_PREF."stock_master SET overhead_cost=".db_escape($overhead_cost)."
105                 WHERE stock_id=".db_escape($stock_id);
106         db_query($sql,"The cost details for the inventory item could not be updated");
107 }
108
109 function add_labour_cost($stock_id, $qty, $date_, $costs, $adj_only=false)
110 {
111         if ($qty != 0)
112                 $costs /= $qty;
113         $sql = "SELECT labour_cost FROM ".TB_PREF."stock_master WHERE stock_id = "
114                 .db_escape($stock_id);
115         $result = db_query($sql);
116         $myrow = db_fetch($result);
117         $labour_cost =  $myrow['labour_cost'];
118         $qoh = get_qoh_on_date($stock_id);
119         if ($qoh < 0)
120                 $qoh = 0;
121         if ($adj_only)
122         {
123                 if ($qty != 0)
124                         $costs = $qty * $costs;
125                 if ($qoh>0)
126                         $labour_cost = ($qoh * $labour_cost + $costs) / $qoh;   
127                 else // Journal Entry if QOH is 0/negative 
128                 {
129                         global $Refs;
130
131                         $id = get_next_trans_no(ST_JOURNAL);
132                         $ref = $Refs->get_next(ST_JOURNAL);
133                         
134                         $stock_gl_code = get_stock_gl_code($stock_id);
135                         $memo = "WO labour cost settlement JV for zero/negative respository of ".$stock_id;
136                         //Reverse the inventory effect if $qoh <=0
137                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
138                                 $stock_gl_code["inventory_account"],
139                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo, 
140                                 -$costs);
141                         //GL Posting to inventory adjustment account
142                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
143                                 $stock_gl_code["adjustment_account"],
144                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
145                                 $costs);
146                                 
147                         add_audit_trail(ST_JOURNAL, $id, $date_);
148                         add_comments(ST_JOURNAL, $id, $date_, $memo);
149                         $Refs->save(ST_JOURNAL, $id, $ref);     
150                 }
151         }
152         else
153         {               
154                 if ($qoh + $qty != 0)   
155                         $labour_cost = ($qoh * $labour_cost + $qty * $costs) /  ($qoh + $qty);
156         }       
157         $sql = "UPDATE ".TB_PREF."stock_master SET labour_cost=".db_escape($labour_cost)."
158                 WHERE stock_id=".db_escape($stock_id);
159         db_query($sql,"The cost details for the inventory item could not be updated");
160 }
161
162 function add_issue_cost($stock_id, $qty, $date_, $costs, $adj_only=false)
163 {
164         if ($qty != 0)
165                 $costs /= $qty;
166         $sql = "SELECT material_cost FROM ".TB_PREF."stock_master WHERE stock_id = "
167                 .db_escape($stock_id);
168         $result = db_query($sql);
169         $myrow = db_fetch($result);
170         $material_cost =  $myrow['material_cost'];
171         $qoh = get_qoh_on_date($stock_id);
172         if ($qoh < 0)
173                 $qoh = 0;
174         if ($adj_only)
175         {
176                 if ($qty != 0)
177                         $costs = $qty * $costs;
178                 if ($qoh>0)
179                         $material_cost = $costs / $qoh;
180                 else // Journal Entry if QOH is 0/negative
181                 {
182                         global $Refs;
183
184                         $id = get_next_trans_no(ST_JOURNAL);
185                         $ref = $Refs->get_next(ST_JOURNAL);
186                         
187                         $stock_gl_code = get_stock_gl_code($stock_id);
188                         $memo = "WO Issue settlement JV for zero/negative respository of ".$stock_id;
189                         //Reverse the inventory effect if $qoh <=0
190                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
191                                 $stock_gl_code["inventory_account"],
192                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo, 
193                                 -$costs);
194                         //GL Posting to inventory adjustment account
195                         add_gl_trans_std_cost(ST_JOURNAL, $id, $date_, 
196                                 $stock_gl_code["adjustment_account"],
197                                 $stock_gl_code['dimension_id'], $stock_gl_code['dimension2_id'], $memo,
198                                 $costs);
199                                 
200                         add_audit_trail(ST_JOURNAL, $id, $date_);
201                         add_comments(ST_JOURNAL, $id, $date_, $memo);
202                         $Refs->save(ST_JOURNAL, $id, $ref);     
203                 }
204         }
205         else
206         {
207                 if ($qoh + $qty != 0)   
208                         $material_cost = ($qty * $costs) /      ($qoh + $qty);
209         }       
210         $sql = "UPDATE ".TB_PREF."stock_master SET material_cost=material_cost+"
211                 .db_escape($material_cost)
212                 ." WHERE stock_id=".db_escape($stock_id);
213         db_query($sql,"The cost details for the inventory item could not be updated");
214 }
215
216 function add_work_order($wo_ref, $loc_code, $units_reqd, $stock_id,
217         $type, $date_, $required_by, $memo_, $costs, $cr_acc, $labour, $cr_lab_acc)
218 {
219         global $Refs;
220
221         if (!($type == WO_ADVANCED))
222                 return add_work_order_quick($wo_ref, $loc_code, $units_reqd, $stock_id, $type, $date_, $memo_, $costs, $cr_acc, $labour, $cr_lab_acc);
223
224         begin_transaction();
225         $args = func_get_args();
226         $args = (object)array_combine(array('wo_ref', 'loc_code', 'units_reqd', 'stock_id',
227                 'type', 'date_', 'required_by', 'memo_', 'costs', 'cr_acc', 'labour', 'cr_lab_acc'), $args);
228         $args->woid = 0;
229         hook_db_prewrite($args, ST_WORKORDER);
230
231         $date = date2sql($date_);
232         $required = date2sql($required_by);
233
234         $sql = "INSERT INTO ".TB_PREF."workorders (wo_ref, loc_code, units_reqd, stock_id,
235                 type, date_, required_by)
236         VALUES (".db_escape($wo_ref).", ".db_escape($loc_code).", "
237         .db_escape($units_reqd).", ".db_escape($stock_id).",
238                 ".db_escape($type).", '$date', ".db_escape($required).")";
239         db_query($sql, "could not add work order");
240
241         $woid = db_insert_id();
242
243         add_comments(ST_WORKORDER, $woid, $required_by, $memo_);
244
245         $Refs->save(ST_WORKORDER, $woid, $wo_ref);
246         add_audit_trail(ST_WORKORDER, $woid, $date_);
247
248         $args->woid = $woid;
249         hook_db_postwrite($args, ST_WORKORDER);
250         commit_transaction();
251
252         return $woid;
253 }
254
255 //--------------------------------------------------------------------------------------
256
257 function update_work_order($woid, $loc_code, $units_reqd, $stock_id,
258                                         $date_, $required_by, $memo_)
259 {
260         begin_transaction();
261         $args = func_get_args();
262         $args = (object)array_combine(array('woid', 'loc_code', 'units_reqd', 'stock_id',
263                 'date_', 'required_by', 'memo_'), $args);
264         hook_db_prewrite($args, ST_WORKORDER);
265
266         $date = date2sql($date_);
267         $required = date2sql($required_by);
268
269         $sql = "UPDATE ".TB_PREF."workorders SET loc_code=".db_escape($loc_code).",
270                 units_reqd=".db_escape($units_reqd).", stock_id=".db_escape($stock_id).",
271                 required_by=".db_escape($required).",
272                 date_='$date'
273                 WHERE id = ".db_escape($woid);
274
275         db_query($sql, "could not update work order");
276
277         update_comments(ST_WORKORDER, $woid, null, $memo_);
278         add_audit_trail(ST_WORKORDER, $woid, $date_, _("Updated."));
279
280         hook_db_postwrite($args, ST_WORKORDER);
281         commit_transaction();
282 }
283
284 function delete_work_order($woid)
285 {
286         begin_transaction();
287         hook_db_prevoid(ST_WORKORDER, $woid);
288
289         // delete the work order requirements
290         delete_wo_requirements($woid);
291
292         // delete the actual work order
293         $sql = "DELETE FROM ".TB_PREF."workorders WHERE id=".db_escape($woid);
294         db_query($sql,"The work order could not be deleted");
295
296         delete_comments(ST_WORKORDER, $woid);
297         add_audit_trail(ST_WORKORDER, $woid, $_POST['date_'], _("Canceled."));
298
299         commit_transaction();
300 }
301
302 //--------------------------------------------------------------------------------------
303
304 function get_work_order($woid, $allow_null=false)
305 {
306     $sql = "SELECT wo.*,st.description As StockItemName,l.location_name,
307                 l.delivery_address,l.email, l.contact
308                 FROM ".TB_PREF."workorders wo, ".TB_PREF."stock_master st, ".TB_PREF."locations l
309                 WHERE st.stock_id=wo.stock_id
310                 AND     l.loc_code=wo.loc_code
311                 AND wo.id=".db_escape($woid)."
312                 GROUP BY wo.id";
313
314         $result = db_query($sql, "The work order issues could not be retrieved");
315
316         if (!$allow_null && db_num_rows($result) == 0)
317                 display_db_error("Could not find work order $woid", $sql);
318
319         return db_fetch($result);
320 }
321
322 //--------------------------------------------------------------------------------------
323
324 function work_order_has_productions($woid)
325 {
326         $sql = "SELECT COUNT(*) FROM ".TB_PREF."wo_manufacture WHERE workorder_id=".db_escape($woid);
327         $result = db_query($sql, "query work order for productions");
328
329         $myrow = db_fetch_row($result);
330         return ($myrow[0] > 0);
331 }
332
333
334 //--------------------------------------------------------------------------------------
335
336 function work_order_has_issues($woid)
337 {
338         $sql = "SELECT COUNT(*) FROM ".TB_PREF."wo_issues WHERE workorder_id=".db_escape($woid);
339         $result = db_query($sql, "query work order for issues");
340
341         $myrow = db_fetch_row($result);
342         return ($myrow[0] > 0);
343 }
344
345 //--------------------------------------------------------------------------------------
346
347 function work_order_has_payments($woid)
348 {
349         $result = get_gl_wo_cost_trans($woid);
350
351     return (db_num_rows($result) != 0);
352 }
353
354 //--------------------------------------------------------------------------------------
355
356 function release_work_order($woid, $releaseDate, $memo_)
357 {
358         begin_transaction();
359
360         $myrow = get_work_order($woid);
361         $stock_id = $myrow["stock_id"];
362
363         $date = date2sql($releaseDate);
364
365         $sql = "UPDATE ".TB_PREF."workorders SET released_date='$date',
366                 released=1 WHERE id = ".db_escape($woid);
367         db_query($sql, "could not release work order");
368
369         // create Work Order Requirements based on the bom
370         create_wo_requirements($woid, $stock_id);
371
372         add_comments(ST_WORKORDER, $woid, $releaseDate, $memo_);
373         add_audit_trail(ST_WORKORDER, $woid, $releaseDate,_("Released."));
374
375         commit_transaction();
376 }
377
378 //--------------------------------------------------------------------------------------
379
380 function close_work_order($woid)
381 {
382         $sql = "UPDATE ".TB_PREF."workorders SET closed=1 WHERE id = ".db_escape($woid);
383         db_query($sql, "could not close work order");
384 }
385
386 //--------------------------------------------------------------------------------------
387
388 function work_order_is_closed($woid)
389 {
390         $sql = "SELECT closed FROM ".TB_PREF."workorders WHERE id = ".db_escape($woid);
391         $result = db_query($sql, "could not query work order");
392         $row = db_fetch_row($result);
393         return ($row[0] > 0);
394 }
395
396 //--------------------------------------------------------------------------------------
397
398 function work_order_update_finished_quantity($woid, $quantity, $force_close=0)
399 {
400         $sql = "UPDATE ".TB_PREF."workorders SET units_issued = units_issued + ".db_escape($quantity).",
401                 closed = ((units_issued >= units_reqd) OR ".db_escape($force_close).")
402                 WHERE id = ".db_escape($woid);
403
404         db_query($sql, "The work order issued quantity couldn't be updated");
405 }
406
407 //--------------------------------------------------------------------------------------
408
409 function void_work_order($woid)
410 {
411         begin_transaction();
412         hook_db_prevoid(ST_WORKORDER, $woid);
413
414         $work_order = get_work_order($woid);
415         if (!($work_order["type"] == WO_ADVANCED))
416         {
417                 $sql = "UPDATE ".TB_PREF."workorders SET closed=1,units_reqd=0,units_issued=0 WHERE id = "
418                         .db_escape($woid);
419                 db_query($sql, "The work order couldn't be voided");
420
421                 // void all related stock moves
422                 void_stock_move(ST_WORKORDER, $woid);
423
424                 // void any related bank/gl trans
425                 void_bank_trans(ST_WORKORDER, $woid, true);
426
427                 // clear the requirements units received
428                 void_wo_requirements($woid);
429         }
430         else
431         {
432                 // void everything inside the work order : issues, productions, payments
433                 $date = sql2date($work_order['date_']);
434                 
435                 $result = get_work_order_productions($woid); // check the produced quantity
436                 $qty = 0;
437                 while ($row = db_fetch($result))
438                 {
439                         void_work_order_produce($row['id']);
440                         
441                         //Post voided entry if not prevoided explicitly
442                         $void_entry = get_voided_entry(ST_MANURECEIVE, $row['id']);
443                         if ($void_entry)
444                                 continue;
445                         $memo_ = _("Voiding Work Order Trans # ").$woid;
446                         add_audit_trail(ST_MANURECEIVE, $row['id'], today(), _("Voided.")."\n".$memo_);
447                         add_voided_entry(ST_MANURECEIVE, $row['id'], today(), $memo_);
448                 }
449
450                 $result = get_work_order_issues($woid);
451                 $cost = 0;
452                 $issue_no = 0;
453                 while ($row = db_fetch($result))
454                 {
455                         void_work_order_issue($row['issue_no']);
456                         
457                         //Post voided entry if not prevoided explicitly
458                         $void_entry = get_voided_entry(ST_MANUISSUE, $row['issue_no']);
459                         if ($void_entry)
460                                 continue;
461                         $memo_ = _("Voiding Work Order Trans # ").$woid;
462                         add_audit_trail(ST_MANUISSUE, $row['issue_no'], today(), _("Voided.")."\n".$memo_);
463                         add_voided_entry(ST_MANUISSUE, $row['issue_no'], today(), $memo_);                              
464                 }
465
466                 //Adust avg labour cost
467                 $cost = get_gl_wo_cost($woid, WO_LABOUR); 
468                 if ($cost != 0)
469                         add_labour_cost($work_order['stock_id'], 1, $date, -$cost, true);
470                         
471                 //Adust avg overhead cost
472                 $cost = get_gl_wo_cost($woid, WO_OVERHEAD); 
473                 if ($cost != 0)
474                         add_overhead_cost($work_order['stock_id'], 1, $date, -$cost, true);
475                 
476                 $sql = "UPDATE ".TB_PREF."workorders SET closed=1,units_reqd=0,units_issued=0 WHERE id = "
477                         .db_escape($woid);
478                 db_query($sql, "The work order couldn't be voided");
479
480                 // void all related stock moves
481                 void_stock_move(ST_WORKORDER, $woid);
482
483                 // void any related bank/gl trans
484                 void_bank_trans(ST_WORKORDER, $woid, true);
485
486                 // clear the requirements units received
487                 void_wo_requirements($woid);
488         }
489         commit_transaction();
490 }
491
492 function get_sql_for_work_orders($outstanding_only, $all_items)
493 {
494         $sql = "SELECT
495                 workorder.id,
496                 workorder.wo_ref,
497                 workorder.type,
498                 location.location_name,
499                 item.description,
500                 workorder.units_reqd,
501                 workorder.units_issued,
502                 workorder.date_,
503                 workorder.required_by,
504                 workorder.released_date,
505                 workorder.closed,
506                 workorder.released,
507                 workorder.stock_id,
508                 unit.decimals
509                 FROM ".TB_PREF."workorders as workorder,"
510                         .TB_PREF."stock_master as item,"
511                         .TB_PREF."item_units as unit,"
512                         .TB_PREF."locations as location
513                 WHERE workorder.stock_id=item.stock_id 
514                         AND workorder.loc_code=location.loc_code
515                         AND item.units=unit.abbr";
516
517         if (check_value('OpenOnly') || $outstanding_only != 0)
518         {
519                 $sql .= " AND workorder.closed=0";
520         }
521
522         if (isset($_POST['StockLocation']) && $_POST['StockLocation'] != $all_items)
523         {
524                 $sql .= " AND workorder.loc_code=".db_escape($_POST['StockLocation']);
525         }
526
527         if (isset($_POST['OrderNumber']) && $_POST['OrderNumber'] != "")
528         {
529                 $sql .= " AND workorder.wo_ref LIKE ".db_escape('%'.$_POST['OrderNumber'].'%');
530         }
531
532         if (isset($_POST['SelectedStockItem']) && $_POST['SelectedStockItem'] != $all_items)
533         {
534                 $sql .= " AND workorder.stock_id=".db_escape($_POST['SelectedStockItem']);
535         }
536
537         if (check_value('OverdueOnly'))
538         {
539                 $Today = date2sql(Today());
540
541                 $sql .= " AND workorder.required_by < '$Today' ";
542         }
543         return $sql;
544 }
545
546 function get_sql_for_where_used()
547 {
548         $sql = "SELECT 
549                         bom.parent,
550                         workcentre.name As WorkCentreName,
551                         location.location_name,
552                         bom.quantity,
553                         parent.description
554                         FROM ".TB_PREF."bom as bom, "
555                                 .TB_PREF."stock_master as parent, "
556                                 .TB_PREF."workcentres as workcentre, "
557                                 .TB_PREF."locations as location
558                         WHERE bom.parent = parent.stock_id 
559                                 AND bom.workcentre_added = workcentre.id
560                                 AND bom.loc_code = location.loc_code
561                                 AND bom.component=".db_escape($_POST['stock_id']);
562         return $sql;                    
563 }
564 //--------------------------------------------------------------------------------------
565 function get_gl_wo_cost($woid, $cost_type)
566 {
567         $cost = 0;
568         $result = get_gl_wo_cost_trans($woid, $cost_type);
569         while ($row = db_fetch($result))
570                 $cost += -$row['amount'];
571         return $cost;   
572 }
573
574 ?>