Example #1
0
} else {
    if ($_REQUEST['a'] == "logout") {
        $auth->logout();
        returnResult($result);
    }
}
// the hello request checks server connectivity aswell as providing the status of the logged in user
if ($_REQUEST['a'] == "hello") {
    $result['data'] = new stdClass();
    if ($auth->isCustomerLoggedIn()) {
        $result['data']->user = $auth->getCustomer();
    } else {
        $result['data']->user = false;
    }
    // unlike other hello requests, this also provide some current business info.
    $conf = WposAdminSettings::getSettingsObject('general');
    $result['data']->bizname = $conf->bizname;
    $result['data']->bizlogo = $conf->bizlogo;
    returnResult($result);
}
// Decode JSON data if provided
if ($_REQUEST['data'] != "") {
    if (($requests = json_decode($_REQUEST['data'])) == false) {
        $result['error'] = "Could not parse the provided json request";
        returnResult($result);
    }
} else {
    $requests = new stdClass();
}
// Route the provided requests
if ($_REQUEST['a'] !== "multi") {
Example #2
0
 public function upgrade($version)
 {
     $auth = new Auth();
     if (!$auth->isLoggedIn() || !$auth->isAdmin()) {
         return "Must be logged in as admin";
     }
     $path = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['APP_ROOT'] . "library/installer/schemas/update" . $version . ".sql";
     if (!file_exists($path)) {
         return "Schema does not exist";
     }
     $settings = WposAdminSettings::getSettingsObject('general');
     if (floatval($settings->version) >= floatval($version)) {
         return "Db already at the latest version";
     }
     $sql = file_get_contents($path);
     try {
         $result = $this->db->_db->exec($sql);
         if ($result !== false) {
             switch ($version) {
                 case "1.0":
                     // set sales type & channel
                     $sql = "UPDATE `sales` SET `type`='sale', `channel`='pos';";
                     if ($this->db->_db->exec($sql) === false) {
                         return $this->db->_db->errorInfo()[0];
                     }
                     // set payment dt to process dt and update sales json with extra params
                     $sql = "SELECT * FROM `sales`;";
                     $sales = $this->db->select($sql, []);
                     foreach ($sales as $sale) {
                         $data = json_decode($sale['data']);
                         $data->id = $sale['id'];
                         $data->balance = 0.0;
                         $data->dt = $sale['dt'];
                         $data->status = $sale['status'];
                         if ($data == false) {
                             die("Prevented null data entry");
                         }
                         $sql = "UPDATE `sales` SET `data`=:data WHERE `id`=:saleid";
                         $this->db->update($sql, [":data" => json_encode($data), ":saleid" => $sale['id']]);
                         $sql = "UPDATE `sale_payments` SET `processdt=:processdt WHERE `saleid`=:saleid";
                         $this->db->update($sql, [":processdt" => $sale['processdt'], ":saleid" => $sale['id']]);
                     }
                     // update config, add google keys
                     WposAdminSettings::putValue('general', 'version', '1.0');
                     WposAdminSettings::putValue('general', 'gcontact', 0);
                     WposAdminSettings::putValue('general', 'gcontacttoken', '');
                     WposAdminSettings::putValue('pos', 'priceedit', 'blank');
                     // copy new templates
                     copy($_SERVER['DOCUMENT_ROOT'] . $_SERVER['APP_ROOT'] . 'docs-template/templates', $_SERVER['DOCUMENT_ROOT'] . $_SERVER['APP_ROOT'] . 'docs/');
                     break;
                 case "1.1":
                     WposAdminSettings::putValue('general', 'version', '1.1');
             }
             return true;
         } else {
             return $this->db->_db->errorInfo()[0];
         }
     } catch (Exception $e) {
         return $e->getMessage();
     }
 }
Example #3
0
 public function upgrade($version, $authneeded = true)
 {
     if ($authneeded) {
         $auth = new Auth();
         if (!$auth->isLoggedIn() || !$auth->isAdmin()) {
             return "Must be logged in as admin";
         }
     }
     $path = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['APP_ROOT'] . "library/installer/schemas/update" . $version . ".sql";
     if (!file_exists($path)) {
         return "Schema does not exist";
     }
     $settings = WposAdminSettings::getSettingsObject('general');
     if (floatval($settings->version) >= floatval($version)) {
         return "Db already at the latest version";
     }
     $sql = file_get_contents($path);
     try {
         $result = $this->db->_db->exec($sql);
         /*if ($result===false){
               echo $this->db->_db->errorInfo()[0];
           }*/
         switch ($version) {
             case "1.0":
                 // set sales type & channel
                 $sql = "UPDATE `sales` SET `type`='sale', `channel`='pos';";
                 if ($this->db->_db->exec($sql) === false) {
                     return $this->db->_db->errorInfo()[0];
                 }
                 // set payment dt to process dt and update sales json with extra params
                 $sql = "SELECT * FROM `sales`;";
                 $sales = $this->db->select($sql, []);
                 foreach ($sales as $sale) {
                     $data = json_decode($sale['data']);
                     $data->id = $sale['id'];
                     $data->balance = 0.0;
                     $data->dt = $sale['dt'];
                     $data->status = $sale['status'];
                     if ($data == false) {
                         die("Prevented null data entry");
                     }
                     $sql = "UPDATE `sales` SET `data`=:data WHERE `id`=:saleid";
                     $this->db->update($sql, [":data" => json_encode($data), ":saleid" => $sale['id']]);
                     $sql = "UPDATE `sale_payments` SET `processdt=:processdt WHERE `saleid`=:saleid";
                     $this->db->update($sql, [":processdt" => $sale['processdt'], ":saleid" => $sale['id']]);
                 }
                 // update config, add google keys
                 WposAdminSettings::putValue('general', 'version', '1.0');
                 WposAdminSettings::putValue('general', 'gcontact', 0);
                 WposAdminSettings::putValue('general', 'gcontacttoken', '');
                 WposAdminSettings::putValue('pos', 'priceedit', 'blank');
                 // copy new templates
                 copy($_SERVER['DOCUMENT_ROOT'] . $_SERVER['APP_ROOT'] . 'docs-template/templates', $_SERVER['DOCUMENT_ROOT'] . $_SERVER['APP_ROOT'] . 'docs/');
                 break;
             case "1.1":
                 WposAdminSettings::putValue('general', 'version', '1.1');
                 break;
             case "1.2":
                 // update item tax values
                 $sql = "SELECT * FROM `sale_items`;";
                 $items = $this->db->select($sql, []);
                 foreach ($items as $item) {
                     if (is_numeric($item['tax'])) {
                         $taxdata = new stdClass();
                         $taxdata->values = new stdClass();
                         $taxdata->inclusive = true;
                         if ($item['tax'] > 0) {
                             $taxdata->values->{"1"} = $item['tax'];
                             $taxdata->total = $item['tax'];
                         } else {
                             $taxdata->total = 0;
                         }
                         $sql = "UPDATE `sale_items` SET `tax`=:tax WHERE `id`=:id";
                         $this->db->update($sql, [":tax" => json_encode($taxdata), ":id" => $item['id']]);
                     } else {
                         echo "Item record " . $item['id'] . " already updated, skipping item table update...<br/>";
                     }
                 }
                 // remove the "notax taxdata field, update gst to id=1"
                 $sql = "SELECT * FROM `sales`;";
                 $sales = $this->db->select($sql, []);
                 foreach ($sales as $sale) {
                     $needsupdate = false;
                     $data = json_decode($sale['data']);
                     if ($data == false) {
                         die("Prevented null data entry");
                     }
                     if (isset($data->taxdata->{"1"}) && $data->taxdata->{"1"} == 0) {
                         if (isset($data->taxdata->{"2"})) {
                             $data->taxdata->{"1"} = $data->taxdata->{"2"};
                             unset($data->taxdata->{"2"});
                         } else {
                             unset($data->taxdata->{"1"});
                         }
                         $needsupdate = true;
                     } else {
                         echo "Record " . $sale['id'] . " already updated, skipping sale taxdata update...<br/>";
                     }
                     foreach ($data->items as $skey => $sitem) {
                         if (is_numeric($sitem->tax)) {
                             $taxdata = new stdClass();
                             $taxdata->values = new stdClass();
                             $taxdata->inclusive = true;
                             if ($sitem->tax > 0) {
                                 $taxdata->values->{"1"} = $sitem->tax;
                                 $taxdata->total = $sitem->tax;
                             } else {
                                 $taxdata->total = 0;
                             }
                             $data->items[$skey]->tax = $taxdata;
                             $needsupdate = true;
                         } else {
                             echo "Item record " . $sale['id'] . " already updated, skipping sale itemdata update...<br/>";
                         }
                     }
                     if ($needsupdate) {
                         $sql = "UPDATE `sales` SET `data`=:data WHERE `id`=:saleid";
                         $this->db->update($sql, [":data" => json_encode($data), ":saleid" => $sale['id']]);
                     }
                 }
                 // update stored item schema
                 $sql = "SELECT * FROM `stored_items`;";
                 $items = $this->db->select($sql, []);
                 $error = false;
                 foreach ($items as $item) {
                     if ($item['data'] == "") {
                         $id = $item['id'];
                         unset($item['id']);
                         $item['type'] = "general";
                         $item['modifiers'] = new stdClass();
                         $data = json_encode($item);
                         if ($data != false) {
                             $sql = "UPDATE `stored_items` SET `data`=:data WHERE `id`=:id";
                             if (!$this->db->update($sql, [":data" => $data, ":id" => $id])) {
                                 $error = true;
                             }
                         }
                     }
                 }
                 if (!$error) {
                     $sql = "ALTER TABLE `stored_items` DROP `qty`, DROP `description`, DROP `taxid`;";
                     $this->db->update($sql, []);
                 }
                 // update devices schema
                 $sql = "SELECT * FROM `devices`;";
                 $devices = $this->db->select($sql, []);
                 foreach ($devices as $device) {
                     if ($device['data'] == "") {
                         $data = new stdClass();
                         $data->name = $device['name'];
                         $data->locationid = $device['locationid'];
                         $data->type = "general_register";
                         $data->ordertype = "terminal";
                         $data->orderdisplay = 1;
                         $data->kitchenid = 0;
                         $data = json_encode($data);
                         if ($data != false) {
                             $sql = "UPDATE `devices` SET `data`=:data WHERE `id`=:id";
                             $this->db->update($sql, [":data" => $data, ":id" => $device['id']]);
                         }
                     } else {
                         echo "Device record " . $device['id'] . " already updated, skipping sale itemdata update...<br/>";
                     }
                 }
                 WposAdminSettings::putValue('general', 'currencyformat', '$~2~.~,~0');
                 WposAdminSettings::putValue('general', 'version', '1.2');
         }
         // restart node server
         $socket = new WposSocketControl();
         $socket->restartSocketServer(['error' => 'OK']);
         return "Update Completed Successfully!";
     } catch (Exception $e) {
         echo $this->db->_db->errorInfo()[0];
         return $e->getMessage();
     }
 }
 /**
  * Set new token set in the config
  * @param $token
  */
 private static function setNewAccessToken($token)
 {
     // set new access token in the config
     WposAdminSettings::putValue('general', 'gcontacttoken', $token);
 }
Example #5
0
 /**
  * Statically update customer data
  * @param $data
  * @return bool|string
  */
 public static function updateCustomerData($data)
 {
     $settings = WposAdminSettings::getSettingsObject('general');
     $custMdl = new CustomerModel();
     $gid = null;
     if ($settings->gcontact == 1) {
         // get google id
         $gid = $custMdl->get($data->id)[0]['googleid'];
         if ($gid) {
             // edit google
             $gres = GoogleIntergration::setGoogleContact($settings, $data, $gid);
         } else {
             // add google
             $gres = GoogleIntergration::setGoogleContact($settings, $data);
         }
         if ($gres[0] == true) {
             $gid = $gres[1];
         }
     }
     $qresult = $custMdl->edit($data->id, $data->email, $data->name, $data->phone, $data->mobile, $data->address, $data->suburb, $data->postcode, $data->state, $data->country, $data->notes, $gid);
     if ($qresult === false) {
         return "Could not edit the customer: " . $custMdl->errorInfo;
     } else {
         // log data
         Logger::write("Customer updated with id:" . $data->id, "CUSTOMER", json_encode($data));
         return true;
     }
 }
Example #6
0
 /**
  * Email the sale receipt to the specified address
  * @param $email
  * @return mixed
  */
 private function emailReceipt($email)
 {
     // get config
     $config = new WposAdminSettings();
     $recval = $config->getSettingsObject("pos");
     $genval = $config->getSettingsObject("general");
     $utils = new WposAdminUtilities();
     $utils->setCurrencyFormat($genval->currencyformat);
     // create receipt
     $html = '<div style="padding: 10px; padding-left: 5px; padding-right: 5px; margin-top:5px; width:300px; margin: auto; background-color:#FFFFFF;"><img width="95%" src="http://' . $_SERVER['SERVER_ADDR'] . $recval->recemaillogo . '"/><br/>';
     $html .= '<h3 style="text-align: center; margin: 5px;">' . $genval->bizname . '</h3>';
     $html .= '<p style="text-align: center"><strong>' . $recval->recline2 . '</strong>';
     if ($recval->recline3 != "") {
         $html .= '<br/><strong style="text-align: center">' . $recval->recline3 . '</strong>';
     }
     $html .= '</p>';
     // body
     $html .= '<p style="padding-top: 5px;">Transaction Ref:&nbsp;&nbsp;' . $this->ref . '<br/>';
     $html .= 'Sale Time:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . WposAdminUtilities::getDateFromTimeStamp($this->jsonobj->processdt, $genval->dateformat) . '</p>';
     // items
     $html .= '<table style="width: 100%; margin-bottom: 4px; font-size: 13px;">';
     foreach ($this->jsonobj->items as $item) {
         // item mod details
         $modStr = "";
         if (isset($item->mod)) {
             foreach ($item->mod->items as $mod) {
                 $modStr .= '<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . (isset($mod->qty) ? ($mod->qty > 0 ? '+ ' : '') . $mod->qty . ' ' : '') . $mod->name . (isset($mod->value) ? ': ' . $mod->value : '') . ' (' . $utils->currencyFormat($mod->price) . ')';
             }
         }
         $html .= '<tr><td>' . $item->qty . "x " . $item->name . " (" . $utils->currencyFormat($item->unit) . ")" . $modStr . '</td><td style="text-align: right;">' . $utils->currencyFormat($item->price) . '</td></tr>';
     }
     $html .= '<tr style="height: 5px;"><td></td><td></td></tr>';
     // totals
     // subtotal
     $taxcount = count(get_object_vars($this->jsonobj->taxdata));
     if ($taxcount > 0 || $this->jsonobj->discount > 0) {
         // only add if discount or taxes
         $html .= '<tr><td><b>Subtotal: </b></td><td style="text-align: right;"><b style="text-decoration: overline;">' . $utils->currencyFormat($this->jsonobj->subtotal) . '</b></td></tr>';
     }
     // taxes
     if ($taxcount) {
         $taxMdl = new TaxItemsModel();
         $taxes = $taxMdl->get();
         foreach ($taxes as $tax) {
             $taxes[$tax['id']] = $tax;
         }
         foreach ($this->jsonobj->taxdata as $key => $tax) {
             $taxstr = $taxes[$key];
             $taxstr = $taxstr['name'] . ' (' . $taxstr['value'] . '%)';
             $html .= '<tr><td>' . $taxstr . ':</td><td style="text-align: right;">' . $utils->currencyFormat($tax) . '</td></tr>';
         }
     }
     // discount
     $html .= $this->jsonobj->discount > 0 ? '<tr><td>' . $this->jsonobj->discount . '% Discount</td><td style="text-align: right;">' . $utils->currencyFormat(abs(floatval($this->jsonobj->total) - (floatval($this->jsonobj->subtotal) + floatval($this->jsonobj->tax)))) . '</td></tr>' : '';
     // grand total
     $html .= '<tr><td><b>Total (' . $this->jsonobj->numitems . ' items): </b></td><td style="text-align: right;"><b style="text-decoration: overline;">' . $utils->currencyFormat($this->jsonobj->total) . '</b></td></tr>';
     $html .= '<tr style="height: 2px;"><td></td><td></td></tr>';
     // payments
     foreach ($this->jsonobj->payments as $payment) {
         $html .= '<tr><td><span style="font-size: 14px;">' . ucfirst($payment->method) . '</p></td><td style="text-align: right;"><p style="font-size: 14px;">' . $utils->currencyFormat($payment->amount) . '</span></td></tr>';
         if ($payment->method == 'cash') {
             // If cash print tender & change
             $html .= '<tr><td>Tendered:</td><td style="text-align: right;">' . $utils->currencyFormat($payment->tender) . '</td></tr>';
             $html .= '<tr><td>Change:</td><td style="text-align: right;">' . $utils->currencyFormat($payment->change) . '</td></tr>';
         }
     }
     $html .= '</table>';
     // refunds
     if (isset($this->jsonobj->refunddata)) {
         $html .= '<p style="margin-top: 0; margin-bottom: 5px; font-size: 13px;"><strong>Refund</strong></p><table style="width: 100%; font-size: 13px;">';
         foreach ($this->jsonobj->refundata as $refund) {
             $html .= '<tr><td>' . WposAdminUtilities::getDateFromTimeStamp($refund->processdt, $genval->dateformat) . ' (' . sizeof($refund->items) . ' items)</td><td>' . ucfirst($refund->method) . '<span style="float: right;">' . $refund->amount . '</span></td></tr>';
         }
         $html .= '</table>';
     }
     // void
     if (isset($this->jsonobj->voiddata)) {
         $html .= '<h2 style="text-align: center; color: #dc322f; margin-top: 5px;">VOID SALE</h2>';
     }
     // footer
     $html .= '<p style="text-align: center;"><strong>' . $recval->recfooter . '</strong><br/>';
     if ($recval->recqrcode != "") {
         $html .= '<img style="text-align: center;" height="99" src="http://' . $_SERVER['SERVER_ADDR'] . '/wpos/asset/images/qrcode.png"/>';
     }
     $html .= '</p></div>';
     $template = '<html><head><link media="all" href="https://' . $_SERVER['SERVER_NAME'] . '/wpos/admin/assets/css/bootstrap.min.css" rel="stylesheet"/><link media="all" rel="stylesheet" href="https://' . $_SERVER['SERVER_NAME'] . '/wpos/admin/assets/css/font-awesome.min.css"/><link media="all" rel="stylesheet" href="https://' . $_SERVER['SERVER_NAME'] . '/wpos/admin/assets/css/ace-fonts.css"/><link media="all" rel="stylesheet" href="https://' . $_SERVER['SERVER_ADDR'] . '/wpos/admin/assets/css/ace.min.css"/></head><body>%message%</body>';
     $html = str_replace("%message%", $html, $template);
     $wposMail = new WposMail($genval);
     if (($mresult = $wposMail->sendHtmlEmail($email, 'Your ' . $genval->bizname . ' receipt', $html)) !== true) {
         return 'Failed to email receipt: ' . $mresult;
     } else {
         return true;
     }
 }
 /**
  * Generate invoice html
  * @return string
  */
 private function generateInvoiceHtml()
 {
     // copy invoice data, set tax values
     /** @noinspection PhpUnusedLocalVariableInspection */
     $invoice = $this->trans;
     $taxMdl = new TaxItemsModel();
     $taxdata = $taxMdl->get();
     $taxes = [];
     foreach ($taxdata as $value) {
         $taxes[$value['id']] = (object) $value;
     }
     // Get general settings
     $config = new WposAdminSettings();
     $settings = $config->getSettingsObject("general");
     $settings->payinst = $config->getSettingsObject("invoice")->payinst;
     // Get customer record
     $custMdl = new CustomerModel();
     /** @noinspection PhpUnusedLocalVariableInspection */
     $customer = (object) $custMdl->get($this->trans->custid)[0];
     $utils = new WposAdminUtilities();
     $utils->setCurrencyFormat($settings->currencyformat);
     // start output buffer and capture template output
     ob_start();
     include $_SERVER['DOCUMENT_ROOT'] . "/docs/templates/invoice.php";
     $html = ob_get_contents();
     ob_end_clean();
     return $html;
 }
Example #8
0
 /**
  * Get admin dash specific aux values
  * @param array $result current result array
  * @return array API result array
  */
 public function getAdminConfig($result)
 {
     $result['data'] = new stdClass();
     $WposConfig = new WposAdminSettings();
     // Get general & global pos configuration
     $settings = $WposConfig->getAllSettings();
     if ($settings === false) {
         $result['error'] = "Global config could not be retrieved!";
     }
     $result['data']->general = $settings['general'];
     $result['data']->pos = $settings['pos'];
     $result['data']->invoice = $settings['invoice'];
     // get devices and locations
     if (($result['data']->devices = $this->getDevices()) === false || ($result['data']->locations = $this->getLocations()) === false) {
         $result['error'] = "Device or Location info could not be retrieved!";
     }
     // get users
     if (($result['data']->users = $this->getUsers()) === false) {
         $result['error'] = "User info could not be retrieved!";
     }
     // get tax
     if (($result['data']->tax = $this->getTaxRecords()) === false) {
         $result['error'] = "Tax config could not be retrieved!";
     }
     return $result;
 }
Example #9
0
 /**
  * If stime & etime are not set, This function returns sales using the provided devices ID, using POS configuration values.
  *
  * @param $result
  * @return mixed
  */
 public function getSales($result)
 {
     if (!isset($this->data->stime) || !isset($this->data->etime)) {
         // time not set, retrieving POS records, get config.
         $WposConfig = new WposAdminSettings();
         $config = $WposConfig->getSettingsObject("pos");
         // set the sale range based on the config setting
         $etime = time() * 1000;
         $stime = strtotime("-1 " . (isset($config->salerange) ? $config->salerange : "week")) * 1000;
         // determine which devices transactions to include based on config
         if (isset($this->data->deviceid)) {
             switch ($config->saledevice) {
                 case "device":
                     break;
                     // no need to do anything, id already set
                 // no need to do anything, id already set
                 case "all":
                     unset($this->data->deviceid);
                     // unset the device id to get all sales
                     break;
                 case "location":
                     // get location device id array
                     $devMdl = new DevicesModel();
                     $this->data->deviceid = $devMdl->getLocationDeviceIds($this->data->deviceid);
             }
         }
     } else {
         $stime = $this->data->stime;
         $etime = $this->data->etime;
     }
     // Get all transactions within the specified timeframe/devices
     $salesMdl = new SalesModel();
     $dbSales = $salesMdl->getRangeWithRefunds($stime, $etime, isset($this->data->deviceid) ? $this->data->deviceid : null);
     if (is_array($dbSales)) {
         $sales = [];
         foreach ($dbSales as $sale) {
             $sales[$sale['ref']] = json_decode($sale['data'], true);
         }
         $result['data'] = $sales;
     } else {
         if ($dbSales === false) {
             $result['error'] = $salesMdl->errorInfo;
         }
     }
     return $result;
 }
Example #10
0
 private static function getXeroXml($stime, $etime)
 {
     $Wstat = new WposAdminStats();
     $Wstat->setRange($stime, $etime);
     $Wstat->setType('sale');
     $taxStats = $Wstat->getTaxStats([]);
     if (!$taxStats['data']) {
         return "Could not generate export item data: " . $taxStats['error'];
     }
     $payStats = $Wstat->getCountTakingsStats([]);
     if (!$payStats['data']) {
         return "Could not generate export payment data " . $taxStats['error'];
     }
     // get account map
     $accnmap = WposAdminSettings::getSettingsObject("accounting")->xeroaccnmap;
     if ($accnmap == '') {
         return "Xero integration setup not completed, please save account mappings first.";
     }
     // Setup invoice xml
     $invoice = new SimpleXMLElement("<Invoice/>");
     $date = date("Y-m-d", round($etime / 1000));
     $invoice->addChild("Type", "ACCREC");
     $invoice->addChild("Date", $date);
     $invoice->addChild("DueDate", $date);
     $invoice->addChild("InvoiceNumber", "POS-" . str_replace('-', '', $date));
     $invoice->addChild("Reference", "POS Sales");
     $invoice->addChild("LineAmountTypes", "Inclusive");
     $invoice->addChild("Status", "AUTHORISED");
     $contact = $invoice->addChild("Contact");
     $contact->addChild("Name", "POS Sales");
     // Setup refunds xml
     $cnote = new SimpleXMLElement("<CreditNote/>");
     $cnote->addChild("Type", "ACCRECCREDIT");
     $cnote->addChild("Date", $date);
     $cnote->addChild("CreditNoteNumber", "POSR-" . str_replace('-', '', $date));
     $cnote->addChild("Reference", "POS Refunds");
     $cnote->addChild("LineAmountTypes", "Inclusive");
     $cnote->addChild("Status", "AUTHORISED");
     $ccontact = $cnote->addChild("Contact");
     $ccontact->addChild("Name", "POS Sales");
     // Generate line items for each payment method and add types
     $lineItems = $invoice->addChild("LineItems");
     $clineItems = $cnote->addChild("LineItems");
     foreach ($taxStats['data'] as $key => $data) {
         if ($key != 0) {
             $taxType = isset($accnmap->{"tax-" . $key}) ? $accnmap->{"tax-" . $key} : '';
             // Add sales
             $accountCode = isset($accnmap->sales) ? $accnmap->sales : '';
             if ($data->saletotal > 0) {
                 $lineItem = $lineItems->addChild("LineItem");
                 $lineItem->addChild("Quantity", 1);
                 $lineItem->addChild("Description", $data->name . " Sales");
                 $lineItem->addChild("UnitAmount", str_replace(',', '', $data->saletotal + $data->saletax));
                 $lineItem->addChild("AccountCode", $accountCode);
                 $lineItem->addChild("TaxType", $taxType);
             }
             // Add refunds
             if ($data->refundtotal > 0) {
                 //$accountCode = (isset($accnmap->refunds)?$accnmap->refunds:'');
                 $clineItem = $clineItems->addChild("LineItem");
                 $clineItem->addChild("Quantity", 1);
                 $clineItem->addChild("Description", $data->name . " Refunds");
                 $clineItem->addChild("UnitAmount", str_replace(',', '', $data->refundtotal + $data->refundtax));
                 $clineItem->addChild("AccountCode", $accountCode);
                 $clineItem->addChild("TaxType", $taxType);
             }
         } else {
             if ($data->total != 0) {
                 // add cash rounding
                 $taxType = isset($accnmap->{"tax-" . $key}) ? $accnmap->{"tax-" . $key} : '';
                 $accountCode = isset($accnmap->sales) ? $accnmap->sales : '';
                 $clineItem = $lineItems->addChild("LineItem");
                 $clineItem->addChild("Quantity", 1);
                 $clineItem->addChild("Description", "Cash Rounding");
                 $clineItem->addChild("UnitAmount", str_replace(',', '', $data->total));
                 $clineItem->addChild("AccountCode", $accountCode);
                 $clineItem->addChild("TaxType", $taxType);
             }
         }
     }
     // Setup payments xml
     $payments = new SimpleXMLElement("<Payments/>");
     foreach ($payStats['data'] as $key => $data) {
         if ($key != 'Unaccounted') {
             if ($data->saletotal > 0) {
                 // Add Payment
                 $payment = $payments->addChild("Payment");
                 $payment->addChild("Date", $date);
                 $payment->addChild("Reference", ucfirst($key) . " POS Payments");
                 $payment->addChild("Amount", str_replace(',', '', $data->saletotal));
                 $pinv = $payment->addChild("Invoice");
                 $pinv->addChild("InvoiceNumber", "POS-" . str_replace('-', '', $date));
                 if ($key == "eftpos" || $key == "credit") {
                     $key = "card";
                 }
                 $accountCode = isset($accnmap->{"pay-" . $key}) ? $accnmap->{"pay-" . $key} : '';
                 $paccn = $payment->addChild("Account");
                 $paccn->addChild("Code", $accountCode);
             }
             if ($data->refundtotal > 0) {
                 // Add Payment
                 $payment = $payments->addChild("Payment");
                 $payment->addChild("Date", $date);
                 $payment->addChild("Reference", ucfirst($key) . " POS Refunds");
                 $payment->addChild("Amount", str_replace(',', '', $data->refundtotal));
                 $pinv = $payment->addChild("CreditNote");
                 $pinv->addChild("CreditNoteNumber", "POSR-" . str_replace('-', '', $date));
                 if ($key == "eftpos" || $key == "credit" || $key == "tyro") {
                     $key = "card";
                 }
                 $accountCode = isset($accnmap->{"pay-" . $key}) ? $accnmap->{"pay-" . $key} : '';
                 $paccn = $payment->addChild("Account");
                 $paccn->addChild("Code", $accountCode);
             }
         }
     }
     return ['invoice' => $invoice, 'creditnote' => $clineItems->count() > 0 ? $cnote : false, 'payments' => $payments];
 }
Example #11
0
function getCurrentVersion()
{
    try {
        $settings = WposAdminSettings::getSettingsObject("general");
        if (isset($settings->version)) {
            return $settings->version;
        }
    } catch (Exception $ex) {
    }
    return 0;
}
Example #12
0
/**
 * routes api calls and returns the result, allows for multiple API calls at once
 * @param $action
 * @param $data
 * @param $result
 * @return array|mixed
 */
function routeApiCall($action, $data, $result)
{
    global $auth;
    $notinprev = false;
    // Check for action in unprotected area (does not require permission)
    switch ($action) {
        // POS Specific
        case "config/get":
            $setup = new WposPosSetup($data);
            $result = $setup->getDeviceRecord($result);
            break;
        case "items/get":
            $jsondata = new WposPosData();
            $result = $jsondata->getItems($result);
            break;
        case "sales/get":
            $jsondata = new WposPosData($data);
            $result = $jsondata->getSales($result);
            break;
        case "tax/get":
            $jsondata = new WposPosData();
            $result = $jsondata->getTaxes($result);
            break;
        case "customers/get":
            $jsondata = new WposPosData();
            $result = $jsondata->getCustomers($result);
            break;
        case "devices/get":
            $jsondata = new WposPosData();
            $result = $jsondata->getPosDevices($result);
            break;
        case "locations/get":
            $jsondata = new WposPosData();
            $result = $jsondata->getPosLocations($result);
            break;
        case "orders/set":
            $sale = new WposPosSale($data);
            $result = $sale->setOrder($result);
            break;
        case "orders/remove":
            $sale = new WposPosSale($data);
            $result = $sale->removeOrder($result);
            break;
        case "sales/add":
            $sale = new WposPosSale($data);
            $result = $sale->insertTransaction($result);
            break;
        case "sales/void":
            // also used for sale refunds
            $sale = new WposPosSale($data, false);
            $result = $sale->insertVoid($result);
            break;
        case "sales/search":
            $sale = new WposPosData();
            if (isset($data)) {
                $result = $sale->searchSales($data, $result);
            }
            break;
        case "sales/updatenotes":
            $sale = new WposPosSale($data, false);
            $result = $sale->updateTransationNotes($result);
            break;
        case "transactions/get":
            $trans = new WposTransactions($data);
            $result = $trans->getTransaction($result);
            break;
        default:
            $notinprev = true;
    }
    if ($notinprev == false) {
        // an action has been executed: return the data
        return $result;
    }
    // Check if user is allowed to use this API request
    if ($auth->isUserAllowed($action) === false) {
        $result['errorCode'] = "priv";
        $result['error'] = "You do not have permission to perform this action.";
        return $result;
    }
    // Check in permission protected API calls
    switch ($action) {
        // admin only
        // device setup
        case "devices/setup":
            $setup = new WposPosSetup($data);
            $result = $setup->setupDevice($result);
            break;
            // stored items
        // stored items
        case "adminconfig/get":
            $setupMdl = new WposPosSetup();
            $result = $setupMdl->getAdminConfig($result);
            break;
        case "items/add":
            $adminMdl = new WposAdminItems($data);
            $result = $adminMdl->addStoredItem($result);
            break;
        case "items/edit":
            $adminMdl = new WposAdminItems($data);
            $result = $adminMdl->updateStoredItem($result);
            break;
        case "items/delete":
            $adminMdl = new WposAdminItems($data);
            $result = $adminMdl->deleteStoredItem($result);
            break;
            // suppliers
        // suppliers
        case "suppliers/get":
            $jsondata = new WposPosData();
            $result = $jsondata->getSuppliers($result);
            break;
        case "suppliers/add":
            $adminMdl = new WposAdminItems($data);
            $result = $adminMdl->addSupplier($result);
            break;
        case "suppliers/edit":
            $adminMdl = new WposAdminItems($data);
            $result = $adminMdl->updateSupplier($result);
            break;
        case "suppliers/delete":
            $adminMdl = new WposAdminItems($data);
            $result = $adminMdl->deleteSupplier($result);
            break;
            // suppliers
        // suppliers
        case "stock/get":
            $jsondata = new WposPosData();
            $result = $jsondata->getStock($result);
            break;
        case "stock/add":
            $stockMdl = new WposAdminStock($data);
            $result = $stockMdl->addStock($result);
            break;
        case "stock/set":
            $stockMdl = new WposAdminStock($data);
            $result = $stockMdl->setStockLevel($result);
            break;
        case "stock/transfer":
            $stockMdl = new WposAdminStock($data);
            $result = $stockMdl->transferStock($result);
            break;
        case "stock/history":
            $stockMdl = new WposAdminStock($data);
            $result = $stockMdl->getStockHistory($result);
            break;
            // customers
        // customers
        case "customers/add":
            $custMdl = new WposAdminCustomers($data);
            $result = $custMdl->addCustomer($result);
            break;
        case "customers/edit":
            $custMdl = new WposAdminCustomers($data);
            $result = $custMdl->updateCustomer($result);
            break;
        case "customers/delete":
            $custMdl = new WposAdminCustomers($data);
            $result = $custMdl->deleteCustomer($result);
            break;
        case "customers/contacts/add":
            $custMdl = new WposAdminCustomers($data);
            $result = $custMdl->addContact($result);
            break;
        case "customers/contacts/edit":
            $custMdl = new WposAdminCustomers($data);
            $result = $custMdl->updateContact($result);
            break;
        case "customers/contacts/delete":
            $custMdl = new WposAdminCustomers($data);
            $result = $custMdl->deleteContact($result);
            break;
            // TODO: Add to permissions
        // TODO: Add to permissions
        case "customers/setaccess":
            $custMdl = new WposAdminCustomers($data);
            $result = $custMdl->setAccess($result);
            break;
        case "customers/setpassword":
            $custMdl = new WposAdminCustomers($data);
            $result = $custMdl->setPassword($result);
            break;
        case "customers/sendreset":
            $custMdl = new WposAdminCustomers($data);
            $result = $custMdl->sendResetEmail($result);
            break;
            // End to-do
            // USERS
        // End to-do
        // USERS
        case "users/get":
            $data = new WposPosData();
            $result = $data->getUsers($result);
            break;
        case "users/add":
            $adminMdl = new WposAdminItems($data);
            $result = $adminMdl->addUser($result);
            break;
        case "users/edit":
            $adminMdl = new WposAdminItems($data);
            $result = $adminMdl->updateUser($result);
            break;
        case "users/delete":
            $adminMdl = new WposAdminItems($data);
            $result = $adminMdl->deleteUser($result);
            break;
        case "users/disable":
            $setup = new WposAdminItems($data);
            $result = $setup->setUserDisabled($result);
            break;
            // DEVICES
        // DEVICES
        case "devices/add":
            $setup = new WposPosSetup($data);
            $result = $setup->addDevice($result);
            break;
        case "devices/edit":
            $setup = new WposPosSetup($data);
            $result = $setup->updateDevice($result);
            break;
        case "devices/delete":
            $setup = new WposPosSetup($data);
            $result = $setup->deleteDevice($result);
            break;
        case "devices/disable":
            $setup = new WposPosSetup($data);
            $result = $setup->setDeviceDisabled($result);
            break;
            // LOCATIONS
        // LOCATIONS
        case "locations/add":
            $setup = new WposPosSetup($data);
            $result = $setup->addLocation($result);
            break;
        case "locations/edit":
            $setup = new WposPosSetup($data);
            $result = $setup->updateLocationName($result);
            break;
        case "locations/delete":
            $setup = new WposPosSetup($data);
            $result = $setup->deleteLocation($result);
            break;
        case "locations/disable":
            $setup = new WposPosSetup($data);
            $result = $setup->setLocationDisabled($result);
            break;
            // SALES (All transactions)
        // SALES (All transactions)
        case "sales/delete":
            $aSaleMdl = new WposTransactions($data);
            $result = $aSaleMdl->deleteSale($result);
            break;
        case "sales/deletevoid":
            $aSaleMdl = new WposTransactions($data);
            $result = $aSaleMdl->removeVoidRecord($result);
            break;
        case "sales/adminvoid":
            // the admin add void method, only requires sale id and reason
            $aSaleMdl = new WposTransactions($data);
            $result = $aSaleMdl->voidSale($result);
            break;
            // INVOICES
        // INVOICES
        case "invoices/get":
            $invMdl = new WposInvoices($data);
            $result = $invMdl->getInvoices($result);
            break;
        case "invoices/add":
            $invMdl = new WposInvoices($data);
            $result = $invMdl->createInvoice($result);
            break;
        case "invoices/edit":
            $invMdl = new WposInvoices($data);
            $result = $invMdl->updateInvoice($result);
            break;
        case "invoices/delete":
            $invMdl = new WposInvoices($data);
            $result = $invMdl->removeInvoice($result);
            break;
        case "invoices/items/add":
            $invMdl = new WposInvoices($data);
            $result = $invMdl->addItem($result);
            break;
        case "invoices/items/edit":
            $invMdl = new WposInvoices($data);
            $result = $invMdl->updateItem($result);
            break;
        case "invoices/items/delete":
            $invMdl = new WposInvoices($data);
            $result = $invMdl->removeItem($result);
            break;
        case "invoices/payments/add":
            $invMdl = new WposInvoices($data);
            $result = $invMdl->addPayment($result);
            break;
        case "invoices/payments/edit":
            $invMdl = new WposInvoices($data);
            $result = $invMdl->updatePayment($result);
            break;
        case "invoices/payments/delete":
            $invMdl = new WposInvoices($data);
            $result = $invMdl->removePayment($result);
            break;
        case "invoices/history/get":
            $invMdl = new WposTransactions($data);
            $result = $invMdl->getTransactionHistory($result);
            break;
        case "invoices/generate":
            $invMdl = new WposTransactions(null, $_REQUEST['id'], false);
            $invMdl->generateInvoice();
            break;
        case "invoices/email":
            $invMdl = new WposTransactions($data);
            $result = $invMdl->emailInvoice($result);
            break;
            // STATS
        // STATS
        case "stats/general":
            // general overview stats
            $statsMdl = new WposAdminStats($data);
            $result = $statsMdl->getOverviewStats($result);
            break;
        case "stats/takings":
            // account takings stats, categorized by payment method
            $statsMdl = new WposAdminStats($data);
            $result = $statsMdl->getCountTakingsStats($result);
            break;
        case "stats/itemselling":
            // whats selling, grouped by stored items
            $statsMdl = new WposAdminStats($data);
            $result = $statsMdl->getWhatsSellingStats($result);
            break;
        case "stats/supplyselling":
            // whats selling, grouped by suppliers
            $statsMdl = new WposAdminStats($data);
            $result = $statsMdl->getWhatsSellingStats($result, true);
            break;
        case "stats/stock":
            // current stock levels
            $statsMdl = new WposAdminStats($data);
            $result = $statsMdl->getStockLevels($result);
            break;
        case "stats/devices":
            // whats selling, grouped by stored items
            $statsMdl = new WposAdminStats($data);
            $result = $statsMdl->getDeviceBreakdownStats($result);
            break;
        case "stats/locations":
            // whats selling, grouped by stored items
            $statsMdl = new WposAdminStats($data);
            $result = $statsMdl->getDeviceBreakdownStats($result, 'location');
            break;
        case "stats/users":
            // whats selling, grouped by stored items
            $statsMdl = new WposAdminStats($data);
            $result = $statsMdl->getDeviceBreakdownStats($result, 'user');
            break;
        case "stats/tax":
            // whats selling, grouped by stored items
            $statsMdl = new WposAdminStats($data);
            $result = $statsMdl->getTaxStats($result);
            break;
            // GRAPH
        // GRAPH
        case "graph/general":
            // like the general stats, but in graph form/time.
            $graphMdl = new WposAdminGraph($data);
            $result = $graphMdl->getOverviewGraph($result);
            break;
        case "graph/takings":
            // like the general stats, but in graph form/time.
            $graphMdl = new WposAdminGraph($data);
            $result = $graphMdl->getMethodGraph($result);
            break;
        case "graph/devices":
            // like the general stats, but in graph form/time.
            $graphMdl = new WposAdminGraph($data);
            $result = $graphMdl->getDeviceGraph($result);
            break;
        case "graph/locations":
            // like the general stats, but in graph form/time.
            $graphMdl = new WposAdminGraph($data);
            $result = $graphMdl->getLocationGraph($result);
            break;
            // Admin/Global Config
        // Admin/Global Config
        case "settings/get":
            $configMdl = new WposAdminSettings();
            $configMdl->setName($data->name);
            $result = $configMdl->getSettings($result);
            break;
        case "settings/general/get":
            $configMdl = new WposAdminSettings();
            $configMdl->setName("general");
            $result = $configMdl->getSettings($result);
            break;
        case "settings/pos/get":
            $configMdl = new WposAdminSettings();
            $configMdl->setName("pos");
            $result = $configMdl->getSettings($result);
            break;
        case "settings/invoice/get":
            $configMdl = new WposAdminSettings();
            $configMdl->setName("invoice");
            $result = $configMdl->getSettings($result);
            break;
        case "settings/set":
            $configMdl = new WposAdminSettings($data);
            $result = $configMdl->saveSettings($result);
            break;
        case "settings/general/set":
            $configMdl = new WposAdminSettings($data);
            $configMdl->setName("general");
            $result = $configMdl->saveSettings($result);
            break;
        case "settings/pos/set":
            $configMdl = new WposAdminSettings($data);
            $configMdl->setName("pos");
            $result = $configMdl->saveSettings($result);
            break;
        case "settings/invoice/set":
            $configMdl = new WposAdminSettings($data);
            $configMdl->setName("invoice");
            $result = $configMdl->saveSettings($result);
            break;
        case "settings/google/authinit":
            GoogleIntegration::initGoogleAuth();
            break;
        case "settings/google/authremove":
            GoogleIntegration::removeGoogleAuth();
            break;
        case "settings/xero/oauthinit":
            XeroIntegration::initXeroAuth();
            break;
        case "settings/xero/oauthcallback":
            XeroIntegration::processCallbackAuthCode();
            break;
        case "settings/xero/oauthremove":
            XeroIntegration::removeXeroAuth();
            break;
        case "settings/xero/configvalues":
            $result = XeroIntegration::getXeroConfigValues($result);
            break;
        case "settings/xero/export":
            $result = XeroIntegration::exportXeroSales($data->stime, $data->etime);
            break;
        case "node/status":
            $Sserver = new WposSocketControl();
            $result = $Sserver->isServerRunning($result);
            break;
        case "node/start":
            $Sserver = new WposSocketControl();
            $result = $Sserver->startSocketServer($result);
            break;
        case "node/stop":
            $Sserver = new WposSocketControl();
            $result = $Sserver->stopSocketServer($result);
            break;
        case "node/restart":
            $Sserver = new WposSocketControl();
            $result = $Sserver->restartSocketServer($result);
            break;
        case "db/backup":
            $util = new WposAdminUtilities();
            $util->backUpDatabase();
            break;
        case "logs/list":
            $result['data'] = Logger::ls();
            break;
        case "logs/read":
            $result['data'] = Logger::read($data->filename);
            break;
        case "file/upload":
            if (isset($_FILES['file'])) {
                $uploaddir = 'docs';
                $newpath = $uploaddir . DIRECTORY_SEPARATOR . basename($_FILES['file']['name']);
                if (move_uploaded_file($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . $_SERVER['APP_ROOT'] . $newpath) !== false) {
                    $result['data'] = ["path" => "/" . $newpath];
                } else {
                    $result['error'] = "There was an error uploading the file " . $newpath;
                }
            } else {
                $result['error'] = "No file selected";
            }
            break;
            // device message
        // device message
        case "message/send":
            $socket = new WposSocketIO();
            if ($data->device === null) {
                if (($error = $socket->sendBroadcastMessage($data->message)) !== true) {
                    $result['error'] = $error;
                }
            } else {
                $devid = intval($data->device);
                $devices = new stdClass();
                $devices->{$devid} = $devid;
                if (($error = $socket->sendMessageToDevices($devices, $data->message)) !== true) {
                    $result['error'] = $error;
                }
            }
            break;
            // device reset
        // device reset
        case "device/reset":
            $socket = new WposSocketIO();
            if ($data->device === null) {
                if (($error = $socket->sendResetCommand()) !== true) {
                    $result['error'] = $error;
                }
            } else {
                $devid = intval($data->device);
                $devices = new stdClass();
                $devices->{$devid} = $devid;
                if (($error = $socket->sendResetCommand($devices)) !== true) {
                    $result['error'] = $error;
                }
            }
            break;
        default:
            $result["error"] = "Action not defined: " . $action;
            break;
    }
    return $result;
}
 /**
  * Get general config used by customer dashboard
  * @param $result
  * @return mixed
  */
 public function getSettings($result)
 {
     $settings = WposAdminSettings::getSettingsObject('general');
     unset($settings->gcontacttoken);
     $taxMdl = new TaxItemsModel();
     $taxes = $taxMdl->get();
     $taxobj = [];
     foreach ($taxes as $tax) {
         $taxobj[$tax['id']] = $tax;
     }
     $setobj = ["general" => $settings, "tax" => $taxobj];
     $result['data'] = $setobj;
     return $result;
 }