Purchasse Order Inquire: finalized oders are hidden by default.
[fa-stable.git] / purchasing / includes / db / po_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 get_supplier_details_to_order(&$order, $supplier_id)
15 {
16         $sql = "SELECT curr_code, supp_name, tax_group_id, supp.tax_included,
17                         supp.credit_limit - Sum(IFNULL(IF(trans.type=".ST_SUPPCREDIT.", -1, 1) 
18                                 * (ov_amount + ov_gst + ov_discount),0)) as cur_credit,
19                                 terms.terms, terms.days_before_due, terms.day_in_following_month
20                 FROM ".TB_PREF."suppliers supp
21                          LEFT JOIN ".TB_PREF."supp_trans trans ON supp.supplier_id = trans.supplier_id
22                          LEFT JOIN ".TB_PREF."payment_terms terms ON supp.payment_terms=terms.terms_indicator
23                 WHERE supp.supplier_id = ".db_escape($supplier_id)."
24                 GROUP BY
25                           supp.supp_name";
26
27         $result = db_query($sql, "The supplier details could not be retreived");
28         $myrow = db_fetch($result);
29
30         $order->credit = $myrow["cur_credit"];
31         $order->terms = array( 
32                 'description' => $myrow['terms'],
33                 'days_before_due' => $myrow['days_before_due'], 
34                 'day_in_following_month' => $myrow['day_in_following_month'] );
35
36         $_POST['supplier_id'] = $supplier_id;
37         $_POST['supplier_name'] = $myrow["supp_name"];
38         $_POST['curr_code'] = $myrow["curr_code"];
39
40         $order->set_supplier($supplier_id, $myrow["supp_name"], $myrow["curr_code"], 
41                 $myrow["tax_group_id"], $myrow["tax_included"]);
42 }
43
44 //----------------------------------------------------------------------------------------
45
46 function delete_po($po)
47 {
48         global $Refs;
49
50         begin_transaction();
51         hook_db_prevoid($po, ST_PURCHORDER);
52         $sql = "DELETE FROM ".TB_PREF."purch_orders WHERE order_no=".db_escape($po);
53         db_query($sql, "The order header could not be deleted");
54
55         $sql = "DELETE FROM ".TB_PREF."purch_order_details WHERE order_no =".db_escape($po);
56         db_query($sql, "The order detail lines could not be deleted");
57
58         $Refs->restore_last(ST_PURCHORDER, $po);
59         commit_transaction();
60 }
61
62 //----------------------------------------------------------------------------------------
63
64 function add_po(&$po_obj)
65 {
66         global $Refs;
67
68         begin_transaction();
69         hook_db_prewrite($po_obj, ST_PURCHORDER);
70
71      /*Insert to purchase order header record */
72      $sql = "INSERT INTO ".TB_PREF."purch_orders (supplier_id, Comments, ord_date, reference, 
73         requisition_no, into_stock_location, delivery_address, total, tax_included, prep_amount) VALUES(";
74      $sql .= db_escape($po_obj->supplier_id) . "," .
75          db_escape($po_obj->Comments) . ",'" .
76          date2sql($po_obj->orig_order_date) . "', " .
77                  db_escape($po_obj->reference) . ", " .
78          db_escape($po_obj->supp_ref) . ", " .
79          db_escape($po_obj->Location) . ", " .
80          db_escape($po_obj->delivery_address) . ", " .
81          db_escape($po_obj->get_trans_total()). ", " .
82          db_escape($po_obj->tax_included). ", " .
83          db_escape($po_obj->prep_amount). ")";
84
85         db_query($sql, "The purchase order header record could not be inserted");
86
87      /*Get the auto increment value of the order number created from the sql above */
88      $po_obj->order_no = db_insert_id();
89
90      /*Insert the purchase order detail records */
91      foreach ($po_obj->line_items as $line_no => $po_line)
92      {
93                 $sql = "INSERT INTO ".TB_PREF."purch_order_details (order_no, item_code, description, delivery_date,    unit_price,     quantity_ordered) VALUES (";
94                 $sql .= $po_obj->order_no . ", " . db_escape($po_line->stock_id). "," .
95                 db_escape($po_line->item_description). ",'" .
96                 date2sql($po_line->req_del_date) . "'," .
97                 db_escape($po_line->price) . ", " .
98                 db_escape($po_line->quantity). ")";
99                 db_query($sql, "One of the purchase order detail records could not be inserted");
100                 $po_obj->line_items[$line_no]->po_detail_rec = db_insert_id();
101      }
102
103         $Refs->save(ST_PURCHORDER, $po_obj->order_no, $po_obj->reference);
104
105         //add_comments(ST_PURCHORDER, $po_obj->order_no, $po_obj->orig_order_date, $po_obj->Comments);
106
107         add_audit_trail(ST_PURCHORDER, $po_obj->order_no, $po_obj->orig_order_date);
108         hook_db_postwrite($po_obj, ST_PURCHORDER);
109         commit_transaction();
110
111         return $po_obj->order_no;
112 }
113
114 //----------------------------------------------------------------------------------------
115
116 function update_po(&$po_obj)
117 {
118         begin_transaction();
119         hook_db_prewrite($po_obj, ST_PURCHORDER);
120
121     /*Update the purchase order header with any changes */
122     $sql = "UPDATE ".TB_PREF."purch_orders SET Comments=" . db_escape($po_obj->Comments) . ",
123                 requisition_no= ". db_escape( $po_obj->supp_ref). ",
124                 into_stock_location=" . db_escape($po_obj->Location). ",
125                 ord_date='" . date2sql($po_obj->orig_order_date) . "',
126                 delivery_address=" . db_escape($po_obj->delivery_address).",
127                 total=". db_escape($po_obj->get_trans_total()).",
128                 prep_amount=". db_escape($po_obj->prep_amount).",
129                 tax_included=". db_escape($po_obj->tax_included);
130     $sql .= " WHERE order_no = " . $po_obj->order_no;
131         db_query($sql, "The purchase order could not be updated");
132
133         $sql = "DELETE FROM ".TB_PREF."purch_order_details WHERE order_no="
134                 .db_escape($po_obj->order_no);
135         db_query($sql, "could not delete old purch order details");
136
137     /*Now Update the purchase order detail records */
138     foreach ($po_obj->line_items as $po_line)
139     {
140         $sql = "INSERT INTO ".TB_PREF."purch_order_details (po_detail_item, order_no, item_code, 
141                 description, delivery_date, unit_price, quantity_ordered, quantity_received) VALUES ("
142                         .db_escape($po_line->po_detail_rec ? $po_line->po_detail_rec : 0). ","
143                         .$po_obj->order_no . ","
144                         .db_escape($po_line->stock_id). ","
145                         .db_escape($po_line->item_description). ",'"
146                         .date2sql($po_line->req_del_date) . "',"
147                         .db_escape($po_line->price) . ", "
148                         .db_escape($po_line->quantity) . ", "
149                         .db_escape($po_line->qty_received) . ")";
150                 db_query($sql, "One of the purchase order detail records could not be updated");
151     }
152
153 //_vd($po_obj->prepayments);
154         reallocate_payments($po_obj->order_no, ST_PURCHORDER, $po_obj->orig_order_date, $po_obj->get_trans_total(), $po_obj->prepayments);
155 //_vd($p = get_payments_for($po_obj->order_no, ST_PURCHORDER));
156 //_vd(get_supp_trans($p[0]['trans_no_from'], $p[0]['trans_type_from']));
157 //exit;
158
159         // add_comments(ST_PURCHORDER, $po_obj->order_no, $po_obj->orig_order_date, $po_obj->Comments);
160
161         add_audit_trail($po_obj->trans_type, $po_obj->order_no, Today(), _("Updated."));
162         hook_db_postwrite($po_obj, ST_PURCHORDER);
163         commit_transaction();
164
165         return $po_obj->order_no;
166 }
167
168 //----------------------------------------------------------------------------------------
169
170 function read_po_header($order_no, &$order)
171 {
172         $sql = "SELECT ".TB_PREF."purch_orders.*, "
173                 .TB_PREF."suppliers.*, "
174                 .TB_PREF."locations.location_name 
175                 FROM ".TB_PREF."purch_orders, ".TB_PREF."suppliers, ".TB_PREF."locations
176                 WHERE ".TB_PREF."purch_orders.supplier_id = ".TB_PREF."suppliers.supplier_id
177                 AND ".TB_PREF."locations.loc_code = into_stock_location
178                 AND ".TB_PREF."purch_orders.order_no = ".db_escape($order_no);
179
180         $result = db_query($sql, "The order cannot be retrieved");
181
182         if (db_num_rows($result) == 1)
183         {
184
185         $myrow = db_fetch($result);
186
187         $order->trans_type = ST_PURCHORDER;
188         $order->order_no = $order_no;
189
190         $order->set_supplier($myrow["supplier_id"], $myrow["supp_name"], $myrow["curr_code"],
191                 $myrow['tax_group_id'], $myrow["tax_included"]);
192
193                 $order->credit = get_current_supp_credit($order->supplier_id);
194
195         $order->orig_order_date = sql2date($myrow["ord_date"]);
196         $order->Comments = nl2br($myrow["comments"]);
197         $order->Location = $myrow["into_stock_location"];
198         $order->supp_ref = $myrow["requisition_no"];
199         $order->reference = $myrow["reference"];
200         $order->delivery_address = $myrow["delivery_address"];
201         $order->alloc = $myrow["alloc"];
202         $order->prep_amount = $myrow["prep_amount"];
203         $order->prepayments = get_payments_for($order_no, ST_PURCHORDER);
204
205         return true;
206         }
207
208         display_db_error("FATAL : duplicate purchase order found", "", true);
209         return false;
210 }
211
212 //----------------------------------------------------------------------------------------
213
214 function read_po_items($order_no, &$order, $open_items_only=false)
215 {
216         /*now populate the line po array with the purchase order details records */
217
218         $sql = "SELECT ".TB_PREF."purch_order_details.*, units
219                 FROM ".TB_PREF."purch_order_details
220                 LEFT JOIN ".TB_PREF."stock_master
221                 ON ".TB_PREF."purch_order_details.item_code=".TB_PREF."stock_master.stock_id
222                 WHERE order_no =".db_escape($order_no);
223
224     if ($open_items_only)
225                 $sql .= " AND (".TB_PREF."purch_order_details.quantity_ordered > ".TB_PREF."purch_order_details.quantity_received) ";
226
227         $sql .= " ORDER BY po_detail_item";
228
229         $result = db_query($sql, "The lines on the purchase order cannot be retrieved");
230
231     if (db_num_rows($result) > 0)
232     {
233                 while ($myrow = db_fetch($result))
234         {
235                 $data = get_purchase_data($order->supplier_id, $myrow['item_code']);
236                 if ($data !== false)
237                 {
238                         if ($data['supplier_description'] != "")
239                                 $myrow['description'] = $data['supplier_description'];
240                         //if ($data['suppliers_uom'] != "")
241                         //      $myrow['units'] = $data['suppliers_uom'];
242                 }               
243             if (is_null($myrow["units"]))
244             {
245                         $units = "";
246             }
247             else
248             {
249                 $units = $myrow["units"];
250             }
251
252             if ($order->add_to_order($order->lines_on_order, $myrow["item_code"],
253                 $myrow["quantity_ordered"],$myrow["description"],
254                 $myrow["unit_price"],$units, sql2date($myrow["delivery_date"]),
255                 $myrow["qty_invoiced"], $myrow["quantity_received"])) {
256                         $newline = &$order->line_items[$order->lines_on_order-1];
257                                         $newline->po_detail_rec = $myrow["po_detail_item"];
258                                         $newline->standard_cost = $myrow["std_cost_unit"];  /*Needed for receiving goods and GL interface */
259                                 // set for later GRN edition
260 //                      $newline->receive_qty = $newline->quantity - $newline->qty_dispatched;
261                         }
262         } /* line po from purchase order details */
263     } //end of checks on returned data set
264 }
265
266 //----------------------------------------------------------------------------------------
267
268 function read_po($order_no, &$order, $open_items_only=false)
269 {
270         $result = read_po_header($order_no, $order);
271
272         if ($result)
273                 read_po_items($order_no, $order, $open_items_only);
274 }
275
276 //----------------------------------------------------------------------------------------
277
278 function get_po_items($order_no)
279 {
280         $sql = "SELECT item_code, quantity_ordered, quantity_received, qty_invoiced
281                 FROM ".TB_PREF."purch_order_details
282                 WHERE order_no=".db_escape($order_no)
283                 ." ORDER BY po_detail_item";
284
285         $result = db_query($sql, "could not query purch order details");
286     check_db_error("Could not check that the details of the purchase order had not been changed by another user ", $sql);
287     return $result;
288 }
289 //----------------------------------------------------------------------------------------
290
291 function get_short_info($stock_id)
292 {
293         $sql = "SELECT description, units, mb_flag
294                 FROM ".TB_PREF."stock_master WHERE stock_id = ".db_escape($stock_id);
295
296         return db_query($sql,"The stock details for " . $stock_id . " could not be retrieved");
297 }
298
299 function get_sql_for_po_search_completed($from, $to, $supplier_id=ALL_TEXT, $location=ALL_TEXT,
300         $order_number = '', $stock_id = '', $also_closed=false)
301 {
302         $sql = "SELECT 
303                 porder.order_no, 
304                 porder.reference, 
305                 supplier.supp_name, 
306                 location.location_name,
307                 porder.requisition_no, 
308                 porder.ord_date, 
309                 supplier.curr_code, 
310                 Sum(line.unit_price*line.quantity_ordered) AS OrderValue,
311                 porder.into_stock_location,
312                 chk.isopen
313                 FROM ".TB_PREF."purch_orders as porder
314                                 LEFT JOIN (
315                                         SELECT order_no, SUM(quantity_ordered-quantity_received + quantity_ordered-qty_invoiced) isopen
316                                         FROM ".TB_PREF."purch_order_details
317                                         GROUP BY order_no
318                                 ) chk ON chk.order_no=porder.order_no,"
319                         .TB_PREF."purch_order_details as line, "
320                         .TB_PREF."suppliers as supplier, "
321                         .TB_PREF."locations as location
322                 WHERE porder.order_no = line.order_no
323                 AND porder.supplier_id = supplier.supplier_id
324                 AND location.loc_code = porder.into_stock_location ";
325
326         if ($supplier_id != ALL_TEXT)
327                 $sql .= "AND supplier.supplier_id=".$supplier_id." ";
328         if ($order_number != "")
329         {
330                 $sql .= "AND porder.reference LIKE ".db_escape('%'. $order_number . '%');
331         }
332         else
333         {
334
335                 $data_after = date2sql($from);
336                 $date_before = date2sql($to);
337
338                 $sql .= " AND porder.ord_date >= '$data_after'";
339                 $sql .= " AND porder.ord_date <= '$date_before'";
340
341                 if ($location != ALL_TEXT)
342                 {
343                         $sql .= " AND porder.into_stock_location = ".db_escape($location);
344                 }
345                 if ($stock_id !== '')
346                 {
347                         $sql .= " AND line.item_code=".db_escape($stock_id);
348                 }
349                 if ($supplier_id != ALL_TEXT)
350                         $sql .= " AND supplier.supplier_id=".db_escape($supplier_id);
351
352         }
353
354         if (!$also_closed)
355                 $sql .= " AND isopen";
356         $sql .= " GROUP BY porder.order_no";
357         return $sql;
358 }
359
360 function get_sql_for_po_search($from, $to, $supplier_id=ALL_TEXT, $location=ALL_TEXT, $order_number='', $stock_id='')
361 {
362         $sql = "SELECT 
363                 porder.order_no, 
364                 porder.reference,
365                 supplier.supp_name, 
366                 location.location_name,
367                 porder.requisition_no, 
368                 porder.ord_date,
369                 supplier.curr_code,
370                 Sum(line.unit_price*line.quantity_ordered) AS OrderValue,
371                 Sum(line.delivery_date < '". date2sql(Today()) ."'
372                 AND (line.quantity_ordered > line.quantity_received)) As OverDue
373                 FROM ".TB_PREF."purch_orders as porder,"
374                         .TB_PREF."purch_order_details as line, "
375                         .TB_PREF."suppliers as supplier, "
376                         .TB_PREF."locations as location
377                 WHERE porder.order_no = line.order_no
378                 AND porder.supplier_id = supplier.supplier_id
379                 AND location.loc_code = porder.into_stock_location
380                 AND (line.quantity_ordered > line.quantity_received) ";
381
382         if ($order_number != "")
383         {
384                 $sql .= "AND porder.reference LIKE ".db_escape('%'. $order_number . '%');
385         }
386         else
387         {
388                 $data_after = date2sql($from);
389                 $data_before = date2sql($to);
390
391                 $sql .= "  AND porder.ord_date >= '$data_after'";
392                 $sql .= "  AND porder.ord_date <= '$data_before'";
393
394                 if ($location != ALL_TEXT)
395                 {
396                         $sql .= " AND porder.into_stock_location = ".db_escape($location);
397                 }
398
399                 if ($stock_id != '')
400                 {
401                         $sql .= " AND line.item_code=".db_escape($stock_id);
402                 }
403                 if ($supplier_id != ALL_TEXT)
404                         $sql .= " AND supplier.supplier_id=".db_escape($supplier_id);
405         } //end not order number selected
406
407         $sql .= " GROUP BY porder.order_no";
408         return $sql;
409 }
410