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 /* Definition of the cart class
13 this class can hold all the information for:
21 include_once($path_to_root . "/inventory/includes/inventory_db.inc");
22 include_once($path_to_root . "/taxes/tax_calc.inc");
26 var $trans_type; // invoice, order, quotation, delivery note ...
27 var $trans_no = array();// array (num1=>ver1,..) or 0 for new
28 var $so_type = 0; // for sales order: simple=0 template=1
29 var $cart_id; // used to detect multi-tab edition conflits
30 var $line_items; //array of objects of class line_details
32 var $src_docs = array(); // array of arrays(num1=>ver1,...) or 0 for no src
33 var $src_date; // src document date (for info only)
37 var $sales_type; // set to the customer's sales type
38 var $sales_type_name; // set to customer's sales type name
41 var $customer_currency; // set to the customer's currency
42 var $default_discount; // set to the customer's discount %
49 var $delivery_address;
57 var $order_no; // the original order number
60 var $freight_cost = 0;
64 var $price_factor; // ditto for price calculations
66 var $pos; // user assigned POS
69 var $cash_discount; // not used as of FA 2.1
73 var $payment_terms; // cached payment terms
76 var $prepaid=false; // true for documents issued in prepayment mode
77 var $prep_amount=0; // prepayment required for SO, invoiced amount for prepaiament invoice
78 var $sum_paid; // sum of all allocated prepayments both to order and related invoices
79 var $alloc; // sum of payments allocated to this document
80 var $prepayments = array(); // allocation records for this document
83 var $fixed_asset = false;
85 //-------------------------------------------------------------------------
87 // $trans_no==0 => open new/direct document
88 // $trans_no!=0 && $prepare_child==false => update with parent constarints for reedition
89 // $trans_no!=0 && $prepare_child==true => prepare for child doc entry
90 // $prepare_child is set to ST_SALESINVOICE for prepayment invoices
92 function __construct($type, $trans_no=0, $prepare_child=false) {
93 /*Constructor function initialises a new shopping cart */
94 $this->line_items = array();
95 $this->sales_type = "";
96 if ($type == ST_SALESQUOTE)
97 $this->trans_type = $type;
99 $this->trans_type = ST_SALESORDER;
100 $this->dimension_id = 0;
101 $this->dimension2_id = 0;
102 $this->pos = get_sales_point(user_pos());
103 $this->read($type, $trans_no, $prepare_child);
104 $this->cart_id = uniqid('');
108 Optional sorting items by stock_id.
110 function _cmp_lines($a, $b)
112 return strcmp($a->stock_id, $b->stock_id);
116 Returns items array optionally sorted by item code.
122 $items = $this->line_items;
123 if (@$SysPrefs->sort_sales_items)
124 uasort($items, array($this, '_cmp_lines'));
129 // Prepare cart to new child document entry, just after initial parent doc read.
131 function prepare_child($type)
136 $type = get_child_type($this->trans_type);
138 $this->trans_type = $type;
139 $this->reference = $Refs->get_next($this->trans_type, null, array('date' => $this->document_date,
140 'customer' => $this->customer_id, 'branch' => $this->Branch));
141 if ($type == ST_CUSTCREDIT)
142 $this->src_date = $this->document_date;
144 $this->document_date = new_doc_date();
146 for($line_no = 0; $line_no < count($this->line_items); $line_no++) {
147 $line = &$this->line_items[$line_no];
148 $line->src_id = $line->id; // save src line ids for update
149 $line->qty_dispatched = $type == ST_CUSTCREDIT ? '0' :
150 (($this->prepaid && $type == ST_SALESINVOICE) ? $line->quantity : $line->quantity - $line->qty_done);
155 if ($type == ST_CUSTDELIVERY) {
156 $this->order_no = key($this->trans_no);
157 $cust = get_customer($this->customer_id);
158 $this->dimension_id = $cust['dimension_id'];
159 $this->dimension2_id = $cust['dimension2_id'];
161 if ($type == ST_SALESINVOICE) {
162 $this->due_date = get_invoice_duedate($this->payment, $this->document_date);
165 $this->src_docs = $this->trans_no;
170 // Prepares transaction for reedition updating with parent transaction data
172 function set_parent_constraints($sodata, $src_no) {
174 $srcdetails = get_sales_parent_lines($this->trans_type, $src_no);
175 $src_type = get_parent_type($this->trans_type);
177 // calculate & save: qtys on other docs and free qtys on src doc
178 $line_no = 0; $src_docs = array();
179 // Loop speed optimisation below depends on fact
180 // that child line_items contains subset of parent lines in _the_same_ order !
181 while (($line_no < count($this->line_items)) && ($srcline = db_fetch($srcdetails))) {
182 $line = &$this->line_items[$line_no];
183 $src_docs[] = $src_type == ST_SALESORDER ? $srcline['order_no'] : $srcline['debtor_trans_no'];
184 while($srcline['id'] != $line->src_id) // Logic : This will increment the line_items array till sales_order line is matched.
185 { // Fixes Delivery note bug : Parent constraints not working if sales order line deleted after delivery
187 $line = &$this->line_items[$line_no];
189 if ($srcline['id'] == $line->src_id) {
190 if ($this->trans_type == ST_SALESINVOICE)
191 $line->src_no = $srcline['debtor_trans_no'];
192 $line->qty_old = $line->qty_dispatched = $line->quantity;
193 $line->quantity += $srcline['quantity'] -
194 ($src_type==ST_SALESORDER ? $srcline['qty_sent'] : $srcline['qty_done']); // add free qty on src doc
199 if ($src_type == ST_SALESORDER || $src_type == 0) {
200 $this->src_docs = array( $sodata['order_no']=>$sodata['version']);
202 // get src_data from debtor_trans
203 $this->src_docs = get_customer_trans_version($src_type, array_unique($src_docs));
206 //-------------------------------------------------------------------------
207 // Reading document into cart
209 function read($type, $trans_no=0, $prepare_child=false) {
211 global $SysPrefs, $Refs;
213 if (!is_array($trans_no)) $trans_no = array($trans_no);
215 if ($trans_no[0]) { // read old transaction
216 if ($type == ST_SALESORDER || $type == ST_SALESQUOTE) { // sales order || sales quotation
217 read_sales_order($trans_no[0], $this, $type);
218 } else { // other type of sales transaction
219 read_sales_trans($type, $trans_no, $this);
220 $this->prepayments = get_payments_for($trans_no[0], $type, $this->customer_id);
221 $this->update_payments();
222 if ($this->order_no) { // free hand credit notes have no order_no
223 $sodata = get_sales_order_header($this->order_no, ST_SALESORDER);
224 $this->cust_ref = $sodata["customer_ref"];
225 // currently currency is hard linked to debtor account
226 $this->delivery_to = $sodata["deliver_to"];
227 $this->delivery_address = $sodata["delivery_address"];
228 // child transaction reedition - update with parent info unless it is freehand
229 if (!$this->is_prepaid() && !$prepare_child) // this is read for view/reedition
230 $this->set_parent_constraints($sodata, $trans_no[0]);
233 // convert document into child and prepare qtys for entry
235 $this->prepare_child($prepare_child);
237 } else { // new document
238 $this->trans_type = $type;
240 $this->customer_currency = get_company_currency();
241 // set new sales document defaults here
242 if (get_global_customer() != ALL_TEXT)
243 $this->customer_id = get_global_customer();
245 $this->customer_id = '';
246 $this->document_date = new_doc_date();
247 if (!is_date_in_fiscalyear($this->document_date))
248 $this->document_date = end_fiscalyear();
249 $this->reference = $Refs->get_next($this->trans_type, null, array('date' => Today(),
250 'customer' => $this->customer_id));
251 if ($type != ST_SALESORDER && $type != ST_SALESQUOTE) // Added 2.1 Joe Hunt 2008-11-12
253 $dim = get_company_pref('use_dimension');
256 if ($this->customer_id == '')
257 $this->dimension_id = 0;
260 $cust = get_customer($this->customer_id);
261 $this->dimension_id = $cust['dimension_id'];
265 if ($this->customer_id == '')
266 $this->dimension2_id = 0;
268 $this->dimension2_id = $cust['dimension2_id'];
272 if ($type == ST_SALESINVOICE) {
274 get_invoice_duedate($this->payment, $this->document_date);
277 add_days($this->document_date, $SysPrefs->default_delivery_required_by());
279 $this->credit = get_current_cust_credit($this->customer_id);
282 //-------------------------------------------------------------------------
283 // Writing new/modified sales document to database.
284 // Makes parent documents for direct delivery/invoice by recurent call.
285 // $policy - 0 or 1: writeoff/return for IV, back order/cancel for DN
286 function write($policy=0) {
288 global $SysPrefs, $Refs;
290 begin_transaction(); // prevents partial database changes in case of direct delivery/invoice
291 if ($this->reference != 'auto' && $this->trans_no == 0 && !is_new_reference($this->reference, $this->trans_type))
293 if (!empty($SysPrefs->prefs['ref_no_auto_increase']))
294 $this->reference = $Refs->get_next($this->trans_type, null, array('date' => Today()));
295 if (!is_new_reference($this->reference, $this->trans_type))
297 commit_transaction();
301 if (count($this->src_docs) == 0 && ($this->trans_type == ST_SALESINVOICE || $this->trans_type == ST_CUSTDELIVERY) && !$this->is_prepaid()) {
302 // this is direct document - first add parent
303 $ref = $this->reference;
304 $date = $this->document_date;
305 $due_date = $this->due_date;
306 $dimension_id = $this->dimension_id;
307 $dimension2_id = $this->dimension2_id;
308 $this->trans_type = get_parent_type($this->trans_type);
310 $this->reference = 'auto';
311 $trans_no = $this->write(1);
313 // re-read parent document converting it to child
314 $this->read($this->trans_type, $trans_no, true);
315 $this->document_date = $date;
316 $this->reference = $ref;
317 $this->due_date = $due_date;
318 $this->dimension_id = $dimension_id;
319 $this->dimension2_id = $dimension2_id;
321 $this->reference = @html_entity_decode($this->reference, ENT_QUOTES);
322 $this->Comments = @html_entity_decode($this->Comments, ENT_QUOTES);
323 foreach($this->line_items as $lineno => $line) {
324 $this->line_items[$lineno]->stock_id = @html_entity_decode($line->stock_id, ENT_QUOTES);
325 $this->line_items[$lineno]->item_description = @html_entity_decode($line->item_description, ENT_QUOTES);
327 switch($this->trans_type) {
328 case ST_SALESINVOICE:
329 $ret = write_sales_invoice($this); break;
331 $ret = write_credit_note($this, $policy); break;
332 case ST_CUSTDELIVERY:
333 $ret = write_sales_delivery($this, $policy); break;
336 if ($this->trans_no==0) // new document
337 $ret = add_sales_order($this);
339 $ret = update_sales_order($this);
342 commit_transaction();
347 function set_customer($customer_id, $customer_name, $currency, $discount, $payment, $cdiscount=0)
349 $this->customer_name = $customer_name;
350 $this->customer_id = $customer_id;
351 $this->default_discount = $discount;
352 $this->customer_currency = $currency;
353 $this->payment = $payment;
354 $this->payment_terms = get_payment_terms($payment);
355 $this->cash_discount = $cdiscount;
357 if ($this->payment_terms['type'] == PTT_CASH) {
358 $this->Location = $this->pos['pos_location'];
359 $this->location_name = $this->pos['location_name'];
361 $this->credit = get_current_cust_credit($customer_id);
364 function set_branch($branch_id, $tax_group_id, $tax_group_name, $phone='', $email='')
366 $this->Branch = $branch_id;
367 $this->phone = $phone;
368 $this->email = $email;
369 $this->tax_group_id = $tax_group_id;
372 function set_sales_type($sales_type, $sales_name, $tax_included=0, $factor=0)
374 $this->sales_type = $sales_type;
375 $this->sales_type_name = $sales_name;
376 $this->tax_included = $tax_included;
377 $this->price_factor = $factor;
380 function set_location($id, $name)
382 $this->Location = $id;
383 $this->location_name = $name;
386 function set_delivery($shipper, $destination, $address, $freight_cost=null)
388 $this->ship_via = $shipper;
389 $this->deliver_to = $destination;
390 $this->delivery_address = $address;
391 if (isset($freight_cost))
392 $this->freight_cost = $freight_cost;
395 function add_to_cart($line_no, $stock_id, $qty, $price, $disc, $qty_done=0, $unit_cost=0, $description=null, $id=0, $src_no=0,
398 $line = new line_details($stock_id, $qty, $price, $disc,
399 $qty_done, $unit_cost, $description, $id, $src_no, $src_id);
403 $this->line_items[$line_no] = $line;
406 display_error(_("You have to enter valid stock code or nonempty description"));
410 function update_cart_item($line_no, $qty, $price, $disc, $description="")
412 if ($description != "")
413 $this->line_items[$line_no]->item_description = $description;
414 $this->line_items[$line_no]->quantity = $qty;
415 $this->line_items[$line_no]->qty_dispatched = $qty;
416 $this->line_items[$line_no]->price = $price;
417 $this->line_items[$line_no]->discount_percent = $disc;
420 function update_add_cart_item_qty($line_no, $qty)
422 $this->line_items[$line_no]->quantity += $qty;
425 function remove_from_cart($line_no)
427 array_splice($this->line_items, $line_no, 1);
430 function clear_items()
432 unset($this->line_items);
433 $this->line_items = array();
434 $this->sales_type = "";
436 $this->customer_id = $this->order_no = 0;
439 function count_items()
442 foreach ($this->line_items as $line) {
443 if ($line->quantity!=$line->qty_done) $counter++;
448 function get_items_total()
452 foreach ($this->line_items as $ln_itm) {
453 $price = $ln_itm->line_price();
454 $total += round($ln_itm->quantity * $price * (1 - $ln_itm->discount_percent),
460 function get_items_total_dispatch()
464 foreach ($this->line_items as $ln_itm) {
465 $price = $ln_itm->line_price();
466 $total += round(($ln_itm->qty_dispatched * $price * (1 - $ln_itm->discount_percent)),
472 function has_items_dispatch()
474 foreach ($this->line_items as $ln_itm) {
475 if ($ln_itm->qty_dispatched > 0)
481 function any_already_delivered()
483 /* Checks if there have been any line item processed */
485 foreach ($this->line_items as $stock_item) {
486 if ($stock_item->qty_done !=0) {
495 function some_already_delivered($line_no)
497 /* Checks if there have been deliveries of a specific line item */
498 if (isset($this->line_items[$line_no]) &&
499 $this->line_items[$line_no]->qty_done != 0) {
506 Split line value to cost and taxes.
507 Stores calculated amounts in $line->gl_amounts arrays.
509 function split_line_values()
511 // split nominal line values
512 foreach ($this->line_items as $line)
513 $line->split_item_value();
516 function get_taxes($shipping_cost=null)
520 if ($this->ship_via != '') {
521 if ($shipping_cost == null)
522 $shipping_cost = $this->freight_cost;
523 $items[] = $this->ship_via;
524 $prices[] = $shipping_cost;
527 foreach ($this->line_items as $ln_itm) {
528 $items[] = $ln_itm->stock_id;
530 $this->trans_type==ST_SALESORDER ? $ln_itm->quantity : $ln_itm->qty_dispatched) *
531 $ln_itm->line_price()* (1 - $ln_itm->discount_percent)), user_price_dec());
534 $taxes = get_tax_for_items($this->trans_type, $items, $prices, $this->tax_group_id, $this->tax_included);
536 // Adjustment for swiss franken, we always have 5 rappen = 1/20 franken
537 if ($this->customer_currency == 'CHF') {
538 $val = $taxes['1']['Value'];
539 $val1 = (floatval((intval(round(($val*20),0)))/20));
540 $taxes['1']['Value'] = $val1;
546 function get_tax_free_shipping()
549 if ($this->tax_included==0)
550 return $this->freight_cost;
552 return ($this->freight_cost - $this->get_shipping_tax());
555 function get_shipping_tax()
557 $freight = split_item_price($this->ship_via, $this->freight_cost, $this->tax_group_id, $this->tax_included, $this->trans_type);
559 return $freight['Tax'];
562 Returns transaction value including all taxes
564 function get_trans_total() {
566 $total = $this->get_items_total() + $this->freight_cost;
567 $dec = user_price_dec();
568 if (!$this->tax_included ) {
569 $total += $this->get_shipping_tax();
570 $taxes = $this->get_taxes();
571 foreach($taxes as $tax)
572 $total += round($tax['Value'], $dec);
579 Checks cart quantities on document_date.
580 Returns array of stock_ids which stock quantities would go negative on some day.
582 function check_qoh($date=null, $location=null)
584 $low_stock = array();
585 // check only for customer delivery and direct sales invoice
586 if (!($this->trans_type == ST_CUSTDELIVERY || ($this->trans_type == ST_SALESINVOICE && $this->trans_no==0)))
589 // collect quantities by stock_id
591 foreach ($this->line_items as $line_no => $line_item)
593 if (has_stock_holding($line_item->mb_flag))
595 if (!$this->trans_no) // new delivery
596 $qtys[$line_item->stock_id]['qty'] = $line_item->qty_dispatched + @$qtys[$line_item->stock_id]['qty'];
597 else // DN modification: check change in quantity
598 $qtys[$line_item->stock_id]['qty'] = ($line_item->qty_dispatched-$line_item->qty_old) + @$qtys[$line_item->stock_id]['qty'];
599 $qtys[$line_item->stock_id]['line'] = $line_no;
603 foreach($qtys as $stock_id => $sum)
605 if (check_negative_stock($stock_id, -$sum['qty'], $location ? $location : $this->Location, $date ? $date : $this->document_date))
606 $low_stock[] = $stock_id;
613 Returns true for documents issued in prepayment cycle.
615 function is_prepaid()
617 return $this->prepaid;
620 Order is ready for delivery in prepament mode.
622 function is_released()
624 return floatcmp($this->sum_paid, $this->prep_amount) >= 0;
628 Check whether order has been already invoiced/send or not.
630 function is_started()
632 if ($this->trans_no==0)
634 $order_no = array_keys($this->trans_no);
636 return is_sales_order_started(reset($order_no));
640 Check payment terms and prepayments selected for this invoice,
641 and updates partial/final invoice value respectively.
643 function update_payments()
645 $remainder = prepaid_invoice_remainder($this->order_no);
647 // recalculate prepaid part from payments
648 if ($this->payment_terms['type'] == PTT_PREPAY)
649 { // this is partial invoice for selected prepayments made.
651 foreach($this->prepayments as $payment)
652 $paid += $payment['amt'];
653 $this->prep_amount = $this->trans_no ? $paid : min($remainder, $paid);
654 } else // this is final invoice
655 $this->prep_amount = $remainder;
657 } /* end of class defintion */
663 var $item_description;
668 var $src_no; // number of src doc for this line
671 var $discount_percent;
676 var $cart; // line context
677 var $valid; // validation in constructor
679 Line quantity properties in various cart create modes:
682 $quantity - quantity on current document
683 $qty_done - quantity processed on all child documents
684 $qty_dispatched - not used
688 $quantity - free parent quantity including this doc (= max allowed quantity)
689 $qty_done - qty processed on child documents (= min allowed qty)
690 $qty_dispatched - quantity currently selected to process
691 $qty_old - quantity processed on this document before reedition
693 new child entry (view parent followed by prepare_child() call):
694 $quantity - max allowed quantity (get from parent)
695 $qty_done - qty processed on other child documents
696 $qty_dispatched - quantity currently selected to process
697 $qty_old - 0; not used
705 function __construct($stock_id, $qty, $prc, $disc_percent,
706 $qty_done, $unit_cost, $description, $id=0, $src_no=0, $src_id=0)
708 /* Constructor function to add a new LineDetail object with passed params */
711 $this->src_no = $src_no;
712 $this->src_id = $src_id;
713 $item_row = get_item($stock_id);
718 $this->mb_flag = $item_row["mb_flag"];
719 $this->units = $item_row["units"];
720 $this->descr_editable = $item_row["editable"];
721 if ($description == null || !$this->descr_editable)
722 $this->item_description = $item_row["description"];
724 $this->item_description = $description;
725 $this->tax_type = $item_row["tax_type_id"];
726 $this->tax_type_name = $item_row["tax_type_name"];
727 $this->stock_id = $stock_id;
728 $this->quantity = $qty;
729 $this->qty_dispatched = $qty;
731 $this->discount_percent = $disc_percent;
732 $this->qty_done = $qty_done;
733 $this->unit_cost = $unit_cost;
737 // get unit price as stated on document
738 function line_price()
743 function taxfree_charge_price()
745 $this->split_item_value();
746 return $this->gl_amounts['Net'];
750 Splits item value to parts posted to GL.
752 function split_item_value()
754 return $this->gl_amounts = split_item_price($this->stock_id, $this->price*$this->quantity, $this->cart->tax_group_id, $this->cart->tax_included,
755 $this->cart->trans_type);