Example #1
0
 protected function _execute()
 {
     // Clean up id columns to be bigint(20)
     $this->_db_update_table_column('accounts', 'id', '`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT');
     $this->_db_update_table_column('settings', 'id', '`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT');
     $this->_db_update_table_column('taxes', 'id', '`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT');
     // Ensure that all foreign key columns are bigint(20)
     $this->_db_update_table_column('accounts', 'parent_account_id', '`parent_account_id` bigint(20) unsigned NULL DEFAULT NULL');
     $this->_db_update_table_column('account_reconciles', 'account_id', '`account_id` bigint(20) unsigned NULL DEFAULT NULL');
     $this->_db_update_table_column('entities', 'default_account_id', '`default_account_id` bigint(20) unsigned NULL DEFAULT NULL');
     $this->_db_update_table_column('users', 'role_id', '`role_id` bigint(20) unsigned NULL DEFAULT NULL');
     // Add indexes
     foreach ($this->_table_column_add_indexes as $table_name => $columns) {
         foreach ($columns as $column_name) {
             try {
                 $key_exist_check = DB::Query(Database::SELECT, 'SELECT COUNT(TABLE_NAME) as exist_check ' . 'FROM INFORMATION_SCHEMA.STATISTICS WHERE ' . 'TABLE_NAME = "' . $table_name . '" ' . 'AND COLUMN_NAME = "' . $column_name . '"')->execute()->as_array();
                 if ($key_exist_check[0]['exist_check'] == '0') {
                     DB::Query(NULL, 'ALTER TABLE `' . $table_name . '` ' . 'ADD INDEX(`' . $column_name . '`);')->execute();
                 }
             } catch (Exception $e) {
                 throw new Exception('An error occurred when adding an index (' . $table_name . '.' . $column_name . ') to the database: ' . $e->getMessage());
             }
         }
     }
     // Update quantity to three decimal places.
     $this->_db_update_table_column('form_lines', 'quantity', '`quantity` decimal( 13, 3 ) NULL DEFAULT NULL');
     return (object) array();
 }
