/** * 取消订单 * @param $orderId */ public function cancelOrder($orderId) { $openId = (new WeixinUtil())->getOpenId(); if (!$openId) { ResponseUtil::failure('未授权访问!'); } if (!$orderId) { ResponseUtil::failure('没有订单'); } $orderId += 0; $orderModel = new OrderModel(); // 获得订单 $order = $orderModel->readOne($orderId); if (!$order) { ResponseUtil::failure('取消订单失败!'); } // 获得积分ID $couponId = $order['use_coupon_id']; if ($couponId) { (new CustomerCouponModel())->refundCoupon($couponId, $openId); } //取消订单 if ((new CurdUtil(new OrderModel()))->update(array('order_id' => $orderId, 'open_id' => $openId), array('order_status' => OrderModel::ORDER_CANCEL))) { ResponseUtil::executeSuccess('订单取消成功!'); } else { ResponseUtil::failure('取消订单失败!'); } }
public function readAllProjectByCategory($categoryId) { $projects = (new CurdUtil($this->projectModel))->readAll('project_id desc', array('category_id' => $categoryId)); $html = ''; foreach ($projects as $project) { $html .= "<option value={$project['project_id']}>{$project['project_name']}</option>"; } ResponseUtil::json($html); }
public function index() { if ($_FILES[$this->fileName]['size'] <= 0) { ResponseUtil::output(array('error' => 1, 'message' => '图片不能为空,请重试!')); } $upload = new UploadUtil('upload/image'); $data = $upload->upload($this->fileName); if ($data['error'] == 0) { // 缩略图 $upload->resizeImage(array('upload/resize_350x350'), $data['data']); $imageUrl = UploadUtil::buildUploadDocPath($data['data'], '350x350'); ResponseUtil::output(array('error' => 0, 'url' => $imageUrl)); } else { ResponseUtil::output(array('error' => 1, 'message' => '图片上传失败!,请重试!')); } }
/** * 取消订单 * @param string $order_id */ public function CancelOrder($order_id = '') { if (!$order_id) { $this->message('订单ID不能为空!'); } $orderModel = new OrderModel(); // 获得订单 $order = $orderModel->readOne($order_id); if (!$order) { ResponseUtil::failure('取消订单失败!'); } // 获得积分ID $couponId = $order['use_coupon_id']; if ($couponId) { (new CustomerCouponModel())->refundCoupon($couponId, $order['open_id']); } if ((new CurdUtil($this->orderModel))->update(array('order_id' => $order_id), array('order_status' => OrderModel::ORDER_CANCEL, 'complete_time' => DateUtil::now()))) { $this->message('订单已取消!'); } else { $this->message('处理失败!'); } }
public function __construct() { parent::__construct(); if (!UserUtil::getUserId()) { ResponseUtil::redirect(UrlUtil::createBackendUrl('login')); } $controller = strtolower($this->router->class); $method = strtolower($this->router->method); if (UserUtil::isShopKeeper()) { if (!array_key_exists($controller, $this->shopKeeperPermissions)) { $this->message('你没有权限执行本步骤!'); } $methods = $this->shopKeeperPermissions[$controller]; if ($methods == '*') { return true; } else { if (!in_array($method, $methods)) { $this->message('你没有权限执行本步骤!'); } else { return true; } } } }
/** * Magic getter for {@link absoluteBaseUrl}; in the case that web request data * isn't available, it uses a config file. * * @return type */ public function getAbsoluteBaseUrl() { if (!isset($this->_absoluteBaseUrl)) { if (ResponseUtil::isCli()) { // It's assumed that in this case, we're dealing with (for example) // a cron script that sends emails and has to generate URLs. It // needs info about how to access the CRM from the outside... $this->_absoluteBaseUrl = ''; if ($this->contEd('pro') && $this->settings->externalBaseUrl && $this->settings->externalBaseUri) { // Use the base URL from "public info settings" since it's // available: $this->_absoluteBaseUrl = $this->settings->externalBaseUrl . $this->settings->externalBaseUri; } else { if ($file = realpath($this->owner->basePath . '/../webConfig.php')) { // Use the web API config file to construct the URL (our // last hope) include $file; if (isset($url)) { $this->_absoluteBaseUrl = $url; } } else { // There's nothing left we can legitimately do and have it // work correctly! Make something up. $this->_absoluteBaseUrl = 'http://localhost'; } } } else { $this->_absoluteBaseUrl = $this->owner->getBaseUrl(true); } } return $this->_absoluteBaseUrl; }
/** * Wrapper method for * @param type $msg * @param type $error */ public function respond($msg, $error = false) { ResponseUtil::respond($msg, $error); }
/** * 授权 * @param $returnUrl * @return bool */ public function authorize($returnUrl) { if (!$returnUrl) { get_instance()->message('授权回调地址为空!'); } // 如果是微信授权后返回 if (isset($_GET['code'])) { // 获得accessToken $callback = $this->loginCallback($_GET['code']); if (!$callback) { get_instance()->message('获得微信授权失败,请重试!'); } } // 检测是否已经授权 $openId = $this->getOpenId(); if ($openId) { // 刷新token过期 if ($this->isNeedRefreshAccessToken()) { if (!$this->refreshAccessToken()) { ResponseUtil::redirect($this->toAuthorize(UrlUtil::createUrl($returnUrl))); } } } else { // 去微信授权 ResponseUtil::redirect($this->toAuthorize(UrlUtil::createUrl($returnUrl))); } return true; }
break; case 'sendHttp': $r = new ResponseUtil(); if (ctype_digit($subcase) || is_int($subcase)) { $r->sendHttp($subcase); } $r['message'] = 'The response'; $r['error'] = false; switch ($subcase) { case 'badCode': $r->sendHttp(666); break; case 'extraHeader': $r->httpHeader['Content-MD5'] = base64_encode(md5('not the content')); $r->sendHttp(); break; case 'raw': $r->body = 'The message in plain text.'; $r->httpHeader['Content-Type'] = 'text/plain'; $r->sendHttp(); break; } break; case 'setProperties': $r = new ResponseUtil(); $r->setProperties(array('foo' => 'bar', 'message' => 'ni')); $r->sendHttp(); break; default: die('Unknown test case.'); }
/** * Sends a request to pull data from X2Engine, or to delete/unsubscribe. * * @param string $method Request method to use * @param array $data an array to JSON-encode and send */ public function send($method, $data) { if (!extension_loaded('curl')) { return; } // Compose the body of the request to send $payload = json_encode($this->walkData($data)); // Start a cURL session and configure the request $this->_ch = curl_init($this->target_url); curl_setopt_array($this->_ch, array(CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $this->getTimeout(), CURLOPT_HTTPHEADER => array('Content-Type: application/json; charset=utf-8'), CURLOPT_HTTP200ALIASES => array_keys(ResponseUtil::getStatusMessages()))); if (!empty($payload)) { curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $payload); } // Send the request $this->sent = curl_exec($this->_ch); // If the remote end is no longer listening, we can stop sending data if ($this->getStatus() == 410) { $this->setScenario('delete.remote'); $this->delete(); } }
/** * Sends a HTTP response and logs the message that was sent. * * @param integer $status * @param string $message */ public function send($status = 200, $message = '') { $statMessage = ResponseUtil::statusMessage($status); if (!isset($this->response->body)) { // Copy the headers into the response JSON for inferior HTTP client // libraries that don't know how to read response headers: $this->response['httpHeaders'] = $this->response->httpHeader; if (function_exists('getallheaders')) { $this->response['reqHeaders'] = getallheaders(); } } $this->log("sent [{$status} {$statMessage}]" . (empty($message) ? '' : ": {$message}")); $this->response->sendHttp($status, $message); }
public function testRespond() { // Test non-ending responses (ending ones were tested in testEnd) ob_start(); try { ResponseUtil::respond('responded'); $echoed = ob_get_clean(); } catch (Exception $e) { ob_end_flush(); $this->assertTrue(false, 'Ran into error in ResponseUtil::respond! ' . $e->getMessage()); } $this->assertEquals("responded\n", $echoed, 'ResponseUtil::respond() did not respond!'); // A basic web response, without error: $ch = $this->getCurlHandle(array('{case}' => 'respond.errFalse')); $response = json_decode(curl_exec($ch), 1); $this->assertTrue(is_array($response)); $this->assertFalse($response['error']); $this->assertEquals('errFalse', $response['message']); $this->assertResponseCodeIs(200, $ch); // With error: $ch = $this->getCurlHandle(array('{case}' => 'respond.errTrue')); $response = json_decode(curl_exec($ch), 1); $this->assertTrue(is_array($response)); $this->assertTrue($response['error']); $this->assertEquals('errTrue', $response['message']); $this->assertResponseCodeIs(400, $ch); // With extra attribute: $ch = $this->getCurlHandle(array('{case}' => 'respond.property')); $response = json_decode(curl_exec($ch), 1); $this->assertResponseCodeIs(200, $ch); $this->assertArrayHasKey('property', $response); $this->assertEquals('value', $response['property']); }
public function code() { ResponseUtil::createImageVerifyCode(); }
public function getExchangeGoods($exchangeGoodsId) { $openId = (new WeixinUtil())->getOpenId(); if (!$openId) { ResponseUtil::failure('错误的授权!'); } // 查询是否已经领取优惠券 if ((new CustomerExchangeGoodsModel())->readOne($exchangeGoodsId, $openId)) { ResponseUtil::failure('您已经兑换了此商品!'); } $exchangeGoods = (new ExchangeGoodsModel())->readOne($exchangeGoodsId); // 剩余数量为0 if ($exchangeGoods['remain_number'] <= 0) { ResponseUtil::failure('商品已经兑换完!'); } $today = date('Y-m-d'); // 是否到领取时间 if ($today < $exchangeGoods['start_time']) { ResponseUtil::failure('商品未到兑换时间!'); } if ($today > $exchangeGoods['expire_time']) { ResponseUtil::failure('商品已过兑换时间!'); } // 判断积分 $customerModel = new CustomerModel(); $customer = $customerModel->readOne($openId); if ($exchangeGoods['exchange_credits'] > $customer['credits']) { ResponseUtil::failure('积分不足,兑换商品失败!'); } $userName = $this->input->post('contact_name', true); $phoneNumber = $this->input->post('contact_phone', true); $userName = urldecode($userName); // 检查用户 $userName = trim(strip_tags($userName)); if (empty($userName)) { ResponseUtil::failure('联系人不能为空,请检查!'); } if (!preg_match('~^1\\d{10}$~', $phoneNumber)) { ResponseUtil::failure('手机号错误,请检查!'); } $this->db->trans_start(); // 领取 $data = array('exchange_goods_id' => $exchangeGoodsId, 'open_id' => $openId, 'is_get' => 0, 'contact_name' => $userName, 'contact_phone' => $phoneNumber, 'exchange_time' => DateUtil::now()); $customerExchangeGoodsId = (new CustomerExchangeGoodsModel())->create($data); if ($customerExchangeGoodsId) { (new ExchangeGoodsModel())->subExchangeGoodsNumber($exchangeGoodsId); } // 积分 $customerModel->subCredits($openId, $exchangeGoods['exchange_credits']); $this->db->trans_complete(); if ($this->db->trans_status() === FALSE) { $this->db->trans_rollback(); ResponseUtil::failure('兑换商品失败!'); } else { $this->db->trans_commit(); ResponseUtil::executeSuccess('兑换商品成功!'); } }
/** * Runs a named stage of the installation. * * @param $stage The named stage of installation. */ function installStage($stage) { global $editions, $dbConfig, $dbKeys, $dateFields, $enabledModules, $dbo, $config, $confMap, $response, $silent, $stageLabels, $write, $nonFreeTables, $editionHierarchy; switch ($stage) { case 'validate': if ($config['dummy_data'] == 1 && $config['adminUsername'] != 'admin') { addValidationError('adminUsername', 'Cannot change administrator username if installing with sample data.'); } else { if (empty($config['adminUsername'])) { addValidationError('adminUsername', 'Admin username cannot be blank.'); } elseif (is_int(strpos($config['adminUsername'], "'"))) { addValidationError('adminUsername', 'Admin username cannot contain apostrophes'); } elseif (preg_match('/^\\d+$/', $config['adminUsername'])) { addValidationError('adminUsername', 'Admin username must contain at least one non-numeric character.'); } elseif (!preg_match('/^\\w+$/', $config['adminUsername'])) { addValidationError('adminUsername', 'Admin username may contain only alphanumeric characters and underscores.'); } } if (empty($config['adminEmail']) || !preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i', $config['adminEmail'])) { addValidationError('adminEmail', 'Please enter a valid email address.'); } if ($config['adminPass'] == '') { addValidationError('adminPass', 'Admin password cannot be blank.'); } if (!$silent && !isset($_POST['adminPass2'])) { addValidationError('adminPass2', 'Please confirm the admin password.'); } else { if (!$silent && $config['adminPass'] != $_POST['adminPass2']) { addValidationError('adminPass2', 'Admin passwords did not match.'); } } if (!empty($response['errors'])) { if (!$silent) { RIP(installer_t('Please correct the following errors:')); } else { outputErrors(); } } break; case 'module': if (isset($_GET['module'])) { // Install only a named module installModule($_GET['module']); } else { // Install all modules: foreach ($enabledModules as $module) { installModule($module, $silent); } } break; case 'config': // Configure with initial data and write files // Generate config file content: $gii = 1; if ($gii == '1') { $gii = "array(\n\t'class'=>'system.gii.GiiModule',\n\t'password'=>'" . str_replace("'", "\\'", $config['adminPass']) . "', \n\t/* If the following is removed, Gii defaults to localhost only. Edit carefully to taste: */\n\t 'ipFilters'=>false,\n)"; } else { $gii = "array(\n\t'class'=>'system.gii.GiiModule',\n\t'password'=>'password',\n\t/* If the following is removed, Gii defaults to localhost only. Edit carefully to taste: */\n\t 'ipFilters'=>array('127.0.0.1', '::1'),\n)"; } $X2Config = "<?php\n"; foreach (array('appName', 'email', 'host', 'user', 'pass', 'dbname', 'version') as $confKey) { $X2Config .= "\${$confKey} = " . var_export($config[$confMap[$confKey]], 1) . ";\n"; } $X2Config .= "\$buildDate = {$config['buildDate']};\n\$updaterVersion = '{$config['updaterVersion']}';\n"; $X2Config .= empty($config['language']) ? '$language=null;' : "\$language='{$config['language']}';\n?>"; // Save config values to be inserted in the database: $config['time'] = time(); foreach ($dbKeys as $property) { $dbConfig['{' . $property . '}'] = $config[$property]; } $contents = file_get_contents('webConfig.php'); $contents = preg_replace('/\\$url\\s*=\\s*\'\'/', "\$url=" . var_export($config['baseUrl'] . $config['baseUri'], 1), $contents); $contents = preg_replace('/\\$user\\s*=\\s*\'\'/', "\$user="******"\$userKey=" . var_export($config['adminUserKey'], 1), $contents); file_put_contents('webConfig.php', $contents); if ($config['test_db']) { $filename = implode(DIRECTORY_SEPARATOR, array(__DIR__, 'protected', 'config', 'X2Config-test.php')); if (!empty($config['test_url'])) { $defaultConfig = file_get_contents(implode(DIRECTORY_SEPARATOR, array(__DIR__, 'protected', 'tests', 'WebTestConfig_example.php'))); $webTestConfigFile = implode(DIRECTORY_SEPARATOR, array(__DIR__, 'protected', 'tests', 'WebTestConfig.php')); $webTestUrl = rtrim($config['test_url'], '/') . '/'; $webTestRoot = rtrim(preg_replace('#index-test\\.php/?$#', '', trim($config['test_url'])), '/') . '/'; $testConstants = array('TEST_BASE_URL' => var_export($webTestUrl, 1), 'TEST_WEBROOT_URL' => var_export($webTestRoot, 1)); $webTestConfig = $defaultConfig; foreach ($testConstants as $name => $value) { $webTestConfig = preg_replace("/^defined\\('{$name}'\\) or define\\('{$name}'\\s*,.*\$/m", "defined('{$name}') or define('{$name}',{$value});", $webTestConfig); } file_put_contents($webTestConfigFile, $webTestConfig); } } else { $filename = implode(DIRECTORY_SEPARATOR, array(__DIR__, 'protected', 'config', 'X2Config.php')); } $handle = fopen($filename, 'w') or RIP(installer_tr('Could not create configuration file: {filename}.', array('{filename}' => $filename))); // Write core application configuration: fwrite($handle, $X2Config); fclose($handle); // Create an encryption key for credential storage: if (extension_loaded('openssl') && extension_loaded('mcrypt')) { $encryption = new EncryptUtil('protected/config/encryption.key', 'protected/config/encryption.iv'); $encryption->saveNew(); } $dbConfig['{adminPass}'] = md5($config['adminPass']); $dbConfig['{adminUserKey}'] = $config['adminUserKey']; try { foreach (array('', '-pro', '-pla') as $suffix) { $sqlPath = "protected/data/config{$suffix}.sql"; $sqlFile = realpath($sqlPath); if ($sqlFile) { $sql = explode('/*&*/', strtr(file_get_contents($sqlFile), $dbConfig)); foreach ($sql as $sqlLine) { $installConf = $dbo->prepare($sqlLine); if (!$installConf->execute()) { RIP(installer_t('Error applying initial configuration') . ': ' . implode(',', $installConf->errorInfo())); } } } else { if ($suffix == '') { // Minimum requirement RIP(installer_t('Could not find database configuration script') . " {$sqlPath}"); } } } } catch (PDOException $e) { die($e->getMessage()); } // saveCrontab(); break; case 'finalize': /** * Look for additional initialization files and perform final tasks */ foreach ($editions as $ed) { // Add editional prefixes as necessary if (file_exists("initialize_{$ed}.php")) { include "initialize_{$ed}.php"; } } break; default: // Look for a named SQL file and run it: $stagePath = "protected/data/{$stage}.sql"; if ($stage == 'dummy_data') { $stageLabels['dummy_data'] = sprintf($stageLabels['dummy_data'], $config['dummy_data'] ? 'insert' : 'delete'); } if ((bool) (int) $config['dummy_data'] || $stage != 'dummy_data') { if ($sqlFile = realpath($stagePath)) { $sql = explode('/*&*/', file_get_contents($sqlFile)); foreach ($sql as $sqlLine) { $statement = $dbo->prepare($sqlLine); try { if (!$statement->execute()) { RIP(installer_tr('Could not {stage}. SQL statement "{sql}" from {file} failed', array('{stage}' => $stageLabels[$stage], '{sql}' => substr(trim($sqlLine), 0, 50) . (strlen(trim($sqlLine)) > 50 ? '...' : ''), '{file}' => $sqlFile)) . '; ' . implode(',', $statement->errorInfo())); } } catch (PDOException $e) { RIP(installer_tr("Could not {stage}", array('{stage}' => $stageLabels[$stage])) . '; ' . $e->getMessage()); } } // Hunt for init SQL files associated with other editions: foreach ($editions as $ed) { if ($sqlFile = realpath("protected/data/{$stage}-{$ed}.sql")) { $sql = explode('/*&*/', file_get_contents($sqlFile)); foreach ($sql as $sqlLine) { $statement = $dbo->prepare($sqlLine); try { if (!$statement->execute()) { RIP(installer_tr('Could not {stage}. SQL statement "{sql}" from {file} failed', array('{stage}' => $stageLabels[$stage], '{sql}' => substr(trim($sqlLine), 0, 50) . (strlen($sqlLine) > 50 ? '...' : ''), '{file}' => $sqlFile)) . '; ' . implode(',', $statement->errorInfo())); } } catch (PDOException $e) { RIP(installer_tr("Could not {stage}", array('{stage}' => $stageLabels[$stage])) . '; ' . $e->getMessage()); } } } } if ($stage == 'dummy_data') { // Need to update the timestamp fields on all the sample data that has been inserted. $dateGen = @file_get_contents(realpath("protected/data/dummy_data_date")) or RIP("Sample data generation date not set."); $time = time(); $time2 = $time * 2; $timeDiff = $time - (int) trim($dateGen); foreach ($dateFields as $table => $fields) { $tableEdition = 'opensource'; foreach ($editions as $ed) { if (in_array($table, $nonFreeTables[$ed])) { $tableEdition = $ed; break; } } if (!(bool) $editionHierarchy[$config['edition']][$tableEdition]) { // Table not "contained" in the current edition continue; } foreach ($fields as $field) { try { $dbo->exec("UPDATE `{$table}` SET `{$field}`=`{$field}`+{$timeDiff} WHERE `{$field}` IS NOT NULL AND `{$field}`!=0 AND `{$field}`!=''"); } catch (Exception $e) { // Ignore it and move on; table/column doesn't exist. continue; } } // Fix timestamps that are in the future. /* $ordered = array('lastUpdated','createDate'); if(count(array_intersect($ordered,$fields)) == count($ordered)) { $affected = 0; foreach($ordered as $field) { $affected += $dbo->exec("UPDATE `$table` SET `$field`=$time2-`$field` WHERE `$field` > $time"); } if($affected) $dbo->exec("UPDATE `$table` set `lastUpdated`=`createDate`,`createDate`=`lastUpdated` WHERE `createDate` > `lastUpdated`"); } */ } } } else { RIP(installer_t("Could not find installation stage database script") . " {$stagePath}"); } } else { // This is the dummy data stage, and we need to clear out all unneeded files. // However, we should leave the files alone if this is a testing database reinstall. $stageLabels[$stage] = sprintf($stageLabels[$stage], 'remove'); if (($paths = @(require_once realpath('protected/data/dummy_data_files.php'))) && !$config['test_db']) { foreach ($paths as $pathClear) { if ($path = realpath($pathClear)) { FileUtil::rrmdir($path, '/\\.htaccess$/'); } } } } break; } if (in_array($stage, array_keys($stageLabels)) && $stage != 'finalize' && !($stage == 'validate' && $silent)) { ResponseUtil::respond(installer_tr("Completed: {stage}", array('{stage}' => $stageLabels[$stage]))); } }
/** * Sends a HTTP response back to the client. * * @param integer $status The status code to use * @param type $message * @param type $error * @throws Exception */ public function sendHttp($status = null, $message = '', $error = null) { self::$_responding = true; // Close the output buffer; it's now safe to do so, since the header // will soon be sent. $output = ob_get_clean(); ob_end_clean(); $extraOutput = self::$includeExtraneousOutput && !empty($output); $status = $status === null ? (bool) $error ? self::$errorCode : 200 : $status; // Set the response content if ($status !== null && !array_key_exists((int) $status, self::$_statusMessages)) { // Invalid call to this method. Fail noisily. $this->_status = self::$errorCode; $body = '{"error":true,"message":"Internal server error: invalid or ' . 'non-numeric HTTP response status code specifed.","status":500}'; } else { if (!extension_loaded('json') || isset($this->body)) { // We might be doing something other than responding in JSON if (!isset($this->body)) { if (strpos($this->httpHeader['Content-Type'], 'application/json') === 0) { // JSON-format responding in use but not available $this->_status = self::$errorCode; $body = '{"error":true,"message":"The JSON PHP extension is required,' . ' but this server lacks it.","status":' . $this->_status . '}'; } else { // Simply echo the message if JSON isn't available. $this->_status = $status; $body = ($extraOutput ? $output . ' ' : '') . $message; } } else { // The "body" property is in use, which overrides the standard // way of responding with JSON-encoded properties $this->_status = $status; $body = ($extraOutput ? $output . ' ' : '') . $this->body; } } else { if ($status != null) { // Override status. Loose comparison is in use because zero is // an invalid HTTP response code and expected only of certain // cURL libraries when the connection could not be established. $this->_status = $status; } $response = $this->_properties; // Set universal response properties: if (empty($message) && !empty($response['message'])) { $message = $response['message']; } $response['message'] = $message . ($extraOutput ? " Note, extraneous output was generated in the scope of this response: {$output}" : ''); $response['error'] = $error === null ? $this->_status >= 400 : (bool) $error; // Include the status code in the envelope for clients that can't // read HTTP headers: $response['status'] = $this->_status; // Compose the body of the response as a JSON-encoded object: $body = json_encode($response); } } // Send the response $this->sendHttpHeader(); echo $body; // Shut down self::$_response = null; self::end(); }
/** * 获得有效的预约时间 * 首先查询 指定日期 美容师休息表, 获得休息时间 * 再查询 指定日期 美容师 已接受预定的 时间 * * @param $beautician_id 美容师ID * @param $day 查询日期 */ public function getValidAppointmentTime($beautician_id, $day) { if (!$beautician_id || !$day) { ResponseUtil::failure('参数错误!'); } $today = date('Y-m-d'); if ($day < $today) { ResponseUtil::failure('错误的预约时间!'); } // 查询美容师 $beautician = (new BeauticianModel())->readOne($beautician_id); if (!$beautician) { ResponseUtil::failure('美容师不存在!'); } // 查询休息时间 $beauticianRest = (new CurdUtil(new BeauticianRestModel()))->readAll('beautician_rest_id desc', array('beautician_id' => $beautician_id, 'disabled' => 0, 'rest_day' => $day)); // 获得工作时间 $workTime = new WorkTimeUtil(); list($dayStart, $dayEnd) = $workTime->explode($workTime->getAllDay()); // 指定日期的所有预约时间段 $appointmentTimes = DateUtil::generateAppointmentTime($day, $dayStart, $dayEnd); // 美容师制定日期休息时间段 // 当值为0时, 说明不能预约 if ($beauticianRest) { foreach ($beauticianRest as $_beauticianRest) { $beauticianRestAppointmentTimes = DateUtil::generateAppointmentTime($day, $_beauticianRest['start_time'], $_beauticianRest['end_time']); foreach ($appointmentTimes as $k => $time) { if (array_key_exists($k, $beauticianRestAppointmentTimes)) { $appointmentTimes[$k] = 0; } } } } // 获得制定日期已经预约的时间段,订单状态为已支付 $payedOrders = (new OrderModel())->getOrderByBeauticianIdAndAppointmentDay($beautician_id, $day); if ($payedOrders) { foreach ($payedOrders as $payedOrder) { $orderAppointmentTime = DateUtil::generateAppointmentTime($payedOrder['appointment_day'], $payedOrder['appointment_start_time'], $payedOrder['appointment_end_time']); foreach ($appointmentTimes as $k => $time) { if (array_key_exists($k, $orderAppointmentTime)) { $appointmentTimes[$k] = 0; } } } } // 小于当前时间不能预约 if ($today == $day) { $now = date('H:i'); foreach ($appointmentTimes as $k => $time) { if ($k < $now) { $appointmentTimes[$k] = 0; } } } // 查询线下预约 $offlineOrders = (new OfflineOrderModel())->getOrderByBeauticianIdAndAppointmentDay($beautician_id, $day); if ($offlineOrders) { foreach ($offlineOrders as $offlineOrder) { $orderAppointmentTime = DateUtil::generateAppointmentTime($offlineOrder['appointment_day'], $offlineOrder['appointment_start_time'], $offlineOrder['appointment_end_time']); foreach ($appointmentTimes as $k => $time) { if (array_key_exists($k, $orderAppointmentTime)) { $appointmentTimes[$k] = 0; } } } } $beauticianWorkTime = (new WorkTimeUtil())->beauticianWorkTime; $week = DateUtil::calcDayInWeek($day); $workTimeType = $beauticianWorkTime[$beautician_id][$week]; // 判断早班,晚班 if ($workTimeType == BeauticianModel::ALL_DAY) { } elseif ($workTimeType == BeauticianModel::MORNING_SHIFT) { $morningShiftTimes = $workTime->explode($workTime->getMorningShift()); $workAppointmentTime = DateUtil::generateAppointmentTime($day, $morningShiftTimes[0], $morningShiftTimes[1]); foreach ($appointmentTimes as $k => $time) { if (!array_key_exists($k, $workAppointmentTime)) { $appointmentTimes[$k] = 0; } } } elseif ($workTimeType == BeauticianModel::NIGHT_SHIFT) { $nightShiftTimes = $workTime->explode($workTime->getNightShift()); $workAppointmentTime = DateUtil::generateAppointmentTime($day, $nightShiftTimes[0], $nightShiftTimes[1]); foreach ($appointmentTimes as $k => $time) { if (!array_key_exists($k, $workAppointmentTime)) { $appointmentTimes[$k] = 0; } } } elseif ($workTimeType == BeauticianModel::MIDDAY_SHIFT) { $middayShiftTimes = $workTime->explode($workTime->getMiddayShift()); $workAppointmentTime = DateUtil::generateAppointmentTime($day, $middayShiftTimes[0], $middayShiftTimes[1]); foreach ($appointmentTimes as $k => $time) { if (!array_key_exists($k, $workAppointmentTime)) { $appointmentTimes[$k] = 0; } } } elseif ($workTimeType == BeauticianModel::REST_SHIFT) { foreach ($appointmentTimes as $k => $time) { $appointmentTimes[$k] = 0; } } else { } // 渲染视图 $render = $this->load->view('frontend/appointment/appointmentTimes', array('appointmentTimes' => $appointmentTimes), true); ResponseUtil::executeSuccess('成功', $render); }
/** * 下单 * @param $shopId * @param $beauticianId * @param $appointmentDay * @param $appointmentTime * @param $userName * @param $phoneNumber */ public function order($shopId, $beauticianId, $appointmentDay, $appointmentTime, $userName, $phoneNumber) { $openId = (new WeixinUtil())->getOpenId(); if (!$openId) { $this->message('错误的授权'); } if (!(new ShopModel())->isValidShopId($shopId)) { $this->message('门店信息错误,请检查!'); } // 检查美容师 if (!(new BeauticianModel())->isValidBeautician($beauticianId)) { $this->message('美容师信息错误,请检查!'); } $userName = urldecode($userName); // 检查用户 $userName = trim(strip_tags($userName)); if (empty($userName)) { $this->message('联系人不能为空,请检查!'); } if (!preg_match('~^1\\d{10}$~', $phoneNumber)) { $this->message('手机号错误,请检查!'); } // 检查日期,日期为今天或者以后 $today = date('Y-m-d'); if ($appointmentDay < $today) { $this->message('错误的预约日期!'); } // 检查时间 $appointmentTime = explode(',', urldecode($appointmentTime)); if (!$appointmentTime || count($appointmentTime) < 1) { $this->message('错误的预约时间!'); } // 只有30分钟的项目 if (count($appointmentTime) == 1) { array_push($appointmentTime, $appointmentTime[0]); } // 只保留头和尾的两个数据 $startTime = array_shift($appointmentTime); $endTime = array_pop($appointmentTime); if ($endTime < $startTime) { $this->message('错误的预约时间!'); } // 预约时间是否小于当前时间 $now = date('Y-m-d H:i'); if (DateUtil::buildDateTime($appointmentDay, $startTime) < $now) { $this->message('错误的预约开始时间!'); } if (DateUtil::buildDateTime($appointmentDay, $endTime) < $now) { $this->message('错误的预约结束时间!'); } // 结束时间 + 30分钟为真正的结束时间 //$timeStamp = DateUtil::buildDateTime($appointmentDay, $endTime); //$timeStamp += 1800; //$endTime = date('H:i', $timeStamp); // 处理优惠 $couponId = $this->input->get('coupon_id', true) + 0; $couponCode = $this->input->get('coupon_code', true) + 0; $customerCouponModel = new CustomerCouponModel(); $couponCodeModel = new CouponCodeModel(); $today = date('Y-m-d'); if ($couponId) { $couponCode = ''; $coupon = $customerCouponModel->readOneById($couponId); // 判断是否能使用 if ($coupon['is_use'] == 1) { $this->message('选择的优惠券已被使用!'); } // 是否到领取时间 if ($today < $coupon['start_time']) { $this->message('优惠券未到使用时间!'); } if ($today > $coupon['expire_time']) { $this->message('优惠券已到期!'); } } else { if ($couponCode) { $couponId = ''; $queryCouponCode = $couponCodeModel->readOneByCode($couponCode); if (!$queryCouponCode) { $this->message('优惠码不存在!'); } // 是否到使用时间 if ($today < $queryCouponCode['start_time']) { $this->message('优惠码未到使用时间!'); } // 是有已过期 if ($today > $queryCouponCode['expire_time']) { $this->message('优惠码已到期!'); } } else { } } //**********处理下单************// $projectId = (new CartUtil())->cart(); if (empty($projectId) || $projectId <= 0) { $this->message('预约项目为空!'); } if ((new ProjectPropertyModel())->projectOnlyForNewUser($projectId, $openId)) { $this->message('此美容项目只针对新用户!'); } $orderProjectModel = new OrderProjectModel(); // 获得购物车的项目 $project = (new ProjectModel())->readOne($projectId); // 判断订单金额是否可以使用优惠券 $totalFee = $originalTotalFee = $project['price']; if ($couponId && $project['can_use_coupon']) { if ($totalFee < $coupon['use_rule']) { $this->message('当前订单金额不足' . $coupon['use_rule'] . '元,不能使用此优惠券'); } } else { if ($couponCode && $project['can_use_coupon_code']) { if ($totalFee < $queryCouponCode['use_rule']) { $this->message('当前订单金额不足' . $queryCouponCode['use_rule'] . '元,不能使用此优惠码'); } } else { } } // 生成订单号, 有重复订单号则重新生成,直到不重复为止 $orderNo = StringUtil::generateOrderNo(); $orderModel = new OrderModel(); while ((new CurdUtil($orderModel))->readOne(array('order_no' => $orderNo))) { $orderNo = StringUtil::generateOrderNo(); } // 优惠 if ($couponId && $project['can_use_coupon']) { // 使用优惠码, 抵消金额 $totalFee -= $coupon['counteract_amount']; } else { if ($couponCode && $project['can_use_coupon_code']) { $totalFee *= $queryCouponCode['discount']; } else { } } // 订单数据 $orderData = array('order_no' => $orderNo, 'shop_id' => $shopId, 'create_time' => DateUtil::now(), 'original_total_fee' => $originalTotalFee, 'total_fee' => $totalFee, 'open_id' => $openId, 'order_status' => OrderModel::ORDER_NOT_PAY, 'beautician_id' => $beauticianId, 'appointment_day' => $appointmentDay, 'appointment_start_time' => $startTime, 'appointment_end_time' => $endTime, 'user_name' => $userName, 'phone_number' => $phoneNumber, 'use_coupon_id' => $couponId, 'use_coupon_code' => $couponCode); // 事务开始 $this->db->trans_start(); // 设置优惠券已使用 if ($couponId && $project['can_use_coupon']) { $customerCouponModel->useCoupon($couponId, $openId); } else { if ($couponCode && $project['can_use_coupon_code']) { $couponCodeModel->addUseTimes($couponCode); } else { } } $insertOrderNo = (new CurdUtil($orderModel))->create($orderData); if ($insertOrderNo) { $orderProjectData = array('order_id' => $insertOrderNo, 'project_id' => $project['project_id'], 'project_use_time' => $project['use_time'], 'project_price' => $project['price'], 'create_time' => DateUtil::now(), 'project_name' => $project['project_name'], 'project_cover' => $project['project_cover']); } else { $this->message('提交订单失败,请重试!'); } (new CurdUtil($orderProjectModel))->create($orderProjectData); $this->db->trans_complete(); if ($this->db->trans_status() === FALSE) { $this->db->trans_rollback(); $this->message('提交订单失败,请重试!'); } else { $this->db->trans_commit(); // 清空购物车 (new CartUtil())->emptyCart(); // 跳到 订单显示 ResponseUtil::redirect(UrlUtil::createUrl('order/pay/' . $orderNo)); } }