--- /dev/null
+<?php
+require_once($path_to_root.'/'.'includes/date_functions.inc');
+class Split {
+ public $stard_date;
+ public $end_date;
+
+ function __constructor($start_date, $period) {
+ $this->start_date = $this->end_date = $start_date;
+ $this->extend($period);
+ }
+
+ function extend($days) {
+ $this->end_date = add_days($this->end_date, $days);
+ }
+}
+class Splitter {
+ public $detail_ids = array() ;
+ public $start_date;
+ public $end_date;
+ protected $days;
+ public $quantity_max;
+
+ public function __construct(array $data) {
+ foreach($data['detail'] as $detail_id => $detail) {
+ array_push($this->details_id, $detail_id);
+ }
+ $start_date = $data['start_date'];
+ $end_date = $data['end_date'];
+ $days = date_diff2($start_date, $end_date, 'd');
+ }
+
+ protected function loadDetail($detail_id) {
+ $sql = "SELECT *
+ FROM ".TB_PREF."sales_order_details
+ WHERE id = $detail_id";
+ $result = db_query($sql);
+ return db_fetch($result);
+ }
+
+ public function splitAll() {
+ foreach($this->detail_ids as $detail_id) {
+ $detail = $this->loadDetail($detail_id);
+ $splits = $this->split($detail);
+ $this->saveSplits($detail, $splits);
+ }
+ }
+
+
+
+ /* This function splits on order detail in bits of a specified size.
+ * Each split starting at the end time of the previous one.
+ * the first split starts at the start_date and ends at the end_date.
+ * The 'splitting' split the whole quantity not only the quantity left to dispatch
+ * However, fully dispatched split won't be split in real, but merged with the next one
+ */
+ protected function split($row) {
+ $splits = array();
+ $quantity = $row['quantity'];
+ $quantity_sent = $row['qty_sent'];
+
+ if($quantity >= $quantity_sent) return;
+ if(($quantity-$quantity_sent) % $this->max_quantity < $this->max_quantity) return;
+
+ // determine the number of split needed. This will give us the lenght of a split.
+ $nsplit = ceiling($initial_quantity/$this->max_quantity);
+ if($nsplit == 1) return;
+
+ $period = $this->days/$nsplit;
+
+ array_push($splits, $split = new Split($start_date, $period));
+ $split_quantity = min($quantity, $this->max_quantity);
+ while($split_quantity > 0) {
+ $split->quantity += $split_quantity;
+ // Check if the split has been entirely dispatch or not.
+ if($quantity_dispatched > $split->quantity) {
+ //extend the split
+ $split->extend($period);
+ }
+ else {
+ // create a new split
+ array_push($splits, $split = new Split($split->end_date, $period));
+ $quantity_dispatched = 0; // we don't need to check anymore.
+
+ }
+ $quantity -= $split_quantity;
+ $split_quantity = min($quantity, $this->max_quantity);
+ }
+
+ return $splits;
+ }
+
+}
+?>