Example #2
0
 protected function _execute()
 {
     // SELECT DISTINCT DESCRIPTIONS FIRST.
     $description_query = 'SELECT form_lines.description as description FROM form_lines RIGHT JOIN forms ON form_lines.form_id = forms.id ';
     $description_query .= ' WHERE forms.type = "sale" ';
     if ($this->_search_description) {
         foreach (explode(' ', $this->_search_description) as $search_description_term) {
             if (trim($search_description_term)) {
                 $description_query .= ' AND form_lines.description LIKE "%' . $search_description_term . '%" ';
             }
         }
     }
     $description_query .= ' GROUP BY form_lines.description LIMIT 10';
     $description_results = DB::Query(Database::SELECT, $description_query)->execute()->as_array();
     $sale_lines = array();
     foreach ($description_results as $description_result) {
         $line_query = 'SELECT form_lines.account_id as account_id, form_lines.amount as amount, form_lines.quantity as quantity, form_lines.total as total FROM form_lines RIGHT JOIN forms ON form_lines.forM_id = forms.id ';
         $line_query .= ' WHERE form_lines.description = "' . $description_result['description'] . '" ';
         $line_query .= ' AND forms.type = "sale" ';
         $line_query .= ' AND form_lines.amount >= 0 ';
         $line_query .= ' ORDER BY forms.date_created DESC LIMIT 1';
         $line_result = DB::Query(Database::SELECT, $line_query)->execute()->as_array();
         $sale_lines[] = (object) array('description' => $description_result['description'], 'amount' => $line_result[0]['amount'], 'quantity' => $line_result[0]['quantity'], 'total' => $line_result[0]['total'], 'account_id' => $line_result[0]['account_id']);
     }
     usort($sale_lines, array($this, '_sort_lines_by_description'));
     return (object) array("sale_lines" => $sale_lines);
 }
    public function action_index()
    {
        $driverposition = ORM::factory("driverposition");
        if (isset($_POST["delete"])) {
            DB::Query(Database::DELETE, '
				DELETE FROM driverpositions
				WHERE id != 1')->execute();
        } else {
            if (isset($_POST["driver_id"])) {
                $driver_id = json_decode($_POST["driver_id"]);
                $client_id = json_decode($_POST["client_id"]);
                $lat = json_decode($_POST["lat"]);
                $lng = json_decode($_POST["lng"]);
                $driverposition->driver_id = $driver_id;
                $driverposition->client_id = $client_id;
                $driverposition->lat = $lat;
                $driverposition->lng = $lng;
                $driverposition->notes = $notes;
                $driverposition->time = time();
                $driverposition->save();
            }
        }
        $drivers = ORM::factory("driverposition")->find_all();
        $view = View::factory('driverpositionupdate/index')->set('drivers', $drivers);
        $this->response->body($view);
    }
 public function __construct($controller, $name, $show_actions = true)
 {
     $TempBasketID = Store_BasketController::get_temp_basket_id();
     $order_id = DB::Query("SELECT id FROM `order` WHERE (`TempBasketID`='" . $TempBasketID . "')")->value();
     /* Basket GridField */
     $config = new GridFieldConfig();
     $dataColumns = new GridFieldDataColumns();
     $dataColumns->setDisplayFields(array('getPhoto' => "Photo", 'Title' => 'Product', 'Price' => 'Item Price', 'Quantity' => 'Quantity', 'productPrice' => 'Total Price', 'getfriendlyTaxCalculation' => 'Tax Inc/Exc', 'TaxClassName' => 'Tax'));
     $config->addComponent($dataColumns);
     $config->addComponent(new GridFieldTitleHeader());
     $basket = GridField::create("BasketItems", "", DataObject::get("Order_Items", "(OrderID='" . $order_id . "')"), $config);
     /* Basket Subtotal */
     $subtotal = new Order();
     $subtotal = $subtotal->calculateSubTotal($order_id);
     $subtotal = ReadonlyField::create("SubTotal", "Basket Total (" . Product::getDefaultCurrency() . ")", $subtotal);
     /* Fields */
     $fields = FieldList::create($basket, $subtotal, ReadonlyField::create("Tax", "Tax", "Calculated on the Order Summary page."));
     /* Actions */
     $actions = FieldList::create(CompositeField::create(FormAction::create('continueshopping', 'Continue Shopping'), FormAction::create('placeorder', 'Place Order')));
     /* Required Fields */
     $required = new RequiredFields(array());
     /*
      * Now we create the actual form with our fields and actions defined 
      * within this class.
      */
     return parent::__construct($controller, $name, $fields, $show_actions ? $actions : FieldList::create(), $required);
 }
 /**
  * Connect to a secondary MySQL database, execute the query and set the database to the default connection
  **/
 public static function query_remote($query)
 {
     self::connect_remote();
     $res = DB::Query($query);
     self::$insert_id = DB::getConn()->getGeneratedID('RestDataObject');
     self::return_to_default_config();
     return $res;
 }
Example #6
0
 /**
  * MAGIC METHOD called when property does not exist in config class
  * will save property values in config table based off of $column
  *
  * @param		string			$column
  * @param		string			$value
  * @return 		void
  */
 public function __set($column, $value)
 {
     if (array_key_exists($column, $this->config)) {
         $query = DB::Query(Database::UPDATE, 'UPDATE `config` SET `value` = :value WHERE `key` = :key');
         $query->param(':key', $column)->param(':value', $value);
         $query->execute('default');
     }
 }
 /**
  * 修改团购下线时间 
  */
 function edit_product_end_time($product_num, $end_time)
 {
     $team_id = DB::Exist('team', array('serv_code' => $product_num));
     if (!$team_id) {
         return $this->response('edit_product_end_time', '1006', '合作方无此产品的信息');
     }
     DB::Query("update team set end_time = " . $end_time . " where serv_code = " . $product_num);
     return $this->response('edit_product_end_time', '0000', '修改团购下线时间成功');
 }
Example #8
0
 private function _check_calibrate_forms()
 {
     $calibrate_transaction_ids_query = 'SELECT forms_transactions.* FROM (  ' . '    SELECT transactions.id as transaction_id,  ' . '        forms.id as form_id, ' . '        forms.type as form_type, ' . '        forms.create_transaction_id as create_transaction_id, ' . '        forms.invoice_transaction_id as invoice_transaction_id, ' . '        forms.cancel_transaction_id as cancel_transaction_id ' . '    FROM  ' . '    transactions INNER JOIN forms ' . '    ON transactions.form_id = forms.id  ' . ') forms_transactions  ' . 'WHERE ' . 'NOT(forms_transactions.transaction_id <=> forms_transactions.create_transaction_id) AND ' . 'NOT(forms_transactions.transaction_id <=> forms_transactions.invoice_transaction_id) AND ' . 'NOT(forms_transactions.transaction_id <=> forms_transactions.cancel_transaction_id) ';
     $calibrate_transaction_ids = DB::Query(Database::SELECT, $calibrate_transaction_ids_query)->execute()->as_array();
     if ($calibrate_transaction_ids && count($calibrate_transaction_ids)) {
         return TRUE;
     }
     return FALSE;
 }
Example #9
0
 protected function _execute()
 {
     $fye_date = $this->_get_books_closed_date();
     $purchase_ids = DB::Query(Database::SELECT, ' SELECT ' . ' id ' . ' FROM forms ' . ' WHERE ' . ' type = "purchase" AND ' . ' date_created > DATE("' . $fye_date . '") AND ' . ' ( ' . '   ( create_transaction_id IS NULL ) OR ' . '   ( date_billed IS NOT NULL AND invoice_transaction_id IS NULL ) OR ' . '   ( date_cancelled IS NOT NULL AND cancel_transaction_id IS NULL ) ' . ' ) ')->execute()->as_array();
     $ids = array();
     foreach ($purchase_ids as $purchase_id) {
         $ids[] = $purchase_id['id'];
     }
     return (object) array('ids' => $ids);
 }
 /**
  * ImageGalleryAlbumItems()
  * @note gets ImageGalleryItems for an ImageGalleryAlbum record
  * @note we don't use the ORM here as the image_gallery module may no longer exist in the code base
  */
 protected function ImageGalleryAlbumItems($album_id)
 {
     $items = array();
     if ($results = DB::Query("SELECT i.* FROM ImageGalleryItem i WHERE i.AlbumID = {$album_id}")) {
         foreach ($results as $record) {
             $items[] = $record;
         }
     }
     return $items;
 }
 /**
  * update_temp_order_addresses
  * Given the parameters, update an order record 
  * to use the correct addresses from the customers
  * address book.
  *
  * @param String $TempBasketID The TempBasketID for the current basket
  * @param String $AddressID The address to use
  * @param String $AddressType The address to update. Either shipping|billing.
  *
  * @return Boolean
  */
 public static function update_temp_order_addresses($TempBasketID, $AddressID, $AddressType)
 {
     /* The column to update */
     $Column = $AddressType == 'billing' ? "BillingAddressID" : "ShippingAddressID";
     /* Run the DB::Query */
     if (DB::Query("UPDATE `order` SET {$Column}='{$AddressID}' WHERE TempBasketID='{$TempBasketID}'")) {
         return true;
     } else {
         return false;
     }
 }
Example #12
0
function zuitu_upgrade($action, $version = 'V1.0')
{
    $result = zuitu_action($action, $version);
    if (is_array($result) && 'db' == $action) {
        foreach ($result as $onesql) {
            $r = DB::Query($onesql);
        }
        return true;
    }
    return $result;
}
Example #13
0
 function action_index()
 {
     $this->request->title = "Schedule Page";
     $hourHeight = 50;
     $borderWidth = 1;
     $db = Database::instance();
     $query = DB::Query(Database::SELECT, 'SELECT * FROM eventTypes', 'Model_User');
     $result = $query->execute();
     $eventTypes = $result->as_array('id');
     $query = DB::Query(Database::SELECT, "SELECT UNIX_TIMESTAMP(date(startTime)) as day,        max(hour(endTime)) as maxHour,        max(minute(endTime)) as maxMin,        min(hour(startTime)) as minHour,        min(minute(startTime)) as minMin        from events group by date(startTime)");
     $result = $query->execute();
     $hourData = $result->as_array('day');
     $query = DB::Query(Database::SELECT, "SELECT e.*,r.name AS roomName,date(e.startTime) as eventDate FROM events e JOIN rooms r ON (e.roomId=r.id)");
     $result = $query->execute();
     do {
         $day = strtotime($result->get('eventDate'));
         $startTime = strtotime($result->get('startTime'));
         $realEndTime = strtotime($result->get('endTime'));
         $endTime = $realEndTime;
         do {
             $sameDay = date('z', $startTime) == date('z', $endTime);
             if (!$sameDay) {
                 $endTime = strtotime(date('Y-m-d', $startTime) . 'T23:59:59' . date('O', $startTime));
             }
             $eventData = array('name' => $result->get('name'), 'length' => 1, 'startTime' => $startTime, 'endTime' => $endTime, 'startTimeString' => date('c', $startTime), 'endTimeString' => date('c', $endTime));
             foreach (range(1, 4) as $i) {
                 $eventTypeName = $result->get('eventType' . $i) ? $eventTypes[$result->get('eventType' . $i)]['nameKey'] : 'closed';
                 $eventData['type'][$eventTypeName] = 1;
             }
             $eventData['type'] = array_keys($eventData['type']);
             $eventData['length'] = (int) floor(($eventData['endTime'] - $eventData['startTime']) / 60 / 30);
             $data[$result->get('roomName')][$day][$startTime] = $eventData;
             if (!$sameDay) {
                 $hourData[$day]['maxHour'] = 23;
                 $hourData[$day]['maxMin'] = 00;
                 $startTime += 60 * 60 * 24;
                 /* = 1 day*/
                 $day += 60 * 60 * 24;
                 /* = 1 day*/
                 $startTime = strtotime(date('Y-m-d', $startTime) . 'T00:00:00' . date('O', $startTime));
                 $endTime = $realEndTime;
                 $hourData[$day]['minHour'] = 00;
                 $hourData[$day]['minMin'] = 00;
             }
         } while (!$sameDay);
     } while ($result->next() && $result->valid());
     $days = array_keys($hourData);
     $rooms = array_keys($data);
     sort($rooms);
     $this->template->content = View::factory('schedule/index', array('eventTypes' => $eventTypes, 'borderWidth' => $borderWidth, 'days' => $days, 'rooms' => $rooms, 'hourData' => $hourData, 'hourHeight' => $hourHeight, 'data' => $data));
     if (class_exists('DebugToolbar')) {
         echo DebugToolbar::render();
     }
 }
Example #14
0
function backup_import($fname)
{
    global $db;
    $sqls = file($fname);
    foreach ($sqls as $sql) {
        str_replace("\r", "", $sql);
        str_replace("\n", "", $sql);
        DB::Query($sql);
    }
    return true;
}
Example #15
0
 protected function _execute()
 {
     if ($this->_customer_id and !$this->_load_customer($this->_customer_id)->loaded()) {
         throw new Exception("Invalid report customer ID: customer not found.");
     }
     // Look up all sale IDs
     $sale_ids_query = 'SELECT id FROM forms WHERE type = "sale" AND date_due IS NULL AND date_cancelled IS NULL ';
     if ($this->_customer_id) {
         $sale_ids_query .= ' AND entity_id = "' . $this->_customer_id . '" ';
     }
     if ($this->_days_old_minimum) {
         $sale_ids_query .= ' AND date_created <= DATE("' . date("Y-m-d", strtotime("-" . $this->_days_old_minimum . " Days")) . '") ';
     }
     if ($this->_balance_filter) {
         if ($this->_balance_filter == "unpaid") {
             $sale_ids_query .= ' AND ( balance + total ) = 0 ';
         } else {
             if ($this->_balance_filter == "paid") {
                 $sale_ids_query .= ' AND ( balance + total ) != 0 ';
             } else {
                 throw new Exception("Invalid balance_filter: must be paid or unpaid.");
             }
         }
     }
     $sale_ids_query .= ' ORDER BY date_created ASC, id ASC ';
     $sale_ids = DB::Query(Database::SELECT, $sale_ids_query)->execute()->as_array();
     $customers = array();
     $timestamp_today = strtotime(date("Y-m-d"));
     $total_total = 0.0;
     $paid_total = 0.0;
     $balance_total = 0.0;
     foreach ($sale_ids as $sale_id) {
         $sale = ORM::Factory('form_sale', $sale_id);
         if (!isset($customers[$sale->entity_id])) {
             $customers[$sale->entity_id] = new stdClass();
             $customers[$sale->entity_id]->customer_name = $sale->entity->first_name . ' ' . $sale->entity->last_name;
             $customers[$sale->entity_id]->customer_company_name = $sale->entity->company_name;
             $customers[$sale->entity_id]->customer_phone_number = $sale->entity->phone_number;
             $customers[$sale->entity_id]->sales = array();
             $customers[$sale->entity_id]->total_total = 0.0;
             $customers[$sale->entity_id]->paid_total = 0.0;
             $customers[$sale->entity_id]->balance_total = 0.0;
         }
         $report_sale = (object) array('id' => $sale->id, 'date_created' => $sale->date_created, 'date_due' => $sale->date_due, 'sale_number' => $sale->code, 'balance' => $sale->balance * -1, 'total' => $sale->total, 'paid' => $sale->total - $sale->balance * -1, 'days_late' => round(($timestamp_today - strtotime($sale->date_created)) / 86400));
         $customers[$sale->entity_id]->total_total = $this->_beans_round($customers[$sale->entity_id]->total_total + $report_sale->total);
         $customers[$sale->entity_id]->paid_total = $this->_beans_round($customers[$sale->entity_id]->paid_total + $report_sale->paid);
         $customers[$sale->entity_id]->balance_total = $this->_beans_round($customers[$sale->entity_id]->balance_total + $report_sale->balance);
         $total_total = $this->_beans_round($total_total + $report_sale->total);
         $paid_total = $this->_beans_round($paid_total + $report_sale->paid);
         $balance_total = $this->_beans_round($balance_total + $report_sale->balance);
         $customers[$sale->entity_id]->sales[] = $report_sale;
     }
     return (object) array('date' => date("Y-m-d"), 'customer_id' => $this->_customer_id, 'days_old_minimum' => $this->_days_old_minimum, 'balance_filter' => $this->_balance_filter, 'customers' => $customers, 'total_customers' => count($customers), 'total_total' => $total_total, 'paid_total' => $paid_total, 'balance_total' => $balance_total);
 }
Example #16
0
 protected function _execute()
 {
     if (!$this->_account_reconcile->loaded()) {
         throw new Exception("Account reconciliation could not be found.");
     }
     $latest_reconciliation = ORM::Factory('account_reconcile')->where('account_id', '=', $this->_account_reconcile->account_id)->order_by('date', 'desc')->find();
     if ($latest_reconciliation->id != $this->_account_reconcile->id) {
         throw new Exception("Can only delete the most recent reconciliation for an account.");
     }
     DB::Query(NULL, ' UPDATE ' . ' account_transactions ' . ' SET ' . ' account_reconcile_id = NULL ' . ' WHERE ' . ' account_reconcile_id = ' . $this->_account_reconcile->id . ' ')->execute();
     $this->_account_reconcile->delete();
     return (object) array();
 }
Example #17
0
	static public function SongMultiByDate($score,$date){
		$sql = "UPDATE `user` SET `score` = `score` + ".$score." WHERE `create_time` <= ".$date;
		$result = DB::Query($sql);
		
		$u = array(
				'user_id' => 0,
				'admin_id' => 0,
				'score' => $score,
				'action' => 'multi',
				'detail_id' =>0,
				'create_time' => time(),
				'other_time'=>$date
		);
		return DB::Insert('credit', $u);
	}
Example #18
0
 function delete_feed($p = array())
 {
     $time = TIMESTAMP;
     if ($p['all']) {
         DB::Query("delete from " . DB::table('feed_log'));
     } elseif ($p['week']) {
         $time = $time - 7 * 24 * 3600;
         DB::Query("delete from " . DB::table('feed_log') . " where `dateline` < '{$time}'");
     } elseif ($p['month']) {
         $time = $time - 30 * 24 * 3600;
         DB::Query("delete from " . DB::table('feed_log') . " where `dateline` < '{$time}'");
     } elseif ($p['ids']) {
         $dids = is_array($p['ids']) ? $p['ids'] : (array) $p['ids'];
         DB::Query("delete from " . DB::table('feed_log') . " where `id` in(" . jimplode($dids) . ")");
     }
 }
Example #19
0
 function ImportSpeakersFromSched()
 {
     $feed = new RestfulService('http://openstacksummitoctober2015tokyo.sched.org/api/role/export?api_key=47dfbdc49d82ff16669df259952656fa&role=speaker&format=xml&fields=username,name,email', 7200);
     $feedXML = $feed->request()->getBody();
     $feedXML = preg_replace('/&(?!#?[a-z0-9]+;)/', '&amp;', $feedXML);
     $results = $feed->getValues($feedXML, 'speaker');
     // A new import overwrites previous data.
     // The table is trucated to remove previous entries and avoid duplicates.
     DB::Query("TRUNCATE SchedSpeaker");
     foreach ($results as $item) {
         $Speaker = new SchedSpeaker();
         $Speaker->username = $item->username;
         $Speaker->email = $item->email;
         $Speaker->name = $item->name;
         $Speaker->write();
     }
     echo "Speakers imported successfully.";
 }
Example #20
0
 protected function _execute()
 {
     if (!$this->_tax->loaded()) {
         throw new Exception("Tax could not be found.");
     }
     if (!$this->_date_start) {
         throw new Exception("Invalid date start: none provided.");
     }
     if ($this->_date_start != date("Y-m-d", strtotime($this->_date_start))) {
         throw new Exception("Invalid date start: must be in YYYY-MM-DD format.");
     }
     if (!$this->_date_end) {
         throw new Exception("Invalid date start: none provided.");
     }
     if ($this->_date_end != date("Y-m-d", strtotime($this->_date_end))) {
         throw new Exception("Invalid date start: must be in YYYY-MM-DD format.");
     }
     $periods = array('paid' => 'tax_payment_id IS NOT NULL AND date <= DATE("' . $this->_date_end . '") AND date >= DATE("' . $this->_date_start . '")', 'due' => 'tax_payment_id IS NULL AND date <= DATE("' . $this->_date_end . '")');
     $categories = array('invoiced' => 'type = "invoice"', 'refunded' => 'type = "refund"');
     $taxes = (object) array();
     $taxes->net = (object) array('form_line_amount' => 0.0, 'form_line_taxable_amount' => 0.0, 'amount' => 0.0);
     foreach ($periods as $period => $period_query) {
         $taxes->{$period} = (object) array();
         $taxes->{$period}->net = (object) array('form_line_amount' => 0.0, 'form_line_taxable_amount' => 0.0, 'amount' => 0.0);
         foreach ($categories as $category => $category_query) {
             $taxes->{$period}->{$category} = (object) array('form_line_amount' => 0.0, 'form_line_taxable_amount' => 0.0, 'amount' => 0.0, 'liabilities' => array());
             $tax_item_summaries_query = 'SELECT ' . 'form_id as form_id, ' . 'IFNULL(SUM(form_line_amount),0.00) as form_line_amount, ' . 'IFNULL(SUM(form_line_taxable_amount),0.00) as form_line_taxable_amount, ' . 'IFNULL(SUM(total),0.00) as amount, ' . 'type as type ' . 'FROM tax_items WHERE ' . 'tax_id = ' . $this->_tax->id . ' AND ' . $period_query . ' AND ' . $category_query . ' ' . 'GROUP BY form_id ';
             $tax_item_summaries = DB::Query(Database::SELECT, $tax_item_summaries_query)->execute()->as_array();
             foreach ($tax_item_summaries as $tax_item_summary) {
                 $taxes->net->form_line_amount = $this->_beans_round($taxes->net->form_line_amount + $tax_item_summary['form_line_amount']);
                 $taxes->net->form_line_taxable_amount = $this->_beans_round($taxes->net->form_line_taxable_amount + $tax_item_summary['form_line_taxable_amount']);
                 $taxes->net->amount = $this->_beans_round($taxes->net->amount + $tax_item_summary['amount']);
                 $taxes->{$period}->net->form_line_amount = $this->_beans_round($taxes->{$period}->net->form_line_amount + $tax_item_summary['form_line_amount']);
                 $taxes->{$period}->net->form_line_taxable_amount = $this->_beans_round($taxes->{$period}->net->form_line_taxable_amount + $tax_item_summary['form_line_taxable_amount']);
                 $taxes->{$period}->net->amount = $this->_beans_round($taxes->{$period}->net->amount + $tax_item_summary['amount']);
                 $taxes->{$period}->{$category}->form_line_amount = $this->_beans_round($taxes->{$period}->{$category}->form_line_amount + $tax_item_summary['form_line_amount']);
                 $taxes->{$period}->{$category}->form_line_taxable_amount = $this->_beans_round($taxes->{$period}->{$category}->form_line_taxable_amount + $tax_item_summary['form_line_taxable_amount']);
                 $taxes->{$period}->{$category}->amount = $this->_beans_round($taxes->{$period}->{$category}->amount + $tax_item_summary['amount']);
                 $taxes->{$period}->{$category}->liabilities[] = $this->_return_tax_liability_element($tax_item_summary['form_id'], $tax_item_summary['form_line_amount'], $tax_item_summary['form_line_taxable_amount'], $tax_item_summary['amount'], $tax_item_summary['type']);
             }
         }
     }
     return (object) array('tax' => $this->_return_tax_element($this->_tax), 'taxes' => $taxes, 'date_start' => $this->_date_start, 'date_end' => $this->_date_end);
 }
Example #21
0
	static public function BuyOne($order) {
		$order = Table::FetchForce('order', $order['id']);
		$order_id = abs(intval($order['id']));
		$team_id = abs(intval($order['team_id']));
		$team = Table::FetchForce('team', $order['team_id']);
		$plus = $team['conduser']=='Y' ? 1 : $order['quantity'];
		$team['now_number'] += $plus;

		/* close time */
		if ( $team['max_number']>0 
				&& $team['now_number'] >= $team['max_number'] ) {
			$team['close_time'] = time();
		}

		/* reach time */
		if ( $team['now_number']>=$team['min_number']
			&& $team['reach_time'] == 0 ) {
			$team['reach_time'] = time();
		}

		Table::UpdateCache('team', $team['id'], array(
			'close_time' => $team['close_time'],
			'reach_time' => $team['reach_time'],
			'now_number' => array( "`now_number` + {$plus}", ),
		));
		
		//UPDATE buy_id
		$SQL = "UPDATE `order` o,(SELECT max(buy_id)+1 AS c FROM `order` WHERE state = 'pay' and team_id = '{$team_id}') AS c SET o.buy_id = c.c, o.luky_id = 100000 + floor(rand()*100000) WHERE o.id = '{$order_id}' AND buy_id = 0;";
		DB::Query($SQL);
		/* send sms Immediately  */
		if(option_yes('buycouponsms')) sms_buy($order);
		/* cash flow */
		ZFlow::CreateFromOrder($order);
		/* order : send coupon ? */
		ZCoupon::CheckOrder($order);
		/* order : send voucher ? */
		ZVoucher::CheckOrder($order);
        /* order : send express sms ? */
		ZExpress::CheckOrder($order);
		/* order : invite buy */
		ZInvite::CheckInvite($order);
		
		ZCredit::UpdateFromOrder($order);
	}
Example #22
0
 public function delete_project($project_id)
 {
     // Delete all database entries related to project
     DB::delete('doc_clusters')->where('project_id', '=', $project_id)->execute();
     DB::delete('active_api_sources')->where('project_id', '=', $project_id)->execute();
     DB::delete('rss_feeds')->where('project_id', '=', $project_id)->execute();
     DB::delete('gather_log')->where('project_id', '=', $project_id)->execute();
     DB::delete('cluster_log')->where('project_id', '=', $project_id)->execute();
     DB::delete('keywords_phrases')->where('project_id', '=', $project_id)->execute();
     DB::delete('metadata_urls')->where('project_id', '=', $project_id)->execute();
     DB::Query(Database::DELETE, "DELETE FROM keyword_metadata USING metadata INNER JOIN keyword_metadata WHERE (metadata.project_id = {$project_id} AND metadata.meta_id = keyword_metadata.meta_id)")->execute();
     DB::Query(Database::DELETE, "DELETE FROM cached_text USING metadata INNER JOIN cached_text WHERE (metadata.project_id = {$project_id} AND metadata.meta_id = cached_text.meta_id)")->execute();
     DB::delete('metadata')->where('project_id', '=', $project_id)->execute();
     DB::delete('projects')->where('project_id', '=', $project_id)->limit(1)->execute();
     // Delete all data files: lemur files + charts
     $this->remove_dir(Kohana::config('myconf.lemur.indexes') . "/{$project_id}");
     $this->remove_dir(Kohana::config('myconf.lemur.docs') . "/{$project_id}");
     $this->remove_dir(Kohana::config('myconf.lemur.params') . "/{$project_id}");
     $this->remove_file(Kohana::config('myconf.path.charts') . "/cluster_{$project_id}.gch");
 }
 function run($request)
 {
     //set starting order number ID
     $number = EcommerceConfig::get("Order", "order_id_start_number");
     $currentMax = 0;
     //set order ID
     if ($number) {
         $count = DB::query("SELECT COUNT( \"ID\" ) FROM \"Order\" ")->value();
         if ($count > 0) {
             $currentMax = DB::Query("SELECT MAX( \"ID\" ) FROM \"Order\"")->value();
         }
         if ($number > $currentMax) {
             DB::query("ALTER TABLE \"Order\"  AUTO_INCREMENT = {$number} ROW_FORMAT = DYNAMIC ");
             DB::alteration_message("Change OrderID start number to " . $number, "created");
         } else {
             DB::alteration_message("Can not set OrderID start number to " . $number . " because this number has already been used.", "deleted");
         }
     } else {
         DB::alteration_message("Starting OrderID has not been set.", "deleted");
     }
 }
Example #24
0
 protected function _execute()
 {
     try {
         $exist_check = DB::Query(Database::SELECT, 'SELECT COUNT(COLUMN_NAME) as exist_check FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "account_transactions" AND COLUMN_NAME = "close_books"')->execute()->as_array();
         if ($exist_check[0]['exist_check'] == '0') {
             // Add the close_books column to account_transactions
             DB::Query(NULL, 'ALTER TABLE  `account_transactions` ADD `close_books` BOOLEAN NOT NULL DEFAULT FALSE')->execute();
             // Update account_transactions to properly reflect the change.
             DB::Query(Database::UPDATE, 'UPDATE account_transactions SET close_books = 1 WHERE transaction_id IN ( SELECT id FROM transactions WHERE close_books IS NOT NULL )')->execute();
         }
     } catch (Exception $e) {
         throw new Exception("An error occurred when migrating your database tables: " . $e->getMessage());
     }
     try {
         $accounts = DB::Query(DATABASE::SELECT, 'SELECT id FROM accounts WHERE parent_account_id IS NOT NULL')->execute()->as_array();
         foreach ($accounts as $account) {
             $previous_balance = 0.0;
             $calibrated_balance = 0.0;
             // Look up all transactions in order.
             $account_transactions = DB::Query(Database::SELECT, 'SELECT id,date,transaction_id,amount,balance FROM account_transactions WHERE account_id = "' . $account['id'] . '" ORDER BY date ASC, close_books DESC, transaction_id ASC')->execute()->as_array();
             foreach ($account_transactions as $account_transaction) {
                 $calibrated_balance = $account_transaction['balance'];
                 if (round($account_transaction['amount'] + $previous_balance, 2) != $calibrated_balance) {
                     $calibrated_balance = round($account_transaction['amount'] + $previous_balance, 2);
                 }
                 // Update if necessary.
                 if ($account_transaction['balance'] != $calibrated_balance) {
                     DB::Query(Database::UPDATE, 'UPDATE account_transactions SET balance = ' . $calibrated_balance . ' WHERE id = "' . $account_transaction['id'] . '"')->execute();
                 }
                 $previous_balance = $calibrated_balance;
             }
             $update_sql = 'UPDATE accounts SET ' . 'balance = ( SELECT IFNULL(SUM(bbalance),0.00) FROM (' . '		SELECT IFNULL(balance,0.00) as bbalance FROM ' . '		account_transactions as aaccount_transactions WHERE ' . '		account_id = "' . $account['id'] . '" ' . '		ORDER BY date DESC, close_books ASC, transaction_id DESC LIMIT 1 FOR UPDATE ' . ') as baccount_transactions ) ' . 'WHERE id = "' . $account['id'] . '"';
             $update_result = DB::Query(Database::UPDATE, $update_sql)->execute();
         }
     } catch (Exception $e) {
         // This is OK - we just need to warn them that the accounts need calibration.
     }
     return (object) array();
 }
Example #25
0
 protected function _execute()
 {
     if (!$this->_payment->loaded()) {
         throw new Exception("Payment could not be found.");
     }
     $form_ids_query = ' SELECT DISTINCT(account_transaction_forms.form_id) as form_id FROM account_transaction_forms ' . ' INNER JOIN account_transactions ON account_transaction_forms.account_transaction_id = account_transactions.id WHERE ' . ' account_transactions.transaction_id = ' . $this->_payment->id;
     $form_ids = DB::Query(Database::SELECT, $form_ids_query)->execute()->as_array();
     $handled_purchase_ids = array();
     foreach ($form_ids as $form_id) {
         $handled_purchase_ids[] = $form_id['form_id'];
     }
     $payment_date = $this->_payment->date;
     $payment_id = $this->_payment->id;
     $account_transaction_delete = new Beans_Account_Transaction_Delete($this->_beans_data_auth((object) array('id' => $this->_payment->id, 'payment_type_handled' => 'vendor')));
     $account_transaction_delete_result = $account_transaction_delete->execute();
     if (!$account_transaction_delete_result->success) {
         throw new Exception("Error cancelling payment: " . $account_transaction_delete_result->error);
     }
     // Recalibrate Vendor Invoices / Cancellations
     $vendor_purchase_calibrate_invoice = new Beans_Vendor_Purchase_Calibrate_Invoice($this->_beans_data_auth((object) array('ids' => $handled_purchase_ids)));
     $vendor_purchase_calibrate_invoice_result = $vendor_purchase_calibrate_invoice->execute();
     if (!$vendor_purchase_calibrate_invoice_result->success) {
         throw new Exception("UNEXPECTED ERROR: COULD NOT CALIBRATE VENDOR PURCHASES: " . $vendor_purchase_calibrate_invoice_result->error);
     }
     // Recalibrate Vendor Invoices / Cancellations
     $vendor_purchase_calibrate_cancel = new Beans_Vendor_Purchase_Calibrate_Cancel($this->_beans_data_auth((object) array('ids' => $handled_purchase_ids)));
     $vendor_purchase_calibrate_cancel_result = $vendor_purchase_calibrate_cancel->execute();
     if (!$vendor_purchase_calibrate_cancel_result->success) {
         throw new Exception("UNEXPECTED ERROR: COULD NOT CALIBRATE VENDOR PURCHASES: " . $vendor_purchase_calibrate_cancel_result->error);
     }
     // Recalibrate any payments tied to these purchases AFTER this transaction.
     $vendor_payment_calibrate = new Beans_Vendor_Payment_Calibrate($this->_beans_data_auth((object) array('form_ids' => $handled_purchase_ids)));
     $vendor_payment_calibrate_result = $vendor_payment_calibrate->execute();
     if (!$vendor_payment_calibrate_result->success) {
         throw new Exception("UNEXPECTED ERROR: COULD NOT CALIBRATE VENDOR PAYMENTS: " . $vendor_payment_calibrate_result->error);
     }
     return (object) array();
 }
Example #26
0
 protected function _execute()
 {
     // Remove extraneous BEANS_VERSION setting
     $version_settings = ORM::Factory('setting')->where('key', '=', 'BEANS_VERSION')->find_all();
     if (count($version_settings) > 1) {
         foreach ($version_settings as $version_setting) {
             $version_setting->delete();
         }
     }
     // Calibrate Accounts
     try {
         $accounts = DB::Query(DATABASE::SELECT, 'SELECT id FROM accounts WHERE parent_account_id IS NOT NULL')->execute()->as_array();
         foreach ($accounts as $account) {
             $previous_balance = 0.0;
             $calibrated_balance = 0.0;
             // Look up all transactions in order.
             $account_transactions = DB::Query(Database::SELECT, 'SELECT id,date,transaction_id,amount,balance FROM account_transactions WHERE account_id = "' . $account['id'] . '" ORDER BY date ASC, close_books DESC, transaction_id ASC')->execute()->as_array();
             foreach ($account_transactions as $account_transaction) {
                 $calibrated_balance = $account_transaction['balance'];
                 if (round($account_transaction['amount'] + $previous_balance, 2) != $calibrated_balance) {
                     $calibrated_balance = round($account_transaction['amount'] + $previous_balance, 2);
                 }
                 // Update if necessary.
                 if ($account_transaction['balance'] != $calibrated_balance) {
                     DB::Query(Database::UPDATE, 'UPDATE account_transactions SET balance = ' . $calibrated_balance . ' WHERE id = "' . $account_transaction['id'] . '"')->execute();
                 }
                 $previous_balance = $calibrated_balance;
             }
             $update_sql = 'UPDATE accounts SET ' . 'balance = ( SELECT IFNULL(SUM(bbalance),0.00) FROM (' . '		SELECT IFNULL(balance,0.00) as bbalance FROM ' . '		account_transactions as aaccount_transactions WHERE ' . '		account_id = "' . $account['id'] . '" ' . '		ORDER BY date DESC, close_books ASC, transaction_id DESC LIMIT 1 FOR UPDATE ' . ') as baccount_transactions ) ' . 'WHERE id = "' . $account['id'] . '"';
             $update_result = DB::Query(Database::UPDATE, $update_sql)->execute();
         }
     } catch (Exception $e) {
         // This is OK - we just need to warn them that the accounts need calibration.
     }
     return (object) array();
 }
Example #27
0
 protected function _execute()
 {
     if (!$this->_payment->loaded()) {
         throw new Exception("Payment could not be found.");
     }
     $form_ids_query = ' SELECT DISTINCT(account_transaction_forms.form_id) as form_id FROM account_transaction_forms ' . ' INNER JOIN account_transactions ON account_transaction_forms.account_transaction_id = account_transactions.id WHERE ' . ' account_transactions.transaction_id = ' . $this->_payment->id;
     $form_ids = DB::Query(Database::SELECT, $form_ids_query)->execute()->as_array();
     $handled_sales_ids = array();
     foreach ($form_ids as $form_id) {
         $handled_sales_ids[] = $form_id['form_id'];
     }
     $payment_date = $this->_payment->date;
     $payment_id = $this->_payment->id;
     // Try to cancel payment.
     $account_transaction_delete = new Beans_Account_Transaction_Delete($this->_beans_data_auth((object) array('id' => $this->_payment->id, 'payment_type_handled' => 'customer')));
     $account_transaction_delete_result = $account_transaction_delete->execute();
     if (!$account_transaction_delete_result->success) {
         throw new Exception("Error cancelling payment: " . $account_transaction_delete_result->error);
     }
     // Recalibrate Customer Invoices / Cancellations
     $customer_sale_calibrate_invoice = new Beans_Customer_Sale_Calibrate_Invoice($this->_beans_data_auth((object) array('ids' => $handled_sales_ids)));
     $customer_sale_calibrate_invoice_result = $customer_sale_calibrate_invoice->execute();
     if (!$customer_sale_calibrate_invoice_result->success) {
         throw new Exception("UNEXPECTED ERROR: COULD NOT CALIBRATE CUSTOMER SALES: " . $customer_sale_calibrate_invoice_result->error);
     }
     // Recalibrate Customer Invoices / Cancellations
     $customer_sale_calibrate_cancel = new Beans_Customer_Sale_Calibrate_Cancel($this->_beans_data_auth((object) array('ids' => $handled_sales_ids)));
     $customer_sale_calibrate_cancel_result = $customer_sale_calibrate_cancel->execute();
     if (!$customer_sale_calibrate_cancel_result->success) {
         throw new Exception("UNEXPECTED ERROR: COULD NOT CALIBRATE CUSTOMER SALES: " . $customer_sale_calibrate_cancel_result->error);
     }
     // Recalibrate any payments tied to these sales AFTER this transaction date.
     $customer_payment_calibrate = new Beans_Customer_Payment_Calibrate($this->_beans_data_auth((object) array('form_ids' => $handled_sales_ids)));
     $customer_payment_calibrate_result = $customer_payment_calibrate->execute();
     return (object) array("success" => TRUE, "auth_error" => "", "error" => "", "data" => (object) array());
 }
Example #28
0
 protected function _execute()
 {
     try {
         $form_type_exist_check = DB::Query(Database::SELECT, 'SELECT COUNT(COLUMN_NAME) as exist_check FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "transactions" AND COLUMN_NAME = "form_type"')->execute()->as_array();
         if ($form_type_exist_check[0]['exist_check'] == '0') {
             DB::Query(NULL, "ALTER TABLE  `transactions` ADD  `form_type` ENUM(  'sale' , 'purchase' , 'expense' , 'tax_payment' ) NULL DEFAULT NULL AFTER  `entity_id` ")->execute();
         }
         $form_id_exist_check = DB::Query(Database::SELECT, 'SELECT COUNT(COLUMN_NAME) as exist_check FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "transactions" AND COLUMN_NAME = "form_id"')->execute()->as_array();
         if ($form_type_exist_check[0]['exist_check'] == '0') {
             DB::Query(NULL, "ALTER TABLE  `transactions` ADD  `form_id` BIGINT UNSIGNED NULL DEFAULT NULL AFTER  `form_type` ")->execute();
         }
     } catch (Exception $e) {
         throw new Exception("An error occurred when migrating your database tables: " . $e->getMessage());
     }
     try {
         $forms = DB::Query(Database::SELECT, 'SELECT id, type, create_transaction_id, invoice_transaction_id, cancel_transaction_id FROM forms WHERE ' . '( create_transaction_id IS NOT NULL OR ' . ' invoice_transaction_id IS NOT NULL OR ' . ' cancel_transaction_id IS NOT NULL )')->execute()->as_array();
         foreach ($forms as $form) {
             if ($form['create_transaction_id']) {
                 DB::Query(Database::UPDATE, 'UPDATE transactions SET form_type = "' . $form['type'] . '", form_id = ' . $form['id'] . ' WHERE id = ' . $form['create_transaction_id'])->execute();
             }
             if ($form['invoice_transaction_id']) {
                 DB::Query(Database::UPDATE, 'UPDATE transactions SET form_type = "' . $form['type'] . '", form_id = ' . $form['id'] . ' WHERE id = ' . $form['invoice_transaction_id'])->execute();
             }
             if ($form['cancel_transaction_id']) {
                 DB::Query(Database::UPDATE, 'UPDATE transactions SET form_type = "' . $form['type'] . '", form_id = ' . $form['id'] . ' WHERE id = ' . $form['cancel_transaction_id'])->execute();
             }
         }
         $tax_payments = DB::Query(Database::SELECT, ' SELECT id, transaction_id FROM tax_payments WHERE transaction_id IS NOT NULL')->execute()->as_array();
         foreach ($tax_payments as $tax_payment) {
             DB::Query(Database::UPDATE, 'UPDATE transactions SET form_type = "tax_payment", form_id = ' . $tax_payment['id'] . ' WHERE id = ' . $tax_payment['transaction_id'])->execute();
         }
     } catch (Exception $e) {
         throw new Exception("Error creating appropriate records in transactions. " . $e->getMessage());
     }
     return (object) array();
 }
Example #29
0
         } else {
             Session::Set('error', "备份表-{$table}-失败");
         }
         _go_reload();
     }
 } else {
     //分卷备份
     if (!$_POST['filesize']) {
         Session::Set('error', "请填写备份文件分卷大小!");
         _go_reload();
     }
     $sql = null;
     $sql .= backup_make_header($table);
     $p = 1;
     $filenamep = date("Ymd") . Utility::GenSecret(4) . "_{$table}";
     $query = DB::Query("SELECT * FROM `{$table}`");
     while ($r = DB::NextRecord($query)) {
         $sql .= backup_make_record($table, $r);
         if (strlen($sql) >= $_POST['filesize'] * 1024) {
             $filename = $filenamep . ("_v" . $p . ".sql");
             if (true !== backup_write_file($sql, $filename)) {
                 Session::Set('error', "备份表-{$table}-{$p}-失败");
                 _go_reload();
             }
             $p++;
             $sql = null;
         }
     }
     if ($sql) {
         if (true !== backup_write_file($sql, $filename)) {
             Session::Set('error', "备份表-{$table}-失败");
Example #30
0
 function AvailableCountries()
 {
     $query = DB::Query("SELECT DISTINCT C.Name FROM Countries AS C\n                            RIGHT JOIN PresentationSpeaker AS PS ON PS.Country = C.Code\n                            WHERE PS.AvailableForBureau = 1");
     $country_list = array();
     foreach ($query as $country) {
         $country_list[] = new ArrayData(array("Country" => $country['Name']));
     }
     return new ArrayList($country_list);
 }