Added audit trail.
[fa-stable.git] / sales / includes / db / sales_order_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 function get_demand_qty($stockid, $location)
14 {
15         $sql = "SELECT SUM(".TB_PREF."sales_order_details.quantity - ".TB_PREF."sales_order_details.qty_sent) AS QtyDemand
16                                 FROM ".TB_PREF."sales_order_details,
17                                         ".TB_PREF."sales_orders
18                                 WHERE ".TB_PREF."sales_order_details.order_no=".TB_PREF."sales_orders.order_no AND
19                                         ".TB_PREF."sales_orders.from_stk_loc ='$location' AND
20                                         ".TB_PREF."sales_order_details.stk_code = '$stockid'";
21
22         $TransResult = db_query($sql,"No transactions were returned");
23         $DemandRow = db_fetch($TransResult);
24         return $DemandRow['QtyDemand'];
25 }
26
27 function get_demand_asm_qty($stockid, $location)
28 {
29         $sql = "SELECT SUM((".TB_PREF."sales_order_details.quantity-".TB_PREF."sales_order_details.qty_sent)*".TB_PREF."bom.quantity)
30                                 AS Dem
31                                 FROM ".TB_PREF."sales_order_details,
32                                                 ".TB_PREF."sales_orders,
33                                                 ".TB_PREF."bom,
34                                                 ".TB_PREF."stock_master
35                                 WHERE ".TB_PREF."sales_order_details.stk_code=".TB_PREF."bom.parent AND
36                                 ".TB_PREF."sales_orders.order_no = ".TB_PREF."sales_order_details.order_no AND
37                                 ".TB_PREF."sales_orders.from_stk_loc='$location' AND
38                                 ".TB_PREF."sales_order_details.quantity-".TB_PREF."sales_order_details.qty_sent > 0 AND
39                                 ".TB_PREF."bom.component='$stockid' AND
40                                 ".TB_PREF."stock_master.stock_id=".TB_PREF."bom.parent AND
41                                 ".TB_PREF."stock_master.mb_flag='A'";
42
43         $TransResult = db_query($sql,"No transactions were returned");
44         if (db_num_rows($TransResult)==1)
45         {
46                 $DemandRow = db_fetch_row($TransResult);
47                 $DemandQty = $DemandRow[0];
48         }
49         else
50                 $DemandQty = 0.0;
51
52         return $DemandQty;
53 }
54
55 function add_sales_order(&$order)
56 {
57         global $loc_notification, $path_to_root;
58
59         begin_transaction();
60
61         $del_date = date2sql($order->due_date);
62         $order_type = 0; // this is default on new order
63         $sql = "INSERT INTO ".TB_PREF."sales_orders (type, debtor_no, branch_code, customer_ref, comments, ord_date,
64                 order_type, ship_via, deliver_to, delivery_address, contact_phone,
65                 contact_email, freight_cost, from_stk_loc, delivery_date)
66                 VALUES (" .db_escape($order_type) . "," . db_escape($order->customer_id) .
67                  ", " . db_escape($order->Branch) . ", ".
68                         db_escape($order->cust_ref) .",". 
69                         db_escape($order->Comments) .",'" . 
70                         date2sql($order->document_date) . "', " .
71                         db_escape($order->sales_type) . ", " .
72                         db_escape($order->ship_via)."," . 
73                         db_escape($order->deliver_to) . "," .
74                         db_escape($order->delivery_address) . ", " .
75                         db_escape($order->phone) . ", " . 
76                         db_escape($order->email) . ", " .
77                         db_escape($order->freight_cost) .", " . 
78                         db_escape($order->Location) .", " .
79                         db_escape($del_date) . ")";
80
81         db_query($sql, "order Cannot be Added");
82
83         $order_no = db_insert_id();
84         $order->trans_no = array($order_no=>0);
85
86         if ($loc_notification == 1)
87         {
88                 include_once($path_to_root . "/inventory/includes/inventory_db.inc");
89                 $st_ids = array();
90                 $st_names = array();
91                 $st_num = array();
92                 $st_reorder = array();
93         }
94         foreach ($order->line_items as $line)
95         {
96                 if ($loc_notification == 1 && is_inventory_item($line->stock_id))
97                 {
98                         $sql = "SELECT ".TB_PREF."loc_stock.*, ".TB_PREF."locations.location_name, ".TB_PREF."locations.email
99                                 FROM ".TB_PREF."loc_stock, ".TB_PREF."locations
100                                 WHERE ".TB_PREF."loc_stock.loc_code=".TB_PREF."locations.loc_code
101                                 AND ".TB_PREF."loc_stock.stock_id = '" . $line->stock_id . "'
102                                 AND ".TB_PREF."loc_stock.loc_code = '" . $order->Location . "'";
103                         $res = db_query($sql,"a location could not be retreived");
104                         $loc = db_fetch($res);
105                         if ($loc['email'] != "")
106                         {
107                                 $qoh = get_qoh_on_date($line->stock_id, $order->Location);
108                                 $qoh -= get_demand_qty($line->stock_id, $order->Location);
109                                 $qoh -= get_demand_asm_qty($line->stock_id, $order->Location);
110                                 $qoh -= $line->quantity;
111                                 if ($qoh < $loc['reorder_level'])
112                                 {
113                                         $st_ids[] = $line->stock_id;
114                                         $st_names[] = $line->item_description;
115                                         $st_num[] = $qoh - $loc['reorder_level'];
116                                         $st_reorder[] = $loc['reorder_level'];
117                                 }
118                         }
119                 }
120
121                 $sql = "INSERT INTO ".TB_PREF."sales_order_details (order_no, stk_code, description, unit_price, quantity, discount_percent) VALUES (";
122                 $sql .= $order_no .
123                                 ",".db_escape($line->stock_id).", "
124                                 .db_escape($line->item_description).", $line->price,
125                                 $line->quantity,
126                                 $line->discount_percent)";
127                 db_query($sql, "order Details Cannot be Added");
128
129         } /* inserted line items into sales order details */
130
131         add_audit_trail(30, $order_no, $order->document_date);
132         commit_transaction();
133
134         if ($loc_notification == 1 && count($st_ids) > 0)
135         {
136                 require_once($path_to_root . "/reporting/includes/class.mail.inc");
137                 $company = get_company_prefs();
138                 $mail = new email($company['coy_name'], $company['email']);
139                 $from = $company['coy_name'] . " <" . $company['email'] . ">";
140                 $to = $loc['location_name'] . " <" . $loc['email'] . ">";
141                 $subject = _("Stocks below Re-Order Level at " . $loc['location_name']);
142                 $msg = "\n";
143                 for ($i = 0; $i < count($st_ids); $i++)
144                         $msg .= $st_ids[$i] . " " . $st_names[$i] . ", " . _("Re-Order Level") . ": " . $st_reorder[$i] . ", " . _("Below") . ": " . $st_num[$i] . "\n";
145                 $msg .= "\n" . _("Please reorder") . "\n\n";
146                 $msg .= $company['coy_name'];
147                 $mail->to($to);
148                 $mail->subject($subject);
149                 $mail->text($msg);
150                 $ret = $mail->send();
151         }
152         return $order_no;
153 }
154
155 //----------------------------------------------------------------------------------------
156
157 function delete_sales_order($order_no)
158 {
159         begin_transaction();
160
161         $sql = "DELETE FROM ".TB_PREF."sales_orders WHERE order_no=" . $order_no;
162         db_query($sql, "order Header Delete");
163
164         $sql = "DELETE FROM ".TB_PREF."sales_order_details WHERE order_no =" . $order_no;
165         db_query($sql, "order Detail Delete");
166
167         add_audit_trail(30, $order_no, Today(), _("Deleted."));
168         commit_transaction();
169 }
170
171 //----------------------------------------------------------------------------------------
172 // Mark changes in sales_order_details
173 //
174 function update_sales_order_version($order)
175 {
176   foreach ($order as $so_num => $so_ver) {
177   $sql= 'UPDATE '.TB_PREF.'sales_orders SET version=version+1 WHERE order_no='. $so_num.
178         ' AND version='.$so_ver;
179   db_query($sql, 'Concurrent editing conflict while sales order update');
180   }
181 }
182
183 //----------------------------------------------------------------------------------------
184
185 function update_sales_order($order)
186 {
187         global $loc_notification, $path_to_root;
188
189         $del_date = date2sql($order->due_date);
190         $ord_date = date2sql($order->document_date);
191         $order_no =  key($order->trans_no);
192         $version= current($order->trans_no);
193
194         begin_transaction();
195
196         $sql = "UPDATE ".TB_PREF."sales_orders SET type =".$order->so_type." ,
197                 debtor_no = " . db_escape($order->customer_id) . ",
198                 branch_code = " . db_escape($order->Branch) . ",
199                 customer_ref = ". db_escape($order->cust_ref) .",
200                 comments = ". db_escape($order->Comments) .",
201                 ord_date = " . db_escape($ord_date) . ",
202                 order_type = " .db_escape($order->sales_type) . ",
203                 ship_via = " . db_escape($order->ship_via) .",
204                 deliver_to = " . db_escape($order->deliver_to) . ",
205                 delivery_address = " . db_escape($order->delivery_address) . ",
206                 contact_phone = " .db_escape($order->phone) . ",
207                 contact_email = " .db_escape($order->email) . ",
208                 freight_cost = " .db_escape($order->freight_cost) .",
209                 from_stk_loc = " .db_escape($order->Location) .",
210                 delivery_date = " .db_escape($del_date). ",
211                 version = ".($version+1)."
212          WHERE order_no=" . $order_no ."
213          AND version=".$version;
214         db_query($sql, "order Cannot be Updated, this can be concurrent edition conflict");
215
216         $sql = "DELETE FROM ".TB_PREF."sales_order_details WHERE order_no =" . $order_no;
217
218         db_query($sql, "Old order Cannot be Deleted");
219
220         if ($loc_notification == 1)
221         {
222                 include_once($path_to_root . "/inventory/includes/inventory_db.inc");
223                 $st_ids = array();
224                 $st_names = array();
225                 $st_num = array();
226                 $st_reorder = array();
227         }
228         foreach ($order->line_items as $line)
229         {
230                 if ($loc_notification == 1 && is_inventory_item($line->stock_id))
231                 {
232                         $sql = "SELECT ".TB_PREF."loc_stock.*, "
233                                   .TB_PREF."locations.location_name, "
234                                   .TB_PREF."locations.email
235                                 FROM ".TB_PREF."loc_stock, "
236                                   .TB_PREF."locations
237                                 WHERE ".TB_PREF."loc_stock.loc_code=".TB_PREF."locations.loc_code
238                                  AND ".TB_PREF."loc_stock.stock_id = '" . $line->stock_id . "'
239                                  AND ".TB_PREF."loc_stock.loc_code = '" . $order->Location . "'";
240                         $res = db_query($sql,"a location could not be retreived");
241                         $loc = db_fetch($res);
242                         if ($loc['email'] != "")
243                         {
244                                 $qoh = get_qoh_on_date($line->stock_id, $order->Location);
245                                 $qoh -= get_demand_qty($line->stock_id, $order->Location);
246                                 $qoh -= get_demand_asm_qty($line->stock_id, $order->Location);
247                                 $qoh -= $line->quantity;
248                                 if ($qoh < $loc['reorder_level'])
249                                 {
250                                         $st_ids[] = $line->stock_id;
251                                         $st_names[] = $line->item_description;
252                                         $st_num[] = $qoh - $loc['reorder_level'];
253                                         $st_reorder[] = $loc['reorder_level'];
254                                 }
255                         }
256                 }
257                 $sql = "INSERT INTO ".TB_PREF."sales_order_details
258                  (order_no, stk_code,  description, unit_price, quantity,
259                   discount_percent, qty_sent)
260                  VALUES (";
261                 $sql .= $order_no . ","
262                   .db_escape($line->stock_id) . ","
263                   .db_escape($line->item_description) . ", "
264                   .db_escape($line->price) . ", "
265                   .db_escape($line->quantity) . ", "
266                   .db_escape($line->discount_percent) . ", "
267                   .db_escape($line->qty_done) ." )";
268
269                 db_query($sql, "Old order Cannot be Inserted");
270
271         } /* inserted line items into sales order details */
272
273         add_audit_trail(30, $order_no, $order->document_date, _("Updated."));
274         commit_transaction();
275         if ($loc_notification == 1 && count($st_ids) > 0)
276         {
277                 require_once($path_to_root . "/reporting/includes/class.mail.inc");
278                 $company = get_company_prefs();
279                 $mail = new email($company['coy_name'], $company['email']);
280                 $from = $company['coy_name'] . " <" . $company['email'] . ">";
281                 $to = $loc['location_name'] . " <" . $loc['email'] . ">";
282                 $subject = _("Stocks below Re-Order Level at " . $loc['location_name']);
283                 $msg = "\n";
284                 for ($i = 0; $i < count($st_ids); $i++)
285                         $msg .= $st_ids[$i] . " " . $st_names[$i] . ", "
286                           . _("Re-Order Level") . ": " . $st_reorder[$i] . ", "
287                           . _("Below") . ": " . $st_num[$i] . "\n";
288                 $msg .= "\n" . _("Please reorder") . "\n\n";
289                 $msg .= $company['coy_name'];
290                 $mail->to($to);
291                 $mail->subject($subject);
292                 $mail->text($msg);
293                 $ret = $mail->send();
294         }
295 }
296
297 //----------------------------------------------------------------------------------------
298
299 function get_sales_order_header($order_no)
300 {
301         $sql = "SELECT ".TB_PREF."sales_orders.*, "
302           .TB_PREF."debtors_master.name, "
303           .TB_PREF."debtors_master.curr_code, "
304           .TB_PREF."locations.location_name, "
305           .TB_PREF."debtors_master.payment_terms, "
306           .TB_PREF."debtors_master.discount, "
307           .TB_PREF."sales_types.sales_type, "
308           .TB_PREF."sales_types.id AS sales_type_id, "
309           .TB_PREF."sales_types.tax_included, "
310           .TB_PREF."shippers.shipper_name, "
311           .TB_PREF."tax_groups.name AS tax_group_name , "
312           .TB_PREF."tax_groups.id AS tax_group_id
313         FROM ".TB_PREF."sales_orders, "
314           .TB_PREF."debtors_master, "
315           .TB_PREF."sales_types, "
316           .TB_PREF."tax_groups, "
317           .TB_PREF."cust_branch, "
318           .TB_PREF."locations, "
319           .TB_PREF."shippers
320         WHERE ".TB_PREF."sales_orders.order_type=".TB_PREF."sales_types.id
321                 AND ".TB_PREF."cust_branch.branch_code = ".TB_PREF."sales_orders.branch_code
322                 AND ".TB_PREF."cust_branch.tax_group_id = ".TB_PREF."tax_groups.id
323                 AND ".TB_PREF."sales_orders.debtor_no = ".TB_PREF."debtors_master.debtor_no
324                 AND ".TB_PREF."locations.loc_code = ".TB_PREF."sales_orders.from_stk_loc
325                 AND ".TB_PREF."shippers.shipper_id = ".TB_PREF."sales_orders.ship_via
326                 AND ".TB_PREF."sales_orders.order_no = " . $order_no ;
327         $result = db_query($sql, "order Retreival");
328
329         $num = db_num_rows($result);
330         if ($num > 1)
331         {
332                 display_db_error("FATAL : sales order query returned a duplicate - " . db_num_rows($result), $sql, true);
333         }
334         else if ($num == 1)
335         {
336                 return db_fetch($result);
337         }
338         else
339                 display_db_error("FATAL : sales order return nothing - " . db_num_rows($result), $sql, true);
340
341 }
342
343 //----------------------------------------------------------------------------------------
344
345 function get_sales_order_details($order_no) {
346         $sql = "SELECT id, stk_code, unit_price, "
347                 .TB_PREF."sales_order_details.description,"
348                 .TB_PREF."sales_order_details.quantity,
349                   discount_percent,
350                   qty_sent as qty_done, "
351                 .TB_PREF."stock_master.units,
352                 ".TB_PREF."stock_master.material_cost + "
353                         .TB_PREF."stock_master.labour_cost + "
354                         .TB_PREF."stock_master.overhead_cost AS standard_cost
355         FROM ".TB_PREF."sales_order_details, ".TB_PREF."stock_master
356         WHERE ".TB_PREF."sales_order_details.stk_code = ".TB_PREF."stock_master.stock_id
357         AND order_no =" . $order_no . " ORDER BY id";
358
359         return db_query($sql, "Retreive order Line Items");
360 }
361 //----------------------------------------------------------------------------------------
362
363 function read_sales_order($order_no, &$order)
364 {
365         $myrow = get_sales_order_header($order_no);
366
367         $order->trans_type = 30;
368         $order->so_type =  $myrow["type"];
369         $order->trans_no = array($order_no=> $myrow["version"]);
370
371         $order->set_customer($myrow["debtor_no"], $myrow["name"],
372           $myrow["curr_code"], $myrow["discount"]);
373
374         $order->set_branch($myrow["branch_code"], $myrow["tax_group_id"],
375           $myrow["tax_group_name"], $myrow["contact_phone"], $myrow["contact_email"]);
376
377         $order->set_sales_type($myrow["sales_type_id"], $myrow["sales_type"], 
378             $myrow["tax_included"], 0); // no default price calculations on edit
379
380         $order->set_location($myrow["from_stk_loc"], $myrow["location_name"]);
381
382         $order->set_delivery($myrow["ship_via"], $myrow["deliver_to"],
383           $myrow["delivery_address"], $myrow["freight_cost"]);
384
385         $order->cust_ref = $myrow["customer_ref"];
386         $order->sales_type =$myrow["order_type"];
387         $order->Comments = $myrow["comments"];
388         $order->due_date = sql2date($myrow["delivery_date"]);
389         $order->document_date = sql2date($myrow["ord_date"]);
390
391         $result = get_sales_order_details($order_no);
392         if (db_num_rows($result) > 0)
393         {
394                 $line_no=0;
395                 while ($myrow = db_fetch($result))
396                 {
397                         $order->add_to_cart($line_no,$myrow["stk_code"],$myrow["quantity"],
398                                 $myrow["unit_price"], $myrow["discount_percent"],
399                                 $myrow["qty_done"], $myrow["standard_cost"], $myrow["description"], $myrow["id"] );
400                 $line_no++;
401                 }
402         }
403
404         return true;
405 }
406
407 //----------------------------------------------------------------------------------------
408
409 function sales_order_has_deliveries($order_no)
410 {
411         $sql = "SELECT SUM(qty_sent) FROM ".TB_PREF.
412         "sales_order_details WHERE order_no=$order_no";
413
414         $result = db_query($sql, "could not query for sales order usage");
415
416         $row = db_fetch_row($result);
417
418         return ($row[0] > 0);
419 }
420
421 //----------------------------------------------------------------------------------------
422
423 function close_sales_order($order_no)
424 {
425         // set the quantity of each item to the already sent quantity. this will mark item as closed.
426         $sql = "UPDATE ".TB_PREF."sales_order_details
427                 SET quantity = qty_sent,
428                         type = 0,
429                         WHERE order_no = $order_no";
430
431         db_query($sql, "The sales order detail record could not be updated");
432 }
433
434 //---------------------------------------------------------------------------------------------------------------
435
436 function get_invoice_duedate($debtorno, $invdate)
437 {
438         if (!is_date($invdate))
439         {
440                 return new_doc_date();
441         }
442         $sql = "SELECT ".TB_PREF."debtors_master.debtor_no, ".TB_PREF."debtors_master.payment_terms, ".TB_PREF."payment_terms.* FROM ".TB_PREF."debtors_master,
443                 ".TB_PREF."payment_terms WHERE ".TB_PREF."debtors_master.payment_terms = ".TB_PREF."payment_terms.terms_indicator AND
444                 ".TB_PREF."debtors_master.debtor_no = '$debtorno'";
445
446         $result = db_query($sql,"The customer details could not be retrieved");
447         $myrow = db_fetch($result);
448
449         if (db_num_rows($result) == 0)
450                 return $invdate;
451         if ($myrow['day_in_following_month'] > 0)
452                 $duedate = add_days(end_month($invdate), $myrow['day_in_following_month']);
453         else
454                 $duedate = add_days($invdate, $myrow['days_before_due']);
455         return $duedate;
456 }
457
458 function get_customer_to_order($customer_id) {
459
460         // Now check to ensure this account is not on hold */
461         $sql = "SELECT ".TB_PREF."debtors_master.name, "
462                   .TB_PREF."debtors_master.address, "
463                   .TB_PREF."credit_status.dissallow_invoices, "
464                   .TB_PREF."debtors_master.sales_type AS salestype, "
465                   .TB_PREF."debtors_master.dimension_id, "
466                   .TB_PREF."debtors_master.dimension2_id, "
467                   .TB_PREF."sales_types.sales_type, "
468                   .TB_PREF."sales_types.tax_included, "
469                   .TB_PREF."sales_types.factor, "
470                   .TB_PREF."debtors_master.curr_code, "
471                   .TB_PREF."debtors_master.discount,"
472                   .TB_PREF."debtors_master.pymt_discount
473                 FROM ".TB_PREF."debtors_master, "
474                   .TB_PREF."credit_status, "
475                   .TB_PREF."sales_types
476                 WHERE ".TB_PREF."debtors_master.sales_type="
477                   .TB_PREF."sales_types.id
478                 AND ".TB_PREF."debtors_master.credit_status=".TB_PREF."credit_status.id
479                 AND ".TB_PREF."debtors_master.debtor_no = '" . $customer_id . "'";
480
481         $result =db_query($sql,"Customer Record Retreive");
482         return  db_fetch($result);
483 }
484
485 function get_branch_to_order($customer_id, $branch_id) {
486
487         // the branch was also selected from the customer selection so default the delivery details from the customer branches table cust_branch. The order process will ask for branch details later anyway
488                 $sql = "SELECT ".TB_PREF."cust_branch.br_name, "
489                         .TB_PREF."cust_branch.br_address, "
490                         .TB_PREF."cust_branch.br_post_address, "
491                         .TB_PREF."cust_branch.phone, "
492                         .TB_PREF."cust_branch.email,
493                           default_location, location_name, default_ship_via, "
494                         .TB_PREF."tax_groups.name AS tax_group_name, "
495                         .TB_PREF."tax_groups.id AS tax_group_id
496                         FROM ".TB_PREF."cust_branch, "
497                           .TB_PREF."tax_groups, "
498                           .TB_PREF."locations
499                         WHERE ".TB_PREF."cust_branch.tax_group_id = ".TB_PREF."tax_groups.id
500                                 AND ".TB_PREF."locations.loc_code=default_location
501                                 AND ".TB_PREF."cust_branch.branch_code='" . $branch_id . "'
502                                 AND ".TB_PREF."cust_branch.debtor_no = '" . $customer_id . "'";
503
504             return db_query($sql,"Customer Branch Record Retreive");
505 }
506 ?>