carrier_operator

This commit is contained in:
邓皓元 2018-12-25 16:43:03 +08:00
parent 9349b43730
commit 8e8ecf8d35
7 changed files with 128 additions and 424 deletions

View File

@ -1,391 +0,0 @@
<?php
namespace App\Domains\Virtual\Commands\Sync;
use Carbon\Carbon;
use App\Models\Card\Card;
use App\Models\Virtual\Order;
use App\Models\Virtual\OrderCard;
use Illuminate\Support\Facades\DB;
use App\Models\Virtual\OrderRenewalCard;
use App\Domains\Virtual\Services\CommonService;
use App\Domains\Virtual\Services\ProductService;
use App\Domains\Card\Repositories\BlocRepository;
use App\Domains\Card\Repositories\CardRepository;
use App\Domains\Virtual\Repositories\CompanyRepository;
use App\Domains\Virtual\Repositories\PackageRepository;
use App\Domains\Virtual\Repositories\ProductRepository;
class CardSync extends Command
{
protected $name = 'virtual:sync-card';
protected $description = '同步VD卡信息数据';
protected static $carrierOperators = [10 => 0, 11 => 1, 12 => 2];
protected static $payChannels = [10 => 'wx', 11 => 'alipay', 12 => 'bank'];
protected $blocs;
protected $packages;
protected $products;
protected $limit = 1;
const FILENAME = 'app/command/sync-card.json';
const INIT_ID = 0;
public function handle()
{
$contents = $this->getFile();
$maxId = $contents['maxId'];
$nextId = $contents['maxId'];
$this->saveFile(1, $maxId);
$query = DB::connection('vd_old')->table('ckb_custom')
->select(['id', 'custom_no', 'imsi', 'carrieroperator', 'iccid', 'card_number', 'card_from', 'iccid', 'company', 'custom_state', 'create_time' ,'update_time'])
->where('id', '>', $maxId);
$logQuery = DB::connection('vd_old')->table('ckb_custom_handle_log')
->select(['type', 'company', 'pay_type', 'content', 'valid_start_time', 'valid_end_time', 'sale_account', 'order_account', 'create_time']);
$total = $query->count();
$this->line('待同步条数:' . $total);
if ($total) {
$this->blocs = app(BlocRepository::class)->get()->pluck('id', 'shorthand')->toArray();
$this->packages = app(PackageRepository::class)->get()->keyBy('sn');
$this->products = app(ProductRepository::class)->get()->keyBy('sn');
}
$page = 1;
while ($total) {
echo $page . PHP_EOL;
$value = $query->offset(($page - 1) * $this->limit)->limit($this->limit)->get()->first();
if (!$value) {
break;
}
$value = (array)$value;
$logs = $logQuery->where('custom_no', $value['custom_no'])->get()->collect();
$existed = Card::where('sim', $value['card_number'])->first();
DB::beginTransaction();
try {
$card = $this->handleCard($value, $logs, $existed);
$this->handleOrder($card, $logs, $existed);
$this->handleRenewals($card, $logs, $existed);
$this->handleRenewalPackages($card, $logs, $existed);
$this->handleFlows($card, $logs, $existed);
DB::commit();
} catch (\Exception $e) {
DB::rollback();
throw $e;
}
$nextId = $value['id'];
if ($page * $this->limit >= $total) {
break;
}
$page++;
}
app(CardRepository::class)->forgetCached();
$this->saveFile(0, $nextId);
}
// 卡数据转换
protected function handleCard($value, $logs, $existed)
{
// 判断卡类型
$type = ($value['card_number'][3] >= 5) ? 1 : ($existed ? 0 : 2);
// 激活记录
$activateLog = $logs->where('type', 10)->first();
$activated_at = $activateLog ? date('Y-m-d H:i:s', $activateLog['valid_start_time']) : null;
$cardData = [
'sim' => $value['card_number'],
'imsi' => $value['imsi'],
'iccid' => $value['iccid'],
'bloc_id' => $this->blocs[$value['card_from']] ?? 0,
'carrier_operator' => self::$carrierOperators[$value['carrieroperator']],
'activated_at' => $existed['activated_at'] ?? $activated_at,
'virtual_activated_at' => $activated_at,
'type' => $type,
'cancelled_at' => ($value['custom_state'] === 13) ? date('Y-m-d H:i:s', $value['update_time']) : null,
'created_at' => date('Y-m-d H:i:s', $value['create_time']),
'updated_at' => date('Y-m-d H:i:s', $value['update_time']),
];
if ($existed) {
$card = Card::where('sim', $card['sim'])->update($cardData);
} else {
$card = Card::create($cardData);
}
return $card;
}
// 销售记录
protected function handleOrder($card, $logs, $existed)
{
if (!$res = $logs->where('type', 13)->first()) {
return null;
}
$package = $this->getPackage($res['content']);
$unit_price = floatval($res['sale_account']) * 100;
$custom_price = floatval($res['order_account']) * 100;
$product = $this->getProduct($package, $res['company'], $unit_price);
// 按规则生成订单编号 (月+公司+产品)
$sn = date('Ym', $res['create_time']) . sprintf('%08d', $custom_price) . sprintf('%04d', $product['id']);
$orderData = [
'sn' => $sn,
'source' => 1,
'type' => 0,
'company_id' => $res['company'],
'package_id' => $package['id'],
'product_id' => $product['id'],
'pay_channel' => self::$payChannels[$res['pay_type']],
'unit_price' => $unit_price,
'counts' => 1,
'total_price' => $unit_price,
'custom_price' => $custom_price,
'order_at' => date('Y-m-d H:i:s', $res['create_time']),
'order_status' => 4,
'transaction_status' => 1,
'created_at' => date('Y-m-d H:i:s', $res['create_time']),
];
if ($order = Order::where('sn', $orderData['sn'])->first()) {
$order->counts = $order->counts + 1;
$order->total_price = $order->total_price + $unit_price;
$order->custom_price = $order->custom_price + $custom_price;
$order->save();
} else {
$order = Order::create($orderData);
}
OrderCard::upsert([
'sim' => $card['sim'],
'order_id' => $order['id'],
'company_id' => $order['company_id'],
'package_id' => $order['package_id'],
], ['sim', 'order_id']);
}
// 续费记录
protected function handleRenewals($card, $logs, $existed)
{
$res = $logs->where('type', 11)->values()->all();
if (empty($res)) {
return ;
}
$array = [];
foreach ($res as $item) {
$package = $this->getPackage($item['content']);
$unit_price = floatval($item['sale_account']) * 100;
$custom_price = floatval($item['order_account']) * 100;
$sn = date('Ym', $item['create_time']) . sprintf('%04d', $item['company']) . sprintf('%04d', $package['id']) . sprintf('%04d', $custom_price);
if (!$array[$sn]) {
$array[$sn] = [
'sn' => $sn,
'type' => 1,
'company_id' => $item['company'],
'package_id' => $package->id,
'unit_price' => $unit_price,
'counts' => 1,
'total_price' => $unit_price,
'custom_price' => $custom_price,
'order_at' => date('Y-m-d H:i:s', $item['create_time']),
];
} else {
$array[$sn] = [];
}
if ($order = Order::where('sn', $orderData['sn'])->first()) {
$order->counts = $order->counts + 1;
$order->total_price = $order->total_price + $unit_price;
$order->custom_price = $order->custom_price + $custom_price;
$order->save();
} else {
$order = Order::create($orderData);
}
if ($orderRenewalCard = OrderRenewalCard::where('sim', $card['sim'])->where('order_id', $order->id)->first()) {
$orderRenewalCard->count = $orderRenewalCard->count + 1;
$orderRenewalCard->save();
} else {
OrderRenewalCard::upsert([
'sim' => $card->sim,
'order_id' => $order->id,
'company_id' => $order->company_id,
'package_id' => $order->package_id,
'counts' => 1,
'unit_price' => $order->unit_price
], ['sim', 'order_id']);
}
}
}
// 续费包记录
protected function handleRenewalPackages($card, $logs, $existed)
{
$res = $logs->where('type', 14)->values()->all();
if (empty($res)) {
return ;
}
foreach ($res as $item) {
$package = $this->getPackage($item['content']);
$unit_price = floatval($item['sale_account']) * 100;
$custom_price = floatval($item['order_account']) * 100;
$sn = date('Ym', $item['create_time']) . sprintf('%04d', $item['company']) . sprintf('%04d', $package['id']) . sprintf('%04d', $custom_price);
$array[] = [
'sn' => $sn,
'type' => 2,
'company_id' => $item['company'],
'unit_price' => $unit_price,
'counts' => DB::raw('counts + 1'),
'total_price' => DB::raw("total_price + {$unit_price}"),
'custom_price' => DB::raw("custom_price + {$custom_price}"),
'order_at' => date('Y-m-d H:i:s', $item['create_time']),
];
}
}
// 加油包记录
protected function handleFlows($card, $logs, $existed)
{
$res = $logs->where('type', 15)->values()->all();
if (empty($res)) {
return ;
}
foreach ($res as $item) {
$package = $this->getPackage($item['content']);
$unit_price = floatval($item['sale_account']) * 100;
$custom_price = floatval($item['order_account']) * 100;
$sn = date('Ym', $item['create_time']) . sprintf('%04d', $item['company']) . sprintf('%04d', $package['id']) . sprintf('%04d', $custom_price);
$array[] = [
'sn' => $sn,
'type' => 3,
'company_id' => $item['company'],
'unit_price' => $unit_price,
'counts' => DB::raw('counts + 1'),
'total_price' => DB::raw("total_price + {$unit_price}"),
'custom_price' => DB::raw("custom_price + {$custom_price}"),
'order_at' => date('Y-m-d H:i:s', $item['create_time']),
];
}
}
/**
* 获取套餐
*
* @param string $sn
* @return void
*/
protected function getPackage($sn)
{
if (!$package = $this->packages[$sn]) {
throw new \Exception('套餐不存在');
}
return $package;
}
/**
* 获取定价
*
* @param string $sn
* @return void
*/
protected function getProduct($package, $companyId, $price)
{
$sn = strtoupper($package['sn'] . '_' . $companyId . '_' . $price);
if (!$product = $this->products[$sn]) {
$product = app(ProductService::class)->store([
'name' => $package['name'] . '' . $price,
'company_id' => $companyId,
'package_id' => $package['id'],
'base_price' => $price,
'renewal_price' => $price,
]);
$this->products[$sn] = $product;
}
return $product;
}
/**
* 获取文件内容
*
* @return void
*/
protected function getFile()
{
$file = storage_path(self::FILENAME);
if (!file_exists($file)) {
$dir = dirname($file);
if (null !== $dir && !is_dir($dir)) {
mkdir($dir, 0777, true);
}
$this->saveFile(0, self::INIT_ID);
}
$contents = file_get_contents($file);
return json_decode($contents, 256);
}
/**
* 写入文件
*
* @param integer $status 状态 1运行中 0运行结束
* @param integer $maxId 最后查询的ID
* @return void
*/
protected function saveFile(int $status, int $maxId)
{
$file = storage_path(self::FILENAME);
$contents = json_encode([
'status' => $status,
'maxId' => $maxId,
]);
file_put_contents($file, $contents);
}
}

