PageRenderTime 53ms CodeModel.GetById 1ms app.highlight 47ms RepoModel.GetById 1ms app.codeStats 0ms

/controllers/orders.php

https://bitbucket.org/cpoppema/stockpiler
PHP | 402 lines | 352 code | 40 blank | 10 comment | 44 complexity | eca977c62bc01f8e89f2a6e072c0a88f MD5 | raw file
  1<?php
  2
  3    const MSG_SUCCESS_ADD_ORDER = 'Your order was added successfully!';
  4    const MSG_SUCCESS_EDIT_ORDER = 'Your order was updated successfully!';
  5
  6    const MSG_UNAUTHORIZED_ADD_ORDER = 'You are not authorized to add an order!';
  7    const MSG_UNAUTHORIZED_EDIT_ORDER = 'You are not authorized to edit an order!';
  8
  9
 10    function orders_history()
 11    {
 12        Security_Authorize();
 13
 14        $orders = R::findAll('order', 'order by id desc');
 15        $index = R::$adapter->getAffectedRows();
 16
 17        R::preload($orders, array('product'));
 18
 19        foreach($orders as $order)
 20        {
 21
 22            // Calculate progress
 23            $progress_current = 0;
 24            $deliveries = R::find('stock', 'order_id = ? and (iscanceled = 0 or iscanceled is null)', array($order->id));
 25            foreach($deliveries as $delivery)
 26            {
 27                $progress_current += $delivery->amount;
 28            }
 29            $progress_total = $order['amount'];
 30
 31            $progress_perc = 1;
 32            $progress_class = 'danger';
 33            if ($progress_current > 0)
 34            {
 35                $progress_class = 'warning';
 36                $progress_perc = floor(($progress_current / $progress_total) * 100);
 37            }
 38            elseif ($progress_current == $progress_total)
 39            {
 40                $progress_class = 'success';
 41                $progress_perc = 100;
 42            }
 43
 44            if ($progress_class != 'danger')
 45            {
 46                if ($progress_current == $progress_total)
 47                {
 48                    $progress_bar = "<div class='progress progress-success'><div class='bar' style='width: 100%'>{$progress_total}</div></div>";
 49                } else {
 50                    $progress_bar = "<div class='progress'><div class='bar bar-{$progress_class}' style='width: {$progress_perc}%'>{$progress_current}</div><div class='bar bar-danger' style='width: ". (100 - $progress_perc) . "%'>{$progress_total}</div></div>";
 51                }
 52            } else {
 53                $progress_bar = "<div class='progress'><div class='bar bar-success' style='width: 2%'></div><div class='bar bar-danger' style='width: 98%'>0 / {$progress_total}</div></div>";
 54            }
 55
 56            $css_class = 'error';
 57            if ($order['hasarrived'] == 1)
 58            {
 59                $css_class = 'success';
 60            }
 61            if ($order['iscanceled'] == 1)
 62            {
 63                $css_class = 'warning';
 64            }
 65
 66            if ($order['iscanceled'] == 1 && $_SESSION['CurrentUser_HideInacitve'])
 67            {
 68                $css_class .= ' hide';
 69            }
 70
 71            $body .= "<tr class='" . $css_class . "'>\n";
 72
 73            $body .= "<th>\n";
 74            $body .= $index;
 75            $body .= "</th>\n";
 76            $body .= "<td class='name'>\n";
 77            $body .= $order['product']['name'];
 78            $body .= "</td>\n";
 79            $body .= "<td class='code'>\n";
 80            $body .= $order['product']['code'];
 81            $body .= "</td>\n";
 82            $body .= "<td>\n";
 83            $body .= $progress_bar;
 84            $body .= "</td>\n";
 85
 86			if ($_SESSION["CurrentUser_IsReadOnly"] != "1")
 87			{
 88				$body .= "<td>\n";
 89				$body .= "<a href='" . option('base_uri') . "orders/" . $order['id'] . "'>Edit</a>\n";
 90				$body .= "</td>\n";
 91            }
 92
 93            $body .= "</tr>\n";
 94
 95            $index--;
 96        }
 97
 98        if (count($orders) == 0)
 99        {
100            $body .= "<tr>\n";
101            $body .= "<td colspan='5'>You're an order.</td>\n";
102            $body .= "</tr>\n";
103        }
104
105        // Get typeahead data
106        $names = array();
107        $codes = array();
108        $products = R::findAll('product', 'order by name asc, code asc');
109        foreach ($products as $product) {
110            $names[] = $product['name'];
111            $codes[] = $product['code'];
112        }
113        set("names", $names);
114        set("codes", $codes);
115        set("title", "Order History");
116        set("body", $body);
117        return html("orders/history.php");
118    }
119
120    function orders_add()
121    {
122        Security_Authorize();
123
124        if ($_SESSION['CurrentUser_IsReadOnly'] == "1")
125        {
126            header("Location: " . option('base_uri') . "&error=" . MSG_UNAUTHORIZED_ADD_ORDER);
127            exit;
128        }
129
130        // Get typeahead data
131        $names = array();
132        $codes = array();
133        $products = R::find('product', 'isdeleted = 0 or isdeleted is null order by name asc, code asc');
134        foreach ($products as $product) {
135            $names[] = $product['name'];
136            $codes[] = $product['code'];
137        }
138        set("names", $names);
139        set("codes", $codes);
140        set("title", "New Order");
141        return html("orders/add.php");
142    }
143
144    function orders_add_post()
145    {
146        Security_Authorize();
147
148        if ($_SESSION['CurrentUser_IsReadOnly'] == "1")
149        {
150            header("Location: " . option('base_uri') . "&error=" . MSG_UNAUTHORIZED_ADD_ORDER);
151            exit;
152        }
153
154        if (empty($_POST['name']) || strlen(trim($_POST['name'])) == 0)
155        {
156            $_GET['error'] = "You need to provide at least the product's name!";
157        }
158        if ( !isset($_POST['amount']) || $_POST['amount'] <= 0)
159        {
160            $_GET['error'] = "Care to tell us how much you really want to order?!";
161        } else {
162            $product = R::findOne('product', 'name = ? and (isdeleted = 0 or isdeleted is null)', array($_POST['name']));
163            if (R::$adapter->getAffectedRows() < 1)
164            {
165                $_GET['error'] = "The name you provided was not found! Did you tried to order a previous deleted product perhaps?";
166            } else {
167                // Add Order
168                $order = R::dispense('order');
169                $order->product = $product;
170                $order->amount =  $_POST['amount'];
171                $order->hasarrived = false;
172                $order->iscanceled = false;
173                $order->reason = null;
174                $id = R::store($order);
175
176                // Log adding order
177                $entry = R::dispense('log');
178                $entry->action = 'created';
179                $entry->object = $order->getID();
180                $entry->object_type = $order->getMeta('type');
181                $entry->user_id = $_SESSION['CurrentUser_ID'];
182                $entry->date = R::isoDateTime();
183                R::store($entry);
184
185                // Order added, go to list
186                header("Location: " . option('base_uri') . "orders&success=" . MSG_SUCCESS_ADD_ORDER);
187                exit;
188            }
189        }
190
191        // Get typeahead data
192        $names = array();
193        $codes = array();
194        $products = R::find('product', 'isdeleted = 0 or isdeleted is null order by name asc, code asc');
195        foreach ($products as $product) {
196            $names[] = $product['name'];
197            $codes[] = $product['code'];
198        }
199        set("names", $names);
200        set("codes", $codes);
201
202        // Errors, go to form
203        set("title", "New Order");
204        return html("orders/add.php");
205    }
206
207    function orders_edit()
208    {
209        Security_Authorize();
210
211        if ($_SESSION['CurrentUser_IsReadOnly'] == "1")
212        {
213            header("Location: " . option('base_uri') . "&error=" . MSG_UNAUTHORIZED_EDIT_ORDER);
214            exit;
215        }
216
217        $order = R::load('order', params('id'));
218        if (!$order->id)
219        {
220            set("title", "Not Found");
221            set("type", "order");
222            return html("error/notfound.php");
223        }
224
225        // Find partial deliveries
226        $deliveries = R::find('stock', 'order_id = ? and (iscanceled = 0 or iscanceled is null) order by id asc', array($order->id));
227        $progress_total = $order->amount;
228
229        $index = 1;
230
231        $has_all_products = false;
232        $progress_current = 0;
233        $partial_deliveries_body = "";
234        foreach($deliveries as $delivery)
235        {
236            $progress_current += $delivery->amount;
237            $progress_perc = floor(($progress_current / $progress_total) * 100);
238
239            $partial_deliveries_body .= "<tr>";
240            $partial_deliveries_body .= "<th>" . $index . "</th>";
241            $partial_deliveries_body .= "<td>&plus;" . $delivery->amount . "</td>";
242
243            $partial_deliveries_body .=  "<td>";
244
245            if ($progress_current == $progress_total)
246            {
247                $has_all_products = true;
248                $partial_deliveries_body .= "<div class='progress progress-success'><div class='bar' style='width: 100%'>{$progress_total}</div></div>";
249            } else {
250                $partial_deliveries_body .= "<div class='progress'><div class='bar bar-warning' style='width: {$progress_perc}%'>{$progress_current}</div><div class='bar bar-danger' style='width: " .  (100 - $progress_perc) . "%'>{$progress_total}</div></div>";
251            }
252            $partial_deliveries_body .= "</td>";
253            if ($_SESSION["CurrentUser_IsReadOnly"] != "1")
254            {
255                $partial_deliveries_body .= "<td style='width: 100px;'>";
256                $partial_deliveries_body .= "<a href='" . url_for('stock') . "/" . $delivery->getID() . "'>Edit</a>";
257                $partial_deliveries_body .= "</td>";
258            }
259            $partial_deliveries_body .= "</tr>";
260
261            $index++;
262        }
263
264        // Update has_arrived (in light of partial delivery or maybe canceled deliveries)
265        $order->hasarrived = $progress_current == $progress_total;
266        R::store($order);
267
268        $max_partial_amount = $progress_total - $progress_current;
269
270        R::preload($order, array('product'));
271        set("title", "Edit Order");
272        set("order", $order);
273        set("has_all_products", $has_all_products);
274        set("max_partial_amount", $max_partial_amount);
275        set("partial_deliveries_body", $partial_deliveries_body);
276        return html("orders/edit.php");
277    }
278
279    function orders_edit_post()
280    {
281        Security_Authorize();
282
283        if ($_SESSION['CurrentUser_IsReadOnly'] == "1")
284        {
285            header("Location: " . option('base_uri') . "&error=" . MSG_UNAUTHORIZED_EDIT_ORDER);
286            exit;
287        }
288
289        $order = R::load('order', params('id'));
290        if (!$order->id)
291        {
292            set("title", "Not Found");
293            set("type", "order");
294            return html("error/notfound.php");
295        }
296
297        // Log editing order
298        $entry = R::dispense('log');
299        $entry->action = 'modified';
300        if ($_POST['iscanceled'] == 1)
301        {
302            if ($order->iscanceled != 1)
303            {
304                $entry->action = 'canceled';
305            } else {
306                $entry->action = 'modified when canceled';
307            }
308        }
309        elseif ($order->iscanceled == 1)
310        {
311            $entry->action = 'uncanceled';
312        }
313
314        // Add partial delivery
315        if (isset($_POST['partial-delivery']))
316        {
317            $progress_current = R::getCol('SELECT SUM(amount) as amount FROM stock WHERE order_id = ? and (iscanceled = 0 or iscanceled is null)', array($order->id));
318            if ((int) $progress_current[0]['amount'] + (int) $_POST['partial-amount'] > (int) $order->amount)
319            {
320                header("Location: " . option('base_uri') . "orders/" . $order->getID() . "&error=You cannot add more than you've initially ordered.");
321                exit;
322            }
323
324            // Add Partal Delivery
325            $stock = R::dispense('stock');
326            R::preload($order, array('product'));
327            $stock->product = R::load('product', $order->product->getID());
328            $stock->type = 'delivery';
329            $stock->amount =  $_POST['partial-amount'];
330            $stock->reason = null;
331            $stock->iscanceled = false;
332            $stock->order = $order;
333            $id = R::store($stock);
334
335            // Log editing order
336            $entry = R::dispense('log');
337            $entry->action = 'modified';
338            $entry->object = $order->getID();
339            $entry->object_type = $order->getMeta('type');
340            $entry->user_id = $_SESSION['CurrentUser_ID'];
341            $entry->date = R::isoDateTime();
342            R::store($entry);
343
344            // Log adding delivery
345            $new_entry = R::dispense('log');
346            $new_entry->action = 'created';
347            $new_entry->object = $stock->getID();
348            $new_entry->object_type = $stock->getMeta('type');
349            $new_entry->user_id = $_SESSION['CurrentUser_ID'];
350            // Use same timestamp
351            $new_entry->date = $entry->date;
352            R::store($new_entry);
353
354            header("Location: " . option('base_uri') . "orders/" . $order->getID());
355            exit;
356        } else {
357            // Edit order
358            $order->amount = $_POST['amount'];
359            $order->hasarrived = (int) $_POST['hasarrived'];
360            $order->iscanceled = (int) $_POST['iscanceled'];
361            R::store($order);
362
363            // Continue log entry editing order
364            $entry->object = $order->getID();
365            $entry->object_type = $order->getMeta('type');
366            $entry->user_id = $_SESSION['CurrentUser_ID'];
367            $entry->date = R::isoDateTime();
368            R::store($entry);
369
370            // Check if order is marked as arrived
371            if ($order->hasarrived == 1)
372            {
373                // Calculate amount of products delivered
374                $progress_current = R::getCol('SELECT SUM(amount) as amount FROM stock WHERE order_id = ? and (iscanceled = 0 or iscanceled is null)', array($order->id));
375                $amount = (int) $order->amount - (int) $progress_current[0]['amount'];
376
377                // Add Delivery
378                $stock = R::dispense('stock');
379                R::preload($order, array('product'));
380                $stock->product = R::load('product', $order->product->getID());
381                $stock->type = 'delivery';
382                $stock->amount =  $amount;
383                $stock->reason = null;
384                $stock->iscanceled = false;
385                $stock->order = $order;
386                $id = R::store($stock);
387
388                // Log adding delivery
389                $new_entry = R::dispense('log');
390                $new_entry->action = 'created';
391                $new_entry->object = $stock->getID();
392                $new_entry->object_type = $stock->getMeta('type');
393                $new_entry->user_id = $_SESSION['CurrentUser_ID'];
394                // Use same timestamp
395                $new_entry->date = $entry->date;
396                R::store($new_entry);
397            }
398
399            header("Location: " . option('base_uri') . "orders/&success=" . MSG_SUCCESS_EDIT_ORDER);
400            exit;
401        }
402    }