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