Commit b56527f2 authored by hangjun83's avatar hangjun83

openapi 1.1

parent 9570074d
<?php
namespace App\Console\Commands;
use App\Services\Api\RhawnOrdersService;
use App\Services\AuthService;
use App\Services\CustomerService;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
class TestJobCommand extends Command
{
use ConfirmableTrait;
/**
* 命令行的名称及用法。
*
* @var string
*/
protected $signature = 'test:job
{--action_type= : 任务操作类型}
{--params= : 任务参数}';
/**
* 命令行的概述。
*
* @var string
*/
protected $description = 'test任务命令行';
/**
* 创建新的命令实例。
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* 运行命令。
* @throws \Exception
*/
public function handle()
{
if (! $this->confirmToProceed()) {
return 1;
}
if($this->hasArgument('help')){
$this->help();
}else{
$action_type = $this->option('action_type');
$params = $this->option('params');
if(empty($action_type)){
$this->error('缺少命令参数,请输入具体的参数命令.如需帮助请输入 --help');
exit;
}
$service = app(RhawnOrdersService::class);
switch($action_type){
case 'test' :
$service->getCustomerRhawnOrdersList(['customer_code' => '80330','page_size' => 100, 'page_no' => 1]);
break;
case 'getCustomerOrderDetail' :
$service->getCustomerOrderDetail(['customer_code' => '80330','order_number' => '20170911-1305']);
break;
case 'createNewCustomerOrders' :
$service->createNewCustomerOrders([
'customer_code' => '80056',
"so_cus_po" => '2000000011111',
"so_ca_name" => '张三',
"so_ca_mobile" => '13321686555',
"so_ca_phone" => '61111111',
"so_ca_province" => '上海',
"so_ca_city" => '上海市',
//"so_ca_county" => '奉贤区',
"so_ca_street" => '望园路88888号888室',
"so_note" => '测试',
'items' => [
[
'p_code' => 'R000001-20mg',
'num' => 1,
'si_molbase_pog' => ''
]
]
]);
break;
case 'cancelCustomerOrder' :
$service->cancelCustomerOrder(['customer_code' => '80056','order_number' => '20220929-1225649']);
break;
case 'createPlatformCustomer' :
$customerService = app(CustomerService::class);
$customerService->createPlatformCustomer(['customer_code' => '80056','customer_company' => '测试']);
break;
case 'refreshCustomerToken' :
$customerService = app(CustomerService::class);
$customerService->refreshCustomerToken(['platform_customer_id' => '2']);
break;
case 'getToken' :
$authService = app(AuthService::class);
$authService->getToken(['token' => '2tylDpWuvLAfWmAX1']);
break;
default:
}
}
}
public function help()
{
$helpStr = "参数帮助说明";
$this->comment($this->setHelp($helpStr)->getProcessedHelp());
$this->line("action_type: 具体动作参数\n\n initProductToExcel => 初始化批量商品 \n batchUpdateProduct => 批量更新商品\n\nparams : 操作需要传入的参数.非必填项");
}
}
...@@ -11,18 +11,15 @@ ...@@ -11,18 +11,15 @@
namespace App\Http\Controllers\Middleware; namespace App\Http\Controllers\Middleware;
use App\Repositories\Contracts\ThirdApiPlatformRepository; use App\Services\CustomerService;
use App\Repositories\Enums\ResponseCodeEnum;
use App\Services\RoleAndPermissionsService;
use App\Services\ThirdPlatform\ZhenKhService; use App\Services\ThirdPlatform\ZhenKhService;
use Carbon\Exceptions\UnitNotConfiguredException;
use Closure; use Closure;
use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Str; use Jiannei\Response\Laravel\Support\Facades\Response;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use App\Support\Traits\Helpers; use App\Support\Traits\Helpers;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class Authenticate class Authenticate
...@@ -58,21 +55,32 @@ class Authenticate ...@@ -58,21 +55,32 @@ class Authenticate
public function handle($request, Closure $next, $guard = null) public function handle($request, Closure $next, $guard = null)
{ {
$token = trim(str_ireplace('bearer', '', $request->header('authorization'))); $token = trim(str_ireplace('bearer', '', $request->header('authorization')));
try{
$decodeToken = $this->decodeToken($token); $decodeToken = $this->decodeToken($token);
if(empty($decodeToken) || (!is_array($decodeToken) && !$decodeToken['hash'])){
return Response::fail('客户token无效',500,'');
}
}catch(\Throwable $exception){
return Response::fail('客户token无效',500,'');
}
$params = $request->all(); $params = $request->all();
if(!isset($params['platform']) || empty($params['platform'])){ if(isset($params['platform']) && !empty($params['platform'])){
throw new UnauthorizedHttpException('JWTAuth','平台参数错误');
}
switch($params['platform']){ switch($params['platform']){
case 'zkh' : $platformToken = app(ZhenKhService::class)->apiService->getPlatformInfo('platform_token');break; case 'zkh' : $platformToken = app(ZhenKhService::class)->apiService->getPlatformInfo('platform_token');break;
} }
if(empty($platformToken) || $decodeToken['hash'] !== $platformToken){ if(empty($platformToken) || $decodeToken['hash'] !== $platformToken){
throw new UnauthorizedHttpException('JWTAuth','无效的平台token'); throw new UnauthorizedHttpException('JWTAuth','无效的平台token');
} }
}
if(empty($decodeToken) || (!is_array($decodeToken) && !$decodeToken['hash'])){ else{
throw new UnauthorizedHttpException('JWTAuth', 'Unable to authenticate with invalid token.'); $customerService = app(CustomerService::class);
try{
$customer = $customerService->getCustomerInfoByToken($decodeToken['hash']);
$request->attributes->add(['customer_code' => $customer['cus_number']]);
}catch(\Throwable $exception){
return Response::fail('客户token无效',500,'');
}
} }
return $next($request); return $next($request);
......
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Http\Controllers\Middleware;
use Carbon\Carbon;
use Illuminate\Http\Response;
use Illuminate\Routing\Middleware\ThrottleRequests;
class RateLimits extends ThrottleRequests
{
protected function resolveRequestSignature($request)
{
//用户唯一性通过方法、路径、ip、用户token通过sha1方式加密
return sha1(implode('|', [
$request->method(),
$request->root(),
$request->path(),
$request->ip(),
$request->header('X-Access-Token')
]
));
}
protected function buildResponse($key, $maxAttempts)
{
//超时返回429
$response = new Response('Too frequent access.', 429);
$retryAfter = $this->limiter->availableIn($key);
return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter,1),
$retryAfter
);
}
}
\ No newline at end of file
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Http\Controllers\Swagger\Responses\Rhawn;
use Illuminate\Http\JsonResponse;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\Items;
/**
* @Schema(
* title="订单配货单响应内容",
* description="订单配货单响应内容"
* )
*
* @package App\Http\Responses
*/
class OrdersDispatchList extends JsonResponse
{
/**
* @Property(
* type="integer",
* description="soId"
* )
*
* @var string
*/
public $dpCode;
/**
* @Property(
* type="string",
* description="订单编号"
* )
*
* @var string
*/
public $soNo;
/**
* @Property(
* type="string",
* description="快递名称"
* )
*
* @var string
*/
public $dpExpressName;
/**
* @Property(
* type="string",
* description="快递单号"
* )
*
* @var string
*/
public $dpExpressNo;
/**
* @Property(
* type="array",
* @Items(ref="#/components/schemas/OrdersDispatchProperty")
* )
*
* @var array
*/
public $detail = [];
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Http\Controllers\Swagger\Responses\Rhawn;
use Illuminate\Http\JsonResponse;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\Items;
/**
* @Schema(
* title="订单列表响应内容",
* description="订单列表响应内容"
* )
*
* @package App\Http\Responses
*/
class OrdersList extends JsonResponse
{
/**
* @Property(
* type="integer",
* description="总页数"
* )
*
* @var integer
*/
public $totalPage;
/**
* @Property(
* type="integer",
* description="当前页数"
* )
*
* @var integer
*/
public $pageNo;
/**
* @Property(
* type="array",
* @Items(ref="#/components/schemas/OrdersProperty")
* )
*
* @var array
*/
public $list = [];
}
<?php
namespace App\Http\Controllers\Swagger\Responses\Rhawn\Properties;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
/**
* @Schema(
* title="产品详情内容",
* description="产品详情内容"
* )
*/
class ProductByCas
{
/**
* @Property(
* type="string",
* description="产品编号"
* )
*
* @var string
*/
public $code;
/**
* @Property(
* type="string",
* description="cas"
* )
*
* @var string
*/
public $cas;
/**
* @Property(
* type="string",
* description="中文名称"
* )
*
* @var string
*/
public $chemCnName;
/**
* @Property(
* type="string",
* description="英文名称"
* )
*
* @var string
*/
public $chemEnName;
/**
* @Property(
* type="string",
* description="中文名称"
* )
*
* @var string
*/
public $cnName;
/**
* @Property(
* type="string",
* description="英文名称"
* )
*
* @var string
*/
public $enName;
/**
* @Property(
* type="string",
* description="项目规格"
* )
*
* @var string
*/
public $level;
/**
* @Property(
* type="number",
* description="单价"
* )
*
* @var string
*/
public $price;
/**
* @Property(
* type="number",
* description="市场价"
* )
*
* @var string
*/
public $marketPrice;
/**
* @Property(
* type="integer",
* description="状态"
* )
*
* @var string
*/
public $status;
/**
* @Property(
* type="integer",
* description="是否易制爆"
* )
*
* @var string
*/
public $ifExplode;
/**
* @Property(
* type="integer",
* description="是否危化品"
* )
*
* @var string
*/
public $ifDangers;
/**
* @Property(
* type="string",
* description="包装"
* )
*
* @var string
*/
public $pack;
/**
* @Property(
* type="number",
* description="重量"
* )
*
* @var string
*/
public $weight;
/**
* @Property(
* type="string",
* description="标签"
* )
*
* @var string
*/
public $tag;
/**
* @Property(
* type="string",
* description="城市"
* )
*
* @var string
*/
public $city;
/**
* @Property(
* type="string",
* description="货期"
* )
*
* @var string
*/
public $stock;
/**
* @Property(
* type="string",
* description="项目规格"
* )
*
* @var string
*/
public $pacs;
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Http\Controllers\Swagger\Responses\Rhawn;
use Illuminate\Http\JsonResponse;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\Items;
/**
* @Schema(
* title="订单列表响应内容",
* description="订单列表响应内容"
* )
*
* @package App\Http\Responses
*/
class ProductsList extends JsonResponse
{
/**
* @Property(
* type="integer",
* description="总页数"
* )
*
* @var integer
*/
public $totalPage;
/**
* @Property(
* type="integer",
* description="当前页数"
* )
*
* @var integer
*/
public $pageNo;
/**
* @Property(
* type="array",
* @Items(ref="#/components/schemas/ProductsProperty")
* )
*
* @var array
*/
public $list = [];
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Http\Controllers\Swagger\Responses\Rhawn\Properties;
use Illuminate\Http\JsonResponse;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
/**
* @Schema(
* title="订单配货单项内容",
* description="订单配货单项内容"
* )
*
* @package App\Http\Responses
*/
class OrdersDispatchProperty
{
/**
* @Property(
* type="integer",
* description="发货数量"
* )
*
* @var string
*/
public $dpdNum;
/**
* @Property(
* type="integer",
* description="发货金额"
* )
*
* @var string
*/
public $dpdAmount;
/**
* @Property(
* type="integer",
* description="产品编号"
* )
*
* @var string
*/
public $pCode;
/**
* @Property(
* type="integer",
* description="产品英文名称"
* )
*
* @var string
*/
public $pEnName;
/**
* @Property(
* type="integer",
* description="产品中文名称"
* )
*
* @var string
*/
public $pCnName;
/**
* @Property(
* type="string",
* description="cas"
* )
*
* @var string
*/
public $cas;
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Http\Controllers\Swagger\Responses\Rhawn\Properties;
use Illuminate\Http\JsonResponse;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
/**
* @Schema(
* title="订单项内容",
* description="订单项内容"
* )
*
* @package App\Http\Responses
*/
class OrdersProperty
{
/**
* @Property(
* type="integer",
* description="soId"
* )
*
* @var string
*/
public $soId;
/**
* @Property(
* type="string",
* description="订单编号"
* )
*
* @var string
*/
public $soNo;
/**
* @Property(
* type="number",
* description="订单金额"
* )
*
* @var string
*/
public $soTotal;
/**
* @Property(
* type="integer",
* description="订单审核状态"
* )
*
* @var string
*/
public $soReviewStatus;
/**
* @Property(
* type="integer",
* description="订单支付状态"
* )
*
* @var string
*/
public $soPayStatus;
/**
* @Property(
* type="integer",
* description="下单时间"
* )
*
* @var string
*/
public $soCtime;
}
<?php
namespace App\Http\Controllers\Swagger\Responses\Rhawn\Properties;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
/**
* @Schema(
* title="产品详情内容",
* description="产品详情内容"
* )
*/
class ProductDetailProperty
{
/**
* @Property(
* type="string",
* description="产品编号"
* )
*
* @var string
*/
public $code;
/**
* @Property(
* type="string",
* description="cas"
* )
*
* @var string
*/
public $cas;
/**
* @Property(
* type="string",
* description="中文名称"
* )
*
* @var string
*/
public $chemCnName;
/**
* @Property(
* type="string",
* description="英文名称"
* )
*
* @var string
*/
public $chemEnName;
/**
* @Property(
* type="string",
* description="中文名称"
* )
*
* @var string
*/
public $cnName;
/**
* @Property(
* type="string",
* description="英文名称"
* )
*
* @var string
*/
public $enName;
/**
* @Property(
* type="string",
* description="项目规格"
* )
*
* @var string
*/
public $level;
/**
* @Property(
* type="string",
* description="货期"
* )
*
* @var string
*/
public $delivery;
/**
* @Property(
* type="number",
* description="单价"
* )
*
* @var string
*/
public $price;
/**
* @Property(
* type="number",
* description="市场价"
* )
*
* @var string
*/
public $marketPrice;
/**
* @Property(
* type="integer",
* description="状态"
* )
*
* @var string
*/
public $status;
}
<?php
namespace App\Http\Controllers\Swagger\Responses\Rhawn\Properties;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
/**
* @Schema(
* title="产品项内容",
* description="产品项内容"
* )
*/
class ProductsProperty
{
/**
* @Property(
* type="string",
* description="产品编号"
* )
*
* @var string
*/
public $code;
/**
* @Property(
* type="string",
* description="cas"
* )
*
* @var string
*/
public $cas;
/**
* @Property(
* type="string",
* description="中文名称"
* )
*
* @var string
*/
public $chemCnName;
/**
* @Property(
* type="string",
* description="英文名称"
* )
*
* @var string
*/
public $chemEnName;
/**
* @Property(
* type="string",
* description="中文名称"
* )
*
* @var string
*/
public $cnName;
/**
* @Property(
* type="string",
* description="英文名称"
* )
*
* @var string
*/
public $enName;
/**
* @Property(
* type="string",
* description="项目规格"
* )
*
* @var string
*/
public $level;
/**
* @Property(
* type="string",
* description="货期"
* )
*
* @var string
*/
public $delivery;
/**
* @Property(
* type="number",
* description="单价"
* )
*
* @var string
*/
public $price;
/**
* @Property(
* type="number",
* description="市场价"
* )
*
* @var string
*/
public $marketPrice;
/**
* @Property(
* type="integer",
* description="是否易制爆"
* )
*
* @var string
*/
public $ifExplode;
/**
* @Property(
* type="integer",
* description="是否易制毒"
* )
*
* @var string
*/
public $ifDrag;
/**
* @Property(
* type="integer",
* description="是否危化品"
* )
*
* @var string
*/
public $ifDangers;
/**
* @Property(
* type="integer",
* description="状态"
* )
*
* @var string
*/
public $status;
/**
* @Property(
* type="string",
* description="包装"
* )
*
* @var string
*/
public $pack;
/**
* @Property(
* type="number",
* description="重量"
* )
*
* @var string
*/
public $weight;
/**
* @Property(
* type="string",
* description="标签"
* )
*
* @var string
*/
public $tag;
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Http\Controllers\V1\Auth;
use App\Services\AuthService;
use Illuminate\Http\Request;
use App\Http\Controllers\V1\Controller;
use App\Support\Traits\Helpers;
use Jiannei\Response\Laravel\Support\Facades\Response;
use OpenApi\Annotations\Post;
use OpenApi\Annotations\RequestBody;
use OpenApi\Annotations\MediaType;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\Response as AnnotationResponse;
use OpenApi\Annotations as OA;
class CustomerAuthController extends Controller
{
use Helpers;
public function __construct(AuthService $authService)
{
$this->authService = $authService;
}
/**
* @Post(
* path="/openapi/auth/getToken",
* tags={"AuthToken"},
* summary="获取用户auth token,用于接口的用户权限验证",
* description="获取用户auth token",
* @RequestBody(
* @MediaType(
* mediaType="application/json",
* @Schema(
* required={"customerToken"},
* @Property(property="customerToken", @Schema(type="string"),description="用户私有key"),
* example={"customerToken" : "XXXX"}
* )
* )
* ),
* @AnnotationResponse(
* response="200",
* description="正常操作响应",
* @MediaType(
* mediaType="application/json",
* @Schema(
* allOf={
* @Schema(ref="#/components/schemas/ApiResponse"),
* }
* )
* )
* ),
* )
*/
public function getToken(Request $request)
{
$message = [
'customerToken.required' => "客户token必传",
];
$this->validateRequest($request, $message);
$params = $request->all();
$params = $this->formatKeysfromArray($params,'toUnderScore');
try{
$token = $this->authService->getToken($params);
return Response::success($token,'操作成功');
}catch(\Throwable $exception){
return Response::fail('获取token失败',500);
}
}
}
...@@ -14,6 +14,36 @@ namespace App\Http\Controllers\V1; ...@@ -14,6 +14,36 @@ namespace App\Http\Controllers\V1;
use Jiannei\Response\Laravel\Support\Facades\Response; use Jiannei\Response\Laravel\Support\Facades\Response;
use Jiannei\Response\Laravel\Support\Traits\ExceptionTrait; use Jiannei\Response\Laravel\Support\Traits\ExceptionTrait;
use Laravel\Lumen\Routing\Controller as BaseController; use Laravel\Lumen\Routing\Controller as BaseController;
use OpenApi\Annotations\Info;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Server;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\SecurityScheme;
/**
*
* @Info(
* version="1.0",
* title="罗恩开放平台 API接口文档"
* )
*
* @Schema(
* schema="ApiResponse",
* type="object",
* title="接口返回统一响应实体",
* @Property(property="status", type="string", description="响应结果提示"),
* @Property(
* property="code",
* type="string",
* description="响应代码"
* ),
* @Property(property="message", type="string", description="响应结果提示"),
* @Property(property="data", type="object", description="响应结果数据集"),
* @Property(property="error", type="object", description="响应错误结果数据集")
* )
*
*/
abstract class Controller extends BaseController abstract class Controller extends BaseController
{ {
...@@ -43,4 +73,12 @@ abstract class Controller extends BaseController ...@@ -43,4 +73,12 @@ abstract class Controller extends BaseController
} }
return true; return true;
} }
public function returnErrorExecptionResponse(\Exception $exception, string $message = '')
{
if($exception->getCode() == 500){
return Response::fail($exception->getMessage(),200);
}
return Response::fail($message == '' ? $exception->getMessage() : $message,200);
}
} }
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Http\Controllers\V1\Rhawn;
use App\Services\Api\RhawnOrdersService;
use Illuminate\Http\Request;
use Jiannei\Response\Laravel\Support\Facades\Response;
use App\Http\Controllers\V1\Controller;
use App\Support\Traits\Helpers;
use OpenApi\Annotations\Post;
use OpenApi\Annotations\RequestBody;
use OpenApi\Annotations\MediaType;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\Response as AnnotationResponse;
use OpenApi\Annotations as OA;
class OrdersController extends Controller
{
use Helpers;
public function __construct(RhawnOrdersService $rhawnOrdersService)
{
$this->rhawnOrdersService= $rhawnOrdersService;
}
/**
* @Post(
* path="/openapi/orders/getRhawnOrders",
* tags={"订单相关接口"},
* summary="获取用户订单列表数据集",
* description="订单列表",
* @RequestBody(
* @MediaType(
* mediaType="application/json",
* @Schema(
* required={"pageSize", "pageNo"},
* @Property(property="pageSize", @Schema(type="integer"),description="返回数据集数量"),
* @Property(property="pageNo", @Schema(type="integer"),description="当前页数"),
* example={"pageSize" : 100, "pageNo" : 1}
* )
* )
* ),
* @OA\Parameter(
* description="用户获取的token值",
* in="header",
* name="authorization",
* required=true,
* @OA\Schema(type="string"),
* @OA\Examples(example="authorization", value="bearerNWJiNDhkNzlmNjg0N2FlMmZiYjliZWM3NGVkNzIyMjNleUpsZUhCcGNtVWlPakUyTmpRMk1EazJORGNzSW1oaGMyZ2lPaUl5ZEhsc1JIQlhkWFpNUVdaWGJVRllJbjA9",summary=""),
* ),
* @AnnotationResponse(
* response="200",
* description="正常操作响应",
* @MediaType(
* mediaType="application/json",
* @Schema(
* allOf={
* @Schema(ref="#/components/schemas/ApiResponse"),
* @Schema(
* type="object",
* @Property(property="data", ref="#/components/schemas/OrdersList")
* )
* }
* )
* )
* ),
* security={
* {"bearer_token":{}}
* }
* )
*/
public function getCustomerOrders(Request $request)
{
$customerCode = $request->get('customer_code');
if(!$customerCode){
return Response::ok('客户编号不存在!');
}
$params = [
'customer_code' => $customerCode
];
try{
$orderList = $this->rhawnOrdersService->getCustomerRhawnOrdersList($params);
if($orderList){
$orderList = $this->formatKeysfromArray($orderList,'toCamelCase');
}
return Response::success($orderList,'操作成功');
}catch(\Throwable $exception){
return $this->returnErrorExecptionResponse($exception,'获取订单列表失败');
}
}
/**
* 获取订单详情
* @param Request $request
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
*/
public function getCustomerOrderDetail(Request $request)
{
$customerCode = $request->get('customer_code');
if(!$customerCode){
return Response::ok('客户编号不存在!');
}
$requestParams = $this->formatKeysfromArray($request->all(),'toUnderScore');
$requestParams = array_merge($requestParams,['customer_code' => $customerCode]);
try{
$orderDetail = $this->rhawnOrdersService->getCustomerOrderDetail($requestParams);
if($orderDetail){
$orderDetail = $this->formatKeysfromArray($orderDetail,'toCamelCase');
}
return Response::success($orderDetail,'操作成功');
}catch(\Throwable $exception){
return $this->returnErrorExecptionResponse($exception,'获取订单详情失败');
}
}
/**
*
* @Post(
* path="/openapi/orders/createRhawnOrders",
* tags={"订单相关接口"},
* summary="生成一个用户新订单",
* description="生成新订单",
* @RequestBody(
* @MediaType(
* mediaType="application/json",
* @Schema(
* required={"soCusPo", "soCaName","soCaMobile","soCaPhone","soCaProvince","soCaCity","soCaStreet","soNote","items"},
* @Property(property="soCusPo", @Schema(type="string"),description="客户编号"),
* @Property(property="soCaName", @Schema(type="string"),description="收货人"),
* @Property(property="soCaMobile", @Schema(type="string"),description="收货人手机"),
* @Property(property="soCaPhone", @Schema(type="string"),description="收货人电话"),
* @Property(property="soCaProvince", @Schema(type="string"),description="收货人省份"),
* @Property(property="soCaCity", @Schema(type="string"),description="收货人城市"),
* @Property(property="soCaStreet", @Schema(type="string"),description="收货人区县"),
* @Property(property="soNote", @Schema(type="string"),description="备注"),
* @Property(property="items", type="array",
* @OA\items(
* @Property(property="pCode", @Schema(type="string"),description="产品code"),
* @Property(property="num", @Schema(type="integer"),description="产品数量"),
* ),description="当前页数"),
* example={
"soCusPo": "2000000011111",
"soCaName": "张三",
"soCaMobile": "13321686555",
"soCaPhone": "61111111",
"soCaProvince": "上海",
"soCaCity": "上海市",
"soCaStreet": "望园路88888号888室",
"soNote": "测试",
"items": {{
"pCode": "R000001-20mg",
"num" : "1",
* }}
* }
* )
* )
* ),
* @OA\Parameter(
* description="用户获取的token值",
* in="header",
* name="authorization",
* required=true,
* @OA\Schema(type="string"),
* @OA\Examples(example="authorization", value="bearerNWJiNDhkNzlmNjg0N2FlMmZiYjliZWM3NGVkNzIyMjNleUpsZUhCcGNtVWlPakUyTmpRMk1EazJORGNzSW1oaGMyZ2lPaUl5ZEhsc1JIQlhkWFpNUVdaWGJVRllJbjA9",summary=""),
* ),
* @AnnotationResponse(
* response="200",
* description="正常操作响应",
* @MediaType(
* mediaType="application/json",
* @Schema(
* allOf={
* @Schema(ref="#/components/schemas/ApiResponse"),
* @Schema(
* type="object",
* @Property(property="data", ref="#/components/schemas/OrdersList")
* )
* }
* )
* )
* ),
* security={
* {"bearer_token":{}}
* }
* )
*/
public function createCustomerNewOrder(Request $request)
{
$customerCode = $request->get('customer_code');
if(!$customerCode){
return Response::ok('客户编号不存在!');
}
$requestParams = $this->formatKeysfromArray($request->all(),'toUnderScore');
$requestParams = array_merge($requestParams,['customer_code' => $customerCode]);
try{
$orderDetail = $this->rhawnOrdersService->createNewCustomerOrders($requestParams);
if($orderDetail){
$orderDetail = $this->formatKeysfromArray($orderDetail,'toCamelCase');
}
return Response::success($orderDetail,'操作成功');
}catch(\Throwable $exception){
return $this->returnErrorExecptionResponse($exception,'生成订单失败');
}
}
/**
* @Post(
* path="/openapi/orders/cancelRhawnOrders",
* tags={"订单相关接口"},
* summary="取消一个用户已有的订单",
* description="订单取消",
* @RequestBody(
* @MediaType(
* mediaType="application/json",
* @Schema(
* required={"orderNumber"},
* @Property(property="orderNumber", @Schema(type="string"),description="订单编号"),
* example={"orderNumber" : "20221008-122565111"}
* )
* )
* ),
* @OA\Parameter(
* description="用户获取的token值",
* in="header",
* name="authorization",
* required=true,
* @OA\Schema(type="string"),
* @OA\Examples(example="authorization", value="bearerNWJiNDhkNzlmNjg0N2FlMmZiYjliZWM3NGVkNzIyMjNleUpsZUhCcGNtVWlPakUyTmpRMk1EazJORGNzSW1oaGMyZ2lPaUl5ZEhsc1JIQlhkWFpNUVdaWGJVRllJbjA9",summary=""),
* ),
* @AnnotationResponse(
* response="200",
* description="正常操作响应",
* @MediaType(
* mediaType="application/json",
* @Schema(
* allOf={
* @Schema(ref="#/components/schemas/ApiResponse"),
* @Schema(
* type="object",
* @Property(property="data", ref="#/components/schemas/OrdersList")
* )
* }
* )
* )
* ),
* security={
* {"bearer_token":{}}
* }
* )
*/
public function cancelCustomerOrder(Request $request)
{
$customerCode = $request->get('customer_code');
if(!$customerCode){
return Response::ok('客户编号不存在!');
}
$requestParams = $this->formatKeysfromArray($request->all(),'toUnderScore');
$requestParams = array_merge($requestParams,['customer_code' => $customerCode]);
try{
$result = $this->rhawnOrdersService->cancelCustomerOrder($requestParams);
if($result){
return Response::success([],'取消订单成功');
}
return Response::fail('取消订单失败',200);
}catch(\Throwable $exception){
return $this->returnErrorExecptionResponse($exception,'取消订单失败');
}
}
/**
* @Post(
* path="/openapi/orders/getOrdersDispatch",
* tags={"订单相关接口"},
* summary="获取订单的配货单信息",
* description="配货单信息",
* @RequestBody(
* @MediaType(
* mediaType="application/json",
* @Schema(
* required={"orderNumber"},
* @Property(property="orderNumber", @Schema(type="string"),description="订单编号"),
* example={"orderNumber" : "20221008-122565111"}
* )
* )
* ),
* @OA\Parameter(
* description="用户获取的token值",
* in="header",
* name="authorization",
* required=true,
* @OA\Schema(type="string"),
* @OA\Examples(example="authorization", value="bearerNWJiNDhkNzlmNjg0N2FlMmZiYjliZWM3NGVkNzIyMjNleUpsZUhCcGNtVWlPakUyTmpRMk1EazJORGNzSW1oaGMyZ2lPaUl5ZEhsc1JIQlhkWFpNUVdaWGJVRllJbjA9",summary=""),
* ),
* @AnnotationResponse(
* response="200",
* description="正常操作响应",
* @MediaType(
* mediaType="application/json",
* @Schema(
* allOf={
* @Schema(ref="#/components/schemas/ApiResponse"),
* @Schema(
* type="object",
* @Property(property="data", ref="#/components/schemas/OrdersDispatchList")
* )
* }
* )
* )
* ),
* security={
* {"bearer_token":{}}
* }
* )
*/
public function getOrdersDispatch(Request $request)
{
$customerCode = $request->get('customer_code');
if(!$customerCode){
return Response::ok('客户编号不存在!');
}
$requestParams = $this->formatKeysfromArray($request->all(),'toUnderScore');
$requestParams = array_merge($requestParams,['customer_code' => $customerCode]);
try{
$dpDetail = $this->rhawnOrdersService->getOrderDispatchByOrderNumber($requestParams);
if($dpDetail){
$dpDetail = $this->formatKeysfromArray($dpDetail,'toCamelCase');
}
return Response::success($dpDetail,'操作成功');
}catch(\Throwable $exception){
return $this->returnErrorExecptionResponse($exception,'获取订单配货单信息失败');
}
}
}
<?php
namespace App\Http\Controllers\V1\Rhawn;
use App\Services\Api\RhawnOrdersService;
use App\Services\Api\RhawnProductsService;
use Illuminate\Http\Request;
use Jiannei\Response\Laravel\Support\Facades\Response;
use App\Http\Controllers\V1\Controller;
use App\Support\Traits\Helpers;
use OpenApi\Annotations\Post;
use OpenApi\Annotations\RequestBody;
use OpenApi\Annotations\MediaType;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\Response as AnnotationResponse;
use OpenApi\Annotations as OA;
class ProductsController extends Controller
{
use Helpers;
public function __construct(RhawnProductsService $rhawnProductsService)
{
$this->rhawnProductsService = $rhawnProductsService;
}
/**
* @Post(
* path="/openapi/products/getAllProducts",
* tags={"产品相关接口"},
* summary="获取所有产品列表数据集",
* description="产品列表",
* @RequestBody(
* @MediaType(
* mediaType="application/json",
* @Schema(
* required={"pageSize", "pageNo"},
* @Property(property="pageSize", @Schema(type="integer"),description="返回数据集数量"),
* @Property(property="pageNo", @Schema(type="integer"),description="当前页数"),
* example={"pageSize" : 100, "pageNo" : 1}
* )
* )
* ),
* @OA\Parameter(
* description="用户获取的token值",
* in="header",
* name="authorization",
* required=true,
* @OA\Schema(type="string"),
* @OA\Examples(example="authorization", value="bearerNWJiNDhkNzlmNjg0N2FlMmZiYjliZWM3NGVkNzIyMjNleUpsZUhCcGNtVWlPakUyTmpRMk1EazJORGNzSW1oaGMyZ2lPaUl5ZEhsc1JIQlhkWFpNUVdaWGJVRllJbjA9",summary=""),
* ),
* @AnnotationResponse(
* response="200",
* description="正常操作响应",
* @MediaType(
* mediaType="application/json",
* @Schema(
* allOf={
* @Schema(ref="#/components/schemas/ApiResponse"),
* @Schema(
* type="object",
* @Property(property="data", ref="#/components/schemas/ProductsList")
* )
* }
* )
* )
* ),
* security={
* {"bearer_token":{}}
* }
* )
*/
public function getAllProductsList(Request $request)
{
$customerCode = $request->get('customer_code');
if(!$customerCode){
return Response::ok('客户编号不存在!');
}
$params = [
'customer_code' => $customerCode
];
try{
$productList = $this->rhawnProductsService->getAllProducts($params);
if($productList){
$productList = $this->formatKeysfromArray($productList,'toCamelCase');
}
return Response::success($productList,'操作成功');
}catch(\Throwable $exception){
return $this->returnErrorExecptionResponse($exception,'获取产品列表失败');
}
}
/**
* @Post(
* path="/openapi/products/getProductDetail",
* tags={"产品相关接口"},
* summary="获取产品详情数据集",
* description="产品详情",
* @RequestBody(
* @MediaType(
* mediaType="application/json",
* @Schema(
* required={"productCode"},
* @Property(property="productCode", @Schema(type="string"),description="产品编号"),
* example={"productCode" : "R003250-1ml"}
* )
* )
* ),
* @OA\Parameter(
* description="用户获取的token值",
* in="header",
* name="authorization",
* required=true,
* @OA\Schema(type="string"),
* @OA\Examples(example="authorization", value="bearerNWJiNDhkNzlmNjg0N2FlMmZiYjliZWM3NGVkNzIyMjNleUpsZUhCcGNtVWlPakUyTmpRMk1EazJORGNzSW1oaGMyZ2lPaUl5ZEhsc1JIQlhkWFpNUVdaWGJVRllJbjA9",summary=""),
* ),
* @AnnotationResponse(
* response="200",
* description="正常操作响应",
* @MediaType(
* mediaType="application/json",
* @Schema(
* allOf={
* @Schema(ref="#/components/schemas/ApiResponse"),
* @Schema(
* type="object",
* @Property(property="data", ref="#/components/schemas/ProductDetailProperty")
* )
* }
* )
* )
* ),
* security={
* {"bearer_token":{}}
* }
* )
*/
public function getProductDetail(Request $request)
{
$customerCode = $request->get('customer_code');
if(!$customerCode){
return Response::ok('客户编号不存在!');
}
$requestParams = $this->formatKeysfromArray($request->all(),'toUnderScore');
$requestParams = array_merge($requestParams,['customer_code' => $customerCode]);
try{
$productDetail = $this->rhawnProductsService->getProductDetail($requestParams);
if($productDetail){
$productDetail = $this->formatKeysfromArray($productDetail,'toCamelCase');
}
return Response::success($productDetail,'操作成功');
}catch(\Throwable $exception){
return $this->returnErrorExecptionResponse($exception,'获取产品详情失败');
}
}
/**
* @Post(
* path="/openapi/products/getProductByCas",
* tags={"产品相关接口"},
* summary="根据cas号获取产品详情数据集",
* description="产品详情",
* @RequestBody(
* @MediaType(
* mediaType="application/json",
* @Schema(
* required={"cas"},
* @Property(property="cas", @Schema(type="string"),description="cas"),
* example={"cas" : "57960-19-7"}
* )
* )
* ),
* @OA\Parameter(
* description="用户获取的token值",
* in="header",
* name="authorization",
* required=true,
* @OA\Schema(type="string"),
* @OA\Examples(example="authorization", value="bearerNWJiNDhkNzlmNjg0N2FlMmZiYjliZWM3NGVkNzIyMjNleUpsZUhCcGNtVWlPakUyTmpRMk1EazJORGNzSW1oaGMyZ2lPaUl5ZEhsc1JIQlhkWFpNUVdaWGJVRllJbjA9",summary=""),
* ),
* @AnnotationResponse(
* response="200",
* description="正常操作响应",
* @MediaType(
* mediaType="application/json",
* @Schema(
* allOf={
* @Schema(ref="#/components/schemas/ApiResponse"),
* @Schema(
* type="object",
* @Property(property="data", ref="#/components/schemas/ProductByCas")
* )
* }
* )
* )
* ),
* security={
* {"bearer_token":{}}
* }
* )
*/
public function getProductByCas(Request $request)
{
$customerCode = $request->get('customer_code');
if(!$customerCode){
return Response::ok('客户编号不存在!');
}
$requestParams = $this->formatKeysfromArray($request->all(),'toUnderScore');
$requestParams = array_merge($requestParams,['customer_code' => $customerCode]);
try{
$productDetail = $this->rhawnProductsService->getProductByCas($requestParams);
if($productDetail){
$productDetail = $this->formatKeysfromArray($productDetail,'toCamelCase');
}
return Response::success($productDetail,'操作成功');
}catch(\Throwable $exception){
return $this->returnErrorExecptionResponse($exception,'获取产品详情失败');
}
}
}
<?php
namespace App\Http\Controllers\V1;
use OpenApi\Annotations\SecurityScheme;
/**
* @SecurityScheme(
* type="apiKey",
* scheme="bearer_token",
* in="header",
* securityScheme="bearer_token",
* description="用户token验证",
* name="authorization"
* )
*/
class SecurityController
{
}
...@@ -55,6 +55,17 @@ class AppServiceProvider extends ServiceProvider ...@@ -55,6 +55,17 @@ class AppServiceProvider extends ServiceProvider
return new Client(); return new Client();
}); });
$this->app['Dingo\Api\Exception\Handler']->setErrorFormat([
'error' => [
'message' => ':message',
'errors' => ':errors',
'code' => ':code',
'status' => ':status_code',
]
]);
$this->app->instance('path.storage', app()->storagePath());
$this->commands([ $this->commands([
\App\Console\Commands\IntegleJobCommand::class, \App\Console\Commands\IntegleJobCommand::class,
...@@ -62,7 +73,8 @@ class AppServiceProvider extends ServiceProvider ...@@ -62,7 +73,8 @@ class AppServiceProvider extends ServiceProvider
\App\Console\Commands\BideJobCommand::class, \App\Console\Commands\BideJobCommand::class,
\App\Console\Commands\BjsJobCommand::class, \App\Console\Commands\BjsJobCommand::class,
\App\Console\Commands\ZhenkhJobCommand::class, \App\Console\Commands\ZhenkhJobCommand::class,
\App\Console\Commands\KafkaConsumerCommand::class \App\Console\Commands\KafkaConsumerCommand::class,
\App\Console\Commands\TestJobCommand::class
]); ]);
} }
......
...@@ -9,19 +9,13 @@ ...@@ -9,19 +9,13 @@
* with this source code in the file LICENSE. * with this source code in the file LICENSE.
*/ */
namespace App\Repositories\Presenters; namespace App\Repositories\Contracts;
use App\Repositories\Transformers\PostTransformer; use Prettus\Repository\Contracts\RepositoryInterface;
class PostPresenter extends Presenter /**
{ * Interface UserRepository.
/**
* Prepare data to present.
*
* @return \League\Fractal\TransformerAbstract
*/ */
public function getTransformer() interface PlatformCustomerRepository extends RepositoryInterface
{ {
return new PostTransformer();
}
} }
...@@ -81,4 +81,14 @@ abstract class BaseRepository extends BaseRepositoryEloquent ...@@ -81,4 +81,14 @@ abstract class BaseRepository extends BaseRepositoryEloquent
return $returnRecord; return $returnRecord;
} }
protected function getConnectionName()
{
return app($this->model())->getConnectionName();
}
protected function getTableName()
{
return app($this->model())->getTable();
}
} }
<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\PlatformCustomerRepository;
use App\Repositories\Criteria\RequestCriteria;
use App\Repositories\Models\PlatformCustomer;
use Illuminate\Support\Facades\DB;
/**
* Class UserRepositoryEloquent.
*/
class PlatformCustomerRepositoryEloquent extends BaseRepository implements PlatformCustomerRepository
{
public function model()
{
return PlatformCustomer::class;
}
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
...@@ -2,18 +2,17 @@ ...@@ -2,18 +2,17 @@
namespace App\Repositories\Eloquent; namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\RhawnSordersRepository;
use App\Repositories\Criteria\RequestCriteria; use App\Repositories\Criteria\RequestCriteria;
use App\Repositories\Models\RhawnSorders; use App\Repositories\Transformers\Rhawn\OrdersListTransformer;
use App\Repositories\Eloquent\BaseRepository; use App\Rhawn\Repositories\Eloquent\RhawnCustomerRepositoryEloquent;
use App\Rhawn\Repositories\Eloquent\RhawnProductRepositoryEloquent;
use App\Rhawn\Repositories\Models\RhawnSorders;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Prettus\Validator\Contracts\ValidatorInterface;
/** /**
* Class UserRepositoryEloquent. * Class UserRepositoryEloquent.
*/ */
class RhawnSordersRepositoryEloquent extends BaseRepository implements RhawnSordersRepository class RhawnSordersRepositoryEloquent extends \App\Rhawn\Repositories\Eloquent\RhawnSordersRepositoryEloquent
{ {
/** /**
* Specify Model class name. * Specify Model class name.
...@@ -25,68 +24,22 @@ class RhawnSordersRepositoryEloquent extends BaseRepository implements RhawnSord ...@@ -25,68 +24,22 @@ class RhawnSordersRepositoryEloquent extends BaseRepository implements RhawnSord
return RhawnSorders::class; return RhawnSorders::class;
} }
/** public function boot()
* 返回指定订单编号的订单信息
* @param $order_no
* @return mixed
*/
public function getSorderFromOrderNo($orderNo)
{ {
$where = [ $this->pushCriteria(app(RequestCriteria::class));
'so_no' => $orderNo
];
return $this->findWhere($where)->first();
} }
public function getSorderFromOrderCusPo($orderNo) public function getCustomerOrderList($cusId,$pageSize,$offset)
{ {
$where = [ $orderList = parent::getOrdersListThroughtUserId($cusId,$pageSize,$offset);
'so_cus_po' => $orderNo return app(OrdersListTransformer::class)->transform($orderList);
];
return $this->findWhere($where)->first();
}
/**
* 获取订单详情
* @param $orderNo
* @return mixed
*/
public function getSorderItemsFromOrderNo($orderNo){
$soItems = $this
->join('soitems','soitems.so_id','sorders.so_id')
->where('sorders.so_no',$orderNo)->get();
return $soItems;
} }
/** public function orderTotalByCusId($cusId)
* 获取订单相关信息(包括,产品,客户,品牌等)
* @param $so_id
* @return mixed
*/
public function getSorderDetailFromOrderId($so_id)
{ {
$sOrderInfo = $this return parent::count([
->join('customers','sorders.cus_id','customers.cus_id') 'cus_id' => $cusId
->where('sorders.so_id',$so_id) ]);
->get();
if(!$sOrderInfo){
return ;
} }
$sOrderInfo = current($sOrderInfo->toArray());
$items = DB::connection('bh_mysql')->table('soitems')
->join('products','soitems.p_id','products.p_id')
->join('chemicals','products.c_id','chemicals.c_id')
->join('brands','products.b_id','brands.b_id')
->where('soitems.so_id',$so_id)
->get();
if(!$items){
$sOrderInfo['items'] = [];
}
$sOrderInfo['items'] = $items->toArray();
return $sOrderInfo;
}
} }
...@@ -9,19 +9,21 @@ ...@@ -9,19 +9,21 @@
* with this source code in the file LICENSE. * with this source code in the file LICENSE.
*/ */
namespace App\Repositories\Presenters; namespace App\Repositories\Models;
use App\Repositories\Transformers\UserTransformer; class PlatformCustomer extends Model
class UserPresenter extends Presenter
{ {
protected $connection = 'mysql';
protected $table = 'customer_platform_info';
/** /**
* Prepare data to present. * The attributes that are mass assignable.
* *
* @return \League\Fractal\TransformerAbstract * @var array
*/ */
public function getTransformer() protected $fillable = [
{ 'cus_id', 'cus_number', 'company_name', 'token', 'platform_params', 'status', 'created_by','updated_by'
return new UserTransformer(); ];
}
} }
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Presenters;
use Exception;
use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Pagination\AbstractPaginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use League\Fractal\Pagination\Cursor;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Resource\Collection;
use Prettus\Repository\Presenter\FractalPresenter;
abstract class Presenter extends FractalPresenter
{
protected $cursor = null;
public function makeCursor($current, $previous, $next, $count)
{
$this->cursor = new Cursor(...func_get_args());
}
/**
* Prepare data to present.
*
* @param $data
* @return mixed
*
* @throws Exception
*/
public function present($data)
{
if (! class_exists('League\Fractal\Manager')) {
throw new Exception(trans('repository::packages.league_fractal_required'));
}
if ($data instanceof EloquentCollection) {
$this->resource = $this->transformCollection($data);
} elseif ($data instanceof AbstractPaginator) {
$this->resource = $this->transformPaginator($data);
} else {
$this->resource = $this->transformItem($data);
}
return $this->fractal->createData($this->resource)->toArray();
}
/**
* @param $data
* @return \League\Fractal\Resource\Collection
*/
protected function transformCollection($data)
{
$resource = new Collection($data, $this->getTransformer(), $this->resourceKeyCollection);
if ($this->cursor) {
$resource->setCursor($this->cursor);
}
return $resource;
}
/**
* @param AbstractPaginator|LengthAwarePaginator|Paginator $paginator
* @return \League\Fractal\Resource\Collection
*/
protected function transformPaginator($paginator)
{
$collection = $paginator->getCollection();
$resource = new Collection($collection, $this->getTransformer(), $this->resourceKeyCollection);
if ($paginator instanceof Paginator) {
$items = $paginator->items();
$total = 0;
$perPage = $paginator->perPage();
$currentPage = $paginator->currentPage();
$options = array_merge(['hasMore' => $paginator->hasMorePages()], $paginator->getOptions());
$paginator = Container::getInstance()->makeWith(LengthAwarePaginator::class, compact(
'items', 'total', 'perPage', 'currentPage', 'options'
));
}
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
return $resource;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Transformers\Rhawn;
use League\Fractal\TransformerAbstract;
class OrdersDispatchTransformer extends TransformerAbstract
{
/**
* 格式化结果
* @param $dpdetail
* @return array
*/
public function transform($dpdetail)
{
$dpdTransReturn = [];
$dp = [];
if($dpdetail){
foreach($dpdetail as $detail){
$temp = $dp = [];
if(!isset($dpdTransReturn[$detail['dp_code']])){
$temp['dp_code'] = $detail['dp_code'];
$temp['so_no'] = $detail['so_no'];
//$temp['dp_express_code'] = $detail['dp_express_com'];
$temp['dp_express_name'] = $this->getExpressName($detail['dp_express_com']);
$temp['dp_express_no'] = $detail['dp_express_no'];
$dpdTransReturn[$detail['dp_code']] = $temp;
}
$dp['dpd_num'] = $detail['dpd_num'];
$dp['dpd_amount'] = $detail['dpd_amount'];
$dp['p_code'] = $detail['si_id']['p_code'];
$dp['p_en_name'] = $detail['si_id']['p_en_name'];
$dp['p_cn_name'] = $detail['si_id']['p_cn_name'];
$dp['cas'] = $detail['si_id']['c_cas'];
$dpdTransReturn[$detail['dp_code']]['detail'][] = $dp;
}
}
$dpdTransReturn = array_values($dpdTransReturn);
return $dpdTransReturn;
}
private function getExpressName($code)
{
$express = ['SH'=>'随货',
'JD'=>'京东',
'SF'=>'顺丰',
'ZT'=>'中通',
'YD'=>'韵达',
'ZJS'=>'宅急送',
'DBL'=>'德邦',
'YTO'=>'圆通',
'YZPY'=>'邮政',
'AN'=>'安能',
'STO'=>'申通',
'HHTT'=>'天天',
'WL'=>'物流',
'ziti'=>'自提'
];
return $express[$code];
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Transformers\Rhawn;
use League\Fractal\TransformerAbstract;
class OrdersListTransformer extends TransformerAbstract
{
/**
* 格式化结果
* @param $rhawnSorders
* @return array
*/
public function transform($rhawnSorders)
{
$orderTransReturn = [];
if($rhawnSorders){
foreach($rhawnSorders as $order){
$temp = [];
$temp['so_id'] = $order->so_id;
$temp['so_no'] = $order->so_no;
$temp['so_total'] = $order->so_total;
$temp['so_review_status'] = $order->so_review_status;
$temp['so_pay_status'] = $order->so_pay_status;
$temp['so_ctime'] = $order->so_ctime;
array_push($orderTransReturn,$temp);
}
}
return $orderTransReturn;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Transformers\Rhawn;
use League\Fractal\TransformerAbstract;
class ProductDetailTransformer extends TransformerAbstract
{
/**
* 格式化结果
* @param $rhawnSorders
* @return array
*/
public function transform($products)
{
$productTransReturn = [];
if($products){
$productTransReturn['code'] = $products['p_code'];//中文别名
$productTransReturn['cas'] = $products['c_cas'];//CAS号
$productTransReturn['chem_cn_name'] = $products['c_cn_name'];//中文名
$productTransReturn['chem_en_name'] = $products['c_en_name'];//英文名
$productTransReturn['cn_name'] = $products['p_cn_name'];//中文名
$productTransReturn['en_name'] = $products['p_en_name'];//英文名
$productTransReturn['level'] = $products['p_level'];//项目规格
$productTransReturn['delivery'] = $products['p_tod'];//货期
$productTransReturn['price'] = $products['p_price'];//单价
$productTransReturn['market_price'] = $products['m_price'];//目录价格
if($products['r_status'] == 0 || $products['p_status'] == 0 || $products['p_show'] == 0 || $products['p_if_big'] == 1){
$productTransReturn['status'] = 0;
$productTransReturn['price'] = 0;
$productTransReturn['market_price'] = 0;
}else{
$productTransReturn['status'] = 1;
}
}
return $productTransReturn;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Transformers\Rhawn;
use League\Fractal\TransformerAbstract;
class ProductsTransformer extends TransformerAbstract
{
/**
* 格式化结果
* @param $rhawnSorders
* @return array
*/
public function transform($products,$type = 'all')
{
$productTransReturn = [];
if($products){
foreach($products as $product){
$temp = [];
$temp['code'] = $product['p_code'];//中文别名
$temp['cas'] = $product['c_cas'];//CAS号
$temp['chem_cn_name'] = $product['c_cn_name'];//中文名
$temp['chem_en_name'] = $product['c_en_name'];//中文名
$temp['cn_name'] = $product['p_cn_name'];//中文名
$temp['en_name'] = $product['p_en_name'];//英文名
$temp['level'] = $product['p_level'];//项目规格
if($type == 'all'){
$temp['delivery'] = $product['p_tod'];//货期
}
$temp['price'] = $product['p_price'];//单价
$temp['market_price'] = $product['m_price'];//目录价格
if($product['r_gz_type'] == 2){
$temp['if_explode'] = 1;//是否易制爆
}else{
$temp['if_explode'] = 0;//是否易制爆
}
if($type == 'all'){
if($product['r_gz_type'] == 1){
$temp['if_drag'] = 1;//是否易制毒
}else{
$temp['if_drag'] = 0;//是否易制毒
}
}
if($product['c_if_dangers'] == 1){
$temp['if_dangers'] = 1;//是否危化品
}else{
$temp['if_dangers'] = 0;//是否危化品
}
if($product['r_status'] == 0 || $product['p_status'] == 0 || $product['p_show'] == 0 || $product['p_if_big'] == 1){
$temp['status'] = 0;
$temp['price'] = 0;
$temp['market_price'] = 0;
}else{
$temp['status'] = 1;
}
$temp['pack'] = $product['p_pack'].$product['p_pack_unit'];//包装规格
$temp['weight'] = $product['p_weight'];//产品重量kg
if($product['p_stock'] > 0){
$temp['tag'] = '当天发货';
}else{
$temp['tag'] = '';
}
if($type == 'bycas'){
$temp['city'] = '上海';
$temp['stock'] = $product['p_tod'];//货期
$temp['pacs'] = $product['p_pack'].$product['p_pack_unit'];//项目规格
}
array_push($productTransReturn,$temp);
}
}
return $productTransReturn;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Rhawn\Providers;
use Illuminate\Filesystem\Filesystem;
use Prettus\Repository\Providers\LumenRepositoryServiceProvider;
class RhawnRepositoryServiceProvider extends LumenRepositoryServiceProvider
{
public function register()
{
parent::register();
$this->bindRepository();
}
protected function bindRepository()
{
$fileObj = (new Filesystem());
$files = $fileObj->files(base_path('app/Rhawn/Repositories/Contracts'));
if($files){
collect($files)->map(function ($file){
$fileName = $file->getRelativePathname();
list($name,$extend) = explode('.',$fileName);
$class = "App\Rhawn\Repositories\Contracts\\".$name;
$concrete = "App\Rhawn\Repositories\Eloquent\\".$name."Eloquent";
$this->app->bind($class,$concrete);
});
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Rhawn\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface RhawnCustomerRepository extends RepositoryInterface
{
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Rhawn\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface RhawnProductRepository extends RepositoryInterface
{
}
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
* with this source code in the file LICENSE. * with this source code in the file LICENSE.
*/ */
namespace App\Repositories\Contracts; namespace App\Rhawn\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface; use Prettus\Repository\Contracts\RepositoryInterface;
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
* with this source code in the file LICENSE. * with this source code in the file LICENSE.
*/ */
namespace App\Repositories\Contracts; namespace App\Rhawn\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface; use Prettus\Repository\Contracts\RepositoryInterface;
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
* with this source code in the file LICENSE. * with this source code in the file LICENSE.
*/ */
namespace App\Repositories\Contracts; namespace App\Rhawn\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface; use Prettus\Repository\Contracts\RepositoryInterface;
......
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Rhawn\Repositories\Eloquent;
use Illuminate\Support\Facades\DB;
use Prettus\Repository\Eloquent\BaseRepository as BaseRepositoryEloquent;
abstract class BaseRepository extends BaseRepositoryEloquent
{
protected function getConnectionName()
{
return app($this->model())->getConnectionName();
}
protected function getTableName()
{
return app($this->model())->getTable();
}
public function getConnection()
{
return DB::connection($this->getConnectionName());
}
}
<?php
namespace App\Rhawn\Repositories\Eloquent;
use App\Rhawn\Repositories\Contracts\RhawnCustomerRepository;
use App\Rhawn\Repositories\Models\RhawnCustomer;
use Illuminate\Support\Facades\DB;
use Prettus\Validator\Contracts\ValidatorInterface;
/**
* Class UserRepositoryEloquent.
*/
class RhawnCustomerRepositoryEloquent extends BaseRepository implements RhawnCustomerRepository
{
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return RhawnCustomer::class;
}
public function getRhawnCustomerThroughtCusCode($cusCode)
{
$customer = $this->findWhere(['cus_no' => $cusCode])->first();
if($customer){
return $customer->toArray();
}
return null;
}
/**
* 获取客户折扣信息
* @param $cusCode
* @return array
*/
public function getCustomerDiscountByCusCode($cusCode)
{
$customerDiscount = RhawnCustomer::query()
->join('cusdiscount','cusdiscount.cus_id','customers.cus_id')
->where('customers.cus_no',$cusCode)
->get();
$cusdiscountArr = [];
if($customerDiscount){
$customerDiscount = $customerDiscount->toArray();
foreach($customerDiscount as $k=>$v){
$cusdiscountArr[$v['b_id']]['cd_discount'] = $v['cd_discount'];
$cusdiscountArr[$v['b_id']]['cd_pre_discount'] = $v['cd_pre_discount'];
}
}
return $cusdiscountArr;
}
/**
* 获取客户地址信息
* @param $cusCode
* @return array|null
*/
public function getCustomerAddressByCusCode($cusCode)
{
$customerAddress = RhawnCustomer::query()
->join('cusiaddrs','cusiaddrs.cus_id','customers.cus_id')
->where('customers.cus_no',$cusCode)
->orderBy('cusiaddrs.cia_if_default','DESC')
->orderBy('cusiaddrs.cia_id','DESC')
->get();
if($customerAddress){
return $customerAddress->toArray();
}
return null;
}
/**
* 获取客户开票信息
* @param $cusCode
* @return array
*/
public function getCustomerInvoiceByCusCode($cusCode)
{
$customerInvoice = RhawnCustomer::query()
->join('cusinvoice','cusinvoice.cus_id','customers.cus_id')
->where('customers.cus_no',$cusCode)
->orderBy('cusinvoice.ci_if_default','DESC')
->orderBy('cusinvoice.ci_id','DESC')
->get();
if($customerInvoice){
$customerInvoice = $customerInvoice->toArray();
foreach($customerInvoice as &$invoice){
if($invoice['ci_type'] == 1){
$invoice['ci_type_name'] = '普票';
}
if($invoice['ci_type'] == 2){
$invoice['ci_type_name'] = '专票';
}
}
return $customerInvoice;
}
return null;
}
}
<?php
namespace App\Rhawn\Repositories\Eloquent;
use App\Rhawn\Repositories\Contracts\RhawnProductRepository;
use App\Rhawn\Repositories\Models\RhawnProducts;
use Illuminate\Support\Facades\DB;
use Prettus\Validator\Contracts\ValidatorInterface;
/**
* Class UserRepositoryEloquent.
*/
class RhawnProductRepositoryEloquent extends BaseRepository implements RhawnProductRepository
{
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return RhawnProducts::class;
}
/**
* 根据p_code获取产品信息
* @param $pCode
* @return null
*/
public function getProductByPcode($pCode)
{
$productsModel = $this->join('chemicals', 'chemicals.c_id','products.c_id')->join('raw', 'raw.r_id','products.r_id');
if(!is_array($pCode)){
$productsModel->where('products.p_code',$pCode);
}else{
$productsModel->whereIn('products.p_code',$pCode);
}
$product = $productsModel->get();
if($product){
return $product->toArray();
}
return null;
}
public function getProductsByWhere(array $where)
{
$productsModel = $this->join('chemicals', 'chemicals.c_id','products.c_id');
foreach($where as $key => $w){
if(!is_array($w)){
$productsModel->where($key,$w);
}else{
$productsModel->whereIn($key,$w);
}
}
$product = $productsModel->get();
if($product){
return $product->toArray();
}
return null;
}
/**
* 根据pid获取产品对应的促销信息
* @param $pId
* @return array|null
*/
public function getProductPromotionByPid($pId)
{
$promotionsModel = DB::connection($this->getConnectionName())
->table('promotions_products')
->join('promotions','promotions.pt_id','promotions_products.pt_id');
if(is_array($pId)){
$promotionsModel->whereIn('promotions_products.p_id',$pId);
}else{
$promotionsModel->where('promotions_products.p_id',$pId);
}
/*$promotions = $promotionsModel->where('promotions.pt_start','<=',time())
->where('promotions.pt_end','>=',time())
->get();*/
$promotions = $promotionsModel->get();
if($promotions){
$promotions = $promotions->toArray();
return $promotions;
}
return null;
}
/**
* 获取所有产品的包装规格
* @return array
*/
public function getProductPackagesThroughGroupByPackUnit()
{
$packages = RhawnProducts::query()
->select('p_pack','p_pack_unit')
->groupBy('p_pack','p_pack_unit')
->get();
return $packages->toArray();
}
/**
* 获取产品信息
* @param $where
* @param $offset
* @param $pageSize
* @return null
*/
public function getProductsList($where, $offset, $limit)
{
$productsModel = $this->join('chemicals', 'chemicals.c_id','products.c_id')->join('raw', 'raw.r_id','products.r_id');
if(!empty($where)){
foreach($where as $key => $w){
if(!is_array($w)){
$productsModel->where($key,$w);
}else{
$productsModel->whereIn($key,$w);
}
}
}
$product = $productsModel->offset($offset)->limit($limit)->get();
if($product){
return $product->toArray();
}
return null;
}
public function getProductsByCas($cas)
{
$productsModel = $this->join('chemicals', 'chemicals.c_id','products.c_id')->join('raw', 'raw.r_id','products.r_id');
$product = $productsModel->where('chemicals.c_cas',$cas)->get();
if($product){
return $product->toArray();
}
return null;
}
}
<?php <?php
namespace App\Repositories\Eloquent; namespace App\Rhawn\Repositories\Eloquent;
use App\Repositories\Contracts\RhawnRawRepository; use App\Rhawn\Repositories\Contracts\RhawnRawRepository;
use App\Repositories\Criteria\RequestCriteria; use App\Rhawn\Repositories\Models\RhawnProducts;
use App\Repositories\Eloquent\BaseRepository; use App\Rhawn\Repositories\Models\RhawnRaw;
use App\Repositories\Models\RhawnProducts;
use App\Repositories\Models\RhawnRaw;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Prettus\Validator\Contracts\ValidatorInterface; use Prettus\Validator\Contracts\ValidatorInterface;
...@@ -29,21 +26,7 @@ class RhawnRawRepositoryEloquent extends BaseRepository implements RhawnRawRepos ...@@ -29,21 +26,7 @@ class RhawnRawRepositoryEloquent extends BaseRepository implements RhawnRawRepos
return RhawnRaw::class; return RhawnRaw::class;
} }
/** public function getRawListLimit($pageSize = 1000, $offset = 0)
* Boot up the repository, pushing criteria.
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
public function total(){
return $this->count();
}
public function getRawProductList($pageSize = 1000, $offset = 0)
{ {
$rawList = RhawnRaw::query() $rawList = RhawnRaw::query()
->join('chemicals', 'chemicals.c_id','raw.c_id') ->join('chemicals', 'chemicals.c_id','raw.c_id')
...@@ -54,43 +37,37 @@ class RhawnRawRepositoryEloquent extends BaseRepository implements RhawnRawRepos ...@@ -54,43 +37,37 @@ class RhawnRawRepositoryEloquent extends BaseRepository implements RhawnRawRepos
return $rawList->toArray(); return $rawList->toArray();
} }
public function getRawProductsThroughtCode($rawCode) /**
* 通过rawcode获取产品及规格信息
* @param $rawCode
* @return array
*/
public function getRawProductsThroughtRawCode($rawCode)
{ {
$raw = RhawnRaw::query() return $this->getRawProducts([
->join('products', 'products.c_id','raw.c_id') 'r_code',$rawCode
->join('chemicals', 'chemicals.c_id','raw.c_id'); ]);
if(!is_array($rawCode)){
$raw->where('r_code',$rawCode);
}else{
$raw->whereIn('r_code',$rawCode);
}
$rawList = $raw->get();
return $rawList->toArray();
} }
public function getProductPackage($rawProductIds) public function getRawProducts($where)
{ {
$packagesList = RhawnProducts::query() $raw = RhawnRaw::query()
->join('raw','raw.r_id','products.r_id') ->join('products', 'products.c_id','raw.c_id')
->join('chemicals', 'chemicals.c_id','raw.c_id'); ->join('chemicals', 'chemicals.c_id','raw.c_id');
foreach($where as $key => $w){
if(is_array($rawProductIds)){ if(!is_array($w)){
$packagesList = $packagesList->whereIn('raw.r_id',$rawProductIds); $raw->where($key,$w);
}else{ }else{
$packagesList = $packagesList->where('raw.r_id',$rawProductIds); $raw->whereIn($key,$w);
} }
$packagesList = $packagesList->get(); }
return $raw->get()->toArray();
return $packagesList->toArray();
} }
public function getProductPackagesThroughGroupByPackUnit() public function getProductPackage($rawProductIds)
{ {
$packages = RhawnProducts::query() return $this->getRawProducts([
->select('p_pack','p_pack_unit') 'r_id',$rawProductIds
->groupBy('p_pack','p_pack_unit') ]);
->get();
return $packages->toArray();
} }
} }
<?php <?php
namespace App\Repositories\Eloquent; namespace App\Rhawn\Repositories\Eloquent;
use App\Repositories\Contracts\RhawnSoitemsRepository; use App\Rhawn\Repositories\Contracts\RhawnSoitemsRepository;
use App\Repositories\Contracts\RhawnSordersRepository; use App\Rhawn\Repositories\Contracts\RhawnSordersRepository;
use App\Repositories\Criteria\RequestCriteria; use App\Rhawn\Repositories\Models\RhawnSoitems;
use App\Repositories\Eloquent\BaseRepository;
use App\Repositories\Models\RhawnSoitems;
use Prettus\Validator\Contracts\ValidatorInterface; use Prettus\Validator\Contracts\ValidatorInterface;
/** /**
...@@ -15,9 +12,6 @@ use Prettus\Validator\Contracts\ValidatorInterface; ...@@ -15,9 +12,6 @@ use Prettus\Validator\Contracts\ValidatorInterface;
*/ */
class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoitemsRepository class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoitemsRepository
{ {
protected $fieldSearchable = [
];
/** /**
* Specify Model class name. * Specify Model class name.
* *
...@@ -28,16 +22,6 @@ class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoit ...@@ -28,16 +22,6 @@ class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoit
return RhawnSoitems::class; return RhawnSoitems::class;
} }
/**
* Boot up the repository, pushing criteria.
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
/** /**
* 获取订单详情 * 获取订单详情
* @param $orderId * @param $orderId
...@@ -57,7 +41,10 @@ class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoit ...@@ -57,7 +41,10 @@ class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoit
->join('brands','products.b_id','brands.b_id') ->join('brands','products.b_id','brands.b_id')
->where('soitems.so_id',$order->so_id)->get(); ->where('soitems.so_id',$order->so_id)->get();
return $soItems; if($soItems){
return $soItems->toArray();
}
return null;
} }
public function getSorderItemsDetailFromItemId($itemId,$pid=null) public function getSorderItemsDetailFromItemId($itemId,$pid=null)
...@@ -73,8 +60,11 @@ class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoit ...@@ -73,8 +60,11 @@ class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoit
$soItems = $soItems->where('soitems.p_id',$pid); $soItems = $soItems->where('soitems.p_id',$pid);
} }
$soItems = $soItems->get(); $soItems = $soItems->get();
if($soItems){
return $soItems->toArray();
}
return $soItems; return null;
} }
/** /**
...@@ -90,11 +80,20 @@ class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoit ...@@ -90,11 +80,20 @@ class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoit
} }
//查询订单的详情 //查询订单的详情
$soItems = RhawnSoitems::query() $soModel = RhawnSoitems::query()
->join('products','soitems.p_id','products.p_id') ->join('products','soitems.p_id','products.p_id')
->where('soitems.si_id',$si_id)->get(); ->join('chemicals','chemicals.c_id','products.c_id');
if(is_array($si_id)){
$soModel->whereIn('soitems.si_id',$si_id);
}else{
$soModel->where('soitems.si_id',$si_id);
}
$soItems = $soModel->get();
if($soItems){
return $soItems->toArray();
}
return $soItems; return null;
} }
public function getOrderItemsStockFromItemIds($id) public function getOrderItemsStockFromItemIds($id)
...@@ -118,7 +117,10 @@ class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoit ...@@ -118,7 +117,10 @@ class RhawnSoitemsRepositoryEloquent extends BaseRepository implements RhawnSoit
->where('si_if_cancel',0) ->where('si_if_cancel',0)
//->where('dpdetail.dpd_invoiced','=',0) //->where('dpdetail.dpd_invoiced','=',0)
->get(); ->get();
if($soItemStock){
return $soItemStock->toArray();
}
return $soItemStock; return null;
} }
} }
<?php
namespace App\Rhawn\Repositories\Eloquent;
use App\Rhawn\Repositories\Contracts\RhawnSordersRepository;
use App\Rhawn\Repositories\Models\RhawnSorders;
use Illuminate\Support\Facades\DB;
use Prettus\Validator\Contracts\ValidatorInterface;
use function Symfony\Component\String\s;
/**
* Class UserRepositoryEloquent.
*/
class RhawnSordersRepositoryEloquent extends BaseRepository implements RhawnSordersRepository
{
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return RhawnSorders::class;
}
/**
* 返回指定订单编号的订单信息
* @param $order_no
* @return mixed
*/
public function getSorderFromOrderNo($orderNo)
{
$where = [
'so_no' => $orderNo
];
return $this->findWhere($where)->first();
}
public function getSorderFromOrderCusPo($orderNo)
{
$where = [
'so_cus_po' => $orderNo
];
return $this->findWhere($where)->first();
}
/**
* 获取订单详情
* @param $orderNo
* @return mixed
*/
public function getSorderItemsFromOrderNo($orderNo){
$soItems = $this
->join('soitems','soitems.so_id','sorders.so_id')
->where('sorders.so_no',$orderNo)->get();
if($soItems){
return $soItems->toArray();
}
return null;
}
/**
* 获取订单相关信息(包括,产品,客户,品牌等)
* @param $so_id
* @return mixed
*/
public function getSorderDetailFromOrderId($so_id)
{
$sOrderInfo = $this
->join('customers','sorders.cus_id','customers.cus_id')
->where('sorders.so_id',$so_id)
->get();
if(!$sOrderInfo){
return null;
}
$sOrderInfo = current($sOrderInfo->toArray());
$items = DB::connection($this->getConnectionName())->table('soitems')
->join('products','soitems.p_id','products.p_id')
->join('chemicals','products.c_id','chemicals.c_id')
->join('brands','products.b_id','brands.b_id')
->where('soitems.so_id',$so_id)
->get();
if(!$items){
$sOrderInfo['items'] = [];
}
$sOrderInfo['items'] = $items->toArray();
return $sOrderInfo;
}
/**
* 获取客户订单
* @param $userId
* @param $pageSize
* @param $offset
* @return array|null
*/
public function getOrdersListThroughtUserId($userId,$offset,$limit)
{
$sOrderInfo = DB::connection($this->getConnectionName())->table($this->getTableName())
->join('customers','customers.cus_id','sorders.cus_id')
->where('sorders.cus_id',$userId)
->offset($offset)
->limit($limit)
->get();
if($sOrderInfo){
return $sOrderInfo->toArray();
}
return null;
}
/**
* 获取客户订单详情
* @param $cusId
* @param $orderId
* @return null
*/
public function getCustomerOrderItemsByOrderId($cusId,$orderId)
{
$sOrderInfo = $this
->join('customers','sorders.cus_id','customers.cus_id')
->where('sorders.so_id',$orderId)
->where('sorders.cus_id',$cusId)
->first();
if(!$sOrderInfo){
return null;
}
$sOrderInfo = $sOrderInfo->toArray();
$itemRepository = app(RhawnSoitemsRepositoryEloquent::class);
$items = $itemRepository->getSorderItemsDetailFromOrderId($sOrderInfo['so_id']);
var_dump($items);
exit;
$sOrderInfo['items'] = [];
if($items){
$sOrderInfo['items'] = $items;
}
return $sOrderInfo;
}
public function getOrderDispatch($orderNumber)
{
$dpModel = $this->join('dispatch','dispatch.so_id','sorders.so_id')
->join('dpdetail','dpdetail.dp_id','dispatch.dp_id');
if(is_array($orderNumber)){
$dpModel->whereIn('sorders.so_no',$orderNumber);
}else{
$dpModel->where('sorders.so_no',$orderNumber);
}
$dpdetail = $dpModel->get();
if($dpdetail){
return $dpdetail->toArray();
}
return null;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Rhawn\Repositories\Models;
use App\Repositories\Models\Model;
class RhawnCustomer extends Model
{
protected $table = 'customers';
protected $connection = 'rhawn_mysql';
protected $primaryKey = 'cus_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
];
protected $guarded = ['created_at', 'updated_at'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
/**
* update时不做自动更新时间操作
* @return null
*/
public function getUpdatedAtColumn()
{
return null;
}
public function getCreatedAtColumn()
{
return null;
}
}
\ No newline at end of file
...@@ -9,7 +9,9 @@ ...@@ -9,7 +9,9 @@
* with this source code in the file LICENSE. * with this source code in the file LICENSE.
*/ */
namespace App\Repositories\Models; namespace App\Rhawn\Repositories\Models;
use App\Repositories\Models\Model;
class RhawnProducts extends Model class RhawnProducts extends Model
{ {
......
...@@ -9,7 +9,9 @@ ...@@ -9,7 +9,9 @@
* with this source code in the file LICENSE. * with this source code in the file LICENSE.
*/ */
namespace App\Repositories\Models; namespace App\Rhawn\Repositories\Models;
use App\Repositories\Models\Model;
class RhawnRaw extends Model class RhawnRaw extends Model
{ {
......
...@@ -9,7 +9,9 @@ ...@@ -9,7 +9,9 @@
* with this source code in the file LICENSE. * with this source code in the file LICENSE.
*/ */
namespace App\Repositories\Models; namespace App\Rhawn\Repositories\Models;
use App\Repositories\Models\Model;
class RhawnSoitems extends Model class RhawnSoitems extends Model
{ {
......
...@@ -9,7 +9,9 @@ ...@@ -9,7 +9,9 @@
* with this source code in the file LICENSE. * with this source code in the file LICENSE.
*/ */
namespace App\Repositories\Models; namespace App\Rhawn\Repositories\Models;
use App\Repositories\Models\Model;
class RhawnSorders extends Model class RhawnSorders extends Model
{ {
......
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Rhawn\Services;
use App\Rhawn\Repositories\Contracts\RhawnCustomerRepository;
use App\Support\Facades\SimpleLogs;
use Illuminate\Support\Facades\DB;
class RhawnCustomerService
{
public function __construct(RhawnCustomerRepository $rhawnCustomerRepository)
{
$this->rhawnCustomerRepository = $rhawnCustomerRepository;
}
public function getRhawnCustomerThroughtCusCode($cusCode)
{
$customerInfo = $this->rhawnCustomerRepository->getRhawnCustomerThroughtCusCode($cusCode);
return $customerInfo;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Rhawn\Services;
use App\Repositories\Eloquent\RhawnSordersRepositoryEloquent;
use App\Rhawn\Repositories\Eloquent\RhawnCustomerRepositoryEloquent;
use App\Rhawn\Repositories\Eloquent\RhawnProductRepositoryEloquent;
use App\Rhawn\Repositories\Eloquent\RhawnSoitemsRepositoryEloquent;
use App\Support\Facades\SimpleLogs;
use Illuminate\Support\Facades\DB;
class RhawnOrdersService
{
public function __construct()
{
$this->rhawnSorderRepository = app(RhawnSordersRepositoryEloquent::class);
}
public function getCustomerOrderItems($cusCode, $soItems)
{
$customerReopository = app(RhawnCustomerRepositoryEloquent::class);
$discount = $customerReopository->getCustomerDiscountByCusCode($cusCode);
$total = 0;
$weight = 0;
$productRepository = app(RhawnProductRepositoryEloquent::class);
foreach($soItems as $k => $v){
$productInfo = $productRepository->getProductByPcode($v['p_code']);
if(!$productInfo){
throw new \Exception($v['p_code'].'不存在!',500);
}
$productInfo = current($productInfo);
if($productInfo['p_status'] == 0 || $productInfo['p_show'] == 0){
throw new \Exception($v['p_code'].'已下架!',500);
}
if(isset($discount[$productInfo['b_id']])){
$productInfo['p_discount'] = round($discount[$productInfo['b_id']]['cd_discount'] * $productInfo['p_price']);
}else{
$productInfo['p_discount'] = $productInfo['p_price'];
}
if(isset($v['si_molbase_pog'])){
$soItems[$k]['si_molbase_pog'] = $v['si_molbase_pog'];
}
//当前产品是否在促销设定里
$promotions = $productRepository->getProductPromotionByPid($productInfo['p_id']);
if($promotions){
foreach($promotions as $promotion){
if($promotion['pt_discount'] != 0){
$productInfo['p_discount'] = round($promotion['pt_discount'] * $productInfo['p_discount']);
}
}
}
$soItems[$k]['amount'] = round(bcmul($productInfo['p_discount'],$v['num'],3),2);
$soItems[$k]['weight'] = round(bcmul($productInfo['p_weight'],$v['num'],3),3);
//得到品牌
$brands = DB::connection($this->rhawnSorderRepository->getConnectionName())
->table('brands')
->where('b_id',$productInfo['b_id'])
->first();
if(!$brands){
throw new \Exception('品牌不存在',500);
}
$productInfo['b_cn_name'] = $brands->b_cn_name;
$soItems[$k]['product_info'] = $productInfo;
$total += $soItems[$k]['amount'];
$weight += $soItems[$k]['weight'];
}
$returnItems = [];
$returnItems['total'] = $total;
$returnItems['weight'] = $weight;
$returnItems['rows'] = $soItems;
return $returnItems;
}
/**
* 新增订单
* @param $data
* @return false
*/
public function createOrders($data)
{
$connection = DB::connection($this->rhawnSorderRepository->getConnectionName());
try{
$connection->beginTransaction();
$data['sorders']['so_no'] = '';
$data['sorders']['so_ctime'] = time();
$data['sorders']['so_creater'] = 0;
$data['sorders']['so_standard'] = '';
$orderId = $connection->table('sorders')->insertGetId($data['sorders']);
$soNo = 1000000 + $orderId;
$soNo = date('Ymd',time()).'-'.$soNo;
$connection->table('sorders')
->where('so_id',$orderId)
->update([
'so_no' => $soNo
]);
$soitems = array();
foreach($data['soitems']['p_id'] as $k => $v){
$soitems[$k]['so_id'] = $orderId;
$soitems[$k]['p_id'] = $v;
$soitems[$k]['si_price'] = $data['soitems']['si_price'][$k];
$soitems[$k]['si_discount'] = $data['soitems']['si_discount'][$k];
$soitems[$k]['si_num'] = $data['soitems']['si_num'][$k];
$soitems[$k]['si_amount'] = $data['soitems']['si_amount'][$k];
$soitems[$k]['si_vamount'] = $data['soitems']['si_vamount'][$k];
$soitems[$k]['si_p_tod'] = $data['soitems']['si_p_tod'][$k];
if(isset($data['soitems']['si_cus_note'][$k])){
$soitems[$k]['si_cus_note'] = $data['soitems']['si_cus_note'][$k];
}else{
$soitems[$k]['si_cus_note'] = '';
}
if(isset($data['soitems']['si_molbase_pog'][$k])){
$soitems[$k]['si_molbase_pog'] = $data['soitems']['si_molbase_pog'][$k];
}else{
$soitems[$k]['si_molbase_pog'] = '';
}
$soitems[$k]['si_nodes'] = '';
$soitems[$k]['si_notes'] = '';
$soitems[$k]['si_sales_note'] = '';
}
if($data['express'] > 0){
$soitems_count = count($soitems);
$soitems[$soitems_count]['so_id'] = $orderId;
$soitems[$soitems_count]['p_id'] = 0;
$soitems[$soitems_count]['si_price'] = 0;
$soitems[$soitems_count]['si_discount'] = 0;
$soitems[$soitems_count]['si_num'] = 0;
$soitems[$soitems_count]['si_amount'] = $data['express'];
$soitems[$soitems_count]['si_vamount'] = 0;
$soitems[$soitems_count]['si_p_tod'] = '';
$soitems[$soitems_count]['si_cus_note'] = '';
$soitems[$soitems_count]['si_molbase_pog'] = '';
}
$connection->table('soitems')->insert($soitems);
if($data['v_id'] != ''){
$orderId = $connection->table('voucher')
->where('v_id',$data['v_id'])
->update([
'so_id' => $orderId
]);
}
$connection->commit();
return $orderId;
}catch(\Throwable $exception){
$connection->rollBack();
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':createOrders','error');
throw $exception;
}
}
/**
* 计算运费
* @param $weight
* @param $province
* @param $total
* @param $if_free_express
* @param $cus_level
* @return float|int
*/
public function getExpress($weight,$province,$total,$if_free_express,$cus_level){
//计算运费 (运费=首重(1kg)*运输系数(首重)+续重(总重量-1kg)*运输系数(续重))
$express = 0;
if($if_free_express == 1 || $cus_level == 3){
return $express;
}else{
if($cus_level == 0){
$max_amount = 150;
}
if($cus_level == 1){
$max_amount = 99;
}
if($cus_level == 2){
$max_amount = 66;
}
//统一调整为满66免运费
//$max_amount = 66;
if($weight == 0){
$weight = 0.1;
}
if($total < $max_amount && $weight > 0){
$weight = ceil($weight);
if($province == '江苏省' || $province == '浙江省' || $province == '上海' || $province == '上海市'){
$express = ($weight - 1)*2 + 6;
}else{
$express = ($weight - 1)*8 + 10;
}
}
return $express;
}
}
public function getCustomerOrderItemsByOrderId($cusId, $orderId)
{
return $this->rhawnSorderRepository->getCustomerOrderItemsByOrderId($cusId, $orderId);
}
public function getSordersByOrderNo($orderNo)
{
$order = $this->rhawnSorderRepository->getSorderFromOrderNo($orderNo);
if($order){
return $order->toArray();
}
return null;
}
/**
* 取消客户订单
* @param $cusId
* @param $orderId
* @return bool
* @throws \Throwable
*/
public function cancelCustomerOrderByOrderId($cusId, $orderId)
{
$connection = $this->rhawnSorderRepository->getConnection();
try{
$connection->beginTransaction();
$connection->table('sorders')
->where('so_id',$orderId)
->where('cus_id',$cusId)
->update([
'so_review_status'=>'3','so_total'=>'0'
]);
$connection->table('soitems')
->where('so_id',$orderId)
->update([
'si_if_cancel'=>'1'
]);
$connection->commit();
return true;
}catch(\Throwable $exception){
$connection->rollBack();
throw $exception;
}
}
/**
* 获取订单配货单详情
* @param $orderNumber
*/
public function getOrderDispatchDetail($orderNumber)
{
try{
$dpdetail = $this->rhawnSorderRepository->getOrderDispatch($orderNumber);
$soItemIds = [];
if($dpdetail){
foreach($dpdetail as $detail){
$soItemIds[] = $detail['si_id'];
}
$soItems = app(RhawnSoitemsRepositoryEloquent::class)->getSorderItemFromItemId($soItemIds);
if(!$soItems){
throw new \Exception('订单项不存在',500);
}
$orderItems = [];
foreach($soItems as $item){
$orderItems[$item['si_id']] = $item;
}
foreach($dpdetail as &$detail){
if(isset($orderItems[$detail['si_id']]) && !empty($orderItems[$detail['si_id']])){
$detail['si_id'] = $orderItems[$detail['si_id']];
}
}
}
return $dpdetail;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':getOrderDispatchDetail','error');
throw $exception;
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Rhawn\Services;
use App\Rhawn\Repositories\Contracts\RhawnProductRepository;
use App\Rhawn\Repositories\Eloquent\RhawnCustomerRepositoryEloquent;
use App\Rhawn\Repositories\Eloquent\RhawnRawRepositoryEloquent;
use App\Support\Facades\SimpleLogs;
use Illuminate\Support\Facades\DB;
class RhawnProductService
{
public function __construct(RhawnProductRepository $rhawnProductRepository)
{
$this->rhawnRawRepository = app(RhawnRawRepositoryEloquent::class);
$this->rhawnProductRepository = $rhawnProductRepository;
}
public function getRawsList($offset = 0, $limit = 100)
{
$rawList = $this->rhawnProductRepository->getRawProductList($limit, $offset);
return $rawList;
}
public function getChemicalPackage($rawIds)
{
$packageList = $this->rhawnRawRepository->getProductPackage($rawIds);
return $packageList;
}
public function getProductPackagesThroughGroupByPackUnit()
{
return $this->rhawnRawRepository->getProductPackagesThroughGroupByPackUnit();
}
public function getChemicalRawThroughtCode($rawCode)
{
return $this->rhawnRawRepository->getRawProductsThroughtCode($rawCode);
}
public function getProductsThroughPid($pId)
{
try{
$dbConnect = DB::connection('rhawn_mysql');
$product = $dbConnect->table('products')
->where('p_id',$pId)
->get()->toArray();
if(count($product) > 0){
return current($product);
}
return null;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':getRawProductsThroughPid ','error');
throw $exception;
}
}
/**
* 通过产品code查找
* @param $pCode
*/
public function getProductsInfoByCode($pCode)
{
$productInfo = $this->rhawnProductRepository->getProductByPcode($pCode);
}
/**
* 获取产品列表(含促销价格)
* @param $offset
* @param $pageSize
* @param array $where
* @return null
*/
public function getProductsListWithPromotions($offset,$limit,$where = [])
{
try{
$products = $this->rhawnProductRepository->getProductsList($where,$limit,$offset);
if($products){
$pids = [];
foreach($products as $product){
$pids[] = $product['p_id'];
}
$promotions = $this->rhawnProductRepository->getProductPromotionByPid($pids);
$productPromotions = [];
if($promotions){
foreach($promotions as $promotion){
$productPromotions[$promotion->p_id] = $promotion;
}
}
foreach($products as &$product){
$product['m_price'] = $product['p_price'];
if(!empty($productPromotions) && isset($productPromotions[$product['p_id']])){
$pPromotions = $productPromotions[$product['p_id']];
if($pPromotions->pt_discount != 0){
$product['p_price'] = round($pPromotions->pt_discount * $product['p_price']);
}
}
}
}
return $products;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':getProductsListWithPromotions ','error');
return null;
}
}
/**
* 根据CAS号获取产品(含促销价格)
* @param $cas
* @return false|mixed|null
*/
public function getProductsWithPromotionsByCas($cas)
{
try{
$products = $this->rhawnProductRepository->getProductsByCas($cas);
if($products){
$products = current($products);
$promotions = $this->rhawnProductRepository->getProductPromotionByPid($products['p_id']);
$productPromotions = [];
if($promotions){
foreach($promotions as $promotion){
$productPromotions[$promotion->p_id] = $promotion;
}
}
$products['m_price'] = $products['p_price'];
if(!empty($productPromotions) && isset($productPromotions[$products['p_id']])){
$pPromotions = $productPromotions[$products['p_id']];
if($pPromotions->pt_discount != 0){
$products['p_price'] = round($pPromotions->pt_discount * $products['p_price']);
}
}
}
return $products;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':getProductsWithPromotionsByCas ','error');
return null;
}
}
/**
* 获取产品详情(含促销价格及会员价格)
* @param $pCode
* @param $cusCode
* @return false|mixed|null
*/
public function getProductDetailWithPromotions($pCode,$cusCode)
{
try{
$products = $this->rhawnProductRepository->getProductByPcode($pCode);
if($products){
$products = current($products);
$discount = app(RhawnCustomerRepositoryEloquent::class)->getCustomerDiscountByCusCode($cusCode);
if($discount){
$products['m_price'] = $products['p_price'];
if(isset($discount[$products['b_id']])){
$products['p_price'] = round($discount[$products['b_id']]['cd_discount'] * $products['p_price']);
}else{
$products['p_price'] = $products['p_price'];
}
}
$promotions = $this->rhawnProductRepository->getProductPromotionByPid($products['p_id']);
$productPromotions = [];
if($promotions){
foreach($promotions as $promotion){
$productPromotions[$promotion->p_id] = $promotion;
}
}
if(!empty($productPromotions) && isset($productPromotions[$products['p_id']])){
$pPromotions = $productPromotions[$products['p_id']];
if($pPromotions->pt_discount != 0){
$products['p_price'] = round($pPromotions->pt_discount * $products['p_price']);
}
}
}
return $products;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':getProductDetailWithPromotions ','error');
return null;
}
}
}
...@@ -9,41 +9,21 @@ ...@@ -9,41 +9,21 @@
* with this source code in the file LICENSE. * with this source code in the file LICENSE.
*/ */
namespace App\Services; namespace App\Rhawn\Services;
use App\Repositories\Contracts\RhawnSoitemsRepository; use App\Rhawn\Repositories\Contracts\RhawnSoitemsRepository;
use App\Repositories\Contracts\RhawnSordersRepository; use App\Rhawn\Repositories\Contracts\RhawnSordersRepository;
use App\Services\ThirdPlatform\ZhenKhService; use App\Services\PlatformDataEntriesService;
use App\Support\Facades\SimpleLogs; use App\Support\Facades\SimpleLogs;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
class RhawnOrdersService class ZhenkhService
{ {
public function __construct() public function __construct()
{ {
$this->dataEntries = app(PlatformDataEntriesService::class); $this->dataEntries = app(PlatformDataEntriesService::class);
} $this->rhawnOrdersRepository = app(RhawnSordersRepository::class);
$this->rhawnSoitemsrepository = app(RhawnSoitemsRepository::class);
/**
* @恢复orderNo
* @param $offset
* @param int $pageSize
* @return false|void
*/
public function rollBackOrderNo($offset,$pageSize = 1000)
{
$dbConnect = DB::connection('rhawn_mysql');
$rows = $dbConnect->table('sorders')
->where('so_no','20220826-1090846')
->offset($offset)
->limit($pageSize)
->get()->toArray();
if(!$rows) return false;
foreach($rows as $row){
$orderNo = 1000000 + $row->so_id;
$orderNo = date('Ymd',$row->so_ctime).'-'.$orderNo;
$dbConnect->table('sorders')->where('so_id',$row->so_id)->update(['so_no' => $orderNo]);
}
} }
/** /**
...@@ -53,13 +33,13 @@ class RhawnOrdersService ...@@ -53,13 +33,13 @@ class RhawnOrdersService
*/ */
public function getSorderDetail($orderNo) public function getSorderDetail($orderNo)
{ {
$sOrder = app(RhawnSordersRepository::class)->getSorderFromOrderNo($orderNo); $sOrder = $this->rhawnOrdersRepository->getSorderFromOrderNo($orderNo);
if(!$sOrder){ if(!$sOrder){
throw new \LogicException('该订单编号不存在!',500); throw new \LogicException('该订单编号不存在!',500);
} }
//查询订单的详情 //查询订单的详情
$soItems = app(RhawnSoitemsRepository::class)->getSorderItemsDetailFromOrderId($sOrder->so_id); $soItems = $this->rhawnSoitemsrepository->getSorderItemsDetailFromOrderId($sOrder->so_id);
$soItems = $soItems->toArray(); $soItems = $soItems->toArray();
$returnItem = []; $returnItem = [];
if($soItems){ if($soItems){
...@@ -97,7 +77,7 @@ class RhawnOrdersService ...@@ -97,7 +77,7 @@ class RhawnOrdersService
*/ */
public function getSorderDeliveryDetail($deliveryCode) public function getSorderDeliveryDetail($deliveryCode)
{ {
$dbConnect = DB::connection('rhawn_mysql'); $dbConnect = DB::connection($this->rhawnOrdersRepository->getConnectionName());
$dpdetail = $dbConnect->table('dispatch') $dpdetail = $dbConnect->table('dispatch')
->join('dpdetail','dpdetail.dp_id','dispatch.dp_id') ->join('dpdetail','dpdetail.dp_id','dispatch.dp_id')
->join('sorders','sorders.so_id','dispatch.so_id') ->join('sorders','sorders.so_id','dispatch.so_id')
...@@ -122,10 +102,9 @@ class RhawnOrdersService ...@@ -122,10 +102,9 @@ class RhawnOrdersService
return false; return false;
} }
$dbConnect = DB::connection('rhawn_mysql'); $dbConnect = DB::connection($this->rhawnOrdersRepository->getConnectionName());
//判断订单是否已经存在 //判断订单是否已经存在
$oneOrder = $dbConnect->table('sorders') $oneOrder = $dbConnect->table($this->rhawnOrdersRepository->getTableName())
->where('so_cus_po',$order['purchaseOrderId']) ->where('so_cus_po',$order['purchaseOrderId'])
->get()->toArray(); ->get()->toArray();
if($oneOrder){ if($oneOrder){
...@@ -185,12 +164,12 @@ class RhawnOrdersService ...@@ -185,12 +164,12 @@ class RhawnOrdersService
try{ try{
$dbConnect->beginTransaction(); $dbConnect->beginTransaction();
$orderId = $dbConnect->table('sorders')->insertGetId($updateOrderArray); $orderId = $dbConnect->table($this->rhawnOrdersRepository->getTableName())->insertGetId($updateOrderArray);
if($orderId > 0){ if($orderId > 0){
$so_no = 1000000 + $orderId; $so_no = 1000000 + $orderId;
$so_no = date('Ymd',time()).'-'.$so_no; $so_no = date('Ymd',time()).'-'.$so_no;
$dbConnect->table('sorders') $dbConnect->table($this->rhawnOrdersRepository->getTableName())
->where('so_id',$orderId) ->where('so_id',$orderId)
->update(['so_no' => $so_no]); ->update(['so_no' => $so_no]);
...@@ -228,7 +207,7 @@ class RhawnOrdersService ...@@ -228,7 +207,7 @@ class RhawnOrdersService
$orderItemsArray['si_sales_note'] = ''; $orderItemsArray['si_sales_note'] = '';
$orderItemsArray['si_cus_note'] = ''; $orderItemsArray['si_cus_note'] = '';
$dbConnect->table('soitems')->insert($orderItemsArray); $dbConnect->table($this->rhawnSoitemsrepository->getTableName())->insert($orderItemsArray);
} }
} }
} }
...@@ -249,7 +228,7 @@ class RhawnOrdersService ...@@ -249,7 +228,7 @@ class RhawnOrdersService
$soitems[$soitems_count]['si_cus_note'] = ''; $soitems[$soitems_count]['si_cus_note'] = '';
$soitems[$soitems_count]['si_molbase_pog'] = ''; $soitems[$soitems_count]['si_molbase_pog'] = '';
$dbConnect->table('soitems')->insert($soitems); $dbConnect->table($this->rhawnSoitemsrepository->getTableName())->insert($soitems);
} }
} }
...@@ -260,4 +239,81 @@ class RhawnOrdersService ...@@ -260,4 +239,81 @@ class RhawnOrdersService
} }
} }
/**
* 保存震坤行同步商品数据
* @param $goods
*/
public function updateZhenkhGoods($goods)
{
try{
$dbConnect = DB::connection('rhawn_mysql');
$zkhGoods = [];
$zkhGoods['zg_sku'] = $goods['zkhSku'];
$zkhGoods['zg_r_sku'] = $goods['supplierSkuNo'];
if(isset($goods['addressList']['0'])){
$zkhGoods['zg_addr'] = implode(',',$goods['addressList']);
}
$zkhGoods['zg_unit'] = $goods['priceUnit'];
if($zkhGoods['zg_r_sku'] != ''){
$zkhGoodsResult = $dbConnect->table('products')
->where('p_code',$zkhGoods['zg_r_sku'])
->get()->toArray();
if($zkhGoodsResult){
$zkhGoodsResult = current($zkhGoodsResult);
$zkhGoods['zg_r_pid'] = $zkhGoodsResult->p_id;
$row = $dbConnect->table('zkh_goods')
->where('zg_r_sku',$zkhGoods['zg_r_sku'])
->where('zg_r_pid',$zkhGoods['zg_r_pid'])
->get()->toArray();
if(count($row) == 0){
$id = $dbConnect->table('zkh_goods')->insertGetId($zkhGoods);
SimpleLogs::writeLog('zkh_goods 新增 id : '.$id.' 成功.', 'sql insert');
$row = $dbConnect->table('zkh_goods')->where('zg_id',$id)->get()->toArray();
}
if($row){
return current($row);
}
}
}
return null;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),'updateZhenkhGoods ','error');
throw $exception;
}
}
/**
* 更新震坤行数据更新时间
* @param $zgId
* @return int
*/
public function updateSyncRunTime($zgId)
{
$dbConnect = DB::connection('rhawn_mysql');
return $dbConnect->table('zkh_goods')->where('zg_id',$zgId)->update(['zg_sync_time' => time()]);
}
/**
* @获取震坤行对应的商品sku
* @param $pCode
* @return array
*/
public function getZkhGoodsSku($pCode)
{
$dbConnect = DB::connection('rhawn_mysql');
$model = $dbConnect->table('zkh_goods');
if(is_array($pCode)){
$model->whereIn('zg_r_pid',$pCode);
}else{
$model->where('zg_r_pid',$pCode);
}
return $model->get()->toArray();
}
} }
\ No newline at end of file
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services\Api;
use App\Repositories\Eloquent\RhawnSordersRepositoryEloquent;
use App\Repositories\Transformers\Rhawn\OrdersDispatchTransformer;
use App\Rhawn\Repositories\Eloquent\RhawnCustomerRepositoryEloquent;
use App\Rhawn\Services\RhawnCustomerService;
use App\Support\Facades\SimpleLogs;
use Illuminate\Support\Facades\DB;
class RhawnOrdersService
{
public function __construct(\App\Rhawn\Services\RhawnOrdersService $rhawnOrdersService)
{
$this->rhawnOrdersService = $rhawnOrdersService;
}
/**
* 获取罗恩订单列表
* @param $requestParams
*/
public function getCustomerRhawnOrdersList($requestParams)
{
try{
$customer = $this->checkCustomerExist($requestParams['customer_code']);
$offset = !isset($requestParams['page_size']) || empty($requestParams['page_size']) ? 100 : $requestParams['page_size'];
if($offset > 100){
$offset = 100;
}
$pageNo = !isset($requestParams['page_no']) || empty($requestParams['page_no']) ? 1 : $requestParams['page_no'];
$limit = $pageNo == 1 ? 0 : $pageNo * $offset;
$rhawnOrderRepository = app(RhawnSordersRepositoryEloquent::class);
$orderList = $rhawnOrderRepository->getCustomerOrderList($customer['cus_id'],$limit,$offset);
//获取订单量总数
$total = $rhawnOrderRepository->orderTotalByCusId($customer['cus_id']);
$dataReturn = [];
$dataReturn['data'] = $orderList;
$dataReturn['total_page'] = ceil($total / $offset);
$dataReturn['page_no'] = $pageNo;
return $dataReturn;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':getCustomerRhawnOrdersList','error');
throw $exception;
}
}
/**
* 获取客户订单详情
* @param $requestParams
*/
public function getCustomerOrderDetail($requestParams)
{
try{
$customer = $this->checkCustomerExist($requestParams['customer_code']);
$order = $this->rhawnOrdersService->getSordersByOrderNo($requestParams['order_number']);
if(!$order){
throw new \Exception('订单编号不存在',500);
}
return $this->rhawnOrdersService->getCustomerOrderItemsByOrderId($customer['cus_id'],$order['so_id']);
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':getCustomerOrderDetail','error');
throw $exception;
}
}
/**
* 新增订单
* @param $requestParams
*/
public function createNewCustomerOrders($requestParams)
{
try{
$customer = $this->checkCustomerExist($requestParams['customer_code']);
if(!isset($requestParams['so_ca_county'])){
$requestParams['so_ca_county'] = '';
}
$orderItems = $this->rhawnOrdersService->getCustomerOrderItems($customer['cus_no'],$requestParams['items']);
if(!$orderItems){
throw new \Exception('货号无法匹配',500);
}
$express = $this->rhawnOrdersService->getExpress(
$orderItems['weight'],$requestParams['so_ca_province'],$orderItems['total'],$customer['cus_free_express'],$customer['cus_level']
);
$data = [];
$data['sorders']['cus_id'] = $customer['cus_id'];
$data['sorders']['so_cus_po'] = $requestParams['so_cus_po'];
$data['sorders']['so_ca_name'] = $requestParams['so_ca_name'];
$data['sorders']['so_ca_mobile'] = $requestParams['so_ca_mobile'];
$data['sorders']['so_ca_phone'] = !isset($requestParams['so_ca_phone']) ? '' : $requestParams['so_ca_phone'];
$data['sorders']['so_ca_province'] = $requestParams['so_ca_province'];
$data['sorders']['so_ca_city'] = $requestParams['so_ca_city'];
$data['sorders']['so_ca_county'] = $requestParams['so_ca_county'];
$data['sorders']['so_ca_street'] = $requestParams['so_ca_street'];
//得到收票地址
$rhawnCustomerRepository = app(RhawnCustomerRepositoryEloquent::class);
$cusiaddrs_arr = $rhawnCustomerRepository->getCustomerAddressByCusCode($customer['cus_no']);
$cusinvoice_arr = $rhawnCustomerRepository->getCustomerInvoiceByCusCode($customer['cus_no']);
if(!$cusiaddrs_arr){
throw new \Exception('请至会员中心设置收票地址',500);
}
if(!$cusinvoice_arr){
throw new \Exception('请至会员中心设置发票信息',500);
}
$cusiaddrs_arr = current($cusiaddrs_arr);
$cusinvoice_arr = current($cusinvoice_arr);
$data['sorders']['so_cia_name'] = $cusiaddrs_arr['cia_name'];
$data['sorders']['so_cia_mobile'] = $cusiaddrs_arr['cia_mobile'];
$data['sorders']['so_cia_phone'] = $cusiaddrs_arr['cia_phone'];
$data['sorders']['so_cia_province'] = $cusiaddrs_arr['cia_province'];
$data['sorders']['so_cia_city'] = $cusiaddrs_arr['cia_city'];
$data['sorders']['so_cia_county'] = $cusiaddrs_arr['cia_county'];
$data['sorders']['so_cia_street'] = $cusiaddrs_arr['cia_street'];
$data['sorders']['so_cia_name'] = $cusiaddrs_arr['cia_name'];
$data['sorders']['so_ci_type'] = $cusinvoice_arr['ci_type'];
$data['sorders']['so_ci_title'] = $cusinvoice_arr['ci_title'];
$data['sorders']['so_ci_vatno'] = $cusinvoice_arr['ci_vatno'];
$data['sorders']['so_ci_bank'] = $cusinvoice_arr['ci_bank'];
$data['sorders']['so_ci_bknum'] = $cusinvoice_arr['ci_bknum'];
$data['sorders']['so_ci_addr'] = $cusinvoice_arr['ci_addr'];
$data['sorders']['so_ci_phone'] = $cusinvoice_arr['ci_phone'];
if(!isset($requestParams['so_note'])){
$requestParams['so_note'] = '';
}
$data['sorders']['so_note'] = $requestParams['so_note'];
$data['sorders']['so_send_note'] = $customer['cus_send_note'];
$data['sorders']['so_if_wx'] = 0;
$data['sorders']['so_if_api'] = 1;
$data['sorders']['so_ci_method'] = 1;
$data['sorders']['so_total'] = $orderItems['total'] + $express;
$data['express'] = $express;
$data['v_id'] = '';
foreach($orderItems['rows'] as $k => $v){
$data['soitems']['p_id'][] = $v['product_info']['p_id'];
$data['soitems']['si_price'][] = $v['product_info']['p_price'];
$data['soitems']['si_discount'][] = $v['product_info']['p_discount'];
$data['soitems']['si_num'][] = $v['num'];
$data['soitems']['si_amount'][] = $v['product_info']['p_discount'] * $v['num'];
$data['soitems']['si_p_tod'][] = $v['product_info']['p_tod'];
$data['soitems']['si_vamount'][] = 0;
if(isset($v['si_cus_note'])){
$data['soitems']['si_cus_note'][] = $v['si_cus_note'];
}
if(isset($v['si_molbase_pog'])){
$data['soitems']['si_molbase_pog'][] = $v['si_molbase_pog'];
}
}
$orderId = $this->rhawnOrdersService->createOrders($data);
if($orderId){
return $this->rhawnOrdersService->getCustomerOrderItemsByOrderId($customer['cus_id'],$orderId);
}
return null;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':createNewCustomerOrders','error');
throw $exception;
}
}
/**
* 取消客户订单
* @param $requestParams
*/
public function cancelCustomerOrder($requestParams)
{
try{
$customer = $this->checkCustomerExist($requestParams['customer_code']);
$order = $this->rhawnOrdersService->getSordersByOrderNo($requestParams['order_number']);
if(!$order){
throw new \Exception('订单编号不存在',500);
}
if($order['so_review_status'] != 0){
throw new \Exception('订单不是未审核状态,不能取消!',500);
}
if($order['so_pay_status'] != 0){
throw new \Exception('订单不是未付款状态,不能取消!',500);
}
return $this->rhawnOrdersService->cancelCustomerOrderByOrderId($customer['cus_id'],$order['so_id']);
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':cancelCustomerOrder','error');
throw $exception;
}
}
public function getOrderDispatchByOrderNumber($requestParams)
{
try{
$customer = $this->checkCustomerExist($requestParams['customer_code']);
$order = $this->rhawnOrdersService->getSordersByOrderNo($requestParams['order_number']);
if(!$order){
throw new \Exception('订单编号不存在',500);
}
$dpdetail = $this->rhawnOrdersService->getOrderDispatchDetail($order['so_no']);
if($dpdetail){
$dpdetail = app(OrdersDispatchTransformer::class)->transform($dpdetail);
}
return $dpdetail;
}catch(\Throwable $exception){
var_dump($exception->getMessage());
exit;
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':getOrderDispatchByOrderNumber','error');
throw $exception;
}
}
/**
* 检查客户信息是否存在
* @param $cusCode
* @return mixed
* @throws \Exception
*/
private function checkCustomerExist($cusCode)
{
//查询用户是否存在
$rhawnCustomerService = app(RhawnCustomerService::class);
$customer = $rhawnCustomerService->getRhawnCustomerThroughtCusCode($cusCode);
if(!$customer){
throw new \Exception('客户编号为:['.$cusCode.']的用户不存在!',500);
}
return $customer;
}
}
<?php
namespace App\Services\Api;
use App\Repositories\Transformers\Rhawn\ProductDetailTransformer;
use App\Repositories\Transformers\Rhawn\ProductsTransformer;
use App\Rhawn\Services\RhawnCustomerService;
use App\Support\Facades\SimpleLogs;
use Illuminate\Support\Facades\DB;
class RhawnProductsService
{
public function __construct(\App\Rhawn\Services\RhawnProductService $rhawnProductService)
{
$this->rhawnProductService = $rhawnProductService;
}
public function getAllProducts($requestParams)
{
$customer = $this->checkCustomerExist($requestParams['customer_code']);
$offset = !isset($requestParams['page_size']) || empty($requestParams['page_size']) ? 2000 : $requestParams['page_size'];
if($offset > 100){
$offset = 100;
}
$pageNo = !isset($requestParams['page_no']) || empty($requestParams['page_no']) ? 1 : $requestParams['page_no'];
$limit = $pageNo == 1 ? 0 : $pageNo * $offset;
try{
$where = [];
$products = $this->rhawnProductService->getProductsListWithPromotions($offset,$limit,$where);
$productsTotal = 0;
if($products){
$products = app(ProductsTransformer::class)->transform($products);
$productsTotal = $this->rhawnProductService->rhawnProductRepository->count($where);
}
$dataReturn = [];
$dataReturn['data'] = $products;
$dataReturn['total_page'] = ceil($productsTotal / $offset);
$dataReturn['page_no'] = $pageNo;
return $dataReturn;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':cancelCustomerOrder','error');
throw $exception;
}
}
public function getProductDetail($requestParams)
{
$customer = $this->checkCustomerExist($requestParams['customer_code']);
try{
$products = $this->rhawnProductService->getProductDetailWithPromotions($requestParams['product_code'],$customer['cus_no']);
if($products){
$products = app(ProductDetailTransformer::class)->transform($products);
}
return $products;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':cancelCustomerOrder','error');
throw $exception;
}
}
public function getProductByCas($requestParams)
{
$customer = $this->checkCustomerExist($requestParams['customer_code']);
try{
$products = $this->rhawnProductService->getProductsWithPromotionsByCas($requestParams['cas']);
if($products){
$products = app(ProductsTransformer::class)->transform([$products],'bycas');
$products = current($products);
}
return $products;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':cancelCustomerOrder','error');
throw $exception;
}
}
/**
* 检查客户信息是否存在
* @param $cusCode
* @return mixed
* @throws \Exception
*/
private function checkCustomerExist($cusCode)
{
//查询用户是否存在
$rhawnCustomerService = app(RhawnCustomerService::class);
$customer = $rhawnCustomerService->getRhawnCustomerThroughtCusCode($cusCode);
if(!$customer){
throw new \Exception('客户编号为:['.$cusCode.']的用户不存在!',500);
}
return $customer;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services;
use App\Repositories\Contracts\PlatformCustomerRepository;
use App\Rhawn\Services\RhawnCustomerService;
use App\Support\Facades\SimpleLogs;
use App\Support\Traits\Helpers;
use Illuminate\Support\Facades\DB;
class AuthService
{
use Helpers;
public function __construct(PlatformCustomerRepository $platformCustomerRepository)
{
$this->platformCustomerRepository = $platformCustomerRepository;
}
/**
* 获取token
* @param $requestParams
* @return array
* @throws \Exception
*/
public function getToken($requestParams)
{
$token = $requestParams['customer_token'];
$platformCustomer = $this->platformCustomerRepository->findWhere([
'token' => $token
]);
if(!$platformCustomer->toArray()){
throw new \Exception('token无效',500);
}
$expTimestamp = strtotime(date('Y-m-d H:i:s', strtotime('+1hour')));
$jwtToken = $this->generateToken($token);
return [
'token' => $jwtToken,
'ttl' => $expTimestamp
];
}
}
<?php
namespace App\Services;
use App\Support\Facades\SimpleLogs;
use Illuminate\Support\Facades\DB;
class BhProductsService
{
/**
* 保存bide平台的产品数据
*/
public function storeBideProducts($bideProducts)
{
if (!is_array($bideProducts) || empty($bideProducts)) {
return false;
}
try {
$id = 0;
$dbConnect = DB::connection('bh_mysql');
$dbConnect->beginTransaction();
$chemicalsRow = $dbConnect->table('chemicals')
->where('c_cas', $bideProducts[0]['CASNumber'])
->get()->toArray();
if (empty($chemicalsRow)) {
return false;
}
$chemicalsRow = current($chemicalsRow);
$dbConnect->table('products')
->where('c_id', $chemicalsRow->c_id)
->where('b_id', 10)
->update(['p_status' => 0, 'p_show' => 0, 'modifytime' => time()]);
foreach ($bideProducts as $product) {
if ($product['Weight'] > 0) {
$p_tod = '现货';
} else {
$p_tod = '无货,请咨询';
}
$p_code = $product['ProductNum'] . '-' . $product['PackSize'];
$productRow = $dbConnect->table('products')
->where('b_id', 10)
->where('c_id', $chemicalsRow->c_id)
->where('p_code', 'like', $p_code)
->get()->toArray();
$pro_data = [];
if (empty($productRow)) {
$pro_data['b_id'] = 10;
$pro_data['c_id'] = $chemicalsRow->c_id;
$pro_data['p_code'] = $p_code;
if (!$product['ProductCName']) {
$pro_data['p_cn_name'] = '';
} else {
$pro_data['p_cn_name'] = $product['ProductCName'];
}
if (!$product['ProductEName']) {
$pro_data['p_en_name'] = '';
} else {
$pro_data['p_en_name'] = $product['ProductEName'];
}
$pro_data['p_level'] = $product['Purity'];
$pro_data['p_pack'] = $product['PackSize'];
$pro_data['p_price'] = $product['PriceB'];
$pro_data['p_tod'] = $p_tod;
$pro_data['p_weight'] = '0.01';
$pro_data['p_status'] = 1;
$pro_data['p_show'] = 1;
$pro_data['prom_from'] = 0;
$pro_data['prom_to'] = 0;
$id = $dbConnect->table('products')->insertGetId($pro_data);
} else {
$productRow = current($productRow);
$pro_data['p_status'] = 1;
$pro_data['p_show'] = 1;
$pro_data['p_price'] = $product['PriceB'];
$pro_data['p_tod'] = $p_tod;
$pro_data['modifytime'] = time();
$dbConnect->table('products')
->where('p_id', $productRow->p_id)
->update($pro_data);
$id = $productRow->p_id;
}
}
$dbConnect->commit();
SimpleLogs::writeLog('Bide p_id : '.$id.' cas : '.$chemicalsRow->c_cas. ' 更新成功,更新时间:'.date('Y-m-d H:i:s',time()),__CLASS__.':storeBjsProducts');
return true;
}catch(\Exception $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':storeBjsProducts', 'error');
$dbConnect->rollback();
throw $exception;
}
}
/**
* 保存bjs平台的产品数据
*/
public function storeBjsProducts($bideProducts)
{
if (!is_array($bideProducts) || empty($bideProducts)) {
return false;
}
try {
$id = 0;
$dbConnect = DB::connection('bh_mysql');
$dbConnect->beginTransaction();
$chemicalsRow = $dbConnect->table('chemicals')
->where('c_cas', $bideProducts[0]['CASNumber'])
->get()->toArray();
if (empty($chemicalsRow)) {
return false;
}
$chemicalsRow = current($chemicalsRow);
$dbConnect->table('products')
->where('c_id', $chemicalsRow->c_id)
->where('b_id', 175)
->update(['p_status' => 0, 'p_show' => 0, 'modifytime' => time()]);
foreach ($bideProducts as $product) {
if ($product['Weight'] > 0) {
$p_tod = '现货';
} else {
$p_tod = '无货,请咨询';
}
$p_code = $product['ProductNum'] . '-' . $product['PackSize'];
$productRow = $dbConnect->table('products')
->where('b_id', 175)
->where('c_id', $chemicalsRow->c_id)
->where('p_code', 'like', $p_code)
->get()->toArray();
$pro_data = [];
if (empty($productRow)) {
$pro_data['b_id'] = 175;
$pro_data['c_id'] = $chemicalsRow->c_id;
$pro_data['p_code'] = $p_code;
if (!$product['ProductCName']) {
$pro_data['p_cn_name'] = '';
} else {
$pro_data['p_cn_name'] = $product['ProductCName'];
}
if (!$product['ProductEName']) {
$pro_data['p_en_name'] = '';
} else {
$pro_data['p_en_name'] = $product['ProductEName'];
}
$pro_data['p_level'] = $product['Purity'];
$pro_data['p_pack'] = $product['PackSize'];
$pro_data['p_price'] = $product['Price'];
$pro_data['p_tod'] = $p_tod;
$pro_data['p_weight'] = '0.01';
$pro_data['p_status'] = 1;
$pro_data['p_show'] = 0;
$pro_data['prom_from'] = 0;
$pro_data['prom_to'] = 0;
$id = $dbConnect->table('products')->insertGetId($pro_data);
} else {
$productRow = current($productRow);
$pro_data['p_status'] = 1;
$pro_data['p_show'] = 0;
$pro_data['p_price'] = $product['Price'];
$pro_data['p_tod'] = $p_tod;
$pro_data['modifytime'] = time();
$dbConnect->table('products')
->where('p_id', $productRow->p_id)
->update($pro_data);
$id = $productRow->p_id;
}
}
$dbConnect->commit();
SimpleLogs::writeLog('Bjs p_id : '.$id.' cas : '.$chemicalsRow->c_cas. ' 更新成功,更新时间:'.date('Y-m-d H:i:s',time()),__CLASS__.':storeBjsProducts');
return true;
}catch(\Exception $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':storeBjsProducts', 'error');
$dbConnect->rollback();
throw $exception;
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services;
use App\Repositories\Contracts\PlatformCustomerRepository;
use App\Rhawn\Services\RhawnCustomerService;
use App\Support\Facades\SimpleLogs;
use App\Support\Traits\Helpers;
use Illuminate\Support\Facades\DB;
class CustomerService
{
use Helpers;
public function __construct(PlatformCustomerRepository $platformCustomerRepository)
{
$this->platformCustomerRepository = $platformCustomerRepository;
$this->rhawnCustomerService = app(RhawnCustomerService::class);
}
/**
* 创建api会员信息
* @param $requestParams
* @throws \Exception
*/
public function createPlatformCustomer($requestParams)
{
try{
$customer = $this->rhawnCustomerService->getRhawnCustomerThroughtCusCode($requestParams['customer_code']);
if(!$customer){
throw new \Exception('没有找到该客户',500);
}
$platformCustomer = $this->platformCustomerRepository->findWhere([
'cus_id' => $customer['cus_id'],
'cus_number' => $customer['cus_no']
])->toArray();
if($platformCustomer){
throw new \Exception('平台用户已存在,无需重复注册',500);
}
$newCustomer = [];
$newCustomer['cus_id'] = $customer['cus_id'];
$newCustomer['cus_number'] = $customer['cus_no'];
$newCustomer['company_name'] = $requestParams['customer_company'];
$newCustomer['token'] = $this->randomFromDevice(16);
$newCustomer['platform_params'] = '';
$newCustomer['status'] = 1;
return $this->platformCustomerRepository->create($newCustomer);
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':createCustomer','error');
throw $exception;
}
}
/**
* 获取平台用户信息
* @param $requestParams
*/
public function getPlatformCustomer($requestParams)
{
$platformCustomer = $this->platformCustomerRepository->find($requestParams['platform_customer_id']);
if(!$platformCustomer){
throw new \Exception('平台用户不存在',500);
}
return $platformCustomer;
}
/**
* 更新平台用户token
* @param $requestParams
* @throws \Throwable
*/
public function refreshCustomerToken($requestParams)
{
try{
$platformCustomer = $this->platformCustomerRepository->find($requestParams['platform_customer_id']);
if(!$platformCustomer){
throw new \Exception('平台用户不存在',500);
}
$newToken = $this->randomFromDevice(16);
$this->platformCustomerRepository->update([
'token' => $newToken
],$platformCustomer['id']);
return $newToken;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':refreshCustomerToken','error');
throw $exception;
}
}
/**
* 获取用户信息
* @param $customerCode
*/
public function getRhawnCustomerInfo($customerCode)
{
$customer = $this->rhawnCustomerService->getRhawnCustomerThroughtCusCode($customerCode);
if($customer){
return $customer;
}
return [];
}
/**
* 根据token获取平台用户信息
* @param $token
* @return false|mixed
* @throws \Throwable
*/
public function getCustomerInfoByToken($token)
{
try{
$platformCustomer = $this->platformCustomerRepository->findWhere([
'token' => $token
]);
if(!$platformCustomer){
throw new \Exception('平台用户不存在',500);
}
return current($platformCustomer->toArray());
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':refreshCustomerToken','error');
throw $exception;
}
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services;
use App\Repositories\Contracts\RhawnRawRepository;
use App\Repositories\Enums\ResponseCodeEnum;
use App\Support\Facades\SimpleLogs;
use Illuminate\Support\Facades\DB;
class RhawnChemicalsService
{
public $rhawnRawRepository = null;
public function __construct(RhawnRawRepository $rhawnRawRepository)
{
$this->rhawnRawRepository = $rhawnRawRepository;
}
/**
* @param int $offse
* @param int $limit
*/
public function getChemicalRawList($offset = 0, $limit = 100)
{
$rawList = $this->rhawnRawRepository->getRawProductList($limit, $offset);
return $rawList;
}
public function getChemicalPackage($rawIds)
{
$packageList = $this->rhawnRawRepository->getProductPackage($rawIds);
return $packageList;
}
public function getProductPackagesThroughGroupByPackUnit()
{
return $this->rhawnRawRepository->getProductPackagesThroughGroupByPackUnit();
}
public function getChemicalRawThroughtCode($rawCode)
{
return $this->rhawnRawRepository->getRawProductsThroughtCode($rawCode);
}
/**
* 保存震坤行同步商品数据
* @param $goods
*/
public function updateZhenkhGoods($goods)
{
try{
$dbConnect = DB::connection('rhawn_mysql');
$zkhGoods = [];
$zkhGoods['zg_sku'] = $goods['zkhSku'];
$zkhGoods['zg_r_sku'] = $goods['supplierSkuNo'];
if(isset($goods['addressList']['0'])){
$zkhGoods['zg_addr'] = implode(',',$goods['addressList']);
}
$zkhGoods['zg_unit'] = $goods['priceUnit'];
if($zkhGoods['zg_r_sku'] != ''){
$zkhGoodsResult = $dbConnect->table('products')
->where('p_code',$zkhGoods['zg_r_sku'])
->get()->toArray();
if($zkhGoodsResult){
$zkhGoodsResult = current($zkhGoodsResult);
$zkhGoods['zg_r_pid'] = $zkhGoodsResult->p_id;
$row = $dbConnect->table('zkh_goods')
->where('zg_r_sku',$zkhGoods['zg_r_sku'])
->where('zg_r_pid',$zkhGoods['zg_r_pid'])
->get()->toArray();
if(count($row) == 0){
$id = $dbConnect->table('zkh_goods')->insertGetId($zkhGoods);
SimpleLogs::writeLog('zkh_goods 新增 id : '.$id.' 成功.', 'sql insert');
$row = $dbConnect->table('zkh_goods')->where('zg_id',$id)->get()->toArray();
}
if($row){
return current($row);
}
}
}
return null;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),'updateZhenkhGoods ','error');
throw $exception;
}
}
public function updateSyncRunTime($zgId)
{
$dbConnect = DB::connection('rhawn_mysql');
return $dbConnect->table('zkh_goods')->where('zg_id',$zgId)->update(['zg_sync_time' => time()]);
}
public function getRawProductsThroughPid($pId)
{
try{
$dbConnect = DB::connection('rhawn_mysql');
$product = $dbConnect->table('products')
->where('p_id',$pId)
->get()->toArray();
if(count($product) > 0){
return current($product);
}
return null;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),'getRawProductsThroughPid ','error');
throw $exception;
}
}
/**
* @获取震坤行对应的商品sku
* @param $pCode
* @return array
*/
public function getZkhGoodsSku($pCode)
{
$dbConnect = DB::connection('rhawn_mysql');
$model = $dbConnect->table('zkh_goods');
if(is_array($pCode)){
$model->whereIn('zg_r_pid',$pCode);
}else{
$model->where('zg_r_pid',$pCode);
}
return $model->get()->toArray();
}
}
...@@ -13,12 +13,12 @@ namespace App\Services\ThirdPlatform; ...@@ -13,12 +13,12 @@ namespace App\Services\ThirdPlatform;
use App\Jobs\queue\QueueJob; use App\Jobs\queue\QueueJob;
use App\Repositories\Contracts\ThirdApiPlatformRepository; use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Services\BhProductsService;
use App\Services\Kafka\KafkaService; use App\Services\Kafka\KafkaService;
use App\Services\ThirdPlatform\Api\BideApiService; use App\Services\ThirdPlatform\Api\BideApiService;
use App\Services\ThirdPlatform\PlatformAbstractService; use App\Services\ThirdPlatform\PlatformAbstractService;
use App\Support\Facades\SimpleLogs; use App\Support\Facades\SimpleLogs;
use App\Support\Traits\Helpers; use App\Support\Traits\Helpers;
use Illuminate\Support\Facades\DB;
class BideService class BideService
{ {
...@@ -54,9 +54,111 @@ class BideService ...@@ -54,9 +54,111 @@ class BideService
return ; return ;
} }
try{ try{
$result = app(BhProductsService::class)->storeBideProducts($result); $result = $this->storeBideProducts($result);
}catch(\Exception $exception){ }catch(\Exception $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':batchUpdateApi', 'error'); SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':batchUpdateApi', 'error');
} }
} }
/**
* 保存bide平台的产品数据
*/
public function storeBideProducts($bideProducts)
{
if (!is_array($bideProducts) || empty($bideProducts)) {
return false;
}
try {
$id = 0;
$dbConnect = DB::connection('bh_mysql');
$dbConnect->beginTransaction();
$chemicalsRow = $dbConnect->table('chemicals')
->where('c_cas', $bideProducts[0]['CASNumber'])
->get()->toArray();
if (empty($chemicalsRow)) {
return false;
}
$chemicalsRow = current($chemicalsRow);
$dbConnect->table('products')
->where('c_id', $chemicalsRow->c_id)
->where('b_id', 10)
->update(['p_status' => 0, 'p_show' => 0, 'modifytime' => time()]);
foreach ($bideProducts as $product) {
if ($product['Weight'] > 0) {
$p_tod = '现货';
} else {
$p_tod = '无货,请咨询';
}
$p_code = $product['ProductNum'] . '-' . $product['PackSize'];
$productRow = $dbConnect->table('products')
->where('b_id', 10)
->where('c_id', $chemicalsRow->c_id)
->where('p_code', 'like', $p_code)
->get()->toArray();
$pro_data = [];
if (empty($productRow)) {
$pro_data['b_id'] = 10;
$pro_data['c_id'] = $chemicalsRow->c_id;
$pro_data['p_code'] = $p_code;
if (!$product['ProductCName']) {
$pro_data['p_cn_name'] = '';
} else {
$pro_data['p_cn_name'] = $product['ProductCName'];
}
if (!$product['ProductEName']) {
$pro_data['p_en_name'] = '';
} else {
$pro_data['p_en_name'] = $product['ProductEName'];
}
$pro_data['p_level'] = $product['Purity'];
$pro_data['p_pack'] = $product['PackSize'];
$pro_data['p_price'] = $product['PriceB'];
$pro_data['p_tod'] = $p_tod;
$pro_data['p_weight'] = '0.01';
$pro_data['p_status'] = 1;
$pro_data['p_show'] = 1;
$pro_data['prom_from'] = 0;
$pro_data['prom_to'] = 0;
$id = $dbConnect->table('products')->insertGetId($pro_data);
} else {
$productRow = current($productRow);
$pro_data['p_status'] = 1;
$pro_data['p_show'] = 1;
$pro_data['p_price'] = $product['PriceB'];
$pro_data['p_tod'] = $p_tod;
$pro_data['modifytime'] = time();
$dbConnect->table('products')
->where('p_id', $productRow->p_id)
->update($pro_data);
$id = $productRow->p_id;
}
}
$dbConnect->commit();
SimpleLogs::writeLog('Bide p_id : '.$id.' cas : '.$chemicalsRow->c_cas. ' 更新成功,更新时间:'.date('Y-m-d H:i:s',time()),__CLASS__.':storeBjsProducts');
return true;
}catch(\Exception $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':storeBjsProducts', 'error');
$dbConnect->rollback();
throw $exception;
}
}
} }
...@@ -12,12 +12,12 @@ ...@@ -12,12 +12,12 @@
namespace App\Services\ThirdPlatform; namespace App\Services\ThirdPlatform;
use App\Repositories\Contracts\ThirdApiPlatformRepository; use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Services\BhProductsService;
use App\Services\Kafka\KafkaService; use App\Services\Kafka\KafkaService;
use App\Services\ThirdPlatform\Api\BjsApiService; use App\Services\ThirdPlatform\Api\BjsApiService;
use App\Services\ThirdPlatform\PlatformAbstractService; use App\Services\ThirdPlatform\PlatformAbstractService;
use App\Support\Facades\SimpleLogs; use App\Support\Facades\SimpleLogs;
use App\Support\Traits\Helpers; use App\Support\Traits\Helpers;
use Illuminate\Support\Facades\DB;
class BjsService class BjsService
{ {
...@@ -53,9 +53,112 @@ class BjsService ...@@ -53,9 +53,112 @@ class BjsService
return ; return ;
} }
try{ try{
$result = app(BhProductsService::class)->storeBjsProducts($result); $result = $this->storeBjsProducts($result);
}catch(\Exception $exception){ }catch(\Exception $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':batchUpdateApi', 'error'); SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':batchUpdateApi', 'error');
} }
} }
/**
* 保存bjs平台的产品数据
*/
public function storeBjsProducts($bideProducts)
{
if (!is_array($bideProducts) || empty($bideProducts)) {
return false;
}
try {
$id = 0;
$dbConnect = DB::connection('bh_mysql');
$dbConnect->beginTransaction();
$chemicalsRow = $dbConnect->table('chemicals')
->where('c_cas', $bideProducts[0]['CASNumber'])
->get()->toArray();
if (empty($chemicalsRow)) {
return false;
}
$chemicalsRow = current($chemicalsRow);
$dbConnect->table('products')
->where('c_id', $chemicalsRow->c_id)
->where('b_id', 175)
->update(['p_status' => 0, 'p_show' => 0, 'modifytime' => time()]);
foreach ($bideProducts as $product) {
if ($product['Weight'] > 0) {
$p_tod = '现货';
} else {
$p_tod = '无货,请咨询';
}
$p_code = $product['ProductNum'] . '-' . $product['PackSize'];
$productRow = $dbConnect->table('products')
->where('b_id', 175)
->where('c_id', $chemicalsRow->c_id)
->where('p_code', 'like', $p_code)
->get()->toArray();
$pro_data = [];
if (empty($productRow)) {
$pro_data['b_id'] = 175;
$pro_data['c_id'] = $chemicalsRow->c_id;
$pro_data['p_code'] = $p_code;
if (!$product['ProductCName']) {
$pro_data['p_cn_name'] = '';
} else {
$pro_data['p_cn_name'] = $product['ProductCName'];
}
if (!$product['ProductEName']) {
$pro_data['p_en_name'] = '';
} else {
$pro_data['p_en_name'] = $product['ProductEName'];
}
$pro_data['p_level'] = $product['Purity'];
$pro_data['p_pack'] = $product['PackSize'];
$pro_data['p_price'] = $product['Price'];
$pro_data['p_tod'] = $p_tod;
$pro_data['p_weight'] = '0.01';
$pro_data['p_status'] = 1;
$pro_data['p_show'] = 0;
$pro_data['prom_from'] = 0;
$pro_data['prom_to'] = 0;
$id = $dbConnect->table('products')->insertGetId($pro_data);
} else {
$productRow = current($productRow);
$pro_data['p_status'] = 1;
$pro_data['p_show'] = 0;
$pro_data['p_price'] = $product['Price'];
$pro_data['p_tod'] = $p_tod;
$pro_data['modifytime'] = time();
$dbConnect->table('products')
->where('p_id', $productRow->p_id)
->update($pro_data);
$id = $productRow->p_id;
}
}
$dbConnect->commit();
SimpleLogs::writeLog('Bjs p_id : '.$id.' cas : '.$chemicalsRow->c_cas. ' 更新成功,更新时间:'.date('Y-m-d H:i:s',time()),__CLASS__.':storeBjsProducts');
return true;
}catch(\Exception $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':storeBjsProducts', 'error');
$dbConnect->rollback();
throw $exception;
}
}
} }
...@@ -4,8 +4,8 @@ ...@@ -4,8 +4,8 @@
namespace App\Services\ThirdPlatform; namespace App\Services\ThirdPlatform;
use App\Repositories\Contracts\ThirdApiPlatformRepository; use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Rhawn\Services\RhawnProductService;
use App\Services\Kafka\KafkaService; use App\Services\Kafka\KafkaService;
use App\Services\RhawnChemicalsService;
use App\Services\ThirdPlatform\Api\IntegleApiService; use App\Services\ThirdPlatform\Api\IntegleApiService;
use App\Support\Facades\SimpleKafka; use App\Support\Facades\SimpleKafka;
use App\Support\Facades\SimpleLogs; use App\Support\Facades\SimpleLogs;
...@@ -25,7 +25,7 @@ class InteglePlatformService ...@@ -25,7 +25,7 @@ class InteglePlatformService
{ {
$status = $this->apiService->checkPlatformStatus(); $status = $this->apiService->checkPlatformStatus();
if($status){ if($status){
$rhawnChemicalsService = app(RhawnChemicalsService::class); $rhawnChemicalsService = app(RhawnProductService::class);
$limit = $this->apiService->getPlatformInfo('platform_params')['batchNums']; $limit = $this->apiService->getPlatformInfo('platform_params')['batchNums'];
$page = 0; $page = 0;
......
...@@ -15,16 +15,11 @@ use App\ImportExport\BaseExport; ...@@ -15,16 +15,11 @@ use App\ImportExport\BaseExport;
use App\ImportExport\WuxiLab\WuxiLabExport; use App\ImportExport\WuxiLab\WuxiLabExport;
use App\Repositories\Contracts\ThirdApiPlatformRepository; use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Repositories\Models\RhawnProducts; use App\Repositories\Models\RhawnProducts;
use App\Rhawn\Services\RhawnProductService;
use App\Services\Kafka\KafkaService; use App\Services\Kafka\KafkaService;
use App\Services\RhawnChemicalsService;
use App\Services\ThirdPlatform\Api\WuxiApiService; use App\Services\ThirdPlatform\Api\WuxiApiService;
use App\Services\ThirdPlatform\PlatformAbstractService;
use App\Support\Facades\SimpleKafka; use App\Support\Facades\SimpleKafka;
use App\Support\Facades\SimpleLogs; use App\Support\Facades\SimpleLogs;
use App\Support\Traits\Helpers;
use Illuminate\Filesystem\Filesystem;
use longlang\phpkafka\Protocol\ApiVersions\ApiVersionsResponse;
use function Symfony\Component\String\u;
class WuxiLabService class WuxiLabService
{ {
...@@ -32,7 +27,7 @@ class WuxiLabService ...@@ -32,7 +27,7 @@ class WuxiLabService
public function __construct() public function __construct()
{ {
$this->apiService = (new WuxiApiService(app(ThirdApiPlatformRepository::class))); $this->apiService = (new WuxiApiService(app(ThirdApiPlatformRepository::class)));
$this->rhawnChemicalsService = app(RhawnChemicalsService::class); $this->rhawnChemicalsService = app(RhawnProductService::class);
} }
public function initToken() public function initToken()
...@@ -175,8 +170,7 @@ class WuxiLabService ...@@ -175,8 +170,7 @@ class WuxiLabService
}*/ }*/
$packageList = $this->apiService->getPackageList($token); $packageList = $this->apiService->getPackageList($token);
$rhawnChemicalsService = app(RhawnChemicalsService::class); $packagesUnit = $this->rhawnChemicalsService->getProductPackagesThroughGroupByPackUnit();
$packagesUnit = $rhawnChemicalsService->getProductPackagesThroughGroupByPackUnit();
foreach($packagesUnit as $package){ foreach($packagesUnit as $package){
if(!empty($packageList)){ if(!empty($packageList)){
......
...@@ -2,18 +2,14 @@ ...@@ -2,18 +2,14 @@
namespace App\Services\ThirdPlatform; namespace App\Services\ThirdPlatform;
use App\Jobs\queue\QueueJob;
use App\Mailer\MailService; use App\Mailer\MailService;
use App\Mailer\MailTempl;
use App\Repositories\Contracts\ThirdApiPlatformRepository; use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Rhawn\Services\RhawnProductService;
use App\Services\Kafka\KafkaService; use App\Services\Kafka\KafkaService;
use App\Services\RhawnChemicalsService;
use App\Services\RhawnOrdersService;
use App\Services\ThirdPlatform\Api\ZhenkhApiService; use App\Services\ThirdPlatform\Api\ZhenkhApiService;
use App\Support\Facades\SimpleKafka; use App\Support\Facades\SimpleKafka;
use App\Support\Facades\SimpleLogs; use App\Support\Facades\SimpleLogs;
use App\Support\Traits\Helpers; use App\Support\Traits\Helpers;
use Illuminate\Support\Facades\Mail;
class ZhenKhService class ZhenKhService
{ {
...@@ -22,22 +18,11 @@ class ZhenKhService ...@@ -22,22 +18,11 @@ class ZhenKhService
public function __construct() public function __construct()
{ {
$this->apiService = (new ZhenkhApiService(app(ThirdApiPlatformRepository::class))); $this->apiService = (new ZhenkhApiService(app(ThirdApiPlatformRepository::class)));
$this->rhawnService = app(RhawnChemicalsService::class); $this->rhawnService = app(RhawnProductService::class);
$this->rhawnOrderService = app(RhawnOrdersService::class); $this->zhenKhOrderService = app(\App\Rhawn\Services\ZhenkhService::class);
$this->mailService = app(MailService::class); $this->mailService = app(MailService::class);
} }
public function orderNoRollBack()
{
$page = 1;
$limit = 10000;
while(true){
$result = $this->rhawnOrderService->rollBackOrderNo($page * $limit, $limit);
if(!$result) break;
$page ++;
}
}
public function createJwtToken() public function createJwtToken()
{ {
$token = $this->apiService->getPlatformInfo('platform_token'); $token = $this->apiService->getPlatformInfo('platform_token');
...@@ -261,7 +246,7 @@ class ZhenKhService ...@@ -261,7 +246,7 @@ class ZhenKhService
break; break;
} }
} }
$result = $this->rhawnOrderService->updateZhenkhOrders($order,$orderDetail); $result = $this->zhenKhOrderService->updateZhenkhOrders($order,$orderDetail);
} }
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
...@@ -309,7 +294,7 @@ class ZhenKhService ...@@ -309,7 +294,7 @@ class ZhenKhService
} }
} }
if($orderDetail){ if($orderDetail){
$result = $this->rhawnOrderService->updateZhenkhOrders($order,$orderDetail); $result = $this->zhenKhOrderService->updateZhenkhOrders($order,$orderDetail);
} }
} }
} }
...@@ -339,7 +324,7 @@ class ZhenKhService ...@@ -339,7 +324,7 @@ class ZhenKhService
public function sendDeliveryOrder($deliveryCode) public function sendDeliveryOrder($deliveryCode)
{ {
try{ try{
$orderDelivery = $this->rhawnOrderService->getSorderDeliveryDetail($deliveryCode); $orderDelivery = $this->zhenKhOrderService->getSorderDeliveryDetail($deliveryCode);
$noMatchGoods = []; $noMatchGoods = [];
if($orderDelivery){ if($orderDelivery){
$expressArray = $this->apiService->getPlatformDataEntries('zkh_order_express','data_values'); $expressArray = $this->apiService->getPlatformDataEntries('zkh_order_express','data_values');
...@@ -485,7 +470,7 @@ class ZhenKhService ...@@ -485,7 +470,7 @@ class ZhenKhService
public function orderConfirm($orderNo) public function orderConfirm($orderNo)
{ {
try{ try{
$orderDetail = $this->rhawnOrderService->getSorderDetail($orderNo); $orderDetail = $this->zhenKhOrderService->getSorderDetail($orderNo);
if($orderDetail){ if($orderDetail){
while(true){ while(true){
$result = $this->apiService->orderConfirm(current($orderDetail)['so_cus_po'], $this->getToken()); $result = $this->apiService->orderConfirm(current($orderDetail)['so_cus_po'], $this->getToken());
......
...@@ -80,8 +80,12 @@ $app->configure('repository'); ...@@ -80,8 +80,12 @@ $app->configure('repository');
$app->configure('enum'); $app->configure('enum');
$app->configure('response'); $app->configure('response');
#swagger api文档
$app->configure('swagger-lume');
$app->alias('cache', \Illuminate\Cache\CacheManager::class); $app->alias('cache', \Illuminate\Cache\CacheManager::class);
// 发送邮件相关配置
$app->configure('mail'); $app->configure('mail');
$app->alias('mailer', Illuminate\Mail\Mailer::class); $app->alias('mailer', Illuminate\Mail\Mailer::class);
$app->alias('mailer', Illuminate\Contracts\Mail\Mailer::class); $app->alias('mailer', Illuminate\Contracts\Mail\Mailer::class);
...@@ -95,7 +99,7 @@ $app->alias('mailer', Illuminate\Contracts\Mail\MailQueue::class); ...@@ -95,7 +99,7 @@ $app->alias('mailer', Illuminate\Contracts\Mail\MailQueue::class);
| Next, we will register the middleware with the application. These can | Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a | be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes. | route or middleware that'll be assigned to some specific routes.
|
*/ */
$app->middleware([ $app->middleware([
...@@ -105,6 +109,7 @@ $app->middleware([ ...@@ -105,6 +109,7 @@ $app->middleware([
$app->routeMiddleware([ $app->routeMiddleware([
'apiAuth' => App\Http\Controllers\Middleware\Authenticate::class, 'apiAuth' => App\Http\Controllers\Middleware\Authenticate::class,
'throttle' => App\Http\Controllers\Middleware\RateLimits::class
//'syslog' => App\Http\Controllers\Middleware\SysLog::class, //'syslog' => App\Http\Controllers\Middleware\SysLog::class,
//'enum' => \Jiannei\Enum\Laravel\Http\Middleware\TransformEnums::class, //'enum' => \Jiannei\Enum\Laravel\Http\Middleware\TransformEnums::class,
//'throttle' => \Jiannei\Response\Laravel\Http\Middleware\ThrottleRequests::class, //'throttle' => \Jiannei\Response\Laravel\Http\Middleware\ThrottleRequests::class,
...@@ -126,6 +131,7 @@ $app->routeMiddleware([ ...@@ -126,6 +131,7 @@ $app->routeMiddleware([
*/ */
$app->register(App\Providers\AppServiceProvider::class); $app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\RepositoryServiceProvider::class); $app->register(App\Providers\RepositoryServiceProvider::class);
$app->register(App\Rhawn\Providers\RhawnRepositoryServiceProvider::class);
//$app->register(App\Providers\KafkaServiceProvider::class); //$app->register(App\Providers\KafkaServiceProvider::class);
//$app->register(App\Providers\ListenersEventServiceProvider::class); //$app->register(App\Providers\ListenersEventServiceProvider::class);
//$app->register(App\Providers\EventServiceProvider::class); //$app->register(App\Providers\EventServiceProvider::class);
...@@ -134,7 +140,7 @@ $app->register(App\Providers\RepositoryServiceProvider::class); ...@@ -134,7 +140,7 @@ $app->register(App\Providers\RepositoryServiceProvider::class);
* Package Service Providers... * Package Service Providers...
*/ */
$app->register(\Tymon\JWTAuth\Providers\LumenServiceProvider::class); $app->register(\Tymon\JWTAuth\Providers\LumenServiceProvider::class);
$app->register(\Illuminate\Redis\RedisServiceProvider::class); //$app->register(\Illuminate\Redis\RedisServiceProvider::class);
//$app->register(\Spatie\Permission\PermissionServiceProvider::class); //$app->register(\Spatie\Permission\PermissionServiceProvider::class);
$app->register(Dingo\Api\Provider\LumenServiceProvider::class); $app->register(Dingo\Api\Provider\LumenServiceProvider::class);
...@@ -147,6 +153,8 @@ $app->register(Spatie\CronlessSchedule\CronlessScheduleServiceProvider::class); ...@@ -147,6 +153,8 @@ $app->register(Spatie\CronlessSchedule\CronlessScheduleServiceProvider::class);
$app->register(Illuminate\Mail\MailServiceProvider::class); $app->register(Illuminate\Mail\MailServiceProvider::class);
$app->register(\SwaggerLume\ServiceProvider::class);
/*ext /*ext
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Load The Application Routes | Load The Application Routes
......
...@@ -8,3 +8,4 @@ ...@@ -8,3 +8,4 @@
$api = app('Dingo\Api\Routing\Router'); $api = app('Dingo\Api\Routing\Router');
require __DIR__.'/../routes/api/zhenkunhang.php'; require __DIR__.'/../routes/api/zhenkunhang.php';
require __DIR__.'/../routes/api/rhawn.php';
...@@ -8,8 +8,10 @@ ...@@ -8,8 +8,10 @@
"php": "^7.4|^8.0", "php": "^7.4|^8.0",
"ext-json": "*", "ext-json": "*",
"api-ecosystem-for-laravel/dingo-api": "^3.1", "api-ecosystem-for-laravel/dingo-api": "^3.1",
"darkaonline/swagger-lume": "8.*",
"fruitcake/laravel-cors": "^2.0", "fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.3", "guzzlehttp/guzzle": "^7.3",
"illuminate/mail": "^8.2",
"illuminate/redis": "^8.34", "illuminate/redis": "^8.34",
"jiannei/laravel-enum": "^3.0", "jiannei/laravel-enum": "^3.0",
"jiannei/laravel-response": "^4.0", "jiannei/laravel-response": "^4.0",
...@@ -22,7 +24,7 @@ ...@@ -22,7 +24,7 @@
"spatie/laravel-cronless-schedule": "^1.1", "spatie/laravel-cronless-schedule": "^1.1",
"spatie/laravel-permission": "^5.1", "spatie/laravel-permission": "^5.1",
"tymon/jwt-auth": "^1.0.2", "tymon/jwt-auth": "^1.0.2",
"illuminate/mail":"^8.2" "zircote/swagger-php": "3.*"
}, },
"require-dev": { "require-dev": {
"fzaninotto/faker": "^1.9.1", "fzaninotto/faker": "^1.9.1",
......
...@@ -186,7 +186,7 @@ return [ ...@@ -186,7 +186,7 @@ return [
*/ */
'throttling' => [ 'throttling' => [
'default' => \Dingo\Api\Http\RateLimit\Throttle\Route::class,
], ],
/* /*
......
<?php
return [
'api' => [
/*
|--------------------------------------------------------------------------
| Edit to set the api's title
|--------------------------------------------------------------------------
*/
'title' => '罗恩开放平台 API接口',
],
'routes' => [
/*
|--------------------------------------------------------------------------
| Route for accessing api documentation interface
|--------------------------------------------------------------------------
*/
'api' => '/api/documentation',
/*
|--------------------------------------------------------------------------
| Route for accessing parsed swagger annotations.
|--------------------------------------------------------------------------
*/
'docs' => '/docs',
/*
|--------------------------------------------------------------------------
| Route for Oauth2 authentication callback.
|--------------------------------------------------------------------------
*/
'oauth2_callback' => '/api/oauth2-callback',
/*
|--------------------------------------------------------------------------
| Route for serving assets
|--------------------------------------------------------------------------
*/
'assets' => '/swagger-ui-assets',
/*
|--------------------------------------------------------------------------
| Middleware allows to prevent unexpected access to API documentation
|--------------------------------------------------------------------------
*/
'middleware' => [
'api' => [],
'asset' => [],
'docs' => [],
'oauth2_callback' => [],
],
],
'paths' => [
/*
|--------------------------------------------------------------------------
| Absolute path to location where parsed swagger annotations will be stored
|--------------------------------------------------------------------------
*/
'docs' => storage_path('api-docs'),
/*
|--------------------------------------------------------------------------
| File name of the generated json documentation file
|--------------------------------------------------------------------------
*/
'docs_json' => 'api-docs.json',
/*
|--------------------------------------------------------------------------
| Absolute path to directory containing the swagger annotations are stored.
|--------------------------------------------------------------------------
*/
'annotations' => base_path('app'),
/*
|--------------------------------------------------------------------------
| Absolute path to directories that you would like to exclude from swagger generation
|--------------------------------------------------------------------------
*/
'excludes' => [],
/*
|--------------------------------------------------------------------------
| Edit to set the swagger scan base path
|--------------------------------------------------------------------------
*/
'base' => env('L5_SWAGGER_BASE_PATH', null),
/*
|--------------------------------------------------------------------------
| Absolute path to directory where to export views
|--------------------------------------------------------------------------
*/
'views' => base_path('resources/views/vendor/swagger-lume'),
],
/*
|--------------------------------------------------------------------------
| API security definitions. Will be generated into documentation file.
|--------------------------------------------------------------------------
*/
'security' => [
/*
|--------------------------------------------------------------------------
| Examples of Security definitions
|--------------------------------------------------------------------------
*/
/*
'api_key_security_example' => [ // Unique name of security
'type' => 'apiKey', // The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2".
'description' => 'A short description for security scheme',
'name' => 'api_key', // The name of the header or query parameter to be used.
'in' => 'header', // The location of the API key. Valid values are "query" or "header".
],
'oauth2_security_example' => [ // Unique name of security
'type' => 'oauth2', // The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2".
'description' => 'A short description for oauth2 security scheme.',
'flow' => 'implicit', // The flow used by the OAuth2 security scheme. Valid values are "implicit", "password", "application" or "accessCode".
'authorizationUrl' => 'http://example.com/auth', // The authorization URL to be used for (implicit/accessCode)
//'tokenUrl' => 'http://example.com/auth' // The authorization URL to be used for (password/application/accessCode)
'scopes' => [
'read:projects' => 'read your projects',
'write:projects' => 'modify projects in your account',
]
],*/
/* Open API 3.0 support
'passport' => [ // Unique name of security
'type' => 'oauth2', // The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2".
'description' => 'Laravel passport oauth2 security.',
'in' => 'header',
'scheme' => 'https',
'flows' => [
"password" => [
"authorizationUrl" => config('app.url') . '/oauth/authorize',
"tokenUrl" => config('app.url') . '/oauth/token',
"refreshUrl" => config('app.url') . '/token/refresh',
"scopes" => []
],
],
],
*/
/*
'bearer_token' => [
'type' => 'apiKey',
'description' => '用户token验证',
'in' => 'header',
'name' => 'authorization'
],
*/
],
/*
|--------------------------------------------------------------------------
| Turn this off to remove swagger generation on production
|--------------------------------------------------------------------------
*/
'generate_always' => env('SWAGGER_GENERATE_ALWAYS', false),
/*
|--------------------------------------------------------------------------
| Edit to set the swagger version number
|--------------------------------------------------------------------------
*/
'swagger_version' => env('SWAGGER_VERSION', '3.0'),
/*
|--------------------------------------------------------------------------
| Edit to trust the proxy's ip address - needed for AWS Load Balancer
|--------------------------------------------------------------------------
*/
'proxy' => false,
/*
|--------------------------------------------------------------------------
| Configs plugin allows to fetch external configs instead of passing them to SwaggerUIBundle.
| See more at: https://github.com/swagger-api/swagger-ui#configs-plugin
|--------------------------------------------------------------------------
*/
'additional_config_url' => null,
/*
|--------------------------------------------------------------------------
| Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically),
| 'method' (sort by HTTP method).
| Default is the order returned by the server unchanged.
|--------------------------------------------------------------------------
*/
'operations_sort' => env('L5_SWAGGER_OPERATIONS_SORT', null),
/*
|--------------------------------------------------------------------------
| Uncomment to pass the validatorUrl parameter to SwaggerUi init on the JS
| side. A null value here disables validation.
|--------------------------------------------------------------------------
*/
'validator_url' => null,
/*
|--------------------------------------------------------------------------
| Uncomment to add constants which can be used in anotations
|--------------------------------------------------------------------------
*/
'constants' => [
// 'SWAGGER_LUME_CONST_HOST' => env('SWAGGER_LUME_CONST_HOST', 'http://my-default-host.com'),
],
];
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCustomerPlatformInfoTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('customer_platform_info', function (Blueprint $table) {
$table->id();
$table->integer('cus_id')->nullable()->comment('客户id');
$table->string('cus_number')->comment('客户编号');
$table->string('company_name')->nullable()->comment('公司名称');
$table->string('token')->nullable()->comment('用户token');
$table->string('platform_params')->comment('平台参数');
$table->unsignedTinyInteger('status')->nullable()->comment('平台状态');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('customer_platform_info');
}
}
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$api->version('v1', function($api) {
//获取token
$api->group(['namespace'=>'App\Http\Controllers\V1\Auth','middleware' => ['throttle:60,1']], function($api) {
$api->post('/openapi/auth/getToken', ['uses'=>'CustomerAuthController@getToken']);
});
$api->group(['namespace'=>'App\Http\Controllers\V1\Rhawn','middleware' => ['throttle:60,1','apiAuth'], 'providers' => 'jwt'], function($api) {
// 获取订单列表
$api->post('/openapi/orders/getRhawnOrders', ['permission' => 'orders.getCustomerOrders', 'uses'=>'OrdersController@getCustomerOrders']);
// 获取订单详情
$api->post('/openapi/orders/getRhawnOrderDetail', ['permission' => 'orders.getCustomerOrders', 'uses'=>'OrdersController@getCustomerOrderDetail']);
// 新建订单
$api->post('/openapi/orders/createRhawnOrders', ['permission' => 'orders.createRhawnOrders', 'uses'=>'OrdersController@createCustomerNewOrder']);
// 取消订单
$api->post('/openapi/orders/cancelRhawnOrders', ['permission' => 'orders.cancelRhawnOrders', 'uses'=>'OrdersController@cancelCustomerOrder']);
$api->post('/openapi/orders/getOrdersDispatch', ['permission' => 'orders.getOrdersDispatch', 'uses'=>'OrdersController@getOrdersDispatch']);
});
$api->group(['namespace'=>'App\Http\Controllers\V1\Rhawn','middleware' => ['throttle:60,1','apiAuth'], 'providers' => 'jwt'], function($api) {
$api->post('/openapi/products/getAllProducts', ['permission' => 'orders.getProductList', 'uses'=>'ProductsController@getAllProductsList']);
$api->post('/openapi/products/getProductDetail', ['permission' => 'orders.getProductDetail', 'uses'=>'ProductsController@getProductDetail']);
$api->post('/openapi/products/getProductByCas', ['permission' => 'orders.getProductByCas', 'uses'=>'ProductsController@getProductByCas']);
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment