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