View File

@ -63,7 +63,7 @@ class CardSync extends Command
'imsi' => $value['imsi'],
'iccid' => $value['iccid'],
'bloc_id' => $this->blocs[$value['card_from']] ?? 0,
'carrier_operator' => self::$carrierOperators[$value['carrieroperator']],
'carrier_operator' => self::$carrierOperators[$value['carrieroperator']] ?? 255,
'type' => ($value['card_number'][3] >= 5) ? 1 : 0,
'activated_at' => date('Y-m-d H:i:s', $value['card_cycle_start']),
'virtual_activated_at' => date('Y-m-d H:i:s', $value['card_cycle_start']),

View File

@ -4,11 +4,14 @@ namespace App\Domains\Virtual\Commands\Sync;
use Carbon\Carbon;
use App\Models\Card\Card;
use MongoDB\BSON\UTCDateTime;
use App\Models\Virtual\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;
use App\Domains\Virtual\Services\ProductService;
use App\Domains\Card\Repositories\BlocRepository;
use App\Domains\Card\Repositories\CardRepository;
use App\Domains\Virtual\Repositories\PackageRepository;
use App\Domains\Virtual\Repositories\ProductRepository;
class LogSync extends Command
{
@ -16,31 +19,40 @@ class LogSync extends Command
protected $description = '同步VD订单数据';
protected static $types = [11 => 1, 13 => 0, 14 => 2, 15 => 3];
protected static $carrierOperators = [10 => 0, 11 => 1, 12 => 2];
protected static $payChannels = [10 => 'wx', 11 => 'alipay', 12 => 'bank'];
protected static $orderClasses = [
\App\Models\Virtual\OrderCard::class,
\App\Models\Virtual\OrderRenewalCard::class,
\App\Models\Virtual\OrderRenewalPackageCard::class,
\App\Models\Virtual\OrderFlowPackageCards::class,
];
protected $limit = 1000;
protected $filename = 'sync-log.json';
protected $initCursor = 946656000000; // '2000-01-01 00:00:00'
protected $initCursor = 0; // '2000-01-01 00:00:00'
protected $blocs;
protected $packages;
protected $products;
public function handle()
{
$contents = $this->getFile();
$microtime = $contents['cursor'];
$now_microtime = intval(microtime(true) * 1000);
$nextId = $maxId = $contents['cursor'];
$this->saveFile(1, $microtime);
$this->saveFile(1, $maxId);
$utcDateTime = new UTCDateTime($microtime);
$this->blocs = app(BlocRepository::class)->get()->pluck('id', 'shorthand')->toArray();
$this->packages = app(PackageRepository::class)->get()->keyBy('sn');
$this->products = app(ProductRepository::class)->get()->keyBy('sn');
Artisan::call('real:sync-bloc');
$blocs = app(BlocRepository::class)->get()->pluck('id', 'sn')->toArray();
$query = DB::connection('mongo')->table('tblCard')
->select(['cNo', 'iccid', 'imsi', 'comId', 'oType', 'saDate', 'sDate'])
->where('isDel', '<>', 1)
->where('sDate', '>', $utcDateTime);
$query = DB::connection('vd_old')->table('logs')
->where('type', '<>', 10)
->where('create_time', '>', $timestamp);
$total = $query->count();
@ -52,24 +64,74 @@ class LogSync extends Command
echo $page . PHP_EOL;
$res = $query->offset(($page - 1) * $this->limit)->limit($this->limit)->get();
$values = [];
DB::beginTransaction();
foreach ($res as $key => $value) {
$activated_at = $value['saDate'] ? $value['saDate']->toDateTime()->format('Y-m-d H:i:s') : null;
$sim = intval(preg_replace('/\D/', '', $value['cNo']));
$values[$sim] = [
'sim' => $sim,
'imsi' => $value['imsi'] ?? '',
'iccid' => $value['iccid'] ?? '',
'bloc_id' => $blocs[$value['comId']] ?? 0,
'carrier_operator' => self::$carrierOperators[$value['oType']] ?? 255,
'activated_at' => $activated_at,
'created_at' => $value['sDate']->toDateTime()->format('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
$package = $this->getPackage($value['content']);
$unit_price = floatval($value['sale_account']) * 100;
$custom_price = floatval($value['order_account']) * 100;
$product = $this->getProduct($package, $value['company'], $unit_price);
$type = self::$types[$value['type']];
$pay_channel = self::$payChannels[$value['pay_type']];
// 按规则生成订单编号 (月6+类型1+公司3+套餐4+价格6)
$sn = date('Ym', $value['create_time']) . $type . sprintf('%03d', $value['company']) . sprintf('%04d', $package['id']) . sprintf('%06d', $custom_price);
$data = [
'sn' => $sn,
'source' => 1,
'type' => $type,
'company_id' => $value['company'],
'package_id' => $package['id'],
'product_id' => $product['id'],
'pay_channel' => $pay_channel,
'unit_price' => $unit_price,
'counts' => 1,
'total_price' => $unit_price,
'custom_price' => $custom_price,
'order_at' => date('Y-m-d H:i:s', $res['create_time']),
'order_status' => 4,
'transaction_status' => 1,
'created_at' => date('Y-m-d H:i:s', $res['create_time']),
];
$relationData = [
'sim' => $value['sim'],
'order_id' => $order->id,
'company_id' => $order->company_id,
'package_id' => $order->package_id,
'counts' => 1,
'unit_price' => $order->unit_price
];
try {
if ($order = Order::where('sn', $data['sn'])->first()) {
$order->count = $order->count + 1;
$order->total_price = $order->total_price + $unit_price;
$order->custom_price = $order->custom_price + $custom_price;
$order->save();
} else {
$order = Order::create($data);
}
$query = (new $orderClasses[$type])->query();
if ($relation = $query->where('sim', $value['sim'])->where('order_id', $order->id)->first()) {
$relation->count = $relation->count + 1;
$relation->save();
} else {
$relation = $query->create($relationData);
}
} catch (\Exception $e) {
DB::rollback();
throw $e;
}
}
Card::upsert($values, 'sim', true);
DB::commit();
$nextId = $value['id'];
$this->saveFile(0, $nextId);
if ($page * $this->limit >= $total) {
break;
@ -77,9 +139,44 @@ class LogSync extends Command
$page++;
}
}
app(CardRepository::class)->forgetCached();
/**
* 获取套餐
*
* @param string $sn
* @return void
*/
protected function getPackage($sn)
{
if (!$package = $this->packages[$sn]) {
throw new \Exception('套餐不存在');
}
$this->saveFile(0, $now_microtime);
return $package;
}
/**
* 获取定价
*
* @param string $sn
* @return void
*/
protected function getProduct($package, $companyId, $price)
{
$sn = strtoupper($package['sn'] . '_' . $companyId . '_' . $price);
if (!$product = $this->products[$sn]) {
$product = app(ProductService::class)->store([
'name' => $package['name'] . '' . $price,
'company_id' => $companyId,
'package_id' => $package['id'],
'base_price' => $price,
'renewal_price' => $price,
]);
$this->products[$sn] = $product;
}
return $product;
}
}

View File

@ -26,6 +26,7 @@ class VirtualServiceProvider extends ServiceProvider
\App\Domains\Virtual\Commands\Sync\PackageSync::class,
\App\Domains\Virtual\Commands\Sync\ProductSync::class,
\App\Domains\Virtual\Commands\Sync\CardSync::class,
\App\Domains\Virtual\Commands\Sync\LogSync::class,
]);
}

View File

@ -6,7 +6,7 @@ use App\Core\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Virtual\Relations\OrderRelations;
class OrderRenewalPackageCard extends Model
class OrderFlowPackageCards extends Model
{
use SoftDeletes, OrderRelations;

View File

@ -52,8 +52,6 @@ class CreateVirtualOrdersTable extends Migration
$table->index('order_at');
$table->comment('VD订单');
});
}
/**

View File

@ -30,7 +30,6 @@ class CreateVirtualOrderCardsTables extends Migration
$table->integer('company_id')->unsigned()->default(0)->comment('企业ID');
$table->integer('package_id')->unsigned()->default(0)->comment('套餐ID');
$table->integer('counts')->unsigned()->default(1)->comment('数量');
$table->integer('unit_price')->unsigned()->default(0)->comment('单价');
$table->primary(['order_id', 'sim']);
$table->comment($table_comment);
});