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];
 }
 /**
  * Generate plot data using the specified type
  * @param $result
  * @param $graphtype
  * @return mixed
  */
 private function getGraph($result, $graphtype)
 {
     // validate input
     $jsonval = new JsonValidate($this->data, '{"stime":1, "etime":1, "interval":1}');
     if (($errors = $jsonval->validate()) !== true) {
         $result['error'] = $errors;
         return $result;
     }
     // Initialize the stats object
     $stats = new WposAdminStats(null);
     $graph = [];
     $serieslist = [];
     $interval = isset($this->data->interval) ? $this->data->interval : 86400000;
     // default interval is one day
     $curstime = isset($this->data->stime) ? $this->data->stime : strtotime('-1 week') * 1000;
     $curetime = intval($curstime) + intval($interval);
     $stopetime = isset($this->data->etime) ? $this->data->etime : time() * 1000;
     $tempstats = null;
     while ($curstime <= $stopetime) {
         $stats->setRange($curstime, $curetime);
         switch ($graphtype) {
             case 1:
                 $tempstats = $stats->getOverviewStats($result);
                 break;
             case 2:
                 $tempstats = $stats->getCountTakingsStats($result);
                 break;
             case 3:
                 $tempstats = $stats->getDeviceBreakdownStats($result);
                 break;
             case 4:
                 $tempstats = $stats->getDeviceBreakdownStats($result, 'location');
                 break;
         }
         if ($tempstats['error'] == "OK") {
             // put into series list
             foreach ($tempstats['data'] as $key => $value) {
                 $serieslist[$key] = $key;
             }
             // put into array
             $graph[$curstime] = $tempstats['data'];
         } else {
             $result['error'] .= $tempstats['error'];
             break;
         }
         // move to the next segment
         $curstime += $interval;
         $curetime += $interval;
     }
     // if it's not the general graph we need to loop through and fill in null data
     if ($graphtype != 1) {
         $defaultobj = new stdClass();
         $defaultobj->balance = 0;
         // loop through each series value and add 0 values for null data
         foreach ($graph as $ykey => $yvals) {
             //$result['error'].="\n".json_encode($yvals);
             foreach ($serieslist as $value) {
                 // use serieslist to spot null values
                 if ($yvals[$value] == null || empty($yvals)) {
                     // check if series key exists in current timeset
                     //$result['error'].="\nInserting default";
                     $yvals[$value] = $defaultobj;
                     $graph[$ykey] = $yvals;
                 }
             }
         }
     }
     $result['data'] = $graph;
     return $result;
 }
Exemple #3
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;
}