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