Fix [0000106] Error during direct invoice for non-ECB currencies.
[fa-stable.git] / sales / includes / cart_class.inc
1 <?php
2
3 /* Definition of the cart class
4 this class can hold all the information for:
5
6 i)   a sales order
7 ii)  an invoice
8 iii) a credit note
9 iv)  a delivery note
10 */
11
12 include_once($path_to_root . "/inventory/includes/inventory_db.inc");
13 include_once($path_to_root . "/taxes/tax_calc.inc");
14
15 class cart
16 {
17         var $trans_type; // invoice, order, delivery note ...
18         var $trans_no = array();// array (num1=>ver1,..) or 0 for new
19         var $so_type = 0;               // for sales order: simple=0 template=1
20         var $cart_id;           // used to detect multi-tab edition conflits
21         var $line_items;  //array of objects of class line_details
22
23         var $src_docs = array();        // array of arrays(num1=>ver1,...) or 0 for no src
24         var $src_date;                  // src document date (for info only)
25
26         var $document_date;
27         var $due_date;
28         var $sales_type; // set to the customer's sales type
29         var $sales_type_name; // set to customer's sales type name
30         var $tax_included;
31
32         var $customer_currency; // set to the customer's currency
33         var $default_discount; // set to the customer's discount %
34         var $customer_name;
35         var $customer_id;
36         var $Branch;
37         var $email;
38
39         var $deliver_to;
40         var $delivery_address;
41         var $phone;
42
43         var $cust_ref;
44         var $reference;
45         var $Comments;
46         var $Location;
47         var $location_name;
48         var $order_no;          // the original order number
49         var $trans_link = 0;
50
51         var $ship_via;
52         var $freight_cost = 0;
53
54         var $tax_group_id;
55         var $tax_group_name;
56         var $tax_group_array = null; // saves db queries
57         var $price_factor;       // ditto for price calculations
58
59         var     $pos;                   // user assigned POS
60         var $cash;                      // cash transaction
61         var $cash_account;
62         var $account_name;
63         var $cash_discount;     // not used as of FA 2.1
64         var $dimension_id;
65         var $dimension2_id;
66         //-------------------------------------------------------------------------
67         //
68         //  $trans_no==0 => open new/direct document
69         //  $trans_no!=0 && $view==false => read for view
70         //  $trans_no!=0 && $view==true => read for edit (qty update from parent doc)
71         //
72         function Cart($type, $trans_no=0, $view=false ) {
73                 /*Constructor function initialises a new shopping cart */
74                 $this->line_items = array();
75                 $this->sales_type = "";
76                 $this->trans_type = 30;
77                 $this->dimension_id = 0;
78                 $this->dimension2_id = 0;
79                 $this->read($type, $trans_no, $view );
80                 $this->cart_id = uniqid('');
81         }
82
83         //-------------------------------------------------------------------------
84         // Reading document into cart
85         //
86         function read($type, $trans_no = 0, $view=false ) {
87
88                 if (!is_array($trans_no)) $trans_no = array($trans_no);
89                 if ($trans_no[0]) {
90                         if ($type == 30) { // sales order
91                                 read_sales_order($trans_no[0], $this);
92                                 if ($view) {    // prepare for DN/IV entry
93                                         for($line_no = 0; $line_no < count($this->line_items); $line_no++) {
94                                                 $line = &$this->line_items[$line_no];
95                                                 $line->src_id = $line->id; // save src line ids for update
96                                                 $line->qty_dispatched = $line->quantity - $line->qty_done;
97                                         }
98                                 }
99                         } else {        // derivative transaction
100                                         read_sales_trans($type, $trans_no, $this);
101                                         if ($this->order_no) { // free hand credit notes have no order_no
102                                                 $sodata = get_sales_order_header($this->order_no);
103                                                 $this->cust_ref = $sodata["customer_ref"];
104                                         // currently currency is hard linked to debtor account
105                                         //      $this->customer_currency = $sodata["curr_code"];
106                                                 $this->delivery_to = $sodata["deliver_to"];
107                                                 $this->delivery_address = $sodata["delivery_address"];
108                                         }
109                                         if (!$view && ($type!=11 || $this->trans_link!=0)) {
110                                                 $src_type = get_parent_type($type);
111                                                 $src_details = 0;
112                                                 if ($src_type == 30) { // get src data from sales_orders
113                                                         $this->src_docs = array( $sodata['order_no']=>$sodata['version']);
114                                                         $srcdetails = get_sales_order_details($this->order_no);
115                                                 } else {        // get src_data from debtor_trans
116                                                         $this->src_docs = get_customer_trans_version($src_type, get_parent_trans($type,$trans_no[0]));
117                                                         $srcdetails = get_customer_trans_details($src_type,array_keys($this->src_docs));
118                                                 }
119                                                 // calculate & save: qtys on other docs and free qtys on src doc
120                                                 $line_no = 0;
121                                                 for($line_no = 0; $srcline = db_fetch($srcdetails); $line_no++) {
122                                                         $sign = 1; // $type==13 ?  1 : -1; // this is strange debtor_trans atavism
123                                                         $line = &$this->line_items[$line_no];
124
125                                                         $line->src_id = $srcline['id']; // save src line ids for update
126                                                         $line->qty_old = $line->qty_dispatched = $line->quantity;
127                                                         $line->quantity += $sign * ($srcline['quantity'] - $srcline['qty_done']); // add free qty on src doc
128                                                 }
129                                         } else {
130                                                 for($line_no = 0; $line_no < count($this->line_items); $line_no++) {
131                                                         $line = &$this->line_items[$line_no];
132                                                         $line->src_id = $line->id; // save src line ids for update
133                                                         $line->qty_dispatched = $line->quantity;
134                                                 }
135                                         }
136                                 }
137                         } else {
138                                 $this->trans_type = $type;
139                                 $this->trans_no = 0;
140                                 // set new sales document defaults here
141                                 if (get_global_customer() != reserved_words::get_all())
142                                   $this->customer_id = get_global_customer();
143                                 else
144                                   $this->customer_id = '';
145                                 $this->document_date = Today();
146                                 if (!is_date_in_fiscalyear($this->document_date))
147                                         $this->document_date = end_fiscalyear();
148                                 $this->reference = references::get_next($this->trans_type);
149                                 if ($type != 30) // Added 2.1 Joe Hunt 2008-11-12
150                                 {
151                                         $dim = get_company_pref('use_dimension');
152                                         if ($dim > 0)
153                                         {
154                                                 if ($this->customer_id == '')
155                                                         $this->dimension_id = 0;
156                                                 else
157                                                 {
158                                                         $cust = get_customer($this->customer_id);
159                                                         $this->dimension_id = $cust['dimension_id'];
160                                                 }       
161                                                 if ($dim > 1)
162                                                 {
163                                                         if ($this->customer_id == '')
164                                                                 $this->dimension2_id = 0;
165                                                         else
166                                                                 $this->dimension2_id = $cust['dimension2_id'];
167                                                 }               
168                                         }               
169                                 }       
170                                 if ($type == 10) {
171                                   $this->due_date =
172                                         get_invoice_duedate($this->customer_id, $this->document_date);
173                                   $this->pos = user_pos();
174                                   $pos = get_sales_point($this->pos);
175                                   $this->cash = !$pos['credit_sale'];
176                                   if (!$pos['cash_sale'] || !$pos['credit_sale']) 
177                                         $this->pos = -1; // mark not editable payment type
178                                   else
179                                         $this->cash = date_diff($this->due_date, Today(), 'd')<2;
180                                 if ($this->cash) {
181                                         $this->Location = $pos['pos_location'];
182                                         $this->location_name = $pos['location_name'];
183                                         $this->cash_account = $pos['pos_account'];
184                                         $this->account_name = $pos['bank_account_name'];
185                                 }
186                                 } else
187                                   $this->due_date =
188                                         add_days($this->document_date, sys_prefs::default_delivery_required_by());
189                         }
190         }
191
192         //-------------------------------------------------------------------------
193         // Writing new/modified sales document to database.
194         // Makes parent documents for direct delivery/invoice by recurent call.
195         // $policy - 0 or 1:  writeoff/return for IV, back order/cancel for DN
196         function write($policy=0) {
197                 if (count($this->src_docs) == 0 && ($this->trans_type == 10 || $this->trans_type == 13)) {
198                         // this is direct document - first add parent
199                         $src = (PHP_VERSION<5) ? $this : clone( $this ); // make local copy of this cart
200                         $src->trans_type = get_parent_type($src->trans_type);
201                         $src->reference = 'auto';
202
203                         $src->write(1);
204                         $type = $this->trans_type;
205                         $ref = $this->reference;
206                         $date = $this->document_date;
207                         // re-read document
208                         $this->read($src->trans_type, key($src->trans_no), true);
209                         $this->document_date = $date;
210                         $this->reference = $ref;
211                         $this->trans_type = $type;
212                         $this->src_docs= $this->trans_no;
213                         $this->trans_no = 0;
214                         $this->order_no= $this->trans_type==13 ? key($src->trans_no) : $src->order_no;
215                 }
216 // if we want to save old or derivative document first decode html entities
217 // from text fields. For new documents this is not needed.
218                 if ($this->trans_no || $this->trans_type != 30) {
219                         $this->reference = @html_entity_decode($this->reference);
220                         $this->Comments = @html_entity_decode($this->Comments);
221                         foreach($this->line_items as $lineno => $line) {
222                                 $this->line_items[$lineno]->stock_id = @html_entity_decode($line->stock_id);
223                                 $this->line_items[$lineno]->description = @html_entity_decode($line->description);
224                         }
225                 }
226                 switch($this->trans_type) {
227                         case 10:
228                                 return write_sales_invoice($this);
229                         case 11:
230                                 return write_credit_note($this, $policy);
231                         case 13:
232                                 return write_sales_delivery($this, $policy);
233                         case 30:
234                                 if ($this->trans_no==0) // new document
235                                         return add_sales_order($this);
236                                 else
237                                         return update_sales_order($this);
238                 }
239         }
240
241         function set_customer($customer_id, $customer_name, $currency, $discount, $cdiscount=0)
242         {
243                 $this->customer_name = $customer_name;
244                 $this->customer_id = $customer_id;
245                 $this->default_discount = $discount;
246                 $this->cash_discount = $cdiscount;
247                 $this->customer_currency = $currency;
248         }
249
250         function set_branch($branch_id, $tax_group_id, $tax_group_name, $phone='', $email='')
251         {
252                 $this->Branch = $branch_id;
253                 $this->phone = $phone;
254                 $this->email = $email;
255                 $this->tax_group_id = $tax_group_id;
256                 $this->tax_group_array = get_tax_group_items_as_array($tax_group_id);
257         }
258
259         function set_sales_type($sales_type, $sales_name, $tax_included=0, $factor=0)
260         {
261             $this->sales_type = $sales_type;
262             $this->sales_type_name = $sales_name;
263             $this->tax_included = $tax_included;
264             $this->price_factor = $factor;
265         }
266
267         function set_location($id, $name)
268         {
269                 $this->Location = $id;
270                 $this->location_name = $name;
271         }
272
273         function set_delivery($shipper, $destination, $address, $freight_cost=null)
274         {
275                 $this->ship_via = $shipper;
276                 $this->deliver_to = $destination;
277                 $this->delivery_address = $address;
278                 if (isset($freight_cost))
279                         $this->freight_cost = $freight_cost;
280         }
281
282         function add_to_cart($line_no,$stock_id, $qty, $price, $disc, $qty_done=0, $standard_cost=0, $description=null, $id=0, $src_no=0)
283         {
284                 if (isset($stock_id) && $stock_id != "" && isset($qty)/* && $qty > 0*/) {
285                         $this->line_items[$line_no] = new line_details($stock_id, $qty, $price, $disc,
286                                 $qty_done,  $standard_cost, $description, $id, $src_no);
287                         return 1;
288                 } else {
289                         // shouldn't come here under normal circumstances
290                         display_db_error("unexpected - adding an invalid item or null quantity", "", true);
291                 }
292                 return 0;
293         }
294
295         function update_cart_item($line_no, $qty, $price, $disc)
296         {
297                 $this->line_items[$line_no]->quantity = $qty;
298                 $this->line_items[$line_no]->qty_dispatched = $qty;
299                 $this->line_items[$line_no]->price = $price;
300                 $this->line_items[$line_no]->discount_percent = $disc;
301         }
302
303         function update_add_cart_item_qty($line_no, $qty)
304         {
305                 $this->line_items[$line_no]->quantity += $qty;
306         }
307
308         function remove_from_cart($line_no)
309         {
310                 array_splice($this->line_items, $line_no, 1);
311         }
312
313         function clear_items()
314         {
315                 unset($this->line_items);
316                 $this->line_items = array();
317                 $this->sales_type = "";
318                 $this->trans_no = 0;
319                 $this->customer_id = $this->order_no = 0;
320         }
321
322         function count_items()
323         {
324                 $counter=0;
325                 foreach ($this->line_items as $line) {
326                         if ($line->quantity!=$line->qty_done) $counter++;
327                 }
328                 return $counter;
329         }
330
331         function get_items_total()
332         {
333                 $total = 0;
334
335                 foreach ($this->line_items as $ln_itm) {
336                         $price = $ln_itm->line_price();
337                         $total += round($ln_itm->quantity * $price * (1 - $ln_itm->discount_percent), 
338                            user_price_dec());
339                 }
340                 return $total;
341         }
342
343         function get_items_total_dispatch()
344         {
345                 $total = 0;
346
347                 foreach ($this->line_items as $ln_itm) {
348                         $price = $ln_itm->line_price();
349                         $total += round(($ln_itm->qty_dispatched * $price * (1 - $ln_itm->discount_percent)), 
350                            user_price_dec());
351                 }
352                 return $total;
353         }
354
355         function has_items_dispatch()
356         {
357                 foreach ($this->line_items as $ln_itm) {
358                         if ($ln_itm->qty_dispatched > 0)
359                                 return true;
360                 }
361                 return false;
362         }
363
364         function any_already_delivered()
365         {
366                 /* Checks if there have been any line item processed */
367
368                 foreach ($this->line_items as $stock_item) {
369                         if ($stock_item->qty_done !=0) {
370                                 return 1;
371                         }
372                 }
373
374                 return 0;
375
376         }
377
378         function some_already_delivered($line_no)
379         {
380                 /* Checks if there have been deliveries of a specific line item */
381                 if (isset($this->line_items[$line_no]) &&
382                         $this->line_items[$line_no]->qty_done != 0) {
383                         return 1;
384                 }
385                 return 0;
386         }
387
388         function get_taxes($shipping_cost=null)
389         {
390                 $items = array();
391                 $prices = array();
392                 if($shipping_cost==null)
393                         $shipping_cost = $this->freight_cost;
394
395                 foreach ($this->line_items as $ln_itm) {
396                         $items[] = $ln_itm->stock_id;
397                         $prices[] = round(($ln_itm->qty_dispatched *
398                                 $ln_itm->line_price()* (1 - $ln_itm->discount_percent)),  user_price_dec());
399                 }
400
401                 $taxes = get_tax_for_items($items, $prices, $shipping_cost,
402                   $this->tax_group_id, $this->tax_included,  $this->tax_group_array);
403
404     // Adjustment for swiss franken, we always have 5 rappen = 1/20 franken
405     if ($this->customer_currency == 'CHF') {
406                         $val = $taxes['1']['Value'];
407       $val1 = (floatval((intval(round(($val*20),0)))/20));
408                         $taxes['1']['Value'] = $val1;
409                 } 
410                 return $taxes;
411         }
412
413
414         function get_tax_free_shipping()
415         {
416
417                 if ($this->tax_included==0)
418                         return $this->freight_cost;
419                 else
420                         return ($this->freight_cost - $this->get_shipping_tax());
421         }
422
423         function get_shipping_tax()
424         {
425
426                 $tax_items = get_shipping_tax_as_array();
427                 $tax_rate = 0;
428                 if ($tax_items != null) {
429                         foreach ($tax_items as $item_tax) {
430                                 $index = $item_tax['tax_type_id'];
431                                 if (isset($this->tax_group_array[$index])) {
432                                         $tax_rate += $item_tax['rate'];
433                                 }
434                         }
435                 }
436                 if($this->tax_included)
437                         return round($this->freight_cost*$tax_rate/($tax_rate+100),  user_price_dec());
438                 else
439                         return round($this->freight_cost*$tax_rate/100,  user_price_dec());
440         }
441
442 } /* end of class defintion */
443
444 class line_details
445 {
446         var $id;
447         var $stock_id;
448         var $item_description;
449         var $units;
450         var $mb_flag;
451         var $tax_type;
452         var $tax_type_name;
453         var $src_no;    // number of src doc for this line
454         var $src_id;
455         var $quantity;
456         var $price;
457         var $discount_percent;
458         var $qty_done;  // quantity processed on child documents
459         var $qty_dispatched; // quantity selected to process
460         var $qty_old=0; // quantity dispatched before edition
461         var $standard_cost;
462
463         function line_details ($stock_id, $qty, $prc, $disc_percent,
464                 $qty_done, $standard_cost, $description, $id=0, $src_no=0 )
465         {
466         /* Constructor function to add a new LineDetail object with passed params */
467
468                 $this->id = $id;
469                 $this->src_no = $src_no;
470                 $item_row = get_item($stock_id);
471
472                 if ($item_row == null)
473                         display_db_error("invalid item added to order : $stock_id", "");
474
475                 $this->mb_flag = $item_row["mb_flag"];
476                 $this->units = $item_row["units"];
477                 if ($description == null)
478                         $this->item_description = $item_row["description"];
479                 else
480                         $this->item_description = $description;
481                 //$this->standard_cost = $item_row["material_cost"] + $item_row["labour_cost"] + $item_row["overhead_cost"];
482                 $this->tax_type = $item_row["tax_type_id"];
483                 $this->tax_type_name = $item_row["tax_type_name"];
484
485                 $this->stock_id = $stock_id;
486                 $this->quantity = $qty;
487                 $this->qty_dispatched = $qty;
488                 $this->price = $prc;
489                 $this->discount_percent = $disc_percent;
490                 $this->qty_done = $qty_done;
491                 $this->standard_cost = $standard_cost;
492         }
493
494         // get unit price as stated on document
495         function line_price()
496         {
497                 return $this->price;
498         }
499 }
500
501 ?>