提交 52c02d62 authored 作者: qhz's avatar qhz

【开发】 xxl-job php 执行器

上级
流水线 #52472 已失败 于阶段
APP_NAME=skeleton
APP_ENV=dev
#开发阶段,请不要设置 scan_cacheable 为 true,它会导致 收集器缓存 存在时,不会再次扫描文件
scan_cacheable=false
# 进程数
APP_WORKER_NUM=1
# HTTP服务地址
SWOOLE_HTTP_HOST=0.0.0.0
# HTTP服务端口
SWOOLE_HTTP_PORT=9511
# ------------------- 日志配置 ---------------------------------------------------------------------
# 日志路径,不设置环境变量为 BASE_PATH . '/runtime/logs',生产环境建议设置为 其他目录
# LOG_BASE_PATH=/tmp/logs
# 日志级别,可选值为 DEBUG|INFO|NOTICE|WARNING|ERROR|CRITICAL|ALERT|EMERGENCY
LOG_LEVEL_DEFAULT=DEBUG
# 日志保存时间,日志按天分割,超过指定天数会被删除
LOG_MAX_FILES_DEFAULT=7
# 日志formatter,建议开发环境为line,生产环境为json,可选值为 Monolog\Formatter\JsonFormatter|Monolog\Formatter\LineFormatter
LOG_FORMATTER_CLASS=Monolog\Formatter\LineFormatter
LOG_FORMATTER_CLASS_DEFAULT=Monolog\Formatter\LineFormatter
LOG_FORMATTER_CLASS_SQL=Monolog\Formatter\LineFormatter
# stdout logger输出级别,如果要禁用其中一种或者几种,删除其中对应的级别即可
STDOUT_LOG_LEVEL=info,notice,warning,error,critical,alert,emergency
#---------------------------------启用定时任务start-----------------------------------------------------
CRONTAB_ENABLE=true
#---------------------------------定时任务end-----------------------------------------------------
#---------------------------------数据库start-----------------------------------------------------
DB_DRIVER=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=hyperf
DB_USERNAME=root
DB_PASSWORD=
DB_CHARSET=utf8mb4
DB_COLLATION=utf8mb4_unicode_ci
DB_PREFIX=
#品牌商
BRAND_DB_DRIVER=mysql
BRAND_DB_HOST=192.168.0.200
BRAND_DB_PORT=8306
BRAND_DB_DATABASE=ydd_brand_business
BRAND_DB_USERNAME=root
BRAND_DB_PASSWORD=gALC8Lmw3y
BRAND_DB_CHARSET=utf8mb4
BRAND_DB_COLLATION=utf8mb4_unicode_ci
BRAND_DB_PREFIX=ydd_
#---------------------------------防窜货数据库 start---------------------------------------------
DB_REIMBURSEMENT_DRIVER=mysql
DB_REIMBURSEMENT_HOST=192.168.0.200
DB_REIMBURSEMENT_DATABASE=ydd_reimbursement
DB_REIMBURSEMENT_PORT=8306
DB_REIMBURSEMENT_USERNAME=root
DB_REIMBURSEMENT_PASSWORD=gALC8Lmw3y
DB_REIMBURSEMENT_CHARSET=utf8mb4
DB_REIMBURSEMENT_COLLATION=utf8mb4_unicode_ci
DB_REIMBURSEMENT_PREFIX=ydd_
DB_REIMBURSEMENT_MAX_IDLE_TIME=60
#---------------------------------防窜货数据库 end-----------------------------------------------
#云店后台
CLOUD_DB_DRIVER=mysql
CLOUD_DB_HOST=192.168.0.200
CLOUD_DB_PORT=8306
CLOUD_DB_DATABASE=ydd_cloud_store
CLOUD_DB_USERNAME=root
CLOUD_DB_PASSWORD=gALC8Lmw3y
CLOUD_DB_CHARSET=utf8mb4
CLOUD_DB_COLLATION=utf8mb4_unicode_ci
CLOUD_DB_PREFIX=ydd_
# 营销
MARKETING_DB_DRIVER=mysql
MARKETING_DB_HOST=192.168.0.200
MARKETING_DB_PORT=8306
MARKETING_DB_DATABASE=ydd_marketing
MARKETING_DB_USERNAME=root
MARKETING_DB_PASSWORD=gALC8Lmw3y
MARKETING_DB_CHARSET=utf8mb4
MARKETING_DB_COLLATION=utf8mb4_unicode_ci
MARKETING_DB_PREFIX=ydd_
#消费者社区
DB_MEMBER_DRIVER=mysql
DB_MEMBER_HOST=192.168.0.200
DB_MEMBER_PORT=8306
DB_MEMBER_DATABASE=ydd_member
DB_MEMBER_USERNAME=root
DB_MEMBER_PASSWORD=gALC8Lmw3y
DB_MEMBER_CHARSET=utf8mb4
DB_MEMBER_COLLATION=utf8mb4_unicode_ci
DB_MEMBER_PREFIX=ydd_
#码库
CODE_DB_DRIVER=mysql
CODE_DB_HOST=192.168.0.200
CODE_DB_PORT=8306
CODE_DB_DATABASE=ydd_code
CODE_DB_USERNAME=root
CODE_DB_PASSWORD=gALC8Lmw3y
CODE_DB_CHARSET=utf8mb4
CODE_DB_COLLATION=utf8mb4_unicode_ci
CODE_DB_PREFIX=ydd_
#电商通
ECPASS_DB_DRIVER=mysql
ECPASS_DB_HOST=192.168.0.200
ECPASS_DB_PORT=8306
ECPASS_DB_DATABASE=ydd_ecpass
ECPASS_DB_USERNAME=root
ECPASS_DB_PASSWORD=gALC8Lmw3y
ECPASS_DB_CHARSET=utf8mb4
ECPASS_DB_COLLATION=utf8mb4_unicode_ci
ECPASS_DB_PREFIX=ydd_
#---------------------------------数据库end-----------------------------------------------------
REDIS_HOST=localhost
REDIS_AUTH=(null)
REDIS_PORT=6379
REDIS_DB=0
# ------------------- Guzzle配置 -------------------------------------------------------------------
GUZZLE_BRAND_BUSINESS_HOST = http://pps-api.test.2vm.co
# ------------------- Guzzle配置end ----------------------------------------------------------------
.buildpath
.settings/
.project
*.patch
.idea/
.git/
runtime/
vendor/
.phpintel/
.env
.DS_Store
.phpunit*
*.cache
composer.lock
.vscode/
\ No newline at end of file
stages:
- build
dev_build:
stage: build
script:
- ssh -tt -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${DEV_SSH_IP} "cd ${DEV_WEB_DIR} && pwd && git checkout . && git pull origin develop"
- ssh -tt -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${DEV_SSH_IP} "cd ${DEV_WEB_DIR} && pwd && docker exec -it ${DEV_PROJECT_NAME} sh -c 'supervisorctl stop all && supervisorctl start all'"
tags:
- dev-build
only:
- develop
uat_build:
stage: build
script:
- ssh -tt -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${UAT_SSH_IP} "cd ${UAT_WEB_DIR} && pwd && git checkout . && git pull origin uat"
- ssh -tt -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${UAT_SSH_IP} "echo ${UAT_PROJECT_NAME} && docker exec -it ${UAT_PROJECT_NAME} sh -c 'supervisorctl stop all && supervisorctl start all'"
tags:
- uat-build
only:
- uat
master_build:
stage: build
script:
- ssh -tt -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${MASTER_SSH_IP} "cd ${MASTER_WEB_DIR} && pwd && git checkout . && git pull origin master"
- ssh -tt -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${MASTER_SSH_IP} "cd ${YUNWEI_DIR} && pwd && ${ANSIBLE_COMMAND}"
tags:
- master-build
only:
- master
\ No newline at end of file
<?php
$header = <<<'EOF'
This file is part of Hyperf.
@link https://www.hyperf.io
@document https://hyperf.wiki
@contact group@hyperf.io
@license https://github.com/hyperf/hyperf/blob/master/LICENSE
EOF;
return (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setRules([
'@PSR2' => true,
'@Symfony' => true,
'@DoctrineAnnotation' => true,
'@PhpCsFixer' => true,
'header_comment' => [
'comment_type' => 'PHPDoc',
'header' => $header,
'separate' => 'none',
'location' => 'after_declare_strict',
],
'array_syntax' => [
'syntax' => 'short'
],
'list_syntax' => [
'syntax' => 'short'
],
'concat_space' => [
'spacing' => 'one'
],
'blank_line_before_statement' => [
'statements' => [
'declare',
],
],
'general_phpdoc_annotation_remove' => [
'annotations' => [
'author'
],
],
'ordered_imports' => [
'imports_order' => [
'class', 'function', 'const',
],
'sort_algorithm' => 'alpha',
],
'single_line_comment_style' => [
'comment_types' => [
],
],
'yoda_style' => [
'always_move_variable' => false,
'equal' => false,
'identical' => false,
],
'phpdoc_align' => [
'align' => 'left',
],
'multiline_whitespace_before_semicolons' => [
'strategy' => 'no_multi_line',
],
'constant_case' => [
'case' => 'lower',
],
'class_attributes_separation' => true,
'combine_consecutive_unsets' => true,
'declare_strict_types' => true,
'linebreak_after_opening_tag' => true,
'lowercase_static_reference' => true,
'no_useless_else' => true,
'no_unused_imports' => true,
'not_operator_with_successor_space' => true,
'not_operator_with_space' => false,
'ordered_class_elements' => true,
'php_unit_strict' => false,
'phpdoc_separation' => false,
'single_quote' => true,
'standardize_not_equals' => true,
'multiline_comment_opening_closing' => true,
])
->setFinder(
PhpCsFixer\Finder::create()
->exclude('public')
->exclude('runtime')
->exclude('vendor')
->in(__DIR__)
)
->setUsingCache(false);
<?php
namespace PHPSTORM_META {
// Reflect
override(\Psr\Container\ContainerInterface::get(0), map('@'));
override(\Hyperf\Utils\Context::get(0), map('@'));
override(\make(0), map('@'));
override(\di(0), map('@'));
}
\ No newline at end of file
# Default Dockerfile
#
# @link https://www.hyperf.io
# @document https://hyperf.wiki
# @contact group@hyperf.io
# @license https://github.com/hyperf/hyperf/blob/master/LICENSE
FROM hyperf/hyperf:8.0-alpine-v3.12-swoole
LABEL maintainer="Hyperf Developers <group@hyperf.io>" version="1.0" license="MIT" app.name="Hyperf"
##
# ---------- env settings ----------
##
# --build-arg timezone=Asia/Shanghai
ARG timezone
ENV TIMEZONE=${timezone:-"Asia/Shanghai"} \
APP_ENV=prod \
SCAN_CACHEABLE=(true)
# update
RUN set -ex \
# show php version and extensions
&& php -v \
&& php -m \
&& php --ri swoole \
# ---------- some config ----------
&& cd /etc/php8 \
# - config PHP
&& { \
echo "upload_max_filesize=128M"; \
echo "post_max_size=128M"; \
echo "memory_limit=1G"; \
echo "date.timezone=${TIMEZONE}"; \
} | tee conf.d/99_overrides.ini \
# - config timezone
&& ln -sf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime \
&& echo "${TIMEZONE}" > /etc/timezone \
# ---------- clear works ----------
&& rm -rf /var/cache/apk/* /tmp/* /usr/share/man \
&& echo -e "\033[42;37m Build Completed :).\033[0m\n"
WORKDIR /opt/www
# Composer Cache
# COPY ./composer.* /opt/www/
# RUN composer install --no-dev --no-scripts
COPY . /opt/www
RUN composer install --no-dev -o && php bin/hyperf.php
EXPOSE 9501
ENTRYPOINT ["php", "/opt/www/bin/hyperf.php", "start"]
# Introduction
此项目为 xxl-job 的 php 执行器部分
运行环境: PHP8+ , hyperf/xxl-job-incubator": "v0.1.3
xxl-job-incubator: 为 v0.1.3 可以保证 hypref 框架为: ~2.2
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Cache;
use Hyperf\Redis\RedisProxy;
use App\Constants\Cache\BaseAbstract;
use App\Constants\Cache\CacheDatabaseConstants;
class TreasureCache extends BaseAbstract
{
/**
* @var RedisProxy|\Redis
*/
protected $cache;
public function __construct()
{
$this->cache = get_cache_container( CacheDatabaseConstants::ACTIVITY );
}
/**
* 活动前缀
*
* @param $brand_id
* @param string $prefix
* @return string
*/
public static function getActPrefix( $brand_id, $prefix = 'act_tr' )
{
//正式使用redis集群 luaj脚本做限购必须所有key在同一个slot
if ( env( 'APP_ENV' ) == 'prod' ) $prefix = '{' . $prefix . '}';
return self::getPrefix( $brand_id ) . ":" . $prefix;
}
/**
* 获取拼团活动状态,存在则表示正常开启
* @param $brand_id
* @param $act_id
* @return bool
*/
public function isExitGroupStatusCache( $brand_id, $act_id )
{
$key = $this->getGroupStatusCacheKey( $brand_id, $act_id );
return $this->cache->exists( $key );
}
/**
* 拼团活动状态缓存key
*
* @param $brand_id
* @param $act_id
* @return string
*/
public static function getGroupStatusCacheKey( $brand_id, $act_id )
{
return self::getActPrefix( $brand_id ) . "_" . $act_id . '_status';
}
/**
* 活动信息 hash
*
* @param $brand_id
* @return string
*/
public static function getActInfoCacheKey( $brand_id )
{
return self::getActPrefix( $brand_id ) . "_info";
}
/**
* 获取拼团队伍的所有成员信息(uid => order_no )
* @param $brand_id
* @param $group_id
* @return array
*/
public function getGroupAll( $brand_id, $group_id )
{
$key = $this->getActGroupTemporaryDetailCacheKey( $brand_id, $group_id );
return $this->cache->hGetAll( $key );
}
/**
* 删除拼团队伍列表信息
* @param $brand_id
* @param $group_id
* @param $act_id
* @return bool
*/
public function delActTemporaryInfo( $brand_id, $group_id, $act_id )
{
$key = $this->getActGroupTemporaryCacheKey( $brand_id, $act_id );
return $this->cache->hDel( $key, $group_id );
}
/**
* 设置拼团队伍详情信息
* @param $brand_id
* @param $group_id
* @return bool
*/
public function delActTemporaryDetailInfo( $brand_id, $group_id )
{
$key = $this->getActGroupTemporaryDetailCacheKey( $brand_id, $group_id );
return $this->cache->del( $key );
}
/**
* 添加总成团数量
* @param $brand_id
* @param $actId
* @param int $num
* @return int
*/
public function addActGroupsCache( $brand_id, $actId, $num = 1 )
{
$key = $this->getActGroupsCacheKey( $brand_id, $actId );
return $this->cache->incrBy( $key, $num );
}
/**
* 活动被排除的门店key
*
* @param $brand_id
* @param $act_id
* @return string
*/
public static function getActNotStoreIdsCacheKey( $brand_id, $act_id )
{
return self::getActPrefix( $brand_id ) . "_" . $act_id . "_not_stores";
}
/**
* 活动总限购key
*
* @param $brand_id
* @param $actId
* @return string
*/
public static function getActGoodsLimitCacheKey( $brand_id, $actId )
{
return self::getActPrefix( $brand_id ) . "_" . $actId . "_lm";
}
/**
* 门店限购key
*
* @param $brand_id
* @param $act_id
* @return string
*/
public static function getStoreLimitCacheKey( $brand_id, $act_id )
{
return self::getActPrefix( $brand_id ) . "_" . $act_id . "_slm";
}
/**
* 用户限购key
*
* @param $brand_id
* @param $act_id
* @return string
*/
public static function getGoodsUserLimitCacheKey( $brand_id, $act_id )
{
return self::getActPrefix( $brand_id ) . "_" . $act_id . "_ulm";
}
/**
* 获取用户限购
* @param $brand_id
* @param $act_id
* @return bool|mixed|string
*/
public function getGoodsUserLimitCache( $brand_id, $act_id )
{
$key = self::getGoodsUserLimitCacheKey( $brand_id, $act_id );
$num = $this->cache->get( $key );
return $num ? $num : -1;
}
/**
* 获取总限购
*
* @param $brand_id
* @param $actId
* @return int
*/
public function getActGoodsLimitCache( $brand_id, $actId )
{
$key = self::getActGoodsLimitCacheKey( $brand_id, $actId );
return $this->cache->get( $key );
}
/**
* 获取门店限购
*
* @param $brand_id
* @param $act_id
* @param $store_id
* @return string
*/
public function getStoreLimitCache( $brand_id, $act_id, $store_id )
{
$hKey = self::getStoreLimitCacheKey( $brand_id, $act_id );
if ( $this->cache->hExists( $hKey, (string) $store_id ) ) {
return (int) $this->cache->hGet( $hKey, (string) $store_id );
}
return 0;
}
/**
* 设置活动信息缓存
*
* @param $brand_id
* @param $act_id
* @param $data
*/
public function setActInfoCache( $brand_id, $act_id, $data )
{
if ( !$data ) return;
$hKey = self::getActInfoCacheKey( $brand_id );
$this->cache->hSet( $hKey, (string) $act_id, json_encode( $data ) );
}
/**
* 设置总限购
* @param $brand_id
* @param $actId
* @param $limit
* @return bool
*/
public function setActGoodsLimitCache( $brand_id, $actId, $limit )
{
if ( $limit > 0 ) {
$key = self::getActGoodsLimitCacheKey( $brand_id, $actId );
return $this->cache->set( $key, $limit );
}
}
/**
* 获取活动缓存
*
* @param $brand_id
* @param $act_id
* @return array|mixed
*/
public function getActInfoCache( $brand_id, $act_id )
{
$hKey = self::getActInfoCacheKey( $brand_id );
$data = $this->cache->hGet( $hKey, (string) $act_id );
if ( $data ) return json_decode( $data, true );
return [];
}
/**
* 设置活动被排除的门店
*
* @param $brandId
* @param $actId
* @param $data
*/
public function setActNotStoreIdsCache( $brandId, $actId, $data )
{
$key = self::getActNotStoreIdsCacheKey( $brandId, $actId );
$this->cache->set( (string) $key, json_encode( $data ) );
}
/**
* 获取活动排除的门店
* @param $brandId
* @param $actId
* @return array|mixed
*/
public function getActNotStoreIdsCache( $brandId, $actId )
{
$key = self::getActNotStoreIdsCacheKey( $brandId, $actId );
$data = $this->cache->get( (string) $key );
if ( $data ) {
return json_decode( $data, true );
}
return [];
}
/**
* 删除活动缓存
* @param $brand_id
* @param $act_id
* @return int
*/
public function delCache($brand_id, $act_id)
{
//删除基本信息
$key1 = self::getActInfoCacheKey($brand_id);
//总限购
$key2 = self::getActGoodsLimitCacheKey($brand_id, $act_id);
//用户限购
$key3 = self::getGoodsUserLimitCacheKey($brand_id, $act_id);
//门店限购
$key4 = self::getStoreLimitCacheKey($brand_id, $act_id);
//活动状态
$key5 = $this->getStatusCacheKey( $brand_id, $act_id );
//指定门店
$key6 = self::getActStoreIdsCacheKey( $brand_id, $act_id );
//排除门店
$key7 = self::getActNotStoreIdsCacheKey( $brand_id, $act_id );
//指定经销商
$key8 = self::getActDealerIdsCacheKey( $brand_id, $act_id );
//排除经销商
$key9 = self::getActNotDealerIdsCacheKey( $brand_id, $act_id );
$this->cache->hDel($key1, $act_id);
$this->cache->del($key2, $key3, $key4, $key5, $key6, $key7, $key8, $key9);
}
/**
* 活动状态缓存key
*
* @param $brand_id
* @param $act_id
* @return string
*/
public static function getStatusCacheKey( $brand_id, $act_id )
{
return self::getActPrefix( $brand_id ) . "_" . $act_id . '_status';
}
/**
* 设置活动状态
* @param $brand_id
* @param $act_id
* @param $time
* @return bool
*/
public function setStatusCache( $brand_id, $act_id, $time )
{
$key = $this->getStatusCacheKey( $brand_id, $act_id );
return $this->cache->set( $key, $act_id, $time );
}
/**
* 获取活动状态,存在则表示正常开启
* @param $brand_id
* @param $act_id
* @return bool
*/
public function isExitStatusCache( $brand_id, $act_id )
{
$key = $this->getStatusCacheKey( $brand_id, $act_id );
return $this->cache->exists( $key );
}
/**
* 删除活动状态key,表示活动已结束或被禁用
* @param $brand_id
* @param $act_id
* @return bool
*/
public function delStatusCache( $brand_id, $act_id )
{
$key = $this->getStatusCacheKey( $brand_id, $act_id );
return $this->cache->del( $key );
}
/**
* 删除活动排除的门店
* @param $brand_id
* @param $act_id
* @return int
*/
public function delActNotStoreIdsCache( $brand_id, $act_id )
{
$key = $this->getActNotStoreIdsCacheKey( $brand_id, $act_id );
return $this->cache->del( $key );
}
/**
* 活动被指定的门店key
*
* @param $brand_id
* @param $act_id
* @return string
*/
public static function getActStoreIdsCacheKey( $brand_id, $act_id )
{
return self::getActPrefix( $brand_id ) . "_" . $act_id . "_stores";
}
/**
* 设置活动被指定的门店
*
* @param $brandId
* @param $actId
* @param $data
*/
public function setActStoreIdsCache( $brandId, $actId, $data )
{
$key = self::getActStoreIdsCacheKey( $brandId, $actId );
$this->cache->set( (string) $key, json_encode( $data ) );
}
/**
* 获取活动指定的门店
* @param $brandId
* @param $actId
* @return array|mixed
*/
public function getActStoreIdsCache( $brandId, $actId )
{
$key = self::getActStoreIdsCacheKey( $brandId, $actId );
$data = $this->cache->get( (string) $key );
if ( $data ) {
return json_decode( $data, true );
}
return [];
}
/**
* 删除活动指定的门店
* @param $brand_id
* @param $act_id
* @return int
*/
public function delActStoreIdsCache( $brand_id, $act_id )
{
$key = $this->getActStoreIdsCacheKey( $brand_id, $act_id );
return $this->cache->del( $key );
}
/**
* 活动被指定的经销商key
*
* @param $brand_id
* @param $act_id
* @return string
*/
public static function getActDealerIdsCacheKey( $brand_id, $act_id )
{
return self::getActPrefix( $brand_id ) . "_" . $act_id . "_dealers";
}
/**
* 设置活动被指定的经销商
*
* @param $brandId
* @param $actId
* @param $data
*/
public function setActDealerIdsCache( $brandId, $actId, $data )
{
$key = self::getActDealerIdsCacheKey( $brandId, $actId );
$this->cache->set( (string) $key, json_encode( $data ) );
}
/**
* 获取活动指定的经销商
* @param $brandId
* @param $actId
* @return array|mixed
*/
public function getActDealerIdsCache( $brandId, $actId )
{
$key = self::getActDealerIdsCacheKey( $brandId, $actId );
$data = $this->cache->get( (string) $key );
if ( $data ) {
return json_decode( $data, true );
}
return [];
}
/**
* 删除活动指定的经销商
* @param $brand_id
* @param $act_id
* @return int
*/
public function delActDealerIdsCache( $brand_id, $act_id )
{
$key = $this->getActDealerIdsCacheKey( $brand_id, $act_id );
return $this->cache->del( $key );
}
/**
* 活动被排除的经销商key
*
* @param $brand_id
* @param $act_id
* @return string
*/
public static function getActNotDealerIdsCacheKey( $brand_id, $act_id )
{
return self::getActPrefix( $brand_id ) . "_" . $act_id . "_not_dealers";
}
/**
* 设置活动被排除的经销商
*
* @param $brandId
* @param $actId
* @param $data
*/
public function setActNotDealerIdsCache( $brandId, $actId, $data )
{
$key = self::getActNotDealerIdsCacheKey( $brandId, $actId );
$this->cache->set( (string) $key, json_encode( $data ) );
}
/**
* 获取活动排除的经销商
* @param $brandId
* @param $actId
* @return array|mixed
*/
public function getActNotDealerIdsCache( $brandId, $actId )
{
$key = self::getActNotDealerIdsCacheKey( $brandId, $actId );
$data = $this->cache->get( (string) $key );
if ( $data ) {
return json_decode( $data, true );
}
return [];
}
/**
* 删除活动排除的经销商
* @param $brand_id
* @param $act_id
* @return int
*/
public function delActNotDealerIdsCache( $brand_id, $act_id )
{
$key = $this->getActNotDealerIdsCacheKey( $brand_id, $act_id );
return $this->cache->del( $key );
}
public function setActListCache( $brand_id, $ids, $timeout = 180 )
{
$key = self::getActPrefix( $brand_id ) . "_ls";
if ( !$timeout ) {
return $this->cache->set( $key, json_encode( $ids ) );
} else {
return $this->cache->set( $key, json_encode( $ids ), $timeout );
}
}
public function getActListCache( $brand_id )
{
$key = self::getActPrefix( $brand_id ) . "_ls";
$data = $this->cache->get( $key );
return $data ? json_decode( $data, true ) : [];
}
/**
* 获取所有拼团列表信息
* @param $brand_id
* @param $act_id
* @return array
*/
public function getAllTemporaryInfo( $brand_id, $act_id )
{
$key = $this->getActGroupTemporaryCacheKey( $brand_id, $act_id );
return $this->cache->hGetAll( $key );
}
/**
* 团购列表信息
* @param $brand_id
* @param $act_id
* @return string
*/
public function getActGroupTemporaryCacheKey( $brand_id, $act_id )
{
return self::getActPrefix( $brand_id ) . "_" . $act_id . '_temporary';
}
/**
* 获取参与拼团的所有用户
* @param $brand_id
* @param $group_id
* @return array
*/
public function getGroupTeamUid( $brand_id, $group_id )
{
$key = $this->getActGroupTemporaryDetailCacheKey( $brand_id, $group_id );
return $this->cache->hKeys( $key );
}
/**
* 团购列表详情信息
* @param $brand_id
* @param $group_id
* @return string
*/
public function getActGroupTemporaryDetailCacheKey( $brand_id, $group_id )
{
return self::getActPrefix( $brand_id ) . "_" . $group_id . '_temporary_detail';
}
/**
* 获取拼团的有效时间
* @param $brand_id
* @param $group_id
* @param $act_id
* @return bool
*/
public function getGroupTeamTime( $brand_id, $group_id, $act_id )
{
$key = $this->getActGroupTemporaryCacheKey( $brand_id, $act_id );
return $this->cache->hGet( $key, $group_id );
}
/**
* 判断拼团队是否还存在
* @param $brand_id
* @param $group_id
* @param $act_id
* @return bool
*/
public function groupIsExit( $brand_id, $group_id, $act_id )
{
$key = $this->getActGroupTemporaryCacheKey( $brand_id, $act_id );
return $this->cache->hExists( $key, $group_id );
}
/**
* 添加销售额
* @param $brand_id
* @param $act_id
* @param $num
* @return int
*/
public function incActSales( $brand_id, $act_id, $num )
{
$key = self::getActSalesCacheKey( $brand_id, $act_id );
return $this->cache->incrBy( $key, (int) $num );
}
/**
* 销售额key
*
* @param $brand_id
* @param $actId
* @return string
*/
public static function getActSalesCacheKey( $brand_id, $actId )
{
return self::getActPrefix( $brand_id ) . "_" . $actId . "_sales";
}
/**
* 设置拼团列表信息
* @param $brand_id
* @param $group_id
* @param $act_id
* @param $expirationDate
* @return bool
*/
public function setActTemporaryInfo( $brand_id, $group_id, $act_id, $expirationDate )
{
$key = $this->getActGroupTemporaryCacheKey( $brand_id, $act_id );
return $this->cache->hSet( $key, $group_id, time() + $expirationDate * 60 );
}
/**
* 设置拼团队伍详情信息
* @param $brand_id
* @param $group_id
* @param $uid
* @param $orderNo
* @return bool
*/
public function setActTemporaryDetailInfo( $brand_id, $group_id, $uid, $orderNo )
{
$key = $this->getActGroupTemporaryDetailCacheKey( $brand_id, $group_id );
return $this->cache->hSet( $key, $uid, $orderNo );
}
/**
* 获取拼团队伍人数
* @param $brand_id
* @param $group_id
* @return bool|int
*/
public function getNumber4GroupMembers( $brand_id, $group_id )
{
$key = $this->getActGroupTemporaryDetailCacheKey( $brand_id, $group_id );
return $this->cache->hLen( $key );
}
/**
* 判断用户是否在团里
* @param $brand_id
* @param $group_id
* @param $uid
* @return bool
*/
public function memberIsExit( $brand_id, $group_id, $uid )
{
$key = $this->getActGroupTemporaryDetailCacheKey( $brand_id, $group_id );
return $this->cache->hExists( $key, $uid );
}
/**
* 获取总成团数量
* @param $brand_id
* @param $actId
* @return int
*/
public function getActGroupsCache( $brand_id, $actId )
{
$key = $this->getActGroupsCacheKey( $brand_id, $actId );
$num = $this->cache->get( $key );
return $num ? $num : 0;
}
/**
* 总成团数缓存key
* @param $brand_id
* @param $act_id
* @return string
*/
public function getActGroupsCacheKey( $brand_id, $act_id )
{
return self::getActPrefix( $brand_id ) . "_" . $act_id . '_groups';
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Carbon\Carbon;
use App\Model\Marketing\Scan;
use App\Task\ScanStatisticsTask;
use App\Task\ScanAwardStatisticsTask;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Symfony\Component\Console\Input\InputOption;
/**
* @Command
*/
class ActivityStatistics extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
protected $signature = 'act:statistics {day? : day} {--brand_id= : brand_id}';
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct();
}
public function configure()
{
parent::configure();
$this->setDescription('活动统计');
}
public function handle()
{
$day = $this->input->getArgument('day');
$ScanStatisticsTask = make(ScanStatisticsTask::class);
$ScanAwardStatisticsTask = make(ScanAwardStatisticsTask::class);
// 品牌商
$brand_id = $this->input->getOption('brand_id');
if (!empty($brand_id)) {
$ScanStatisticsTask->setBrandId($brand_id);
$ScanAwardStatisticsTask->setBrandId($brand_id);
}
if( empty($day) ) {
$day = Carbon::yesterday('Asia/shanghai')->toDateString();
}
if( $day != 'all' ) {
$ScanStatisticsTask->setDateTime($day);
$ScanAwardStatisticsTask->setDateTime($day);
$this->line('活动扫码统计:' . $day, 'info');
$ScanStatisticsTask->execute();
$this->line('活动参与统计:' . $day, 'info');
$ScanAwardStatisticsTask->execute();
}
// 全数据更新
if( $day == 'all' ) {
if ( $brand_id ) {
$created_time = Scan::where('brand_id',$brand_id)->value('created_time');
} else {
$created_time = Scan::value('created_time');
}
$today = Carbon::today('Asia/shanghai')->toDateString();
$day = Carbon::parse($created_time)->toDateString();
do {
$ScanStatisticsTask->setDateTime($day);
$ScanAwardStatisticsTask->setDateTime($day);
$this->line('活动扫码统计:' . $day, 'info');
$ScanStatisticsTask->execute();
$this->line('活动参与统计:' . $day, 'info');
$ScanAwardStatisticsTask->execute();
# code...
$day = Carbon::parse($day)->addDay()->toDateString();
} while ($day < $today);
}
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use App\Task\ScanTotalStatisticsTask;
use Carbon\Carbon;
use App\Model\Marketing\Scan;
use App\Task\ScanStatisticsTask;
use App\Task\ScanAwardStatisticsTask;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Symfony\Component\Console\Input\InputOption;
/**
* @Command
*/
class AllActivityStatistics extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
protected $signature = 'act:all_statistics {day? : day} {--brand_id= : brand_id}';
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct();
}
public function configure()
{
parent::configure();
$this->setDescription('活动统计');
}
public function handle()
{
$day = $this->input->getArgument('day');
$ScanTotalStatisticsTask = make(ScanTotalStatisticsTask::class);
// 品牌商
$brand_id = $this->input->getOption('brand_id');
if (!empty($brand_id)) {
$ScanTotalStatisticsTask->setBrandId($brand_id);
}
if( empty($day) ) {
$day = Carbon::yesterday('Asia/shanghai')->toDateString();
}
if( $day != 'all' ) {
$ScanTotalStatisticsTask->setDateTime($day);
$this->line('活动扫码总统计:' . $day, 'info');
$ScanTotalStatisticsTask->execute();
}
// 全数据更新
if( $day == 'all' ) {
if ( $brand_id ) {
$created_time = Scan::where('brand_id',$brand_id)->value('created_time');
} else {
$created_time = Scan::value('created_time');
}
$today = Carbon::today('Asia/shanghai')->toDateString();
$day = Carbon::parse($created_time)->toDateString();
do {
$ScanTotalStatisticsTask->setDateTime($day);
$this->line('活动扫码总统计:' . $day, 'info');
$ScanTotalStatisticsTask->execute();
# code...
$day = Carbon::parse($day)->addDay()->toDateString();
} while ($day < $today);
}
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Carbon\Carbon;
use App\Task\BrandConsumeTask;
use Hyperf\Command\Annotation\Command;
use App\Model\Brand\BrandSmallBillModel;
use Hyperf\Command\Command as HyperfCommand;
use Symfony\Component\Console\Input\InputArgument;
/**
* @Command
*/
class BrandConsumeCommand extends HyperfCommand
{
protected $name = 'run:BrandConsume';
public function configure()
{
parent::configure();
$this->setDescription('品牌商小额消费记录信息维护');
}
protected function getArguments()
{
return [
['day', InputArgument::OPTIONAL, '日期']
];
}
public function handle()
{
$day = $this->input->getArgument('day');
$BrandConsumeTask = (new BrandConsumeTask);
if ( $day == 'all' ) {
$days = BrandSmallBillModel::groupBy('day')->pluck('day')->toArray();
foreach ($days as $day) {
$this->line('统计账单'. $day );
$BrandConsumeTask->setDateTime($day)->execute();
}
} else if ( ! $day ) {
$day = Carbon::yesterday('Asia/shanghai')->toDateString();
$BrandConsumeTask->setDateTime($day)->execute();
$this->line('已执行!');
}
}
}
<?php
declare( strict_types=1 );
namespace App\Command;
use App\Model\Brand\PointSet;
use App\Repository\Member\MemberPointRepository;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Symfony\Component\Console\Input\InputArgument;
/**
* @Command
*/
class ClearMemberPointCommand extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct( ContainerInterface $container )
{
$this->container = $container;
parent::__construct( 'clear:memberPoint' );
}
public function configure()
{
parent::configure();
$this->addUsage( 'clear:memberPoint' );
$this->setDescription( '会员积分清零' );
$this->addArgument( 'brand_id', InputArgument::OPTIONAL, '品牌商编号');
}
public function handle()
{
$brand_id = $this->input->getArgument('brand_id');
// 获取需要清理积分的品牌商
$query = PointSet::with('brand');
if($brand_id){
$query->where('brand_id',$brand_id);
}
$brands = $query->get();
// 过滤过期的品牌商
$time = time();
foreach ( $brands as $brand ) {
if ( $brand->brand->status == 1 && $brand->brand->signing_end_time > $time ) {
if($brand->point_is_clear == 2){
//清除所有积分(本定时任务是每年1月1日00:00:00 执行,清除的就是本年之前所有的积分)
$yester_year = date('Y-m-d H:i:s',strtotime(date('Y-01-01 00:00:00')));
}elseif($brand->point_is_clear == 1){
// 获取要清理的截取日期 当前 2023-01-01 00:00:00 获取 2022-01-01 00:00:00 积分保留一年
$yester_year = date('Y-m-d H:i:s',strtotime(date('Y-01-01 00:00:00',strtotime("-1 year"))));
}else{
continue;
}
MemberPointRepository::execSingleBrand( $brand->brand_id, $yester_year,$brand->point_is_clear );
}
}
$this->line('success' );
}
}
<?php
declare( strict_types=1 );
namespace App\Command;
use App\Task\CouponStatisticsTask;
use App\Model\Brand\CouponMemberLog;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Symfony\Component\Console\Input\InputArgument;
/**
* 直播活动订阅消息推送
*
* @Command
*/
class CouponStatisticsCommand extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* 命令
*
* @var string
*/
protected $name = "coupon:statistics";
public function configure()
{
parent::configure();
$this->setDescription('Coupon statistics');
$this->addUsage('Demo:coupon:statistics 2021-11-13');
$this->addArgument('date', InputArgument::OPTIONAL, 'Need to count which date(all: means all statistics)', 'all');
$this->addArgument('end_date', InputArgument::OPTIONAL, 'If it is a specified date range, this parameter must be passed,demo:2021-11-13');
}
public function handle()
{
$task = make(CouponStatisticsTask::class);
$date =$this->input->getArgument('date');
$end_date = $this->input->getArgument('end_date');
//date=all,统计全部数据
if($date == 'all'){
//前一天的时间戳
$yes_time = time() - 86400;
$begin_time = CouponMemberLog::query()->orderBy('create_time')->value('create_time');
$date = date('Y-m-d', $begin_time);
do {
$task->setTime($date)->execute();
$begin_time = $begin_time + 86400;
$date = date('Y-m-d', $begin_time);
} while ($begin_time < $yes_time);
}elseif($date && $end_date){
//指定时间范围
$begin_time = strtotime($date);
$end_time = strtotime($end_date);
do {
$task->setTime($date)->execute();
$begin_time = $begin_time + 86400;
$date = date('Y-m-d', $begin_time);
} while ($begin_time <= $end_time);
}else{
//指定日期
$begin_time = strtotime($date);
if($begin_time > time()){
$this->error('统计实际必须小于今天');
}
$task->setTime($date)->execute();
}
$this->info('success');
}
}
<?php
declare( strict_types=1 );
namespace App\Command;
use App\Model\Brand\PointSet;
use App\Repository\Member\MemberPointRepository;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Symfony\Component\Console\Input\InputArgument;
use App\Model\Brand\Product;
/**
* @Command
*/
class CreateProductInfo extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct( ContainerInterface $container )
{
$this->container = $container;
parent::__construct( 'CreateProductInfo' );
}
public function configure()
{
parent::configure();
$this->addUsage( 'CreateProductInfo' );
$this->setDescription( '数据构造' );
}
public function handle()
{
$allProduct = [
'1.MCS.MCS032' => 2,
'1.MCS.MCS036' => 6,
'1.MCS.MCS038' => 111,
'1.MCS.MCS047' => 4,
'1.MCS.MCS048' => 20,
'1.MCS.MCS050' => 62,
'1.MCS.MCS051' => 112,
'1.MCS.MCS053' => 1,
'1.MCS.MCS055' => 1,
'1.MCS.MCS077' => 6,
'1.MCS.MCS081' => 2,
'1.MCS.MCS091' => 3,
'1.MCS.MCS113' => 10,
'1.MCS.MCS127' => 2,
'1.MCS.MCS131' => 14,
'1.MCS.MCS132' => 102,
'1.MCS.MCS135' => 10,
'1.MCS.MCS141' => 2,
'1.MCS.MCS146' => 189,
'1.MCS.MCS155' => 10,
'1.MCS.MCS159' => 1,
'1.MCS.MCS001' => 360,
'1.MCS.MCS056' => 2,
'1.MCS.MCS511' => 6,
'1.MCS.MCS165' => 1,
'1.MCS.MCS166' => 1,
'1.MCS.MCS168' => 5,
];
$productList = Product::query()->where('brand_id', 10000534)->whereIn('product_sn', array_keys($allProduct))->select('id', 'product_sn', 'product_name')->get();
$insert = 'insert into ydd_reimbursement.ydd_fch_statistics_general_product_stock(brand_id, day, product_id, product_sn, warehouse_id, out_warehouse_num) values ';
foreach($productList as $product) {
$data = [
'brand_id' => 10000534,
'day' => 20250229,
'product_id' => $product->id,
'product_sn' => $product->product_sn,
'warehouse_id' => 1228,
'out_warehouse_num' => isset($allProduct[$product->product_sn]) ? $allProduct[$product->product_sn] : 0,
];
$insert .= "({$data['brand_id']}, {$data['day']}, {$data['product_id']}, '{$data['product_sn']}', {$data['warehouse_id']}, {$data['out_warehouse_num']}), \n";
}
echo $insert . "\n";
$this->line('success' );
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use App\Repository\Reimbursement\GeneralProductBatchStockStatisticsRepository;
use App\Model\Brand\Brand;
use Swoole\Coroutine as co;
/**
* @Command
*/
#[Command]
class GeneralProductBatchStockStatistics extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct('statistics:GeneralProductBatchStock');
}
public function configure()
{
parent::configure();
$this->setDescription('总部商品批次库存统计数据统计');
$this->addArgument('day', InputArgument::REQUIRED, '开始时间:');
$this->addArgument('end_day', InputArgument::REQUIRED, '结束时间');
$this->addArgument( 'brand_id', InputArgument::OPTIONAL, '品牌商编号' );
}
public function handle()
{
$repository = new GeneralProductBatchStockStatisticsRepository();
$this->line('脚本开始执行', 'info');
$brand_id = $this->input->getArgument( 'brand_id' );
$day = $this->input->getArgument('day');
$end_day = $this->input->getArgument('end_day');
$query = Brand::query()->where('status', 1)
->select('brand_no');
if ($brand_id){
$query->where('brand_no',$brand_id);
}
$query->chunkById(100, function($brand) use($repository, $day, $end_day){
foreach($brand as $v){
$this->warn($v['brand_no']. ' 开始执行');
if ($day && $end_day) {
$date = $day;
//指定时间范围
$beginTime = strtotime($day);
$endTime = strtotime($end_day);
do {
if ($date > 0) {
$this->warn(' ' . $v['brand_no']. ' ' .$date);
$repository
->setBrandId($v['brand_no'])
->setTime($date)
->entry();
}
$beginTime = $beginTime + 86400;
$date = date('Ymd', $beginTime);
co::sleep(0.1); // 延时 0.1 秒
} while ($beginTime <= $endTime);
} else {
$this->warn(' ' . $day);
$repository
->setBrandId($v['brand_no'])
->setTime($day)
->entry();
}
}
}, 'brand_no');
$this->info('success');
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use App\Repository\Reimbursement\GeneralProductStockStatisticsRepository;
use App\Model\Brand\Brand;
use Swoole\Coroutine as co;
/**
* @Command
*/
#[Command]
class GeneralProductStockStatistics extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct('statistics:GeneralProductStock');
}
public function configure()
{
parent::configure();
$this->setDescription('总部商品库存统计数据统计');
$this->addArgument('day', InputArgument::REQUIRED, '开始时间:');
$this->addArgument('end_day', InputArgument::REQUIRED, '结束时间');
$this->addArgument( 'brand_id', InputArgument::OPTIONAL, '品牌商编号' );
}
public function handle()
{
$repository = new GeneralProductStockStatisticsRepository();
$this->line('脚本开始执行', 'info');
$brand_id = $this->input->getArgument( 'brand_id' );
$day = $this->input->getArgument('day');
$end_day = $this->input->getArgument('end_day');
$query = Brand::query()->where('status', 1)
->select('brand_no');
if ($brand_id){
$query->where('brand_no',$brand_id);
}
$query->chunkById(100, function($brand) use($repository, $day, $end_day){
foreach($brand as $v){
$this->warn($v['brand_no']. ' 开始执行');
if ($day && $end_day) {
$date = $day;
//指定时间范围
$beginTime = strtotime($day);
$endTime = strtotime($end_day);
do {
if ($date > 0) {
$this->warn(' ' . $v['brand_no']. ' ' .$date);
$repository
->setBrandId($v['brand_no'])
->setTime($date)
->entry();
}
$beginTime = $beginTime + 86400;
$date = date('Ymd', $beginTime);
co::sleep(0.1); // 延时 0.1 秒
} while ($beginTime <= $endTime);
} else {
$this->warn(' ' . $day);
$repository
->setBrandId($v['brand_no'])
->setTime($day)
->entry();
}
}
}, 'brand_no');
$this->info('success');
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use App\Repository\Reimbursement\GeneralProductStockStatisticsYearRepository;
use App\Repository\Reimbursement\GeneralProductBatchStockStatisticsYearRepository;
use App\Repository\Reimbursement\GeneralProductWarehouseStockStatisticsYearRepository;
use App\Model\Brand\Brand;
use Swoole\Coroutine as co;
/**
* @Command
*/
#[Command]
class GeneralProductStockYearStatisticsSummary extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct('statistics:GeneralProductStockYearSummary');
}
public function configure()
{
parent::configure();
$this->setDescription('总部商品库存统计数据统计-年度汇总');
$this->addArgument('year', InputArgument::REQUIRED, '年份:');
$this->addArgument( 'brand_id', InputArgument::OPTIONAL, '品牌商编号' );
}
public function handle()
{
$repository1 = new GeneralProductStockStatisticsYearRepository();
$repository2 = new GeneralProductBatchStockStatisticsYearRepository();
$repository3 = new GeneralProductWarehouseStockStatisticsYearRepository();
$this->line('脚本开始执行', 'info');
$brand_id = $this->input->getArgument( 'brand_id' );
$year = $this->input->getArgument('year');
$query = Brand::query()->where('status', 1)
->select('brand_no');
if ($brand_id){
$query->where('brand_no',$brand_id);
}
$query->chunkById(100, function($brand) use($repository1, $repository2, $repository3, $year){
foreach($brand as $v){
$this->warn($v['brand_no']. ' 开始执行');
$repository1
->setBrandId($v['brand_no'])
->setTime($year)
->entry();
$repository2
->setBrandId($v['brand_no'])
->setTime($year)
->entry();
$repository3
->setBrandId($v['brand_no'])
->setTime($year)
->entry();
co::sleep(0.1); // 延时 0.1 秒
}
}, 'brand_no');
$this->info('success');
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use App\Repository\Reimbursement\GeneralProductWarehouseStockStatisticsRepository;
use App\Model\Brand\Brand;
use Swoole\Coroutine as co;
/**
* @Command
*/
#[Command]
class GeneralProductWarehouseStatistics extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct('statistics:GeneralProductWarehouseStatistics');
}
public function configure()
{
parent::configure();
$this->setDescription('总部商品仓库库存统计数据统计');
$this->addArgument('day', InputArgument::REQUIRED, '开始时间:');
$this->addArgument('end_day', InputArgument::REQUIRED, '结束时间');
$this->addArgument( 'brand_id', InputArgument::OPTIONAL, '品牌商编号' );
}
public function handle()
{
$repository = new GeneralProductWarehouseStockStatisticsRepository();
$this->line('脚本开始执行', 'info');
$brand_id = $this->input->getArgument( 'brand_id' );
$day = $this->input->getArgument('day');
$end_day = $this->input->getArgument('end_day');
$query = Brand::query()->where('status', 1)
->select('brand_no');
if ($brand_id){
$query->where('brand_no',$brand_id);
}
$query->chunkById(100, function($brand) use($repository, $day, $end_day){
foreach($brand as $v){
$this->warn($v['brand_no']. ' 开始执行');
if ($day && $end_day) {
$date = $day;
//指定时间范围
$beginTime = strtotime($day);
$endTime = strtotime($end_day);
do {
if ($date > 0) {
$this->warn(' ' . $v['brand_no']. ' ' .$date);
$repository
->setBrandId($v['brand_no'])
->setTime($date)
->entry();
}
$beginTime = $beginTime + 86400;
$date = date('Ymd', $beginTime);
co::sleep(0.1); // 延时 0.1 秒
} while ($beginTime <= $endTime);
} else {
$this->warn(' ' . $day);
$repository
->setBrandId($v['brand_no'])
->setTime($day)
->entry();
}
}
}, 'brand_no');
$this->info('success');
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Carbon\Carbon;
use App\Task\MemberVipExpireTask;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Symfony\Component\Console\Input\InputOption;
/**
* @Command
*/
class MemberVipExpireCommand extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
protected $signature = 'user:expire_time {--brand_id= : brand_id}';
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct();
}
public function configure()
{
parent::configure();
$this->setDescription('会员到期');
}
public function handle()
{
$task = make(MemberVipExpireTask::class);
// 品牌商
$brand_id = $this->input->getOption('brand_id');
if (!empty($brand_id)) {
$task->setBrandId($brand_id);
}
$task->execute();
$this->line('已执行!');
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use App\Repository\Reimbursement\OutWarehouseStatisticsRepository;
use Carbon\Carbon;
use App\Model\Brand\Brand;
use Swoole\Coroutine as co;
/**
* @Command
*/
#[Command]
class OutWarehouseStatistics extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct('statistics:outwarehouse');
}
public function configure()
{
parent::configure();
$this->setDescription('出库数据统计');
$this->addArgument('day', InputArgument::REQUIRED, '开始时间:');
$this->addArgument('end_day', InputArgument::REQUIRED, '结束时间');
$this->addArgument( 'brand_id', InputArgument::OPTIONAL, '品牌商编号' );
}
public function handle()
{
$repository = new OutWarehouseStatisticsRepository();
$this->line('脚本开始执行', 'info');
$day = $this->input->getArgument('day');
$end_day = $this->input->getArgument('end_day');
$brand_id = $this->input->getArgument( 'brand_id' );
$query = Brand::query()->where('status', 1)
->select('brand_no');
if($brand_id){
$query->where('brand_no', $brand_id);
}
$query->chunkById(100, function($brand) use($day, $end_day, $repository){
foreach($brand as $v){
$this->warn($v['brand_no']. ' 开始执行');
set_auth_brand_id($v['brand_no']);
if ($day && $end_day) {
$date = $day;
//指定时间范围
$beginTime = strtotime($day);
$endTime = strtotime($end_day);
do {
if ($date > 0) {
$this->warn(' ' . $v['brand_no'] . ' '. $date);
$repository
->setBrandId($v['brand_no'])
->setTime($date)
->entry();
}
$beginTime = $beginTime + 86400;
$date = date('Ymd', $beginTime);
co::sleep(0.1); // 延时 0.1 秒
} while ($beginTime <= $endTime);
} else {
$this->warn(' ' . $day);
$repository
->setBrandId($v['brand_no'])
->setTime($day)
->entry();
}
}
}, 'brand_no');
$this->info('success');
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use App\Repository\Reimbursement\RefundWarehouseStatisticsRepository;
use Carbon\Carbon;
use App\Model\Brand\Brand;
use Swoole\Coroutine as co;
/**
* @Command
*/
#[Command]
class RefundWarehouseStatistics extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct('statistics:refundwarehouse');
}
public function configure()
{
parent::configure();
$this->setDescription('退货数据统计');
$this->addArgument( 'start_time', InputArgument::REQUIRED, '开始时间Y-m-d' );
$this->addArgument( 'end_time', InputArgument::REQUIRED, '结束时间Y-m-d' );
$this->addArgument( 'brand_id', InputArgument::OPTIONAL, '品牌商编号' );
}
public function handle()
{
$repository = new RefundWarehouseStatisticsRepository();
$this->line('脚本开始执行', 'info');
$start_day = $this->input->getArgument( 'start_time' );
$end_day = $this->input->getArgument( 'end_time' );
$brand_id = $this->input->getArgument( 'brand_id' );
$start_time = Carbon::parse( $start_day )->startOfDay()->toDateTimeString();
$end_time = Carbon::parse( $end_day )->endOfDay()->toDateTimeString();
$query = Brand::query()->where('status', 1)
->select('brand_no');
if($brand_id){
$query->where('brand_no',$brand_id);
}
$query->chunkById(100, function($brand) use($start_time, $end_time, $repository){
foreach($brand as $v){
$this->warn($v['brand_no']. ' 开始执行');
set_auth_brand_id($v['brand_no']);
$repository
->setBrandId($v['brand_no'])
->setTime($start_time, $end_time)
->entry();
co::sleep(0.1); // 延时 0.1 秒
}
}, 'brand_no');
$this->info('success');
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use App\Task\PointClearTask;
use App\Model\Marketing\Scan;
use App\Task\ScanStatisticsTask;
use App\Task\UserTagAutoSetTask;
use App\Task\ScanAwardStatisticsTask;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use App\Model\Marketing\StatisticsScanProvince;
/**
* @Command
* 执行 数据修复
*/
class RunDebugData extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
// php -d memory_limit=-1 bin/hyperf.php run_debug
protected $signature = 'run_debug';
protected $brand_id = null;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct();
}
public function configure()
{
parent::configure();
$this->setDescription('执行 定时任务的调用');
}
public function handle()
{
$start = '2023-01-01';
do {
$this->line( date('H:i:s') .' -- ' . $start , 'info');
self::rubn( $start );
$start = Carbon::parse( $start )->addDay()->format('Y-m-d');
$day = Carbon::parse( $start )->format('Ymd');
} while ($day < 20231209);
$this->line('任务运行结束!', 'info');
}
public static function rubn( $date_time)
{
$day = Carbon::parse( $date_time )->format('Ymd');
$scan = Scan::query();
// 省级数据统计
$scan->where('day', $day)
->groupBy('brand_id', 'province_id', 'product_id', 'activity_id')
->select(
'brand_id',
'product_id',
'activity_id',
'province_id',
'province',
Db::raw('count(*) as scan_total'),
Db::raw("count(distinct(product_code)) as scan_number"),
Db::raw("count(if(is_first=1,true,null)) as first_scan_num"),
Db::raw("count(if(is_first=0,true,null)) as repeat_scan_num")
)
->chunk(100, function ($list) use ($date_time) {
$created_time = Carbon::now('Asia/shanghai')->toDateTimeString();
foreach ($list as $item) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'product_id' => $item->product_id ?: 0,
'activity_id' => $item->activity_id ?: 0,
'province_id' => $item->province_id ?: 0,
];
$scan = [
'province' => $item->province,
'scan_total' => $item->scan_total ?? 0,
'scan_number' => $item->scan_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0,
'repeat_scan_num' => $item->repeat_scan_num ?? 0,
'created_time' => $created_time
];
StatisticsScanProvince::updateOrInsert($where, $scan);
}
});
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use App\Task\PointClearTask;
use App\Model\Marketing\Scan;
use App\Task\ScanStatisticsTask;
use App\Task\UserTagAutoSetTask;
use App\Task\ScanAwardStatisticsTask;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
use App\Model\Marketing\StatisticsScanCity;
use Hyperf\Command\Command as HyperfCommand;
/**
* @Command
* 执行 数据修复
*/
class RunDebugDataCity extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
// php -d memory_limit=-1 bin/hyperf.php run_debug_city
protected $signature = 'run_debug_city';
protected $brand_id = null;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct();
}
public function configure()
{
parent::configure();
$this->setDescription('执行 定时任务的调用');
}
public function handle()
{
$start = '2023-01-01';
do {
$this->line( date('H:i:s') .' -- ' . $start , 'info');
self::rubn( $start );
$start = Carbon::parse( $start )->addDay()->format('Y-m-d');
$day = Carbon::parse( $start )->format('Ymd');
} while ($day < 20231209);
$this->line('任务运行结束!', 'info');
}
public static function rubn( $date_time )
{
$day = Carbon::parse( $date_time )->format('Ymd');
$scan = Scan::query();
// 市级数据统计
$scan->where('day', $day)
->groupBy('brand_id', 'city_id', 'product_id', 'activity_id')
->select(
'brand_id',
'product_id',
'activity_id',
'province_id',
'city_id',
'province',
'city',
Db::raw('count(*) as scan_total'),
Db::raw("count(distinct(product_code)) as scan_number"),
Db::raw("count(if(is_first=1,true,null)) as first_scan_num"),
Db::raw("count(if(is_first=0,true,null)) as repeat_scan_num")
)
->chunk(100, function ($list) use ($date_time) {
foreach ($list as $item) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'product_id' => $item->product_id ?: 0,
'activity_id' => $item->activity_id ?: 0,
'province_id' => $item->province_id ?: 0,
'city_id' => $item->city_id ?: 0,
];
$scan = [
'province' => $item->province,
'city' => $item->city,
'scan_total' => $item->scan_total ?? 0,
'scan_number' => $item->scan_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0,
'repeat_scan_num' => $item->repeat_scan_num ?? 0
];
StatisticsScanCity::updateOrInsert($where, $scan);
}
});
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use App\Task\PointClearTask;
use App\Model\Marketing\Scan;
use App\Task\ScanStatisticsTask;
use App\Task\UserTagAutoSetTask;
use App\Task\ScanAwardStatisticsTask;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
use App\Model\Marketing\StatisticsScanCity;
use Hyperf\Command\Command as HyperfCommand;
use App\Model\Marketing\StatisticsScanDistrict;
/**
* @Command
* 执行 数据修复
*/
class RunDebugDataDistrict extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
// php -d memory_limit=-1 bin/hyperf.php run_debug_district
protected $signature = 'run_debug_district';
protected $brand_id = null;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct();
}
public function configure()
{
parent::configure();
$this->setDescription('执行 定时任务的调用');
}
public function handle()
{
$start = '2023-01-01';
do {
$this->line( date('H:i:s') .' -- ' . $start , 'info');
self::rubn( $start );
$start = Carbon::parse( $start )->addDay()->format('Y-m-d');
$day = Carbon::parse( $start )->format('Ymd');
} while ($day < 20231209);
$this->line('任务运行结束!', 'info');
}
public static function rubn( $date_time )
{
$day = Carbon::parse( $date_time )->format('Ymd');
$scan = Scan::query();
// 区级数据统计
$scan->where('day', $day)
->groupBy('brand_id', 'district_id', 'product_id', 'activity_id')
->select(
'brand_id',
'product_id',
'activity_id',
'province_id',
'city_id',
'district_id',
'province',
'city',
'district',
Db::raw('count(*) as scan_total'),
Db::raw("count(distinct(product_code)) as scan_number"),
Db::raw("count(if(is_first=1,true,null)) as first_scan_num"),
Db::raw("count(if(is_first=0,true,null)) as repeat_scan_num")
)
->chunk(100, function ($list) use ($date_time) {
foreach ($list as $item) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'product_id' => $item->product_id ?: 0,
'activity_id' => $item->activity_id ?: 0,
'province_id' => $item->province_id ?: 0,
'city_id' => $item->city_id ?: 0,
'district_id' => $item->district_id ?: 0,
];
$scan = [
'province' => $item->province ?: '',
'city' => $item->city ?: '',
'district' => $item->district ?: '',
'scan_total' => $item->scan_total ?? 0,
'scan_number' => $item->scan_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0,
'repeat_scan_num' => $item->repeat_scan_num ?? 0
];
StatisticsScanDistrict::updateOrInsert($where, $scan);
}
});
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use App\Task\BreSyncCodeBymTask;
use App\Task\PointClearTask;
use App\Task\UserTagAutoSetTask;
use App\Task\ScanAwardStatisticsTask;
use Psr\Container\ContainerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
/**
* @Command
* 执行 任务调用
*/
class RunTaskCommand extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
protected $signature = 'run:task {task : task} {brand_id? : brand_id}';
protected $brand_id = null;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct();
}
public function configure()
{
parent::configure();
$this->setDescription('执行 定时任务的调用');
}
public function handle()
{
// 品牌商
$task = $this->input->getArgument('task');
$tasks = [
'point_clear' => PointClearTask::class, // 积分清理任务
'user_tag_auto_set' => UserTagAutoSetTask::class, // 会员打标签
'scan_award_task' => ScanAwardStatisticsTask::class, // 奖项统计
'bre_code_sync' => BreSyncCodeBymTask::class, // 泊然恩同步贝因美码数据
];
if ( !isset( $tasks[ $task ]) ) {
return $this->error('不存此任务!');
}
$taskModel = make( $tasks[ $task ] )->setDateTime( '2023-11-12' );
if($tasks[ $task ]=='bre_code_sync'){
$brand_id = $this->input->getArgument('brand_id');
if($brand_id){
$taskModel->setBrandId($brand_id);
}
}
$taskModel->execute();
$this->line('任务运行结束!', 'info');
}
}
<?php
declare( strict_types=1 );
namespace App\Command;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\Brand\SmsGroupSendDetail;
use App\Model\Brand\SmsSendHistory;
use App\Model\Brand\SmsStatistics;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Schema\Schema;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
/**
* @Command
*/
class SmsStatisticsCommand extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct( ContainerInterface $container )
{
$this->container = $container;
parent::__construct( 'statistics:sms' );
}
public function configure()
{
parent::configure();
$this->addUsage( 'statistics:sms --all' );
$this->setDescription( '短信统计,默认统计昨天的数据' );
$this->addOption( 'all', 'a', InputOption::VALUE_NONE, '是否重新统计所有数据' );
}
protected function getArguments()
{
return [
[ 'date', InputArgument::OPTIONAL, '所要统计的日期' ],
[ 'brand_id', InputArgument::OPTIONAL, '所要统计的品牌商,不传默认统计全部' ],
];
}
public function handle()
{
try {
$date = $this->input->getArgument( 'date' );
$brandId = $this->input->getArgument( 'brand_id' ) ?? 0;
$all = $this->input->getOption( 'all' );
// 从 $input 获取 name 参数
$yesterday = $date ?? date( 'Y-m-d', strtotime( "-1 day" ) );
if ( strtotime( $yesterday ) !== FALSE ) {
//统计昨天所有积分
if ( !$all ) {
$info = SmsStatistics::query()->whereDate( 'date', $yesterday )->first();
if ( $info ) {
throw new BusinessException( 10086, '已存在当天统计数据!' );
}
}
$handel = SmsSendHistory::query();
if ( !$all ) {
$handel->whereRaw( 'from_unixtime(create_time,"%Y-%m-%d") = "' . $yesterday . '"' );
}
if ( $brandId ) {
$handel->where( 'brand_id', $brandId );
}
$result = $handel->selectRaw( 'from_unixtime(create_time,"%Y-%m-%d") as date,brand_id,count(id) as ordinary_number_sent' )
->where( 'status', 2 )
->groupBy( [ 'brand_id', 'date' ] )
->get()
->toArray();
$handel1 = SmsGroupSendDetail::query();
if ( !$all ) {
$handel1->whereRaw( 'date_format(create_time,"%Y-%m-%d") = "' . $yesterday . '"' );
}
if ( $brandId ) {
$handel1->where( 'brand_id', $brandId );
}
$result2 = $handel1->selectRaw( 'date_format(create_time,"%Y-%m-%d") as date,brand_id,count(id) as group_number_sent' )
->where( 'status', 1 )
->groupBy( [ 'brand_id', 'date' ] )
->get()
->toArray();
$data = [];
if ( $result ) {
foreach ( $result as $value ) {
$data[ $value[ 'brand_id' ] ][ $value[ 'date' ] ][ 'ordinary_number_sent' ] = $value[ 'ordinary_number_sent' ];
}
}
if ( $result2 ) {
foreach ( $result2 as $value ) {
$data[ $value[ 'brand_id' ] ][ $value[ 'date' ] ][ 'group_number_sent' ] = $value[ 'group_number_sent' ];
}
}
$insert = [];
foreach ( $data as $d_brandId => $value ) {
foreach ( $value as $s_date => $v ) {
$insert[] = [
'brand_id' => $d_brandId,
'date' => $s_date,
'ordinary_number_sent' => $v[ 'ordinary_number_sent' ] ?? 0,
'group_number_sent' => $v[ 'group_number_sent' ] ?? 0,
];
}
}
if ( $insert ) {
SmsStatistics::insert( $insert );
}
$this->line( date( 'Y-m-d H:i:s', time() ) . "短信统计处理完成", 'info' );
} else {
throw new BusinessException( 10086, '时间格式错误!' );
}
} catch ( \Throwable $exception ) {
$this->line( date( 'Y-m-d H:i:s', time() ) . "短信统计处理异常:" . $exception->getMessage(), 'info' );
}
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use App\Task\VoucherStatusTask;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
/**
* @Command
*/
class VoucherStatusCommand extends HyperfCommand
{
protected $signature = 'run:VoucherStatus';
public function configure()
{
parent::configure();
$this->setDescription('提货卷状态信息维护');
}
public function handle()
{
(new VoucherStatusTask)->execute();
$this->line('已执行!');
}
}
<?php
declare(strict_types=1);
namespace App\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use App\Repository\Reimbursement\WarehouseStatisticsRepository;
use Carbon\Carbon;
use App\Model\Brand\Brand;
use Swoole\Coroutine as co;
/**
* @Command
*/
#[Command]
class WarehouseStatistics extends HyperfCommand
{
/**
* @var ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct('statistics:warehouse');
}
public function configure()
{
parent::configure();
$this->setDescription('入库数据统计');
$this->addArgument('day', InputArgument::REQUIRED, '开始时间:');
$this->addArgument('end_day', InputArgument::REQUIRED, '结束时间');
$this->addArgument( 'brand_id', InputArgument::OPTIONAL, '品牌商编号' );
}
public function handle()
{
$repository = new WarehouseStatisticsRepository();
$this->line('脚本开始执行', 'info');
$day = $this->input->getArgument('day');
$end_day = $this->input->getArgument('end_day');
$brand_id = $this->input->getArgument( 'brand_id' );
$query = Brand::query()->where('status', 1)
->select('brand_no');
if($brand_id){
$query->where('brand_no',$brand_id);
}
$query->chunkById(100, function($brand) use($day, $end_day, $repository){
foreach($brand as $v){
$this->warn($v['brand_no']. ' 开始执行');
set_auth_brand_id($v['brand_no']);
if ($day && $end_day) {
$date = $day;
//指定时间范围
$beginTime = strtotime($day);
$endTime = strtotime($end_day);
do {
if ($date > 0) {
$this->warn(' ' . $v['brand_no'] . ' '. $date);
$repository
->setBrandId($v['brand_no'])
->setTime($date)
->entry();
}
$beginTime = $beginTime + 86400;
$date = date('Ymd', $beginTime);
co::sleep(0.1); // 延时 0.1 秒
} while ($beginTime <= $endTime);
} else {
$this->warn(' ' . $day);
$repository
->setBrandId($v['brand_no'])
->setTime($day)
->entry();
}
}
}, 'brand_no');
$this->info('success');
}
}
<?php
declare( strict_types=1 );
namespace App\Constants\Cache;
abstract class BaseAbstract
{
protected static function getPrefix( $brand_id )
{
return "ydd:" . $brand_id;
}
}
<?php
declare( strict_types=1 );
namespace App\Constants\Cache;
use Hyperf\Constants\Annotation\Constants;
/**
* @Constants
* Class ErrorCode
* @package App\Constants
*/
class CacheDatabaseConstants
{
/** @var string 默认 */
public const DEFAULT = 'default';
/**
* @Message('订单缓存')
*/
public const ORDER = 'order';
/**
* @Message('活动缓存')
*/
public const ACTIVITY = 'activity';
/**
* @Message('分表数据')
*/
public const SHARDING = 'sharding';
}
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Constants;
use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* @Constants
*/
class ErrorCode extends AbstractConstants
{
/**
* @Message("Server Error!")
*/
public const SERVER_ERROR = 500;
}
<?php
declare( strict_types=1 );
namespace App\Context;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
class BrandAuth
{
/**
* @var Model
*/
protected $user;
public function __construct( $user )
{
$this->user = $user;
}
/**
* 获取品牌商ID
*
* @return int
*/
public function brandId()
{
if (!is_null( $this->user)) {
if (isset($this->user['brand_id'])) {
return $this->user['brand_id'];
}
}
throw new BusinessException( ErrorCode::SERVER_ERROR, "登录失效,请重新登录!" );
}
}
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Controller;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;
abstract class AbstractController
{
/**
* @Inject
* @var ContainerInterface
*/
protected $container;
/**
* @Inject
* @var RequestInterface
*/
protected $request;
/**
* @Inject
* @var ResponseInterface
*/
protected $response;
}
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Controller;
use App\Task\ScanTotalStatisticsTask;
class IndexController extends AbstractController
{
public function index()
{
//make(ScanTotalStatisticsTask::class)->execute();
}
}
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Exception;
use App\Constants\ErrorCode;
use Hyperf\Server\Exception\ServerException;
use Throwable;
class BusinessException extends ServerException
{
public function __construct(int $code = 0, string $message = null, Throwable $previous = null)
{
if (is_null($message)) {
$message = ErrorCode::getMessage($code);
}
parent::__construct($message, $code, $previous);
}
}
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Exception\Handler;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
class AppExceptionHandler extends ExceptionHandler
{
/**
* @var StdoutLoggerInterface
*/
protected $logger;
public function __construct(StdoutLoggerInterface $logger)
{
$this->logger = $logger;
}
public function handle(Throwable $throwable, ResponseInterface $response)
{
$this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
$this->logger->error($throwable->getTraceAsString());
return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream('Internal Server Error.'));
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}
<?php
namespace App\Job;
use Hyperf\Di\Annotation\Inject;
use Hyperf\XxlJob\Annotation\XxlJob;
use Hyperf\XxlJob\Logger\JobExecutorLoggerInterface;
use Hyperf\XxlJob\Requests\RunRequest;
use Swoole\Process;
class DemoJob
{
#[Inject]
protected JobExecutorLoggerInterface $jobExecutorLogger;
/**
* 1.任务示例.
*/
#[XxlJob('demoJobHandler')]
public function demoJobHandler(RunRequest $request)
{
//获取参数
$params = $request->getExecutorParams();
//获取logId
$logId = $request->getLogId();
$this->jobExecutorLogger->info('params:' . $params);
for ($i = 1; $i < 5; ++$i) {
sleep(2);
$this->jobExecutorLogger->info($i);
$this->jobExecutorLogger->info('logId:' . $logId);
$this->jobExecutorLogger->info('params:' . $params);
}
}
/**
* 2、分片广播任务
*/
#[XxlJob('shardingJobHandler')]
public function shardingJobHandler(RunRequest $request)
{
// 分片参数
$shardIndex = $request->getBroadcastIndex();
$shardTotal = $request->getBroadcastTotal();
$this->jobExecutorLogger->info(sprintf('分片参数:当前分片序号 = %d, 总分片数 = %d', $shardIndex, $shardTotal));
// 业务逻辑
for ($i = 0; $i < $shardTotal; ++$i) {
if ($i == $shardIndex) {
$this->jobExecutorLogger->info('第 %d 片, 命中分片开始处理', $i);
} else {
$this->jobExecutorLogger->info('第 %d 片, 忽略', $i);
}
}
}
/**
* 3、执行命令.
*/
#[XxlJob('commandJobHandler')]
public function commandJobHandler(RunRequest $request)
{
//获取参数
//例子:php -v
$command = $request->getExecutorParams();
$result = shell_exec($command);
$message = str_replace("\n", '<br>', $result);
$this->jobExecutorLogger->info($message);
}
/**
* 4、param任务
* 参数示例:
* "url: http://www.baidu.com\n" +
* "method: get".
*/
#[XxlJob('paramJobHandler')]
public function paramJobHandler(RunRequest $request)
{
$param = $request->getExecutorParams();
$array = explode(PHP_EOL, $param);
/** array(2) {
[0]=>
string(25) "url: http://www.baidu.com"
[1]=>
string(11) "method: get"
}
*/
var_dump($param, $array);
}
/**
* 5、任务示例:任务初始化与销毁时,支持自定义相关逻辑.
*/
#[XxlJob(value: 'demoJob', init: 'initMethod', destroy: 'destroyMethod')]
public function demoJob()
{
$this->jobExecutorLogger->info('demoJob run...');
}
public function initMethod()
{
$this->jobExecutorLogger->info('initMethod');
}
public function destroyMethod()
{
$this->jobExecutorLogger->info('destroyMethod');
}
}
\ No newline at end of file
<?php
namespace App\Job;
use Hyperf\Di\Annotation\Inject;
use Hyperf\XxlJob\Annotation\XxlJob;
use Hyperf\XxlJob\Handler\AbstractJobHandler;
use Hyperf\XxlJob\Logger\JobExecutorLoggerInterface;
use Hyperf\XxlJob\Requests\RunRequest;
use App\Model\Brand\PointSet;
#[XxlJob("demoJobClassHandler")]
class DemoJobClass extends AbstractJobHandler
{
#[Inject]
protected JobExecutorLoggerInterface $jobExecutorLogger;
/**
* 执行任务
*/
public function execute(RunRequest $request): void
{
// 获取参数
$params = $request->getExecutorParams();
// 获取 LogId
$logId = $request->getLogId();
$brand_id = $params ?? 0;
// 获取需要清理积分的品牌商
$query = PointSet::with('brand');
if($brand_id){
$query->where('brand_id',$brand_id);
}
$brands = $query->get();
// 过滤过期的品牌商
$time = time();
foreach ( $brands as $brand ) {
$data = [
'brand_name' => $brand['brand']['brand_name'] ?? '',
'consume_explain' => $brand['consume_explain'],
'obtain_point' => $brand['obtain_point']
];
$this->jobExecutorLogger->info('brandInfo:' . json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
}
$this->jobExecutorLogger->info('logId:' . $logId);
$this->jobExecutorLogger->info('params:' . $params);
$this->jobExecutorLogger->info('success');
}
}
<?php
declare( strict_types=1 );
namespace App\Kernel\Member;
use Carbon\Carbon;
use App\Model\Brand\Member;
use Hyperf\DbConnection\Db;
use App\Model\Marketing\Scan;
use Psr\Log\LoggerInterface;
use Hyperf\Logger\LoggerFactory;
use App\Model\Member\MemberRelationTag;
class MemebrTagHandle
{
/**
* @var LoggerInterface
*/
private $logger;
/** 品牌商编号 */
private $brand_id;
/** 标签信息 */
private $member_tag_config = [];
/** 需要打此标签的用户ids */
private $set_tag_member_ids = [];
// 用户id 满足 注册时间
private $member_ids_by_reg_time = [];
// 用户id 满足 最后扫码时间
private $member_ids_by_last_scan = [];
// 用户id 满足 最后一次扫码时间距离现在超过
private $member_ids_by_last_scan_beyond = [];
// 用户id 满足 扫码次数
private $member_ids_by_scan_num = [];
// 用户id 满足 首次扫码次数
private $member_ids_by_first_scan = [];
// 用户id 满足 首次扫码总次数
private $member_ids_by_first_all_scan = [];
// 用户id 满足 扫码扫过商品的
private $member_ids_by_scan_product = [];
public function __construct()
{
$this->logger = di( LoggerFactory::class )->get( 'user_tag_auto_set' );
}
/**
* 打标签的主调用方法
*/
public function execute( $member_tag_config )
{
// $this->logger->info("member_tag_config ",$member_tag_config );
$this->member_tag_config = $member_tag_config;
$this->brand_id = $member_tag_config['brand_id'];
// 检查 - 用户注册时间
$this->checkUserRegTime();
// 检查 - 用户最后扫码时间
$this->checkUserLastScan();
// 检查 - 最后一次扫码时间距离现在超过
$this->checkUserLastScanBeyond();
// 检查 - 扫码次数
$this->checkUserScanNum();
// 检查 - 首次扫码次数
$this->checkUserFirstScanNum();
// 检查 - 首次扫码总次数
$this->checkUserFirstScanAllNum();
// 检查 - 扫码扫过商品的
$this->checkUserScanProduct();
// 满足选择的所有条件模式时 数据处理
if ( $member_tag_config['auto_mode'] == 1 ) $this->wholeModeAssociation();
// 为用户id 打标签
if ( !empty( $this->set_tag_member_ids ) ) {
foreach( array_unique($this->set_tag_member_ids) as $member_id ) {
$tag = [
'brand_id' => $this->brand_id,
'member_id' => $member_id,
'tag_id' => $this->member_tag_config['id'],
];
MemberRelationTag::create( $tag );
}
}
}
// 满足全部条件的 数据组合 取共有的 id
private function wholeModeAssociation()
{
$list = [];
if ( $this->member_tag_config['is_auto_create_member'] == 1 ) {
$list[] = $this->member_ids_by_reg_time;
}
if ( $this->member_tag_config['is_auto_last_scan'] == 1 ) {
$list[] = $this->member_ids_by_last_scan;
}
if ( $this->member_tag_config['is_auto_last_scan_beyond'] == 1 ) {
$list[] = $this->member_ids_by_last_scan_beyond;
}
if ( $this->member_tag_config['is_auto_scan_num'] == 1 ) {
$list[] = $this->member_ids_by_scan_num;
}
if ( $this->member_tag_config['is_auto_first_scan'] == 1 ) {
$list[] = $this->member_ids_by_first_scan;
}
if ( $this->member_tag_config['is_auto_first_all_scan'] == 1 ) {
$list[] = $this->member_ids_by_first_all_scan;
}
if ( $this->member_tag_config['is_auto_scan_product'] == 1 ) {
$list[] = $this->member_ids_by_scan_product;
}
if ( count($list) > 1 ) {
$this->set_tag_member_ids = array_unique( array_intersect( ... $list ) );
} else {
$this->set_tag_member_ids = array_unique( $list[0] );
}
}
/**
* 检查 用户注册时间
*/
public function checkUserRegTime()
{
if ( $this->member_tag_config['is_auto_create_member'] != 1 ) {
return false;
}
$auto_create_member = json_decode( $this->member_tag_config['auto_create_member'], true );
// {"start_time":"2023-01-01","end_time":"2023-01-31"}
$start_timestamp = Carbon::parse( $auto_create_member['start_time'] )->startOfDay()->timestamp;
$end_timestamp = Carbon::parse( $auto_create_member['end_time'] )->endOfDay()->timestamp;
// 获取最大的id
$max_id = Member::query()
->where('brand_id', $this->brand_id )
->where('create_time','<', $end_timestamp )
->orderBy('id','desc')
->value('id');
// 获取最小的id
$min_id = Member::query()
->where('brand_id', $this->brand_id )
->where('create_time', '>', $start_timestamp )
->orderBy('id')
->value('id');
// 满足条件的 用户id
$list = Member::query()
->where('brand_id', $this->brand_id )
->whereBetween('id', [ $min_id, $max_id ] )
->whereNotIn('id', [Db::raw( "select `member_id` from `ydd_member`.`ydd_member_relation_tag` where `brand_id`={$this->brand_id} and `tag_id` = {$this->member_tag_config['id']}" )] )
->select('id')
->pluck('id')
->all();
// auto_mode 自动模式 0 满足选择的任一条件即可 1 满足选择的所有条件
if( $this->member_tag_config['auto_mode'] == 1 ) {
$this->member_ids_by_reg_time = $list;
} else {
$this->set_tag_member_ids = array_unique( array_merge( $this->set_tag_member_ids, $list ) );
}
}
/**
* 检查 用户最后扫码时间
*/
public function checkUserLastScan()
{
if ( $this->member_tag_config['is_auto_last_scan'] != 1 ) {
return false;
}
$tag_config = json_decode( $this->member_tag_config['auto_last_scan'], true );
$start_timestamp = Carbon::parse( $tag_config['start_time'] )->startOfDay()->timestamp;
$end_timestamp = Carbon::parse( $tag_config['end_time'] )->endOfDay()->timestamp;
// 获取最大的id
$max_id = Member::query()
->where('brand_id', $this->brand_id )
->where('last_scan_time','<', $end_timestamp )
->orderBy('id','desc')
->value('id');
// 获取最小的id
$min_id = Member::query()
->where('brand_id', $this->brand_id )
->where('last_scan_time', '>', $start_timestamp )
->orderBy('id')
->value('id');
// 满足条件的 用户id
$list = Member::query()
->where('brand_id', $this->brand_id )
->whereBetween('id', [ $min_id, $max_id ] )
->whereNotIn('id', [Db::raw( "select `member_id` from `ydd_member`.`ydd_member_relation_tag` where `brand_id`={$this->brand_id} and `tag_id` = {$this->member_tag_config['id']}" )] )
->select('id')
->pluck('id')
->all();
// auto_mode 自动模式 0 满足选择的任一条件即可 1 满足选择的所有条件
if( $this->member_tag_config['auto_mode'] == 1 ) {
$this->member_ids_by_last_scan = $list;
} else {
$this->set_tag_member_ids = array_unique( array_merge( $this->set_tag_member_ids, $list ) );
}
}
/**
* 检查 最后一次扫码时间距离现在超过
*/
public function checkUserLastScanBeyond()
{
if ( $this->member_tag_config['is_auto_last_scan_beyond'] != 1 ) {
return false;
}
$tag_config = json_decode( $this->member_tag_config['auto_last_scan_beyond'], true );
$start_timestamp = Carbon::now()->subDays($tag_config['day'] )->startOfDay()->timestamp;
// 满足条件的 用户id
$list = Member::query()
->where('brand_id', $this->brand_id )
->where('last_scan_time', '<', $start_timestamp )
->where('last_scan_time', '!=', 0 )
->whereNotIn('id', [Db::raw( "select `member_id` from `ydd_member`.`ydd_member_relation_tag` where `brand_id`={$this->brand_id} and `tag_id` = {$this->member_tag_config['id']}" )] )
->select('id')
->pluck('id')
->all();
// auto_mode 自动模式 0 满足选择的任一条件即可 1 满足选择的所有条件
if( $this->member_tag_config['auto_mode'] == 1 ) {
$this->member_ids_by_last_scan_beyond = $list;
} else {
$this->set_tag_member_ids = array_unique( array_merge( $this->set_tag_member_ids, $list ) );
}
}
/**
* 检查 - 扫码次数
*/
public function checkUserScanNum()
{
if ( $this->member_tag_config['is_auto_scan_num'] != 1 ) {
return false;
}
// {"start_time":"2023-02-01","end_time":"2023-02-28","start_num":"6","end_num":"10"}
$tag_config = json_decode( $this->member_tag_config['auto_scan_num'], true );
$start_day = Carbon::parse( $tag_config['start_time'] )->format('Ymd');
$end_day = Carbon::parse( $tag_config['end_time'] )->format('Ymd');
$min_id = Scan::query()->where('brand_id', $this->brand_id)->where('day', '>=', $start_day)->orderBy('id','asc')->value('id');
$max_id = Scan::query()->where('brand_id', $this->brand_id)->where('day', '<=', $end_day)->orderBy('id','desc')->value('id');
$list = Scan::query()
->where('brand_id', $this->brand_id)
->whereBetween('id', [ $min_id, $max_id ] )
->whereNotIn('member_id', [Db::raw( "select `member_id` from `ydd_member`.`ydd_member_relation_tag` where `brand_id`={$this->brand_id} and `tag_id` = {$this->member_tag_config['id']}" )] )
->select( Db::raw( "count('id') as scan_num"), 'member_id' )
->groupBy('member_id')
->having('scan_num', '>=', $tag_config['start_num'])
->having('scan_num', '<=', $tag_config['end_num'])
->pluck('member_id')
->all();
// auto_mode 自动模式 0 满足选择的任一条件即可 1 满足选择的所有条件
if( $this->member_tag_config['auto_mode'] == 1 ) {
$this->member_ids_by_scan_num = $list;
} else {
$this->set_tag_member_ids = array_unique( array_merge( $this->set_tag_member_ids, $list ) );
}
}
/**
* 检查 - 首次扫码次数
*/
public function checkUserFirstScanNum()
{
if ( $this->member_tag_config['is_auto_first_scan'] != 1 ) {
return false;
}
// {"start_time":"2023-02-01","end_time":"2023-02-17","start_num":"5","end_num":"10"}
$tag_config = json_decode( $this->member_tag_config['auto_first_scan'], true );
$start_day = Carbon::parse( $tag_config['start_time'] )->format('Ymd');
$end_day = Carbon::parse( $tag_config['end_time'] )->format('Ymd');
$min_id = Scan::query()->where('brand_id', $this->brand_id)->where('day', '>=', $start_day)->orderBy('id','asc')->value('id');
$max_id = Scan::query()->where('brand_id', $this->brand_id)->where('day', '<=', $end_day)->orderBy('id','desc')->value('id');
$list = Scan::query()
->where('brand_id', $this->brand_id)
->whereBetween('id', [ $min_id, $max_id ] )
->where('is_first', 1)
->whereNotIn('member_id', [Db::raw( "select `member_id` from `ydd_member`.`ydd_member_relation_tag` where `brand_id`={$this->brand_id} and `tag_id` = {$this->member_tag_config['id']}" )] )
->select( Db::raw( "count('id') as scan_num"), 'member_id' )
->groupBy('member_id')
->having('scan_num', '>=', $tag_config['start_num'])
->having('scan_num', '<=', $tag_config['end_num'])
->pluck('member_id')
->all();
// auto_mode 自动模式 0 满足选择的任一条件即可 1 满足选择的所有条件
if( $this->member_tag_config['auto_mode'] == 1 ) {
$this->member_ids_by_first_scan = $list;
} else {
$this->set_tag_member_ids = array_unique( array_merge( $this->set_tag_member_ids, $list ) );
}
}
/**
* 检查 - 首次扫码总次数
*/
public function checkUserFirstScanAllNum()
{
if ( $this->member_tag_config['is_auto_first_all_scan'] != 1 ) {
return false;
}
//{"start_num":"1","end_num":"111"}
$tag_config = json_decode( $this->member_tag_config['auto_first_all_scan'], true );
$list = Scan::query()
->where('brand_id', $this->brand_id)
->where('is_first', 1)
->whereNotIn('member_id', [Db::raw( "select `member_id` from `ydd_member`.`ydd_member_relation_tag` where `brand_id`={$this->brand_id} and `tag_id` = {$this->member_tag_config['id']}" )] )
->select( Db::raw( "count('id') as scan_num"), 'member_id' )
->groupBy('member_id')
->having('scan_num', '>=', $tag_config['start_num'])
->having('scan_num', '<=', $tag_config['end_num'])
->pluck('member_id')
->all();
// auto_mode 自动模式 0 满足选择的任一条件即可 1 满足选择的所有条件
if( $this->member_tag_config['auto_mode'] == 1 ) {
$this->member_ids_by_first_all_scan = $list;
} else {
$this->set_tag_member_ids = array_unique( array_merge( $this->set_tag_member_ids, $list ) );
}
}
/**
* 检查 - 扫码扫过商品的
*/
public function checkUserScanProduct()
{
if ( $this->member_tag_config['is_auto_scan_product'] != 1 ) {
return false;
}
//[{"id":"4","spec_type":"2","product_name":"阿秋冬复古港风慵懒风毛衣外套针织开衫","product_image":"/ydd_resource/20210128/56f1899eacd7dcee4cfd055f53c691b0.jpg","product_sku_sn":"dsd222","product_sku_name":"藏青色_小码","product_sn":"fdf232","product_price":"69.99","category_name":"华为","select":"1"},{"id":"4","spec_type":"2","product_name":"阿秋冬复古港风慵懒风毛衣外套针织开衫","product_image":"/ydd_resource/20210128/b699c4e8dc207a35ac89f572cb86f8c4.jpg","product_sku_sn":"gdfg6565","product_sku_name":"粉色_小码","product_sn":"fdf232","product_price":"69.99","category_name":"华为","select":"1"}]
$tag_config = json_decode( $this->member_tag_config['auto_scan_product'], true );
// id 产品id product_sn 产品编号 product_sku_sn sku 编号
$list = Scan::query()
->where('brand_id', $this->brand_id)
->where('product_id', '!=', 0 )
->where(function( $query ) use( $tag_config ) {
$one = true;
foreach( $tag_config as $product ) {
$map = [
'product_id' => $product['id'],
//'product_sn' => $product['product_sn'],
];
if ( $product['product_sku_sn'] ) {
$map['product_sku_sn'] = $product['product_sku_sn'];
}
if ( $one ) {
$one = false;
$query->where( $map );
} else {
$query->orWhere( $map );
}
}
})
->whereNotIn('member_id', [Db::raw( "select `member_id` from `ydd_member`.`ydd_member_relation_tag` where `brand_id`={$this->brand_id} and `tag_id` = {$this->member_tag_config['id']}" )] )
->select( 'member_id' )
->groupBy('member_id')
->pluck('member_id')
->all();
// auto_mode 自动模式 0 满足选择的任一条件即可 1 满足选择的所有条件
if( $this->member_tag_config['auto_mode'] == 1 ) {
$this->member_ids_by_scan_product = $list;
} else {
$this->set_tag_member_ids = array_unique( array_merge( $this->set_tag_member_ids, $list ) );
}
}
}
<?php
declare( strict_types=1 );
namespace App\Kernel\TreasureActivity;
use App\Cache\TreasureCache;
use Psr\Log\LoggerInterface;
use Hyperf\Logger\LoggerFactory;
use App\Model\Cloud\TreasureActivity;
class TreasureCacheHandle
{
/**
* @var TreasureCache
*/
protected $cache;
/**
* @var LoggerInterface
*/
private $logger;
public function __construct()
{
$this->logger = di( LoggerFactory::class )->get( 'treasure_cache', 'activity' );
$this->cache = new TreasureCache();
}
public function setActListCache( $brand_id )
{
$ids = TreasureActivity::query()
->where( 'brand_id', $brand_id )
->where( 'act_status', 1 )
->where( 'end_time', '>', time() )
->orderBy( 'start_time' )
->limit( 20 )
->pluck( 'id' )
->toArray();
$this->cache->setActListCache( $brand_id, $ids );
}
public function delActCache( $params )
{
try {
//只删除结束1天后的活动数据
$nowTime = time();
if ( $params['end_time'] < $nowTime && bcsub( (string) $nowTime, (string) $params['end_time'], 0 ) <= 24 * 3600 ) {
$this->logger->info( "活动结束不到一天,暂不删除!", $params );
return;
}
$this->cache->delCache( $params['brand_id'],$params['act_id'] );
return;
} catch ( \Throwable $exception ) {
$this->logger->error( "活动删除缓存异常!", [
$params,
$exception->getMessage(),
$exception->getTrace()
] );
return;
}
}
}
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Listener;
use Hyperf\Database\Events\QueryExecuted;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Arr;
use Hyperf\Utils\Str;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
/**
* Listener
*/
class DbQueryExecutedListener implements ListenerInterface
{
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(ContainerInterface $container)
{
$this->logger = $container->get(LoggerFactory::class)->get('sql','sql');
}
public function listen(): array
{
return [
QueryExecuted::class,
];
}
/**
* @param QueryExecuted $event
*/
public function process(object $event)
{
if ($event instanceof QueryExecuted) {
$sql = $event->sql;
if (! Arr::isAssoc($event->bindings)) {
foreach ($event->bindings as $key => $value) {
$sql = Str::replaceFirst('?', "'{$value}'", $sql);
}
}
$this->logger->info(sprintf('[%s] %s', $event->time, $sql));
}
}
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class BonusCountModel extends Model
{
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = 'brand';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'bonus_count';
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class BonusCountStatisticsModel extends Model
{
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = 'brand';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'bonus_count_statistics';
// 黑名单字段
protected $guarded = [];
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class Brand extends Model
{
use SoftDeletes;
protected $connection = 'brand';
protected $table = 'brand';
protected $hidden = [ 'password' ];
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
protected $casts = [
'member_vip_card_config' => 'json',
];
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class BrandBillModel extends Model
{
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = 'brand';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'brand_bill';
const TYPE_TEXTS = [
self::TYPE_REPLACE_BONUS => "代发红包",
];
const TYPE_REPLACE_BONUS = "replace_bonus"; // 代发红包
public function getTypeTextAttribute()
{
return self::TYPE_TEXTS[ $this->type ] ?? "异常分类";
}
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class BrandSmallBillModel extends Model
{
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = 'brand';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'brand_small_bill';
const TYPE_TEXTS = [
self::TYPE_REPLACE_BONUS => "代发红包",
];
const TYPE_REPLACE_BONUS = "replace_bonus"; // 代发红包
public function getTypeTextAttribute()
{
return self::TYPE_TEXTS[ $this->type ] ?? "异常分类";
}
}
<?php
declare(strict_types=1);
namespace App\Model\Brand;
use App\Model\Model;
class CouponChannelStatistics extends Model
{
protected $connection = 'brand';
protected $table = 'coupon_channel_statistics';
protected $guarded = [];
const CREATED_AT = 'create_time';
const UPDATED_AT = null;
}
<?php
declare(strict_types=1);
namespace App\Model\Brand;
use App\Model\Model;
class CouponMemberLog extends Model
{
protected $connection = 'brand';
protected $table = 'coupon_member_log';
protected $guarded = [];
}
<?php
declare(strict_types=1);
namespace App\Model\Brand;
use App\Model\Model;
class CouponStoreStatistics extends Model
{
protected $connection = 'brand';
protected $table = 'coupon_store_statistics';
protected $guarded = [];
const CREATED_AT = 'create_time';
const UPDATED_AT = null;
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class Dealer extends Model
{
use SoftDeletes;
protected $connection = 'brand';
protected $table = 'dealer';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Model\Brand;
use App\Model\Model;
class ExportLog extends Model
{
protected $connection = 'brand';
protected $table = 'export_log';
/** @var int 优惠券发放明细*/
const TYPE_COUPON_SEND = 1;
/** @var int 优惠券使用明细*/
const TYPE_COUPON_USE = 2;
/** @var array 应用对应模块:品牌 */
const APPLICATION_BRAND = [
self::TYPE_COUPON_SEND,
self::TYPE_COUPON_USE
];
/** @var array 应用对应模块:二维码管理 */
const APPLICATION_QRCODE = [];
/** @var array 应用对应模块:智能营销管理 */
const APPLICATION_SMART_MARKETING = [];
/** @var array 应用对应模块:智能防窜管理 */
const APPLICATION_AUTI_SMUGGLING = [];
/** @var array 应用对应模块:直播云店管理 */
const APPLICATION_LIVE_CLOUD_STORE = [];
/** @var array 具体数据类型 */
const DATA_TYPE = [
self::TYPE_COUPON_SEND => '优惠券发放明细',
self::TYPE_COUPON_USE => '优惠券使用明细',
];
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class Member extends Model
{
use SoftDeletes;
protected $connection = 'brand';
protected $table = 'member';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
public function pointLog()
{
return $this->hasMany(PointUserLog::class,'user_id');
}
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class MemberVipCard extends Model
{
use SoftDeletes;
protected $connection = 'brand';
protected $table = 'member_vip_card';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class MemberVipCardPeriod extends Model
{
use SoftDeletes;
protected $connection = 'brand';
protected $table = 'member_vip_card_period';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
}
<?php
declare ( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class OrderSet extends Model
{
protected $connection = 'brand';
protected $table = 'order_set';
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use App\Model\Brand\Brand;
class PointSet extends Model
{
protected $connection = 'brand';
protected $table = 'point_set';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
// 时间戳
protected $dateFormat = 'U';
/**
* 品牌商
*/
public function brand()
{
return $this->hasOne( Brand::class, 'brand_no', 'brand_id' );
}
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use App\Model\Brand\Brand;
class PointUserLog extends Model
{
protected $connection = 'brand';
protected $table = 'point_user_log';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
// 时间戳
protected $dateFormat = 'U';
protected $fillable = [
'brand_id',
'user_id',
'type',
'action',
'point',
'remark',
'unique_id',
];
}
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $connection = 'r_brand';
protected $table = 'product';
protected $hidden = [ 'password' ];
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
}
<?php
declare ( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class SmsGroupSendDetail extends Model
{
protected $connection = 'brand';
protected $table = 'sms_group_send_detail';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
public function history()
{
return $this->belongsTo(SmsGroupSendHistory::class,'log_id');
}
}
\ No newline at end of file
<?php
declare ( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class SmsGroupSendHistory extends Model
{
protected $connection = 'brand';
protected $table = 'sms_group_send_history';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
}
\ No newline at end of file
<?php
declare ( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class SmsSendHistory extends Model
{
protected $connection = 'brand';
protected $table = 'sms_send_history';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
}
\ No newline at end of file
<?php
declare ( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class SmsStatistics extends Model
{
protected $connection = 'brand';
protected $table = 'sms_statistics';
public $timestamps = false;
}
\ No newline at end of file
<?php
declare ( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class SmsSystemTemplate extends Model
{
use SoftDeletes;
protected $connection = 'brand';
protected $table = 'sms_system_template';
protected $dateFormat = 'U';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
}
<?php
declare ( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class SmsTemplate extends Model
{
use SoftDeletes;
protected $connection = 'brand';
protected $table = 'sms_template';
protected $dateFormat = 'U';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class Store extends Model
{
use SoftDeletes;
protected $connection = 'brand';
protected $table = 'store';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class StoreLevel extends Model
{
protected $connection = 'brand';
protected $table = 'store_level';
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class StoreLevelDemoteConfig extends Model
{
protected $connection = 'brand';
protected $table = 'store_level_demote_config';
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Brand;
use App\Model\Model;
class StoreRebateLog extends Model
{
protected $connection = 'brand';
protected $table = 'store_rebate_log';
public $timestamps = false;
protected $guarded = [];
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Model\Cloud;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class TreasureActivity extends Model
{
use SoftDeletes;
protected $connection = 'cloud';
protected $table = 'treasure_activity';
protected $guarded = [];
/** @var int 参与范围 全部 */
const WITH_STORE_TYPE_ALL_VALUE = 1;
/** @var int 参与范围 指定 */
const WITH_STORE_TYPE_APPOINT_VALUE = 2;
/** @var int 参与范围 排除 */
const WITH_STORE_TYPE_EXCLUDE_VALUE = 3;
const ACT_TABLE_NAME = 'treasure_activity';
const ACT_STATUS_NO = 0;
const ACT_STATUS_YES = 1;
}
<?php
declare( strict_types=1 );
namespace App\Model\Code;
use App\Model\Model;
use Hyperf\DbConnection\Db;
use App\Model\Code\CodeOrderModel;
class BranchCodeModel extends Model
{
protected $connection = 'code';
protected $table = 'code_';
protected $brand_id = '';
protected $guarded = [];
public function __construct( array $attributes = [], $brand_id = '' )
{
parent::__construct( $attributes );
// 设置分表
$this->table = 'code_' . $brand_id;
$this->brand_id = $brand_id;
return $this;
}
public function syncCodes( $filePath )
{
// 格式化连接
if ( PHP_OS == 'WINNT' ) {
$filePath = str_replace( "\\","\\\\", $filePath );
$filePath = str_replace( '/',"\\\\", $filePath );
}
$prefix = $this->getConnection()->getConfig('prefix');
$table = $prefix.$this->getTable();
$rn=PHP_EOL;
$sql = <<<EOF
LOAD DATA LOCAL INFILE '{$filePath}' INTO TABLE {$table}
FIELDS TERMINATED BY ','
ENCLOSED BY ''
LINES TERMINATED BY '{$rn}'
IGNORE 1 LINES
(batch_sn,big_code,small_code,security_code,created_at);
EOF;
return Db::connection('code')->statement( $sql );
}
}
<?php
declare( strict_types=1 );
namespace App\Model\Code;
use App\Model\Model;
use Hyperf\DbConnection\Db;
use App\Constants\ErrorCode;
use Hyperf\Logger\LoggerFactory;
use App\Model\Code\CodeOrderModel;
use App\Exception\BusinessException;
use Hyperf\Database\Model\SoftDeletes;
/**
* 泊然恩码表中间表:贝因美数据写入此表,中源程序同步此表数据
*
*/
class CodeBreModel extends Model
{
protected $connection = 'code';
protected $table = 'code_bre_';
protected $brand_id = '';
protected $guarded = [];
public $timestamps = false;
public function __construct( array $attributes = [], $brand_id = '' )
{
parent::__construct( $attributes );
// 设置分表
$this->table = 'code_bre_' . $brand_id;
$this->brand_id = $brand_id;
return $this;
}
}
<?php
declare( strict_types=1 );
namespace App\Model\Ecpass;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class Order extends Model
{
use SoftDeletes;
protected $connection = 'ecpass';
protected $table = 'order';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
}
<?php
declare(strict_types=1);
namespace App\Model\Ecpass;
use App\Model\Model;
class OrderStatistics extends Model
{
protected $connection = 'ecpass';
protected $table = 'order_statistics';
const CREATED_AT = null;
const UPDATED_AT = null;
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
/**
* @property-read $plan
* @property-read \App\Model\Marketing\Template $template
*/
class Activity extends Model
{
use SoftDeletes;
protected $connection = 'brand';
/**
* 时间维护 创建 更新 删除
*/
const CREATED_AT = 'created_time';
const UPDATED_AT = 'last_change_time';
const DELETED_AT = 'deleted_time';
const IS_OPEN_ENABLE = 1;
const IS_OPEN_DISABLE = 0;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_activitys';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'brand_id', 'activity_name', 'activity_type', 'sort_level', 'status', 'start_time', 'end_time', 'template_uuid', 'award_type', 'remarks', 'is_rule', 'rule_title', 'rule_content',
'is_open_collect_data', 'open_collect_data', 'is_stint_first', 'is_stint_join', 'stint_join_data', 'is_stint_user', 'stint_user_data', 'is_stint_area', 'stint_area_data', 'is_stint_flee_goods', 'is_many_awards', 'many_awards_data', 'is_ploy', 'ploy_remark',
'state', 'created_time', 'created_by_id', 'last_change_time', 'change_by_id', 'deleted_time', 'deleted_by_id', 'activity_photo_id'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'start_time' => 'datetime:Y-m-d H:i:s',
'end_time' => 'datetime:Y-m-d H:i:s',
'created_time' => 'datetime:Y-m-d H:i:s',
'open_collect_data' => 'json',
'stint_join_data' => 'json',
'stint_user_data' => 'json',
'stint_area_data' => 'json',
'many_awards_data' => 'json',
];
/**
* 活动ID
*
* @return void
*/
public function getActivityIdAttribute()
{
return $this->id;
}
/**
* 活动状态的标识 status_title
*/
public function getStatusTitleAttribute()
{
if ($this->is_open == self::IS_OPEN_DISABLE) {
return '已禁用';
}
$arr = [
'1' => '未开始',
'2' => '进行中',
'3' => '已结束',
'4' => '已禁用',
];
return $arr[$this->status] ?? '未开始';
}
/**
* 活动模板关联
*/
public function template()
{
return $this->hasOne(Template::class, 'template_uuid', 'template_uuid');
}
/**
* 获取活动范围 range
* @return array
*/
public function range()
{
return $this->hasMany(CodeLog::class, 'activity_id', 'id');
}
/**
* 获取活动进度 plan
* @return int
*/
public function getPlanAttribute()
{
$now_time = time();
$end_time = strtotime($this->end_time->format('Y-m-d H:i:s'));
$start_time = strtotime($this->start_time->format('Y-m-d H:i:s'));
if ($now_time < $start_time) {
return 0;
}
if ($now_time > $end_time) {
return 100;
}
return intval(($now_time - $start_time) / ($end_time - $start_time) * 100);
}
}
<?php
declare (strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
/**
* 黑名单
*/
class Blacklist extends Model
{
use SoftDeletes;
/**
* 时间维护 创建 更新 删除
*/
const CREATED_AT = 'created_time';
const UPDATED_AT = 'last_change_time';
const DELETED_AT = 'deleted_time';
protected $connection = 'brand';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_blacklists';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'blacklist_limit_start' => 'datetime:Y-m-d H:i:s',
'blacklist_limit_end' => 'datetime:Y-m-d H:i:s',
'releasing_time' => 'datetime:Y-m-d H:i:s',
];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
use App\Model\Brand\Member;
use App\Model\Brand\Product;
use App\Model\Marketing\Activity;
use Hyperf\Database\Model\SoftDeletes;
/**
* 扫码明细
*/
class Scan extends Model
{
// use SoftDeletes;
/**
* 时间维护 创建 更新 删除
*/
const CREATED_AT = 'created_time';
const UPDATED_AT = 'last_change_time';
// const DELETED_AT = 'deleted_time';
protected $connection = 'brand';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_scans';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'fw_first_time' => 'datetime:Y-m-d H:i:s',
'first_time' => 'datetime:Y-m-d H:i:s',
'created_time' => 'datetime:Y-m-d H:i:s',
];
/**
* 活动关联 activity
*/
public function activity()
{
return $this->hasOne(Activity::class, 'id', 'activity_id');
}
/**
* 关联 member
*/
public function member()
{
return $this->hasOne(Member::class, 'id', 'member_id');
}
/**
* 关联产品
*/
public function product()
{
return $this->hasOne(Product::class, 'id', 'product_id');
}
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
use Hyperf\Utils\Arr;
use App\Model\Brand\Member;
use Hyperf\Database\Model\SoftDeletes;
/**
* 活动参与记录
*/
class ScanAward extends Model
{
use SoftDeletes;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_scan_awards';
protected $connection = 'brand';
protected $guarded = [];
/**
* 时间维护 创建 更新 删除
*/
const CREATED_AT = 'created_time';
const UPDATED_AT = 'last_change_time';
const DELETED_AT = 'deleted_time';
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'created_time' => 'datetime:Y-m-d H:i:s',
'point_info' => 'json',
'bonus_info' => 'json',
'gift_info' => 'json',
'receiv_info' => 'json',
'express_info' => 'json'
];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
/**
* 活动统计
*/
class ScanAwardStatistics extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_scan_award_statistics';
protected $connection = 'brand';
protected $guarded = [];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
/**
* 扫码统计
*/
class ScanStatistics extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_scan_statistics';
protected $connection = 'brand';
protected $guarded = [];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
/**
* 扫码统计(省)
*/
class StatisticsScan extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_statistics_scan';
protected $connection = 'marketing';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = [];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
/**
* 扫码统计
*/
class StatisticsScanActivity extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_statistics_scan_activity';
protected $connection = 'marketing';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = [];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
/**
* 扫码统计
*/
class StatisticsScanActivityProduct extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_statistics_scan_activity_product';
protected $connection = 'marketing';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = [];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
/**
* 扫码统计(市)
*/
class StatisticsScanCity extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_statistics_scan_city';
protected $connection = 'marketing';
protected $guarded = [];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
/**
* 扫码统计(区)
*/
class StatisticsScanDistrict extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_statistics_scan_district';
protected $connection = 'marketing';
protected $guarded = [];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
/**
* 扫码统计(省)
*/
class StatisticsScanProduct extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_statistics_scan_product';
protected $connection = 'marketing';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = [];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
/**
* 扫码统计(省)
*/
class StatisticsScanProvince extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_statistics_scan_province';
protected $connection = 'marketing';
protected $guarded = [];
}
<?php
declare(strict_types=1);
namespace App\Model\Marketing;
use App\Model\Model;
/**
* 扫码统计
*/
class StatisticsScanStore extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'fw_statistics_scan_store';
protected $connection = 'marketing';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = [];
}
<?php
declare ( strict_types=1 );
namespace App\Model\Member;
use App\Model\Model;
class MemberRelationTag extends Model
{
protected $connection = 'member';
protected $table = 'member_relation_tag';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
protected $dateFormat = 'U';
protected $guarded = [];
}
<?php
declare ( strict_types=1 );
namespace App\Model\Member;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class MemberTag extends Model
{
use SoftDeletes;
protected $connection = 'member';
protected $table = 'member_tag';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
protected $dateFormat = 'U';
}
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Model;
use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model as BaseModel;
abstract class Model extends BaseModel
{
public static function getTableName()
{
$table = (new static())->getTable();
return $table;
}
//批量更新
public static function updateBatch($multipleData = [], $connection = 'default')
{
try {
if (empty($multipleData)) {
throw new \Exception("数据不能为空");
}
$tableName =Db::connection($connection)->getTablePrefix(). (new static())->getTable(); // 表名
$firstRow = current($multipleData);
$updateColumn = array_keys($firstRow);
// 默认以id为条件更新,如果没有ID则以第一个字段为条件
$referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
unset($updateColumn[0]);
// 拼接sql语句
$updateSql = "UPDATE " . $tableName . " SET ";
$sets = [];
$bindings = [];
$whereIn = '';
foreach ($updateColumn as $uColumn) {
$setSql = "`" . $uColumn . "` = CASE";
foreach ($multipleData as $data) {
$setSql .= " WHEN `" . $referenceColumn . "` = ".$data[$referenceColumn]." THEN ".$data[$uColumn];
$whereIn .= $data[$referenceColumn].',';
$bindings[] = $data[$referenceColumn];
$bindings[] = $data[$uColumn];
}
$setSql .= " ELSE `" . $uColumn . "` END ";
$sets[] = $setSql;
}
$updateSql .= implode(', ', $sets);
//$whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all();
//$bindings = array_merge($bindings, $whereIn);
$whereIn = rtrim($whereIn, ',');
$updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
// 传入预处理sql语句和对应绑定数据
//logger()->info('updateBatchSQL',[$updateSql]);
return DB::connection($connection)->update($updateSql);
} catch (\Exception $e) {
logger()->error('updateBatchSQL',[$e->getMessage()]);
return false;
}
}
/**
* 插入多条
*
* @param $saveData
* @return bool
*/
public static function insertAll( $saveData )
{
return self::insert( $saveData );
}
const updateTmplate = 'INSERT INTO %s (%s) VALUES %s ON DUPLICATE KEY UPDATE %s';
/**
* 根据唯一键进行覆盖更新
*/
public static function mutilDuplicateInsert(array $multipleData, $connection = 'default')
{
try {
if (empty($multipleData)) {
return;
}
$table = Db::connection($connection)->getTablePrefix(). (new static())->getTable(); // 表名
$firstRow = current($multipleData);
$keyStr = '';
$valStr = '';
$updateStr = '';
$key = array_keys($firstRow);
for ($i = 0; $i < count($key); $i++) {
$keyStr .= "`{$key[$i]}`,";
$updateStr .= "`{$key[$i]}` = values(`{$key[$i]}`),";
}
$newVal = 0;
foreach ($multipleData as $k => $v) {
$tmpValStr = '(';
$vv = $v instanceof \stdClass ? get_object_vars($v) : $v;
foreach ($firstRow as $key => $val) {
if (isset($vv[$key])) {
$newVal = $vv[$key];
$newVal = empty($newVal) ? 0 : $newVal;
}
$tmpValStr .= "'{$newVal}',";
}
$tmpValStr = substr($tmpValStr, 0, -1) . '),';
$valStr .= $tmpValStr;
}
$sql = sprintf(self::updateTmplate, $table, trim($keyStr, ','), trim($valStr, ','), trim($updateStr, ","));
return DB::connection($connection)->insert($sql);
} catch (\Exception $e) {
logger()->error('mutilDuplicateInsert',[$e->getMessage()]);
return false;
}
}
}
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class AssetsPointLog extends Model
{
protected $connection = 'reimbursement';
protected $table = 'assets_point_log';
public $timestamps = false;
protected $guarded = [];
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class AssetsStatistics extends Model
{
protected $connection = 'reimbursement';
protected $table = 'assets_statistics';
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
protected $dateFormat = 'U';
protected $guarded = [];
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class GeneralProductBatchStockStatistcs extends Model
{
protected $connection = 'reimbursement';
protected $table = 'fch_statistics_general_product_batch_stock';
public $timestamps = false;
protected $guarded = [];
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class GeneralProductStockStatistcs extends Model
{
protected $connection = 'reimbursement';
protected $table = 'fch_statistics_general_product_stock';
public $timestamps = false;
protected $guarded = [];
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class GeneralProductWarehouseStockStatistcs extends Model
{
protected $connection = 'reimbursement';
protected $table = 'fch_statistics_general_product_warehouse_stock';
public $timestamps = false;
protected $guarded = [];
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class OutWarehouseStatistics extends Model
{
protected $connection = 'reimbursement';
protected $table = 'fch_statistics_outwarehouse_stat';
public $timestamps = false;
protected $guarded = [];
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class OutWarehouseStatisticsYear extends Model
{
protected $connection = 'reimbursement';
protected $table = 'fch_statistics_outwarehouse_stat_year';
public $timestamps = false;
protected $guarded = [];
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class OutWarehousing extends Model
{
use SoftDeletes;
protected $connection = 'reimbursement';
protected $table = 'fch_out_warehousing';
protected $guarded = [];
/** 出库类型 经销商 */
const OUT_WAREHOUSING_TYPE_DEALER = 1;
/** 出库类型 门店 */
const OUT_WAREHOUSING_TYPE_STORE = 2;
/** 出库类型 运营商 */
const OUT_WAREHOUSING_TYPE_OPERATOR = 3;
/** 出库类型 零售 */
const OUT_WAREHOUSING_TYPE_RETAIL = 5;
/** @var int 待出货 */
const STATUS_TO_BE_OUT = 1;
/** @var int 已出货 */
const STATUS_OUTED = 2;
/** @var int 已签收 */
const STATUS_SING_IN = 3;
/** @var int 已关闭 */
const STATUS_CLOSE = 4;
/** @var int 未扫码 */
const SCAN_STATUS_NO = 0;
/** @var int 出库扫码中 */
const SCAN_STATUS_ING = 1;
/** @var int 已出库 */
const SCAN_STATUS_YES = 2;
/** @var int 快速出库 */
const CREATE_TYPE_FAST = 1;
/** @var int 按单出库 */
const CREATE_TYPE_NORMAL = 2;
/** @var int 区间出库 */
const CREATE_TYPE_RANGE = 3;
const OUT_WAREHOUSING_STATUS_TEXT = [
self::STATUS_TO_BE_OUT => '待出货',
self::STATUS_OUTED => '已出货',
self::STATUS_SING_IN => '已签收',
self::STATUS_CLOSE => '已关闭',
];
//收货方用
const OUT_WAREHOUSING_CHANNEL_STATUS_TEXT = [
self::STATUS_TO_BE_OUT => '待出货',
self::STATUS_OUTED => '待签收',
self::STATUS_SING_IN => '已签收',
self::STATUS_CLOSE => '已关闭',
];
const CREATE_TYPE_TEXT = [
self::CREATE_TYPE_FAST => '快速出库',
self::CREATE_TYPE_NORMAL => '按单出库',
self::CREATE_TYPE_RANGE => '区间出库',
];
const IS_ALLOCATION_TEXT = [
1 => '调拨出货单',
0 => '普通出货单',
2 => '跨级出货单',
];
const OUT_OBJECT_TYPE_TEXT = [
1 => '经销商',
2 => '门店',
3 => '运营商',
4 => '外部对象',
];
/** @var int 系统自建 */
const SOURCE_TYPE_SYS = 0;
/** @var int ERP同步 */
const SOURCE_TYPE_ERP = 1;
/** @var int 导入的 */
const SOURCE_TYPE_IMPORT = 2;
/** @var int 订货商城同步的 */
const SOURCE_TYPE_ONLINE = 3;
const SOURCE_TYPE_TEXT = [
self::SOURCE_TYPE_SYS => '系统自建',
self::SOURCE_TYPE_ERP => 'ERP同步',
self::SOURCE_TYPE_IMPORT => '导入',
self::SOURCE_TYPE_ONLINE => '订货商城同步',
];
}
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\ShardingModel;
use Hyperf\Database\Model\SoftDeletes;
class OutWarehousingCode extends ShardingModel
{
use SoftDeletes;
protected $table = 'fch_out_warehousing_code';
protected $guarded = [];
const CODE_TYPE_TEXT = [
1 => '大标',
2 => '中标',
3 => '小标',
];
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class RefundWarehouseStatistics extends Model
{
protected $connection = 'reimbursement';
protected $table = 'fch_statistics_refundwarehouse_stat';
public $timestamps = false;
protected $guarded = [];
}
\ No newline at end of file
<?php
declare ( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class RefundWarehouseStatisticsYear extends Model
{
protected $connection = 'reimbursement';
protected $table = 'fch_statistics_refundwarehouse_stat_year';
public $timestamps = false;
protected $guarded = [];
}
<?php
declare ( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Brand\Dealer;
use App\Model\Brand\Store;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class RefundWarehousing extends Model
{
use SoftDeletes;
protected $connection = 'reimbursement';
protected $table = 'fch_refund_warehousing';
protected $guarded = [];
}
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class TransferWarehousing extends Model
{
use SoftDeletes;
protected $connection = 'reimbursement';
protected $table = 'fch_transfer_warehousing';
protected $guarded = [];
const TRANSFER_STATUS_TO_BE_ADJUSTRD = 1;
const TRANSFER_STATUS_ADJUSTRD = 2;
const TRANSFER_STATUS_CLOSE = 3;
const TRANSFER_STATUS_TEXT = [
self::TRANSFER_STATUS_TO_BE_ADJUSTRD => '待调仓',
self::TRANSFER_STATUS_ADJUSTRD => '已调仓',
self::TRANSFER_STATUS_CLOSE => '已关闭',
];
}
<?php
declare ( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class TransferWarehousingCode extends Model
{
use SoftDeletes;
protected $connection = 'reimbursement';
protected $table = 'fch_transfer_warehousing_code';
protected $guarded = [];
/** @var int 大标类型 */
const CODE_TYPE_BIG = 1;
/** @var int 中标类型 */
const CODE_TYPE_MIDDLE = 2;
/** @var int 小标类型 */
const CODE_TYPE_SMALL = 3;
/** @var string[] 码类型中文 */
const CODE_TYPE_TEXT_DATA = [
self::CODE_TYPE_BIG => '大标',
self::CODE_TYPE_MIDDLE => '中标',
self::CODE_TYPE_SMALL => '小标',
];
}
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class TransferWarehousingProduct extends Model
{
protected $connection = 'reimbursement';
protected $table = 'fch_transfer_warehousing_product';
protected $guarded = [];
public $timestamps = false;
}
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class WarehouseStatistics extends Model
{
protected $connection = 'reimbursement';
protected $table = 'fch_statistics_warehouse_stat';
public $timestamps = false;
protected $guarded = [];
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
class WarehouseStatisticsYear extends Model
{
protected $connection = 'reimbursement';
protected $table = 'fch_statistics_warehouse_stat_year';
public $timestamps = false;
protected $guarded = [];
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
class Warehousing extends Model
{
use SoftDeletes;
protected $connection = 'reimbursement';
protected $table = 'fch_warehousing';
protected $guarded = [];
/** @var int 扫码类型 正常扫码 */
const SCAN_TYPE_NORMAL = 1;
/** @var int 扫码类型 回退扫码 */
const SCAN_TYPE_BACK = 2;
/** @var int 不使用生产批次入库 */
const USE_PRODUCT_BACH_NO = 0;
/** @var int 使用生产批次入库 */
const USE_PRODUCT_BACH_YES = 1;
/** @var int 快速入库 */
const CREATE_TYPE_FAST = 1;
/** @var int 按单入库 */
const CREATE_TYPE_NORMAL = 2;
/** @var int 区间入库 */
const CREATE_TYPE_RANGE = 3;
/** @var int 计划单入库 */
const CREATE_TYPE_PLAN_NO = 4;
const CREATE_TYPE_TEXT = [
self::CREATE_TYPE_FAST => '快速入库',
self::CREATE_TYPE_NORMAL => '按单入库',
self::CREATE_TYPE_RANGE => '区间入库',
self::CREATE_TYPE_PLAN_NO => '计划单入库',
];
}
<?php
declare ( strict_types=1 );
namespace App\Model\Reimbursement;
use App\Model\ShardingModel;
use Hyperf\Database\Model\SoftDeletes;
class WarehousingCode extends ShardingModel
{
use SoftDeletes;
protected $table = 'fch_warehousing_code';
protected $guarded = [];
/** @var int 大标类型 */
const CODE_TYPE_BIG = 1;
/** @var int 中标类型 */
const CODE_TYPE_MIDDLE = 2;
/** @var int 小标类型 */
const CODE_TYPE_SMALL = 3;
/** @var string[] 码类型中文 */
const CODE_TYPE_TEXT_DATA = [
self::CODE_TYPE_BIG => '大标',
self::CODE_TYPE_MIDDLE => '中标',
self::CODE_TYPE_SMALL => '小标',
];
}
<?php
declare( strict_types=1 );
namespace App\Model;
use App\Model\Model;
use App\Constants\Cache\CacheDatabaseConstants;
class ShardingModel extends Model
{
public function __construct(array $attributes = [])
{
$brandAuth = get_auth_brand();
if ($brandAuth) {
$brandId = $brandAuth->brandId();
$tableName = '';
try {
$brandShardingIns = \CommonCacheSdk\BrandShardingCache::getInstance(get_cache_container( CacheDatabaseConstants::SHARDING));
$tableName = $brandShardingIns->getTableName($brandId, $this->table);
} catch (\Exception $e) {
logger('ShardingModel')->error('RedisError: ' . $e->getMessage());
}
if (!empty($tableName)) {
$this->setTable($tableName);
}
}
parent::__construct($attributes);
}
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Model;
use Hyperf\Database\Model\SoftDeletes;
/**
* 提货卷
* Class Vouchers
* @package App\Model\Vouchers
*/
class Vouchers extends Model
{
use SoftDeletes;
protected $connection = 'brand';
protected $name = 'vouchers';
/**
* 时间维护 创建 更新 删除
*/
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
const DELETED_AT = 'delete_time';
}
<?php
declare ( strict_types=1 );
namespace App\Queue;
use App\Job\OrderAfter\GroupJob;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\AsyncQueue\Driver\DriverInterface;
class GroupQueue
{
/**
* @var DriverInterface
*/
protected $driver;
public function __construct( DriverFactory $driverFactory )
{
$this->driver = $driverFactory->get( 'activity' );
}
/**
* 拼团失效处理
* @param array $params
* @param int $delay 延时单位 秒
* @return bool
*/
public function pushGroupJob( array $params, int $delay = 0 ): bool
{
return $this->driver->push( new GroupJob( $params ), $delay );
}
}
<?php
declare(strict_types=1);
namespace App\Repository\Member;
use App\Model\Brand\Member;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use App\Model\Brand\PointUserLog;
class MemberPointRepository
{
public static function execSingleBrand($brand_id,$yester_year,$point_is_clear)
{
$logger = di(LoggerFactory::class)->get('clear_point', 'clear_point');
try {
$time = time();
$logger->info('品牌商-'.$brand_id.'-'.date('Y-m-d H:i:s'));
// 获取 需要清理的用户
Member::query()
->select(['id','point'])
->where( 'brand_id', $brand_id )
->where('point', '>', 0 )
->with([
'pointLog'=>function($q)use($brand_id,$yester_year){
$q->where('brand_id',$brand_id)
->where('take_effect_time','>=',$yester_year)
->where('action',1)
->where('type','!=',11)
->select(Db::raw( "sum(point) as valid_point_num,user_id"))
->groupBy('user_id');
}])
->chunkById(2000, function ($list) use ( $brand_id,$logger,$point_is_clear,$time ) {
$log = $update = [];
foreach ($list as $item) {
$user_point_num = 0;
$valid_point_num = $item['pointLog'][0]['valid_point_num'] ?? 0;
if($point_is_clear == 2){
//清除所有的数据,valid_point_num是今年的数据,存在积分,不能扣减
if($valid_point_num){
$user_point_num = $item->point - $valid_point_num;
}else{
$user_point_num = $item->point;
}
}elseif($item->point > $valid_point_num){
//积分保留一年,清除上上年的积分
$user_point_num = $item->point - $valid_point_num;
}
if($user_point_num){
$log[] = [
'brand_id' => $brand_id,
'user_id' => $item->id,
'type' => 16,
'action' => 2,
'point' => (int)$user_point_num,
'unique_id' => '',
'remark' => '定时积分清理',
'create_time' => $time,
'update_time' => $time,
];
$update[] = [
'id' => $item->id,
'point' => "`point` - {$user_point_num}"
];
}
}
if($update){
$info_data = array_chunk($update,1000);
foreach($info_data as $in){
$logger->info('积分清理扣除',$in);
}
if(Member::updateBatch($update,'brand')){
PointUserLog::insert($log);
}
}
});
}catch(\Exception | \Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "积分清理任务异常:".$brand_id, [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
}
<?php
declare(strict_types=1);
namespace App\Repository\Reimbursement;
use \Carbon\Carbon;
class BaseStockStatisticsRepository
{
public $startTime = null;
public $endTime = null;
public $day = null;
const beforeDay = 30;
protected $beforeDayFlag = false;
public function setBeforeDayModel($beforeDayFlag = true)
{
$this->beforeDayFlag = $beforeDayFlag;
return $this;
}
protected function getTimeInfo()
{
if ($this->beforeDayFlag) {
$startTime = $this->startTime ? $this->changeTimeInfo($this->startTime, self::beforeDay): $this->prevTimeInfo();
$endTime = $this->startTime ? $this->changeTimeInfo($this->startTime, self::beforeDay, 'Y-m-d 23:59:50') : $this->prevTimeInfo();
} else {
$startTime = $this->startTime ? $this->startTime : $this->prevTimeInfo();
$endTime = $this->endTime ? $this->endTime : $this->prevTimeInfo();
}
$this->day = date('Ymd', strtotime($startTime));
return [$startTime, $endTime];
}
protected function changeTimeInfo($dateTime, $beforeDay, $format = 'Y-m-d 00:00:00')
{
$timeInfo = Carbon::parse($dateTime, 'Asia/Shanghai')->subDays($beforeDay)->startOfDay()->rawFormat($format);
return $timeInfo;
}
protected function prevTimeInfo()
{
$preDayStr = ($this->beforeDayFlag ? self::beforeDay : 1 );
$timeInfo = Carbon::now('Asia/Shanghai')->subDays($preDayStr)->startOfDay()->rawFormat('Y-m-d 00:00:00');
return $timeInfo;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Repository\Reimbursement;
use Hyperf\DbConnection\Db;
use App\Model\Reimbursement\WarehouseStatistics;
use App\Model\Reimbursement\OutWarehouseStatistics;
use App\Model\Reimbursement\GeneralProductBatchStockStatistcs;
use App\Repository\Reimbursement\BaseStockStatisticsRepository;
class GeneralProductBatchStockStatisticsRepository extends BaseStockStatisticsRepository
{
public $brandId = 0;
const keyTmp = "%s%s%s%s";
/**
* 设置时间 便于指定时间统计
*
* @param string $startTime
* @param string $endTime
* @return BrandConsumeTask
*/
public function setBrandId($brandId)
{
$this->brandId = $brandId;
return $this;
}
public function setTime($day)
{
$this->startTime = date('Y-m-d 00:00:00', strtotime($day));
$this->endTime = date('Y-m-d 23:59:59', strtotime($day));
return $this;
}
public function entry()
{
if ($this->brandId == 0) {
throw new \Exception('品牌商ID 为空');
}
@list($startTime, $endTime) = $this->getTimeInfo();
$product_list = [];
// 入库数据
$warehousingData = $this->warehousingInfo($startTime, $endTime);
$this->getProductInfo($warehousingData, $product_list);
// 出货数据
$outwarehousingData = $this->outwarehousingInfo($startTime, $endTime);
$this->getProductInfo($outwarehousingData, $product_list);
$this->insertData($product_list);
}
// 数据写入
private function insertData($productList)
{
GeneralProductBatchStockStatistcs::mutilDuplicateInsert($productList, 'reimbursement');
}
// 获取产品数据
private function getProductInfo($data, &$product_list)
{
foreach ($data as $item) {
$key = sprintf(self::keyTmp, $item['product_batch_id'], $item['product_id'], $item['product_sn'], $item['product_sku_sn']);
if (isset($product_list[$key])) {
$product_list[$key]['warehouse_num'] += $item['warehouse_num'] ?? 0;
$product_list[$key]['out_warehouse_num'] += $item['out_warehouse_num'] ?? 0;
$product_list[$key]['out_warehouse_middle_code_num'] += $item['out_warehouse_middle_code_num'] ?? 0;
$product_list[$key]['out_warehouse_big_code_num'] += $item['out_warehouse_big_code_num'] ?? 0;
} else {
$product_list[$key] = [
'brand_id' => $item['brand_id'],
'day' => $this->day,
'product_id'=> $item['product_id'],
'product_sku_sn'=> $item['product_sku_sn'],
'product_sn' => $item['product_sn'],
'warehouse_num' => $item['warehouse_num'] ?? 0,
'out_warehouse_num' => $item['out_warehouse_num'] ?? 0,
'out_warehouse_middle_code_num' => $item['out_warehouse_middle_code_num'] ?? 0,
'out_warehouse_big_code_num' => $item['out_warehouse_big_code_num'] ?? 0,
'product_batch_id' => $item['product_batch_id'] ?? 0,
];
}
}
}
// 入库数据
private function warehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$warehousingData = WarehouseStatistics::where('brand_id', $this->brandId)
->whereBetween('day', [$startTime, $endTime])
->where('product_batch_id', '>', 0)
->groupBy('brand_id', 'day', 'product_batch_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'product_batch_id', 'product_id', 'product_sn', 'product_sku_sn',
Db::raw("SUM(nums) AS warehouse_num"),
)
->get();
return $warehousingData;
}
// 总部出库数据
private function outwarehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$outwarehousingData = OutWarehouseStatistics::where('brand_id', $this->brandId)
->whereBetween('day', [$startTime, $endTime])
->where('out_warehousing_from_id', 0)
->where('product_batch_id', '>', 0)
->groupBy('brand_id', 'day', 'product_batch_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'product_batch_id',
'product_id',
'product_sn',
'product_sku_sn',
Db::raw( 'SUM(out_warehousing_nums) as out_warehouse_num' ),
Db::raw("SUM(out_middle_code_nums) AS out_warehouse_middle_code_num"),
Db::raw("SUM(out_big_code_nums) AS out_warehouse_big_code_num"),
)
->get();
return $outwarehousingData;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Repository\Reimbursement;
use Hyperf\DbConnection\Db;
use App\Model\Reimbursement\WarehouseStatisticsYear;
use App\Model\Reimbursement\OutWarehouseStatisticsYear;
use App\Model\Reimbursement\GeneralProductBatchStockStatistcs;
class GeneralProductBatchStockStatisticsYearRepository
{
public $startTime = null;
public $endTime = null;
public $year = null;
public $brandId = 0;
const keyTmp = "%s%s%s%s%s";
/**
* 设置时间 便于指定时间统计
*
* @param string $startTime
* @param string $endTime
* @return BrandConsumeTask
*/
public function setBrandId($brandId)
{
$this->brandId = $brandId;
return $this;
}
public function setTime($year)
{
$this->startTime = sprintf('%s-01-01 00:00:00', $year);
$this->endTime = sprintf('%s-12-31 23:59:59', $year);
$this->year = $year;
return $this;
}
public function entry()
{
if ($this->brandId == 0) {
throw new \Exception('品牌商ID 为空');
}
$startTime = $this->startTime ? $this->startTime : strtotime( '-1 day');
$endTime = $this->endTime ? $this->endTime : strtotime( '-1 day');
$product_list = [];
// 入库数据
$warehousingData = $this->warehousingInfo($startTime, $endTime);
$this->getProductInfo($warehousingData, $product_list);
// 出货数据
$outwarehousingData = $this->outwarehousingInfo($startTime, $endTime);
$this->getProductInfo($outwarehousingData, $product_list);
$this->insertData($product_list);
}
// 数据写入
private function insertData($productList)
{
GeneralProductBatchStockStatistcs::mutilDuplicateInsert($productList, 'reimbursement');
}
// 获取产品数据
private function getProductInfo($data, &$product_list)
{
foreach ($data as $item) {
$key = sprintf(self::keyTmp, $item['day'],$item['product_batch_id'], $item['product_id'], $item['product_sn'], $item['product_sku_sn']);
if (isset($product_list[$key])) {
$product_list[$key]['warehouse_num'] += $item['warehouse_num'] ?? 0;
$product_list[$key]['out_warehouse_num'] += $item['out_warehouse_num'] ?? 0;
} else {
$product_list[$key] = [
'brand_id' => $item['brand_id'],
'day' => $item['day'],
'product_id'=> $item['product_id'],
'product_sku_sn'=> $item['product_sku_sn'],
'product_sn' => $item['product_sn'],
'warehouse_num' => $item['warehouse_num'] ?? 0,
'out_warehouse_num' => $item['out_warehouse_num'] ?? 0,
'product_batch_id' => $item['product_batch_id'] ?? 0,
];
}
}
}
// 入库数据
private function warehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$warehousingData = WarehouseStatisticsYear::where('brand_id', $this->brandId)
->where('day', $this->year)
->where('product_batch_id', '>', 0)
->groupBy('brand_id', 'day', 'product_batch_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'product_batch_id', 'product_id', 'product_sn', 'product_sku_sn',
Db::raw("SUM(nums) AS warehouse_num"),
)
->get();
return $warehousingData;
}
// 总部出库数据
private function outwarehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$outwarehousingData = OutWarehouseStatisticsYear::where('brand_id', $this->brandId)
->where('day', $this->year)
->where('out_warehousing_from_id', 0)
->where('product_batch_id', '>', 0)
->groupBy('brand_id', 'day', 'product_batch_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'product_batch_id',
'product_id',
'product_sn',
'product_sku_sn',
Db::raw( 'SUM(out_warehousing_nums) as out_warehouse_num' )
)
->get();
return $outwarehousingData;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Repository\Reimbursement;
use Hyperf\DbConnection\Db;
use App\Model\Reimbursement\WarehouseStatistics;
use App\Model\Reimbursement\OutWarehouseStatistics;
use App\Model\Reimbursement\RefundWarehouseStatistics;
use App\Model\Reimbursement\TransferWarehousing;
use App\Model\Reimbursement\TransferWarehousingProduct;
use App\Model\Reimbursement\GeneralProductStockStatistcs;
use App\Repository\Reimbursement\BaseStockStatisticsRepository;
class GeneralProductStockStatisticsRepository extends BaseStockStatisticsRepository
{
public $brandId = 0;
const keyTmp = "%s%s%s%s";
/**
* 设置时间 便于指定时间统计
*
* @param string $startTime
* @param string $endTime
* @return BrandConsumeTask
*/
public function setBrandId($brandId)
{
$this->brandId = $brandId;
return $this;
}
public function setTime($day)
{
$this->startTime = date('Y-m-d 00:00:00', strtotime($day));
$this->endTime = date('Y-m-d 23:59:59', strtotime($day));
return $this;
}
public function entry()
{
if ($this->brandId == 0) {
throw new \Exception('品牌商ID 为空');
}
@list($startTime, $endTime) = $this->getTimeInfo();
$product_list = [];
// 入库数据
$warehousingData = $this->warehousingInfo($startTime, $endTime);
$this->getProductInfo($warehousingData, $product_list);
// 总部调仓入库数据
$transferToWarehousingData = $this->transferToWarehousingInfo($startTime, $endTime);
$this->getProductInfo($transferToWarehousingData, $product_list);
// 退货数据
$refundwarehousData = $this->refundwarehousInfo($startTime, $endTime);
$this->getProductInfo($refundwarehousData, $product_list);
// 出货数据
$outwarehousingData = $this->outwarehousingInfo($startTime, $endTime);
$this->getProductInfo($outwarehousingData, $product_list);
// 总部调仓出库数据
$transferFromWarehousingData = $this->transferFromWarehousingInfo($startTime, $endTime);
$this->getProductInfo($transferFromWarehousingData, $product_list);
$this->insertData($product_list);
}
// 数据写入
private function insertData($productList)
{
GeneralProductStockStatistcs::mutilDuplicateInsert($productList, 'reimbursement');
}
// 获取产品数据
private function getProductInfo($data, &$product_list)
{
foreach ($data as $item) {
$key = sprintf(self::keyTmp, $item['warehouse_id'], $item['product_id'], $item['product_sn'], $item['product_sku_sn']);
if (isset($product_list[$key])) {
$product_list[$key]['warehouse_num'] += $item['warehouse_num'] ?? 0;
$product_list[$key]['out_warehouse_num'] += $item['out_warehouse_num'] ?? 0;
$product_list[$key]['out_warehouse_middle_code_num'] += $item['out_warehouse_middle_code_num'] ?? 0;
$product_list[$key]['out_warehouse_big_code_num'] += $item['out_warehouse_big_code_num'] ?? 0;
$product_list[$key]['refund_warehouse_num'] += $item['refund_warehouse_num'] ?? 0;
$product_list[$key]['transfer_to_warehouse_num'] += $item['transfer_to_warehouse_num'] ?? 0;
$product_list[$key]['transfer_from_warehouse_num'] += $item['transfer_from_warehouse_num'] ?? 0;
} else {
$product_list[$key] = [
'brand_id' => $item['brand_id'],
'day' => $this->day,
'warehouse_id' => $item['warehouse_id'] ?? '0',
'product_id'=> $item['product_id'],
'product_sku_sn'=> $item['product_sku_sn'],
'product_sn' => $item['product_sn'],
'warehouse_num' => $item['warehouse_num'] ?? 0,
'out_warehouse_num' => $item['out_warehouse_num'] ?? 0,
'out_warehouse_middle_code_num' => $item['out_warehouse_middle_code_num'] ?? 0,
'out_warehouse_big_code_num' => $item['out_warehouse_big_code_num'] ?? 0,
'refund_warehouse_num' => $item['refund_warehouse_num'] ?? 0,
'transfer_to_warehouse_num' => $item['transfer_to_warehouse_num'] ?? 0,
'transfer_from_warehouse_num' => $item['transfer_from_warehouse_num'] ?? 0,
];
}
}
}
// 退货数据
private function refundwarehousInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$refundwarehousData = RefundWarehouseStatistics::where('brand_id', $this->brandId)
->whereBetween('day', [$startTime, $endTime])
->where('refund_to_id', 0)
->groupBy('brand_id', 'day', 'refund_warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'refund_warehouse_id as warehouse_id',
'product_id',
'product_sn',
'product_sku_sn',
Db::raw( 'SUM(nums) as refund_warehouse_num' )
)
->get();
return $refundwarehousData;
}
// 入库数据
private function warehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$warehousingData = WarehouseStatistics::where('brand_id', $this->brandId)
->whereBetween('day', [$startTime, $endTime])
->groupBy('brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn',
Db::raw("SUM(nums) AS warehouse_num"),
)
->get();
return $warehousingData;
}
// 总部出库数据
private function outwarehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$outwarehousingData = OutWarehouseStatistics::where('brand_id', $this->brandId)
->whereBetween('day', [$startTime, $endTime])
->where('out_warehousing_from_id', 0)
->groupBy('brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'warehouse_id',
'product_id',
'product_sn',
'product_sku_sn',
Db::raw('SUM(out_warehousing_nums) as out_warehouse_num'),
Db::raw("SUM(out_middle_code_nums) AS out_warehouse_middle_code_num"),
Db::raw("SUM(out_big_code_nums) AS out_warehouse_big_code_num"),
)
->get();
return $outwarehousingData;
}
// 总部调仓入库
private function transferToWarehousingInfo($startTime, $endTime)
{
//总部调仓给它的
$transfer_to_query = TransferWarehousingProduct::query()
->selectRaw( "product_id,product_sku_sn,product_sn,
transfer_warehousing_sn,
SUM( transfer_warehousing_real_num ) AS transfer_warehousing_real_num " )
->where( 'brand_id', $this->brandId );
$transfer_to_query->groupBy( 'transfer_warehousing_sn', 'product_id', 'product_sku_sn' );
$transferToWarehousing = TransferWarehousing::query()
->joinSub( $transfer_to_query, 'product', function ( $join ) {
$join->on( 'fch_transfer_warehousing.transfer_warehousing_sn', '=', 'product.transfer_warehousing_sn' );
} )
->whereIn( 'transfer_status', [1,2])
->where('fch_transfer_warehousing.brand_id', $this->brandId)
->whereBetween('fch_transfer_warehousing.created_at', [$startTime, $endTime])
->select(
'fch_transfer_warehousing.brand_id',
'product_id',
'transfer_to_warehouse_id as warehouse_id',
Db::raw("DATE_FORMAT(ydd_fch_transfer_warehousing.created_at,'%Y%m%d') as day"),
'product_sku_sn',
'product_sn',
Db::raw( 'SUM(transfer_warehousing_real_num) as transfer_to_warehouse_num' )
)
->groupBy('brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->get();
return $transferToWarehousing;
}
// 总部从它这里调仓出去的. 已经扫码的就相当于调仓出库的
private function transferFromWarehousingInfo($startTime, $endTime)
{
$transferFromWarehousing = TransferWarehousing::query()->join('fch_transfer_warehousing_code', 'fch_transfer_warehousing_code.transfer_warehousing_sn', '=', 'fch_transfer_warehousing.transfer_warehousing_sn')
->where('fch_transfer_warehousing.brand_id', $this->brandId)
->whereNull('fch_transfer_warehousing_code.deleted_at')
->whereIn( 'transfer_status', [1,2])
->whereBetween('fch_transfer_warehousing.created_at', [$startTime, $endTime])
->groupBy('fch_transfer_warehousing.brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'fch_transfer_warehousing.brand_id',
Db::raw("DATE_FORMAT(ydd_fch_transfer_warehousing.created_at,'%Y%m%d') as day"),
'fch_transfer_warehousing_code.transfer_warehouse_id as warehouse_id',
'product_id',
'product_sn',
'product_sku_sn',
Db::raw("SUM(ydd_fch_transfer_warehousing_code.code_num) AS transfer_from_warehouse_num")
)->get();
return $transferFromWarehousing;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Repository\Reimbursement;
use Hyperf\DbConnection\Db;
use App\Model\Reimbursement\WarehouseStatisticsYear;
use App\Model\Reimbursement\OutWarehouseStatisticsYear;
use App\Model\Reimbursement\RefundWarehouseStatisticsYear;
use App\Model\Reimbursement\TransferWarehousing;
use App\Model\Reimbursement\TransferWarehousingProduct;
use App\Model\Reimbursement\GeneralProductStockStatistcs;
class GeneralProductStockStatisticsYearRepository
{
public $startTime = null;
public $endTime = null;
public $year = null;
public $brandId = 0;
const keyTmp = "%s%s%s%s%s";
/**
* 设置时间 便于指定时间统计
*
* @param string $startTime
* @param string $endTime
* @return BrandConsumeTask
*/
public function setBrandId($brandId)
{
$this->brandId = $brandId;
return $this;
}
public function setTime($year)
{
$this->startTime = sprintf('%s-01-01 00:00:00', $year);
$this->endTime = sprintf('%s-12-31 23:59:59', $year);
$this->year = $year;
return $this;
}
public function entry()
{
if ($this->brandId == 0) {
throw new \Exception('品牌商ID 为空');
}
$startTime = $this->startTime ? $this->startTime : strtotime( '-1 day');
$endTime = $this->endTime ? $this->endTime : strtotime( '-1 day');
$product_list = [];
// 入库数据
$warehousingData = $this->warehousingInfo($startTime, $endTime);
$this->getProductInfo($warehousingData, $product_list);
// 总部调仓入库数据
$transferToWarehousingData = $this->transferToWarehousingInfo($startTime, $endTime);
$this->getProductInfo($transferToWarehousingData, $product_list);
// 退货数据
$refundwarehousData = $this->refundwarehousInfo($startTime, $endTime);
$this->getProductInfo($refundwarehousData, $product_list);
// 出货数据
$outwarehousingData = $this->outwarehousingInfo($startTime, $endTime);
$this->getProductInfo($outwarehousingData, $product_list);
// 总部调仓出库数据
$transferFromWarehousingData = $this->transferFromWarehousingInfo($startTime, $endTime);
$this->getProductInfo($transferFromWarehousingData, $product_list);
$this->insertData($product_list);
}
// 数据写入
private function insertData($productList)
{
GeneralProductStockStatistcs::mutilDuplicateInsert($productList, 'reimbursement');
}
// 获取产品数据
private function getProductInfo($data, &$product_list)
{
foreach ($data as $item) {
$key = sprintf(self::keyTmp, $item['day'], $item['warehouse_id'], $item['product_id'], $item['product_sn'], $item['product_sku_sn']);
if (isset($product_list[$key])) {
$product_list[$key]['warehouse_num'] += $item['warehouse_num'] ?? 0;
$product_list[$key]['out_warehouse_num'] += $item['out_warehouse_num'] ?? 0;
$product_list[$key]['refund_warehouse_num'] += $item['refund_warehouse_num'] ?? 0;
$product_list[$key]['transfer_to_warehouse_num'] += $item['transfer_to_warehouse_num'] ?? 0;
$product_list[$key]['transfer_from_warehouse_num'] += $item['transfer_from_warehouse_num'] ?? 0;
} else {
$product_list[$key] = [
'brand_id' => $item['brand_id'],
'day' => $item['day'],
'warehouse_id' => $item['warehouse_id'] ?? '0',
'product_id'=> $item['product_id'],
'product_sku_sn'=> $item['product_sku_sn'],
'product_sn' => $item['product_sn'],
'warehouse_num' => $item['warehouse_num'] ?? 0,
'out_warehouse_num' => $item['out_warehouse_num'] ?? 0,
'refund_warehouse_num' => $item['refund_warehouse_num'] ?? 0,
'transfer_to_warehouse_num' => $item['transfer_to_warehouse_num'] ?? 0,
'transfer_from_warehouse_num' => $item['transfer_from_warehouse_num'] ?? 0,
];
}
}
}
// 退货数据
private function refundwarehousInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$refundwarehousData = RefundWarehouseStatisticsYear::where('brand_id', $this->brandId)
->where('day', $this->year)
->where('refund_to_id', 0)
->groupBy('brand_id', 'day', 'refund_warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'refund_warehouse_id as warehouse_id',
'product_id',
'product_sn',
'product_sku_sn',
Db::raw( 'SUM(nums) as refund_warehouse_num' )
)
->get();
return $refundwarehousData;
}
// 入库数据
private function warehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$warehousingData = WarehouseStatisticsYear::where('brand_id', $this->brandId)
->where('day', $this->year)
->groupBy('brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn',
Db::raw("SUM(nums) AS warehouse_num"),
)
->get();
return $warehousingData;
}
// 总部出库数据
private function outwarehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$outwarehousingData = OutWarehouseStatisticsYear::where('brand_id', $this->brandId)
->where('day', $this->year)
->where('out_warehousing_from_id', 0)
->groupBy('brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'warehouse_id',
'product_id',
'product_sn',
'product_sku_sn',
Db::raw( 'SUM(out_warehousing_nums) as out_warehouse_num' )
)
->get();
return $outwarehousingData;
}
// 总部调仓入库
private function transferToWarehousingInfo($startTime, $endTime)
{
//总部调仓给它的
$transfer_to_query = TransferWarehousingProduct::query()
->selectRaw( "product_id,product_sku_sn,product_sn,
transfer_warehousing_sn,
SUM( transfer_warehousing_real_num ) AS transfer_warehousing_real_num " )
->where( 'brand_id', $this->brandId );
$transfer_to_query->groupBy( 'transfer_warehousing_sn', 'product_id', 'product_sku_sn' );
$transferToWarehousing = TransferWarehousing::query()
->joinSub( $transfer_to_query, 'product', function ( $join ) {
$join->on( 'fch_transfer_warehousing.transfer_warehousing_sn', '=', 'product.transfer_warehousing_sn' );
} )
->whereIn( 'transfer_status', [1,2])
->where('fch_transfer_warehousing.brand_id', $this->brandId)
->whereBetween('fch_transfer_warehousing.created_at', [$startTime, $endTime])
->select(
'fch_transfer_warehousing.brand_id',
'product_id',
'transfer_to_warehouse_id as warehouse_id',
Db::raw("DATE_FORMAT(ydd_fch_transfer_warehousing.created_at,'%Y') as day"),
'product_sku_sn',
'product_sn',
Db::raw( 'SUM(transfer_warehousing_real_num) as transfer_to_warehouse_num' )
)
->groupBy('brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->get();
return $transferToWarehousing;
}
// 总部从它这里调仓出去的. 已经扫码的就相当于调仓出库的
private function transferFromWarehousingInfo($startTime, $endTime)
{
$transferFromWarehousing = TransferWarehousing::query()->join('fch_transfer_warehousing_code', 'fch_transfer_warehousing_code.transfer_warehousing_sn', '=', 'fch_transfer_warehousing.transfer_warehousing_sn')
->where('fch_transfer_warehousing.brand_id', $this->brandId)
->where('fch_transfer_warehousing_code.brand_id', $this->brandId)
->whereNull('fch_transfer_warehousing_code.deleted_at')
->whereIn( 'transfer_status', [1,2])
->whereBetween('fch_transfer_warehousing.created_at', [$startTime, $endTime])
->groupBy('fch_transfer_warehousing.brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'fch_transfer_warehousing.brand_id',
Db::raw("DATE_FORMAT(ydd_fch_transfer_warehousing.created_at,'%Y') as day"),
'fch_transfer_warehousing_code.transfer_warehouse_id as warehouse_id',
'product_id',
'product_sn',
'product_sku_sn',
Db::raw("SUM(ydd_fch_transfer_warehousing_code.code_num) AS transfer_from_warehouse_num")
)->get();
return $transferFromWarehousing;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Repository\Reimbursement;
use Hyperf\DbConnection\Db;
use App\Model\Reimbursement\WarehouseStatistics;
use App\Model\Reimbursement\OutWarehouseStatistics;
use App\Model\Reimbursement\GeneralProductWarehouseStockStatistcs;
class GeneralProductWarehouseStockStatisticsRepository
{
public $startTime = null;
public $endTime = null;
public $brandId = 0;
const keyTmp = "%s%s%s%s";
/**
* 设置时间 便于指定时间统计
*
* @param string $startTime
* @param string $endTime
* @return BrandConsumeTask
*/
public function setBrandId($brandId)
{
$this->brandId = $brandId;
return $this;
}
public function setTime($day)
{
$this->startTime = date('Y-m-d 00:00:00', strtotime($day));
$this->endTime = date('Y-m-d 23:59:59', strtotime($day));
return $this;
}
public function entry()
{
if ($this->brandId == 0) {
throw new \Exception('品牌商ID 为空');
}
$startTime = $this->startTime ? $this->startTime : strtotime( '-1 day');
$endTime = $this->endTime ? $this->endTime : strtotime( '-1 day');
$product_list = [];
// 入库数据
$warehousingData = $this->warehousingInfo($startTime, $endTime);
$this->getProductInfo($warehousingData, $product_list);
// 出货数据
$outwarehousingData = $this->outwarehousingInfo($startTime, $endTime);
$this->getProductInfo($outwarehousingData, $product_list);
$this->insertData($product_list);
}
// 数据写入
private function insertData($productList)
{
GeneralProductWarehouseStockStatistcs::mutilDuplicateInsert($productList, 'reimbursement');
}
// 获取产品数据
private function getProductInfo($data, &$product_list)
{
foreach ($data as $item) {
$key = sprintf(self::keyTmp, $item['warehouse_id'], $item['product_id'], $item['product_sn'], $item['product_sku_sn']);
if (isset($product_list[$key])) {
$product_list[$key]['warehouse_num'] += $item['warehouse_num'] ?? 0;
$product_list[$key]['out_warehouse_num'] += $item['out_warehouse_num'] ?? 0;
$product_list[$key]['out_warehouse_middle_code_num'] += $item['out_warehouse_middle_code_num'] ?? 0;
$product_list[$key]['out_warehouse_big_code_num'] += $item['out_warehouse_big_code_num'] ?? 0;
} else {
$product_list[$key] = [
'brand_id' => $item['brand_id'],
'day' => $this->day,
'product_id'=> $item['product_id'],
'product_sku_sn'=> $item['product_sku_sn'],
'product_sn' => $item['product_sn'],
'warehouse_num' => $item['warehouse_num'] ?? 0,
'out_warehouse_num' => $item['out_warehouse_num'] ?? 0,
'out_warehouse_middle_code_num' => $item['out_warehouse_middle_code_num'] ?? 0,
'out_warehouse_big_code_num' => $item['out_warehouse_big_code_num'] ?? 0,
'warehouse_id' => $item['warehouse_id'] ?? 0,
];
}
}
}
// 入库数据
private function warehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$warehousingData = WarehouseStatistics::where('brand_id', $this->brandId)
->whereBetween('day', [$startTime, $endTime])
->groupBy('brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn',
Db::raw("SUM(nums) AS warehouse_num"),
)
->get();
return $warehousingData;
}
// 总部出库数据
private function outwarehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$outwarehousingData = OutWarehouseStatistics::where('brand_id', $this->brandId)
->whereBetween('day', [$startTime, $endTime])
->where('out_warehousing_from_id', 0)
->groupBy('brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'warehouse_id',
'product_id',
'product_sn',
'product_sku_sn',
Db::raw( 'SUM(out_warehousing_nums) as out_warehouse_num' ) ,
Db::raw("SUM(out_middle_code_nums) AS out_warehouse_middle_code_num"),
Db::raw("SUM(out_big_code_nums) AS out_warehouse_big_code_num"),
)
->get();
return $outwarehousingData;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Repository\Reimbursement;
use Hyperf\DbConnection\Db;
use App\Model\Reimbursement\WarehouseStatisticsYear;
use App\Model\Reimbursement\OutWarehouseStatisticsYear;
use App\Model\Reimbursement\GeneralProductWarehouseStockStatistcs;
class GeneralProductWarehouseStockStatisticsYearRepository
{
public $startTime = null;
public $endTime = null;
public $year = null;
public $brandId = 0;
const keyTmp = "%s%s%s%s%s";
/**
* 设置时间 便于指定时间统计
*
* @param string $startTime
* @param string $endTime
* @return BrandConsumeTask
*/
public function setBrandId($brandId)
{
$this->brandId = $brandId;
return $this;
}
public function setTime($year)
{
$this->startTime = sprintf('%s-01-01 00:00:00', $year);
$this->endTime = sprintf('%s-12-31 23:59:59', $year);
$this->year = $year;
return $this;
}
public function entry()
{
if ($this->brandId == 0) {
throw new \Exception('品牌商ID 为空');
}
$startTime = $this->startTime ? $this->startTime : strtotime( '-1 day');
$endTime = $this->endTime ? $this->endTime : strtotime( '-1 day');
$product_list = [];
// 入库数据
$warehousingData = $this->warehousingInfo($startTime, $endTime);
$this->getProductInfo($warehousingData, $product_list);
// 出货数据
$outwarehousingData = $this->outwarehousingInfo($startTime, $endTime);
$this->getProductInfo($outwarehousingData, $product_list);
$this->insertData($product_list);
}
// 数据写入
private function insertData($productList)
{
GeneralProductWarehouseStockStatistcs::mutilDuplicateInsert($productList, 'reimbursement');
}
// 获取产品数据
private function getProductInfo($data, &$product_list)
{
foreach ($data as $item) {
$key = sprintf(self::keyTmp, $item['day'], $item['warehouse_id'], $item['product_id'], $item['product_sn'], $item['product_sku_sn']);
if (isset($product_list[$key])) {
$product_list[$key]['warehouse_num'] += $item['warehouse_num'] ?? 0;
$product_list[$key]['out_warehouse_num'] += $item['out_warehouse_num'] ?? 0;
} else {
$product_list[$key] = [
'brand_id' => $item['brand_id'],
'day' => $item['day'],
'product_id'=> $item['product_id'],
'product_sku_sn'=> $item['product_sku_sn'],
'product_sn' => $item['product_sn'],
'warehouse_num' => $item['warehouse_num'] ?? 0,
'out_warehouse_num' => $item['out_warehouse_num'] ?? 0,
'warehouse_id' => $item['warehouse_id'] ?? 0,
];
}
}
}
// 入库数据
private function warehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$warehousingData = WarehouseStatisticsYear::where('brand_id', $this->brandId)
->where('day', $this->year)
->groupBy('brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn',
Db::raw("SUM(nums) AS warehouse_num"),
)
->get();
return $warehousingData;
}
// 总部出库数据
private function outwarehousingInfo($startTime, $endTime)
{
$startTime = date('Ymd', strtotime($startTime));
$endTime = date('Ymd', strtotime($endTime));
$outwarehousingData = OutWarehouseStatisticsYear::where('brand_id', $this->brandId)
->where('day', $this->year)
->where('out_warehousing_from_id', 0)
->groupBy('brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn')
->select(
'brand_id',
'day',
'warehouse_id',
'product_id',
'product_sn',
'product_sku_sn',
Db::raw( 'SUM(out_warehousing_nums) as out_warehouse_num' )
)
->get();
return $outwarehousingData;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Repository\Reimbursement;
use App\Model\Reimbursement\OutWarehousing;
use Hyperf\DbConnection\Db;
use App\Model\Reimbursement\OutWarehouseStatistics;
use App\Model\Reimbursement\OutWarehousingCode;
use App\Repository\Reimbursement\BaseStockStatisticsRepository;
class OutWarehouseStatisticsRepository extends BaseStockStatisticsRepository
{
public $day = null;
public $year = null;
public $brandId = 0;
const pidTemp = '%s%s%s%s%s';
/**
* 设置时间 便于指定时间统计
*
* @param string $startTime
* @param string $endTime
* @return BrandConsumeTask
*/
public function setBrandId($brandId)
{
$this->brandId = $brandId;
return $this;
}
public function setTime($day)
{
$this->startTime = date('Y-m-d 00:00:00', strtotime($day));
$this->endTime = date('Y-m-d 23:59:59', strtotime($day));
return $this;
}
public function entry()
{
if ($this->brandId == 0) {
throw new \Exception('品牌商ID 为空');
}
// 判断context 品牌商数据是否正常
$brandAuth = get_auth_brand();
if (!$brandAuth) {
throw new \Exception('品牌商ID 为空');
}
@list($startTime, $endTime) = $this->getTimeInfo();
$outwarehousingCodeTable = OutWarehousingCode::getTableName();
// 先按出货时间查询、再接着查签收时间
$timeMode = ['out_warehousing_time', 'signing_time'];
foreach ($timeMode as $model) {
$this->handleOutWarehouseData($model, $startTime, $endTime, $outwarehousingCodeTable);
}
}
// 出库数据
private function handleOutWarehouseData($modelTimeStr, $beginTime, $endTime, $outwarehousingCodeTable)
{
$selectArr = [
'fch_out_warehousing.brand_id',
Db::raw("DATE_FORMAT(out_warehousing_time,'%Y%m%d') as day"),
'warehouse_id',
'product_id',
'product_sn',
'product_sku_sn',
'product_batch_id',
'out_warehousing_type',
'out_warehousing_from_id',
'out_warehousing_to_id',
'create_brand_sale_id as brand_sale_id',
'dealer_sale_id',
];
if ($modelTimeStr == 'out_warehousing_time') {
$selectArr[] = Db::raw("SUM(ydd_".$outwarehousingCodeTable.".code_num) AS out_warehousing_nums");
$selectArr[] = Db::raw("SUM(ydd_".$outwarehousingCodeTable.".middle_code_num) AS out_middle_code_nums");
$selectArr[] = Db::raw("SUM(if(ydd_".$outwarehousingCodeTable.".code_type = 1, 1, 0)) AS out_big_code_nums");
} else if ($modelTimeStr == 'signing_time') {
$selectArr[] = Db::raw("SUM(ydd_".$outwarehousingCodeTable.".code_num) AS signing_nums");
$selectArr[] = Db::raw("SUM(ydd_".$outwarehousingCodeTable.".middle_code_num) AS signing_middle_code_nums");
$selectArr[] = Db::raw("SUM(if(ydd_".$outwarehousingCodeTable.".code_type = 1, 1, 0)) AS signing_big_code_nums");
}
OutWarehousing::query()->join($outwarehousingCodeTable, 'fch_out_warehousing.out_warehousing_sn', '=', $outwarehousingCodeTable.'.out_warehousing_sn')
->where('fch_out_warehousing.brand_id', $this->brandId)
->whereBetween($modelTimeStr, [$beginTime, $endTime])
->whereIn('out_warehousing_status', ['2', '3'])
->whereNull($outwarehousingCodeTable.'.deleted_at')
->groupBy(
'brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn',
'product_batch_id', 'out_warehousing_type', 'out_warehousing_from_id', 'out_warehousing_to_id',
'brand_sale_id', 'dealer_sale_id'
)
->select(
$selectArr
)->chunk(800, function($list) {
$listData = $this->handleInsertData($list->toArray());
OutWarehouseStatistics::mutilDuplicateInsert($listData, 'reimbursement');
});
}
private function handleInsertData($data)
{
foreach ($data as &$d) {
$d['day'] = $this->day;
$outWarehousingType = $d['out_warehousing_type'] ?? '0';
$pid = sprintf(self::pidTemp, $outWarehousingType, $d['out_warehousing_from_id'], $d['out_warehousing_to_id'], $d['warehouse_id'], $d['product_id']);
$d['pid'] = $pid;
}
return $data;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Repository\Reimbursement;
use App\Model\Reimbursement\RefundWarehousing;
use Hyperf\DbConnection\Db;
use App\Model\Reimbursement\RefundWarehouseStatistics;
use App\Repository\Reimbursement\BaseStockStatisticsRepository;
class RefundWarehouseStatisticsRepository extends BaseStockStatisticsRepository
{
public $brandId = 0;
const pidTemp = '%s%s%s%s%s';
/**
* 设置时间 便于指定时间统计
*
* @param string $startTime
* @param string $endTime
* @return BrandConsumeTask
*/
public function setBrandId($brandId)
{
$this->brandId = $brandId;
return $this;
}
public function setTime($startTime, $endTime)
{
$this->startTime = $startTime;
$this->endTime = $endTime;
return $this;
}
public function entry()
{
if ($this->brandId == 0) {
throw new \Exception('品牌商ID 为空');
}
@list($startTime, $endTime) = $this->getTimeInfo();
RefundWarehousing::query()
->join('fch_refund_warehousing_code', 'fch_refund_warehousing_code.refund_warehousing_sn', '=', 'fch_refund_warehousing.refund_warehousing_sn')
->where('fch_refund_warehousing.brand_id', $this->brandId)
->where('fch_refund_warehousing_code.brand_id', $this->brandId)
->whereBetween('fch_refund_warehousing.created_at', [$startTime, $endTime])
->whereNull('fch_refund_warehousing_code.deleted_at')
->groupBy(
'fch_refund_warehousing.brand_id',
'day',
'refund_warehouse_id',
'fch_refund_warehousing_code.product_id',
'fch_refund_warehousing_code.product_sn',
'fch_refund_warehousing_code.product_sku_sn',
'product_batch_id',
'refund_type',
'refund_from_id',
'refund_to_id',
'brand_sale_id',
'dealer_sale_id')
->select(
'fch_refund_warehousing.brand_id',
Db::raw("DATE_FORMAT(ydd_fch_refund_warehousing.created_at,'%Y%m%d') as day"),
'refund_warehouse_id',
'fch_refund_warehousing_code.product_id',
'fch_refund_warehousing_code.product_sn',
'fch_refund_warehousing_code.product_sku_sn',
'product_batch_id',
'refund_type',
'refund_from_id',
'refund_to_id',
'create_brand_sale_id as brand_sale_id',
'dealer_sale_id',
Db::raw("SUM( code_num ) AS nums"),
DB::raw("SUM(middle_code_num) as middle_code_nums"),
DB::raw("SUM(if(code_type=1,1,0)) AS big_code_nums"),
)->chunk(800, function($list) {
$listData = $this->handleInsertData($list->toArray());
RefundWarehouseStatistics::mutilDuplicateInsert($listData, 'reimbursement');
});
}
private function handleInsertData($data)
{
foreach ($data as &$d) {
$refundType = $d['refund_type'] ?? '0';
$pid = sprintf(self::pidTemp, $refundType, $d['refund_from_id'], $d['refund_to_id'], $d['refund_warehouse_id'], $d['product_id']);
$d['pid'] = $pid;
}
return $data;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Repository\Reimbursement;
use App\Model\Reimbursement\Warehousing;
use App\Model\Reimbursement\WarehousingCode;
use Hyperf\DbConnection\Db;
use App\Model\Reimbursement\WarehouseStatistics;
use App\Repository\Reimbursement\BaseStockStatisticsRepository;
class WarehouseStatisticsRepository extends BaseStockStatisticsRepository
{
public $brandId = 0;
const pidTemp = '%s%s%s';
/**
* 设置时间 便于指定时间统计
*
* @param string $startTime
* @param string $endTime
* @return BrandConsumeTask
*/
public function setBrandId($brandId)
{
$this->brandId = $brandId;
return $this;
}
public function setTime($day)
{
$this->startTime = date('Y-m-d 00:00:00', strtotime($day));
$this->endTime = date('Y-m-d 23:59:59', strtotime($day));
return $this;
}
public function entry()
{
if ($this->brandId == 0) {
throw new \Exception('品牌商ID 为空');
}
// 判断context 品牌商数据是否正常
$brandAuth = get_auth_brand();
if (!$brandAuth) {
throw new \Exception('品牌商ID 为空');
}
@list($startTime, $endTime) = $this->getTimeInfo();
$warehousingCodeTable = WarehousingCode::getTableName();
Warehousing::query()->join($warehousingCodeTable, $warehousingCodeTable.'.warehousing_sn', '=', 'fch_warehousing.warehousing_sn')
->where('fch_warehousing.brand_id', $this->brandId)
->where($warehousingCodeTable.'.brand_id', $this->brandId)
->whereNull($warehousingCodeTable.'.deleted_at')
->whereBetween('fch_warehousing.created_at', [$startTime, $endTime])
->groupBy('fch_warehousing.brand_id', 'day', 'warehouse_id', 'product_id', 'product_sn', 'product_sku_sn', 'product_batch_id')
->select(
'fch_warehousing.brand_id',
Db::raw("DATE_FORMAT(ydd_fch_warehousing.created_at,'%Y%m%d') as day"),
'warehouse_id',
'product_id',
'product_sn',
'product_sku_sn',
'product_batch_id',
Db::raw("SUM(ydd_".$warehousingCodeTable.".code_num ) AS nums"),
Db::raw("SUM(ydd_".$warehousingCodeTable.".middle_code_num ) AS middle_code_nums"),
Db::raw("SUM(if(ydd_".$warehousingCodeTable.".code_type=1,1,0)) AS big_code_nums"),
)->chunk(800, function($list) {
$listData = $this->handleInsertData($list->toArray());
WarehouseStatistics::mutilDuplicateInsert($listData, 'reimbursement');
});
}
private function handleInsertData($data)
{
foreach ($data as &$d) {
$pid = sprintf(self::pidTemp, $d['warehouse_id'], $d['product_id'], $d['product_batch_id']);
$d['pid'] = $pid;
}
return $data;
}
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Support;
use GuzzleHttp\Client;
use Hyperf\Guzzle\CoroutineHandler;
use GuzzleHttp\HandlerStack;
class Guzzle
{
/**
* @param $config
* @return Client
*/
public static function getInstance( $config = [] ): Client
{
$client = new Client( [
'base_uri' => isset( $config[ 'host' ] ) ? $config[ 'host' ] : '',
'handler' => HandlerStack::create( new CoroutineHandler() ),
'timeout' => 5,
'swoole' => [
'timeout' => 10,
'socket_buffer_size' => 1024 * 1024 * 2,
],
'headers' => isset( $config[ 'headers' ] ) ? $config[ 'headers' ] : []
] );
return $client;
}
/**
* 支付中心签名验证
* @param array $data
* @param $type
* @return string
*/
public static function md5Sign( array $data, $type = 1 )
{
if ( isset( $data[ "sign" ] ) ) unset( $data[ "sign" ] );
if ( $type == 1 ) {
$key = config( "sign.key" );
}
if ( $type == 2 ) {
$key = config( "signmember.key" );
}
ksort( $data );
$string = http_build_query( $data );
$sign = md5( $string . "&key=" . $key );
return strtoupper( $sign );
}
}
<?php
declare(strict_types=1);
use Hyperf\Redis\RedisFactory;
use Hyperf\Utils\ApplicationContext;
use App\Constants\Cache\CacheDatabaseConstants;
use Hyperf\Utils\Context;
/**
* 创建获取一个container容器
*/
if (!function_exists('di')) {
function di($container)
{
return ApplicationContext::getContainer()->get($container);
}
}
/**
* 获取cache container
* @return int
*/
if (!function_exists('get_cache_container')) {
function get_cache_container($cacheName = CacheDatabaseConstants::DEFAULT)
{
$container = ApplicationContext::getContainer();
return $container->get(RedisFactory::class)->get($cacheName);
}
}
/**
* 打印调试
*/
if ( !function_exists( 'dd' ) ) {
function dd( $params )
{
var_dump( $params );
exit();
}
}
if (!function_exists('logger')) {
/**
* 向日志文件记录日志
* @return \Psr\Log\LoggerInterface
*/
function logger($name = 'hyperf', $group = 'default')
{
return di(\Hyperf\Logger\LoggerFactory::class)->get($name, $group);
}
}
/**
* 日志函数
* 调试用
*/
if (!function_exists('log_info')) {
function log_info($content)
{
$content = is_array($content) ? json_encode($content, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE) : $content;
make(\Hyperf\Logger\LoggerFactory::class )->get()->info($content);
}
}
/**
* 获取品牌商id
*/
if (!function_exists('get_auth_brand')) {
function get_auth_brand()
{
return Context::get(App\Context\BrandAuth::class, false);
}
}
/**
* 设置品牌商id
*/
if (!function_exists('set_auth_brand')) {
function set_auth_brand($data)
{
Context::set(App\Context\BrandAuth::class, new App\Context\BrandAuth($data));
}
}
/**
* 设置品牌商id
*/
if (!function_exists('set_auth_brand_id')) {
function set_auth_brand_id($brandId = 0)
{
$data = ['brand_id' => $brandId];
Context::set(App\Context\BrandAuth::class, new App\Context\BrandAuth($data));
}
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Support;
use Hyperf\Framework\Logger\StdoutLogger as BaseStdoutLogger;
use Psr\Log\LogLevel;
class StdoutLogger extends BaseStdoutLogger
{
/**
* 重写,加上时间
*
* @param string $message
* @param string $level
* @param array $tags
* @return string
*/
protected function getMessage( string $message, string $level = LogLevel::INFO, array $tags = [] )
{
$tag = null;
switch ( $level ) {
case LogLevel::EMERGENCY:
case LogLevel::ALERT:
case LogLevel::CRITICAL:
$tag = 'error';
break;
case LogLevel::ERROR:
$tag = 'fg=red';
break;
case LogLevel::WARNING:
case LogLevel::NOTICE:
$tag = 'comment';
break;
case LogLevel::INFO:
default:
$tag = 'info';
}
$template = sprintf( '[%s] <%s>[%s]</>', date( 'Y-m-d H:i:s' ), $tag, strtoupper( $level ) );
$implodedTags = '';
foreach ( $tags as $value ) {
$implodedTags .= ( ' [' . $value . ']' );
}
return sprintf( $template . $implodedTags . ' %s', $message );
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Task;
use Carbon\Carbon;
use Hyperf\Logger\LoggerFactory;
use App\Model\Marketing\Activity;
class ActivityAutoSwitchTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('crontab', 'crontab');
try {
$now = Carbon::now('Asia/shanghai')->toDateTimeString();
// 未开始
Activity::where('start_time', '>', $now)->where('status', '!=', 1)->update(['status' => 1]);
// 进行中
Activity::where('start_time', '<', $now)->where('end_time', '>', $now)->where('status', '!=', 2)->update(['status' => 2]);
// 已结束
Activity::where('end_time', '<', $now)->where('status', '!=', 3)->update(['status' => 3]);
} catch (\Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "活动自动切换任务异常", [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
public function isEnable(): bool
{
return true;
}
}
<?php
declare(strict_types=1);
namespace App\Task;
use App\Model\Marketing\Blacklist;
use Carbon\Carbon;
use Hyperf\Logger\LoggerFactory;
class BlacklistAutoClearTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('crontab', 'crontab');
try {
$date_time = Carbon::now('Asia/shanghai')->toDateTimeString();
$ids = Blacklist::where('blacklist_limit_end', '<=', $date_time)
->where('blacklist_type', 1)
->where('is_blacklist', 1)
->select('id')
->get()->pluck('id');
Blacklist::whereIn('id', $ids)->update(['releasing_time' => $date_time, 'is_blacklist' => 0]);
} catch (\Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "释放黑名单异常", [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
public function isEnable(): bool
{
return true;
}
}
<?php
declare(strict_types=1);
namespace App\Task;
use App\Model\Brand\BonusCountModel;
use App\Model\Brand\BonusCountStatisticsModel;
use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
class BonusSendCountTask
{
public $day = null;
/**
* 设置时间 便于指定时间统计
*
* @param string $day
* @return BrandConsumeTask
*/
public function setDateTime($day)
{
$this->day = $day;
return $this;
}
public function execute()
{
$logger = ApplicationContext::getContainer()->get( LoggerFactory::class )->get( 'crontab', 'crontab' );
//时间 默认昨天
$now = $this->day ?: Carbon::yesterday('Asia/shanghai')->toDateString();
try {
$list = BonusCountModel::where('send_date',$now)
->where('send_status',1)
->where('split','<>',2)
->groupBy('brand_id','bonus_type','send_date')
->select(Db::raw('sum(bonus_amount) AS `bonus_amount`'),'send_date as date','bonus_type','brand_id' )
->get()
->toArray();
if ( empty( $list ) ) return true;
if(count($list) > 500){
$all_data = array_chunk($list,500);
foreach($all_data as $va){
BonusCountStatisticsModel::insertAll( $va );
}
}else{
BonusCountStatisticsModel::insertAll( $list );
}
} catch (\Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "每日红包统计异常", [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
public function isEnable(): bool
{
return true;
}
}
<?php
declare(strict_types=1);
namespace App\Task;
use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use App\Model\Brand\BrandBillModel;
use Hyperf\Utils\ApplicationContext;
use App\Model\Brand\BrandSmallBillModel;
class BrandConsumeTask
{
public $day = null;
/**
* 设置时间 便于指定时间统计
*
* @param string $day
* @return BrandConsumeTask
*/
public function setDateTime($day)
{
$this->day = $day;
return $this;
}
public function execute()
{
$logger = ApplicationContext::getContainer()->get( LoggerFactory::class )->get( 'crontab', 'crontab' );
//时间 默认昨天
$now = $this->day ?: Carbon::yesterday('Asia/shanghai')->toDateString();
$create_time = time();
try {
// 小额消费写入 当天记录
BrandSmallBillModel::where('day',$now)
->orderByDesc( 'create_time' )
->groupBy('brand_id','type','action')
->select(Db::raw('sum(number) AS `number`'),'type','day','create_time','balance','brand_id','action')
->chunk(100, function ($lits) use( $create_time ) {
foreach ($lits as $item) {
if ( $item->number > 0 ) {
$where = ['type'=>$item->type,'brand_id'=>$item->brand_id,'pm'=>$item->action,'day'=>$item->day];
$data = [
'bill_no' => date( 'YmdHis' ) . rand( 1, 999999 ),
'create_time'=> $create_time,
'brand_id'=>$item->brand_id,
'type'=>$item->type,
'is_have_detail'=>1,
'pm'=>$item->action,
'number'=>$item->number,
'mark'=>'小额账单汇总',
'title'=>$item->day.'的'.$item->type_text,
'day'=>$item->day
];
BrandBillModel::updateOrInsert($where,$data);
}
}
});
} catch (\Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "统计日常品牌商日常消费异常", [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
public function isEnable(): bool
{
return true;
}
}
<?php
declare(strict_types=1);
namespace App\Task;
use App\Model\Code\BranchCodeModel;
use App\Model\Code\CodeBreModel;
use Hyperf\Logger\LoggerFactory;
/**
* 泊然恩同步贝因美码数据
*/
class BreSyncCodeBymTask
{
protected $brandId = '';
protected $batchSns = [
'10000373' => 'bre',
'10000669' => 'hmo',
];
public function execute()
{
$logger = di(LoggerFactory::class)->get('bre', 'crontab');
$brand_ids = ['10000373', '10000669'];
if($this->brandId && in_array($this->brandId,$brand_ids)){
$brand_ids = [$this->brandId];
}
foreach ($brand_ids as $brand_id) {
$this->syncBymData($brand_id,$logger);
}
return true;
}
public function setDateTime()
{
return $this;
}
public function setBrandId($brand_id)
{
$this->brandId = $brand_id;
return $this;
}
protected function syncBymData($brand_id,$logger)
{
try {
$codeModel = make(BranchCodeModel::class,[[],$brand_id]);
$codeBreModel = make(CodeBreModel::class,[[],$brand_id]);
$max_id = $codeBreModel->max('sync_id');
$curr_max_id = $codeBreModel->max('id');
$logger->info(date('Y-m-d H:i:s') . "【{$brand_id}】贝因美数据同步max_id:" . $max_id . " curr_max_id:" . $curr_max_id);
if ($max_id >= $curr_max_id) {
return true;
}
//记录更新这次同步的ID
$codeBreModel->where('id', $curr_max_id)->update(['sync_id' => $curr_max_id]);
//先获取要删除的箱标:is_add=0的数据
$bym_delete_box_code_data = $codeBreModel->where('id', '>', $max_id)->where('is_add', 0)->pluck('box_code');
if ($bym_delete_box_code_data && $bym_delete_box_code_data->toArray()) {
//先删除
$deal_data = array_unique($bym_delete_box_code_data->toArray());
$logger->info(date('Y-m-d H:i:s') . "【{$brand_id}】贝因美数据同步删除:" . count($deal_data));
$codeModel->whereIn('big_code', $deal_data)->delete();
}
//获取新增的数据
$batch_sns = $this->batchSns;
$file_name = BASE_PATH . '/runtime/code/bre_' .$brand_id . '_' . date("YmdHis") . '.txt';
file_put_contents($file_name, 'batch_sn,big_code,small_code,security_code,created_at' . PHP_EOL, FILE_APPEND);
$codeBreModel->where('id', '>', $max_id)
->where('is_add', 1)->chunk(1000, function ($bym_code_data) use ($file_name,$batch_sns,$brand_id) {
foreach ($bym_code_data as $item) {
$row = [
'batch_sn' => $batch_sns[$brand_id],
'big_code' => trim($item['box_code']),
'small_code' => trim($item['trace_code']),
'security_code' => trim($item['point_code']),
'created_at' => trim($item['add_time']),
];
file_put_contents($file_name, implode(',', $row) . PHP_EOL, FILE_APPEND);
}
});
$codeModel->syncCodes($file_name);
@unlink($file_name);
$logger->info(date('Y-m-d H:i:s') . "【{$brand_id}】贝因美数据同步成功:");
} catch (\Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "【{$brand_id}】贝因美数据同步失败:", [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
}
<?php
declare( strict_types=1 );
namespace App\Task;
use Hyperf\Logger\LoggerFactory;
use App\Model\Brand\CouponMemberLog;
use App\Model\Brand\CouponStoreStatistics;
use App\Model\Brand\CouponChannelStatistics;
class CouponStatisticsTask
{
public $startTime = null;
public $endTime = null;
/**
* 设置时间 便于指定时间统计
*
* @param string $day
* @return BrandConsumeTask
*/
public function setTime($day)
{
$this->startTime = strtotime( $day.'00:00:00');
$this->endTime = strtotime( $day.'23:59:59');
return $this;
}
public function execute()
{
$logger = di(LoggerFactory::class)->get('crontab_coupon_statistics', 'crontab');
try {
$startTime = $this->startTime ? $this->startTime : strtotime( '-1 day'.'00:00:00');
$endTime = $this->endTime ? $this->endTime : strtotime( '-1 day'.'23:59:59');
$yesterday = date('Y-m-d', $startTime);
$this->storeStatistics([$startTime, $endTime, $yesterday], $logger);
$this->channelStatistics([$startTime, $endTime, $yesterday], $logger);
} catch ( \Exception | \Throwable $ex ) {
$logger->error('优惠券统计异常处理异常,时间'. $ex->getMessage(), [
$ex->getFile(),
$ex->getCode(),
$ex->getLine()
] );
}
return true;
}
protected function storeStatistics($data, $logger)
{
[$startTime, $endTime, $yesterday] = $data;
$time = time();
try{
//已经统计了,不再统计
if(CouponStoreStatistics::query()->where('date_time', $yesterday)->first()){
return;
}
CouponMemberLog::query()
->whereBetween('create_time',[$startTime, $endTime])
->selectRaw('brand_id,store_id,coupon_id,
sum(case when type=1 then 1 else 0 end) as receive_num,
sum( case when type=2 then 1 else 0 end) as use_num')
->groupBy('store_id', 'coupon_id', 'brand_id')
->chunkById(500, function($list) use($yesterday, $time){
foreach($list as $v){
$data[] = [
'brand_id' => $v['brand_id'],
'store_id' => $v['store_id'],
'coupon_id' => $v['coupon_id'],
'receive_num' => $v['receive_num'],
'use_num' => $v['use_num'],
'date_time' => $yesterday,
'create_time' => $time
];
}
(make(CouponStoreStatistics::class))->insert($data);
});
}catch(\Exception | \Throwable $ex){
$logger->error('优惠券统计门店数据失败'.$ex->getMessage(),[
$ex->getFile(),
$ex->getCode(),
$ex->getLine()
]);
}
}
protected function channelStatistics($data, $logger)
{
[$startTime, $endTime, $yesterday] = $data;
$time = time();
try{
//已经统计了,不再统计
if(CouponChannelStatistics::query()->where('date_time', $yesterday)->first()){
return;
}
CouponMemberLog::query()
->whereBetween('create_time',[$startTime, $endTime])
->selectRaw('id,brand_id,source_type,coupon_id,
sum(case when type=1 then 1 else 0 end) as receive_num,
sum( case when type=2 then 1 else 0 end) as use_num')
->groupBy('source_type', 'coupon_id', 'brand_id')
->chunkById(500, function($list) use($yesterday, $time){
foreach($list as $v){
$data[] = [
'brand_id' => $v['brand_id'],
'source_type' => $v['source_type'],
'coupon_id' => $v['coupon_id'],
'receive_num' => $v['receive_num'],
'use_num' => $v['use_num'],
'date_time' => $yesterday,
'create_time' => $time
];
}
(make(CouponChannelStatistics::class))->insert($data);
});
}catch(\Exception | \Throwable $ex){
$logger->error('优惠券统计渠道数据失败'.$ex->getMessage(),[
$ex->getFile(),
$ex->getCode(),
$ex->getLine()
]);
}
}
}
<?php
declare( strict_types=1 );
namespace App\Task;
use App\Model\Brand\ExportLog;
use App\Support\Guzzle;
use Hyperf\Logger\LoggerFactory;
class DelExportFileTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('crontab', 'crontab');
try {
$brand_export_ids = [];
$guzzle_brand = config('guzzle.brand_business', []);
$client = Guzzle::getInstance([
'host' => $guzzle_brand['host']
]);
ExportLog::query()
->where( 'status', '=', 2 )
->select( [ 'id', 'brand_id'] )
->chunkById( 100, function ( $list ) use( $client, $guzzle_brand, $logger ) {
foreach ( $list as $item ) {
if(in_array($item['type'], ExportLog::APPLICATION_BRAND)){
$brand_export_ids[] = $item['id'];
}
}
if($brand_export_ids){
$data = [
'ids' => $brand_export_ids
];
$response = $client->post($guzzle_brand['del_export_file'], [
'headers' => ['sign' => Guzzle::md5Sign( $data)],
'form_params' => $data,
] );
if ($response->getStatusCode() == 200) {
$body = json_decode((string) $response->getBody()->getContents(), true );
if (isset($body['code']) && $body['code'] == 0) {
$logger->info( '删除过期导出文件失败', $body);
}
}
}
} );
} catch ( \Exception | \Throwable $ex ) {
$logger->error('删除到期导出文件异常'. $ex->getMessage(), [
$ex->getFile(),
$ex->getCode(),
$ex->getLine()
] );
}
return true;
}
}
<?php
declare( strict_types=1 );
namespace App\Task;
use Hyperf\Logger\LoggerFactory;
use App\Model\Cloud\TreasureActivity;
use App\Kernel\TreasureActivity\TreasureCacheHandle;
class DelTreasureActivityCacheTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('treasure', 'activity');
try {
$now_time = time();
$time = 1.5 * 24 * 3600;
$start_time = bcsub( (string) $now_time, (string) $time, 0 );
$cache = new TreasureCacheHandle();
$update_brand_ids = [];
TreasureActivity::query()
->where( 'end_time', '>', $start_time )
->where( 'end_time', '<', $now_time )
->select( [ 'id', 'brand_id', 'end_time' ] )
->chunkById( 100, function ( $list ) use ( $logger, $cache ) {
try {
foreach ( $list as $item ) {
$update_brand_ids[] = $item[ 'brand_id' ];
$cache->delActCache( [
'brand_id' => $item[ 'brand_id' ],
'act_id' => $item[ 'id' ],
'end_time' => $item[ 'end_time' ],
] );
}
} catch ( \Exception $e ) {
$logger->error( $e->getMessage(), $e->getTrace() );
}
} );
//更新列表缓存
$update_brand_ids = array_unique( $update_brand_ids );
foreach ( $update_brand_ids as $brand_id ) {
$cache->setActListCache( $brand_id );
}
} catch ( \Exception | \Throwable $ex ) {
$logger->error('删除夺宝活动缓存异常'. $ex->getMessage(), [
$ex->getFile(),
$ex->getCode(),
$ex->getLine()
] );
}
return true;
}
}
<?php
declare ( strict_types=1 );
namespace App\Task;
use Carbon\Carbon;
use App\Model\Brand\Brand;
use App\Model\Ecpass\Order;
use Hyperf\Logger\LoggerFactory;
use App\Model\Ecpass\OrderStatistics;
class EcpassOrderStatisticsTask
{
public function execute()
{
$logger = di( LoggerFactory::class )->get( 'crontab', 'crontab' );
try {
//$start_time和$end_time保持同一天
$day = Carbon::yesterday( 'Asia/shanghai' )->startOfDay()->toDateString();
$start_time = Carbon::parse( $day )->timestamp;
$end_time = Carbon::parse( $day )->endOfDay()->timestamp;
$brand_ids = Brand::query()->pluck( 'brand_no' )->toArray();
if ( $brand_ids ) {
foreach ($brand_ids as $brand_id) {
Order::query()->where('brand_id',$brand_id)
->where('status',2)
->whereBetween('service_completion_time',[$start_time,$end_time])
->selectRaw( "count(id) as order_nums,store_id")
->groupBy(['store_id'])
->chunk(500, function($list)use($brand_id,$day){
$data = [];
foreach($list as $v){
$data[] = [
'brand_id' => $brand_id,
'days' => $day,
'store_id' => $v['store_id'],
'order_nums' => $v['order_nums'],
];
}
if ( $data ) {
OrderStatistics::insert($data);
}
});
}
}
} catch ( \Throwable $exception ) {
$logger->error( date( 'Y-m-d H:i:s' ) . "电商通订单统计任务异常", [
$exception->getMessage(),
$exception->getTrace()
] );
}
}
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Task;
use Hyperf\Logger\LoggerFactory;
use Hyperf\DbConnection\Db;
use Hyperf\Database\ConnectionResolverInterface;
use Carbon\Carbon;
use App\Model\Brand\Brand;
use App\Repository\Reimbursement\GeneralProductBatchStockStatisticsRepository;
// 每天 - 总部商品批次库存统计
class GeneralProductBatchStockStatisticsTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('OutWarehouseStatisticsTask', 'crontab');
$repository = new GeneralProductBatchStockStatisticsRepository();
try {
$date_time = Carbon::yesterday( 'Asia/shanghai' )->toDateString();
$start_time = date('Y-m-d 00:00:00', strtotime($date_time));
$end_time = date('Y-m-d 23:59:59', strtotime($date_time));
Brand::query()->where('status', 1)
->select('brand_no')
->chunkById(100, function($brand)use($repository, $start_time, $end_time){
foreach($brand as $v){
$brand_id = $v['brand_no'];
$repository
->setBrandId($brand_id)
->setBeforeDayModel()
->setTime($start_time)
->entry();
}
}, 'brand_no');
} catch ( \Exception | \Throwable $ex ) {
$logger->error('出库表统计,异常'. $ex->getMessage(), [
$ex->getMessage(),
$ex->getTrace()
] );
}
return true;
}
}
<?php
declare( strict_types=1 );
namespace App\Task;
use Hyperf\Logger\LoggerFactory;
use Hyperf\DbConnection\Db;
use Hyperf\Database\ConnectionResolverInterface;
use Carbon\Carbon;
use App\Model\Brand\Brand;
use App\Repository\Reimbursement\GeneralProductStockStatisticsRepository;
// 每天 - 总部商品库存统计
class GeneralProductStockStatisticsTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('OutWarehouseStatisticsTask', 'crontab');
$repository = new GeneralProductStockStatisticsRepository();
try {
$date_time = Carbon::yesterday( 'Asia/shanghai' )->toDateString();
$start_time = date('Y-m-d 00:00:00', strtotime($date_time));
$end_time = date('Y-m-d 23:59:59', strtotime($date_time));
Brand::query()->where('status', 1)
->select('brand_no')
->chunkById(100, function($brand)use($repository, $start_time, $end_time){
foreach($brand as $v){
$brand_id = $v['brand_no'];
$repository
->setBrandId($brand_id)
->setBeforeDayModel()
->setTime($start_time)
->entry();
}
}, 'brand_no');
} catch ( \Exception | \Throwable $ex ) {
$logger->error('出库表统计,异常'. $ex->getMessage(), [
$ex->getMessage(),
$ex->getTrace()
] );
}
return true;
}
}
<?php
declare( strict_types=1 );
namespace App\Task;
use Hyperf\Logger\LoggerFactory;
use Hyperf\DbConnection\Db;
use Hyperf\Database\ConnectionResolverInterface;
use Carbon\Carbon;
use App\Model\Brand\Brand;
use App\Repository\Reimbursement\GeneralProductWarehouseStockStatisticsRepository;
// 每天 - 总部商品仓库统计
class GeneralProductWarehouseStatisticsTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('OutWarehouseStatisticsTask', 'crontab');
$repository = new GeneralProductWarehouseStockStatisticsRepository();
try {
$date_time = Carbon::yesterday( 'Asia/shanghai' )->toDateString();
$start_time = date('Y-m-d 00:00:00', strtotime($date_time));
$end_time = date('Y-m-d 23:59:59', strtotime($date_time));
Brand::query()->where('status', 1)
->select('brand_no')
->chunkById(100, function($brand)use($repository, $start_time, $end_time){
foreach($brand as $v){
$brand_id = $v['brand_no'];
$repository
->setBrandId($brand_id)
->setTime($start_time)
->entry();
}
}, 'brand_no');
} catch ( \Exception | \Throwable $ex ) {
$logger->error('出库表统计,异常'. $ex->getMessage(), [
$ex->getMessage(),
$ex->getTrace()
] );
}
return true;
}
}
<?php
declare ( strict_types=1 );
namespace App\Task;
use App\Model\Brand\OrderSet;
use App\Model\Marketing\ScanAward;
use Carbon\Carbon;
use Hyperf\Logger\LoggerFactory;
class GiftVerificationTimeoutTask
{
public function execute()
{
$logger = di( LoggerFactory::class )->get( 'gift_timeout', 'gift_timeout' );
try {
$now = Carbon::now( 'Asia/shanghai' )->timestamp;
//查出满足条件的记录
$config = OrderSet::query()->pluck( 'cannot_write_off_time', 'brand_id' );
$history = ScanAward::query()
->where( 'is_award', 1 )
->where( 'is_gift', 1 )
->where( 'gift_award_status', 4 )
->where( 'write_status', 0 )
->where( 'write_code', '<>', 0 )
->select( [ 'id', 'prize_time', 'brand_id' ] )
->get();
if ( $history ) {
$arr = [];
foreach ( $history as $value ) {
if ( isset( $config[ $value[ 'brand_id' ] ] ) ) {
$dayToSec = $config[ $value[ 'brand_id' ] ] * 86400;
if ( ( strtotime( $value[ 'prize_time' ] ) + $dayToSec ) < $now ) {
$arr[] = $value->toArray();
}
}
}
}
if ( isset( $arr ) && !empty( $arr ) ) {
$ids = array_column( $arr, 'id' );
ScanAward::whereIn( 'id', $ids )->update( [
'write_status' => 2
] );
$logger->info('核销订单超时任务成功,更新数据ID:',$ids);
}
return true;
} catch ( \Exception | \Throwable $ex ) {
$logger->error( '核销订单超时任务异常' . $ex->getMessage(), [
$ex->getFile(),
$ex->getCode(),
$ex->getLine()
] );
}
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
namespace App\Task;
use Carbon\Carbon;
use App\Model\Brand\Brand;
use App\Model\Brand\Member;
use Hyperf\Logger\LoggerFactory;
use App\Model\Brand\MemberVipCard;
use App\Model\Brand\MemberVipCardPeriod;
class MemberVipExpireTask
{
public $brand_id = null;
/**
* 设置品牌商
*
* @param string $brand_id
* @return ScanStatisticsTask
*/
public function setBrandId( $brand_id )
{
$this->brand_id = $brand_id;
return $this;
}
public function execute()
{
$logger = di(LoggerFactory::class)->get('crontab', 'crontab');
try {
$brand_id = $this->brand_id;
if( $this->brand_id ) {
$all_brand = Brand::where( 'status', 1 )->where( 'member_vip_card_type', 2 )->get();
} else {
$all_brand = Brand::where( 'brand_no', $this->brand_id )->where( 'status', 1 )->where( 'member_vip_card_type', 2 )->get();
}
$all_brand_config = $all_brand->pluck('member_vip_card_config','brand_id');
$now_time = Carbon::yesterday('Asia/shanghai')->toDateString();
foreach ($all_brand_config as $brand_id => $config ) {
//expire_exec_type 到期执行类型 1 扣除当前等级所需成长值 2 成长值扣除至0
if ( $config[ 'expire_exec_type' ] == 2 ) {
MemberVipCardPeriod::where('brand_id',$brand_id)->where('expire_time','>',$now_time)->chunk(100, function ($list) use( $config ) {
foreach( $list as $item ) {
Member::where( 'brand_id', $item->brand_id )->where( 'id', $item->member_id )->update( [ 'grow_exp'=>0,'vip_level'=>0 ] );
MemberVipCardPeriod::where('id',$item->id)->delete();
}
});
} else {
$vip_exp = MemberVipCard::where('brand_id',$brand_id)->get()->pluck('vip_exp','vip_number');
MemberVipCardPeriod::where('brand_id',$brand_id)->where('expire_time','>',$now_time)->chunk(100, function ($list) use( $config, $vip_exp ) {
foreach( $list as $item ) {
Member::where( 'brand_id', $item->brand_id )->where( 'id', $item->member_id )->decrement( 'grow_exp', $vip_exp[$item->vip_number ] );
MemberVipCardPeriod::where('id',$item->id)->delete();
}
});
}
}
} catch (\Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "会员卡到期处理", [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
public function isEnable(): bool
{
return true;
}
}
<?php
declare( strict_types=1 );
namespace App\Task;
use Hyperf\Logger\LoggerFactory;
use Hyperf\DbConnection\Db;
use Hyperf\Database\ConnectionResolverInterface;
use Carbon\Carbon;
use App\Model\Brand\Brand;
use App\Repository\Reimbursement\OutWarehouseStatisticsRepository;
// 每天 - 出库表统计
class OutWarehouseStatisticsTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('OutWarehouseStatisticsTask', 'crontab');
$repository = new OutWarehouseStatisticsRepository();
try {
$date_time = Carbon::yesterday( 'Asia/shanghai' )->toDateString();
$start_time = date('Y-m-d 00:00:00', strtotime($date_time));
$end_time = date('Y-m-d 23:59:59', strtotime($date_time));
Brand::query()->where('status', 1)
->select('brand_no')
->chunkById(100, function($brand)use($repository, $start_time, $end_time){
foreach($brand as $v){
$brand_id = $v['brand_no'];
set_auth_brand_id($v['brand_no']);
$repository
->setBrandId($brand_id)
->setBeforeDayModel()
->setTime($start_time)
->entry();
}
}, 'brand_no');
} catch ( \Exception | \Throwable $ex ) {
$logger->error('出库表统计,异常'. $ex->getMessage(), [
$ex->getMessage(),
$ex->getTrace()
] );
}
return true;
}
}
<?php
declare(strict_types=1);
namespace App\Task;
use Carbon\Carbon;
use App\Model\Brand\PointSet;
use Hyperf\Logger\LoggerFactory;
use App\Repository\Member\MemberPointRepository;
/**
* 用户积分清理
* 每年1月1日00:00:00执行操作,清理上上一年消费者获得的积分
* 消费者优先使用n最小的积分,先进先出
* 退款订单涉及退还积分,返还积分有效期不变
* 如:2023年1月1日00点,清理用户2021年获得的积分
*/
class PointClearTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('crontab', 'crontab');
try {
// 获取需要清理积分的品牌商
$brands = PointSet::with('brand')->get();
// 过滤过期的品牌商
$time = time();
foreach ( $brands as $brand ) {
if ( $brand->brand->status == 1 && $brand->brand->signing_end_time > $time ) {
if($brand->point_is_clear == 2){
//清除所有积分(本定时任务是每年1月1日00:00:00 执行,清除的就是本年之前所有的积分)
$yester_year = date('Y-m-d H:i:s',strtotime(date('Y-01-01 00:00:00')));
}elseif($brand->point_is_clear == 1){
// 获取要清理的截取日期 当前 2023-01-01 00:00:00 获取 2022-01-01 00:00:00 积分保留一年
$yester_year = date('Y-m-d H:i:s',strtotime(date('Y-01-01 00:00:00',strtotime("-1 year"))));
}else{
continue;
}
MemberPointRepository::execSingleBrand( $brand->brand_id, $yester_year,$brand->point_is_clear );
}
}
} catch (\Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "积分清理任务:", [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
}
<?php
declare( strict_types=1 );
namespace App\Task;
use Hyperf\Logger\LoggerFactory;
use Carbon\Carbon;
use App\Model\Brand\Brand;
use App\Repository\Reimbursement\RefundWarehouseStatisticsRepository;
// 每天 - 退货表统计
class RefundWarehouseStatisticsTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('RefundWarehouseStatisticsTask', 'crontab');
$repository = new RefundWarehouseStatisticsRepository();
try {
$date_time = Carbon::yesterday( 'Asia/shanghai' )->toDateString();
$start_time = date('Y-m-d 00:00:00', strtotime($date_time));
$end_time = date('Y-m-d 23:59:59', strtotime($date_time));
Brand::query()->where('status', 1)
->select('brand_no')
->chunkById(100, function($brand)use($repository, $start_time, $end_time){
foreach($brand as $v){
$brand_id = $v['brand_no'];
set_auth_brand_id($v['brand_no']);
$repository
->setBrandId($brand_id)
->setBeforeDayModel()
->setTime($start_time, $end_time)
->entry();
}
}, 'brand_no');
} catch ( \Exception | \Throwable $ex ) {
$logger->error('退货表统计,异常'. $ex->getMessage(), [
$ex->getMessage(),
$ex->getTrace()
] );
}
return true;
}
}
<?php
declare(strict_types=1);
namespace App\Task;
use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use App\Model\Marketing\ScanAward;
use App\Model\Marketing\StatisticsScanCity;
use App\Model\Marketing\ScanAwardStatistics;
use App\Model\Marketing\StatisticsScanDistrict;
use App\Model\Marketing\StatisticsScanProvince;
/**
* 统计
*/
class ScanAwardStatisticsTask
{
public $data_time = null;
public $brand_id = null;
/**
* 设置时间 便于指定时间统计
*
* @param string $data_time
* @return ScanAwardStatisticsTask
*/
public function setDateTime($data_time)
{
$this->data_time = $data_time;
return $this;
}
/**
* 设置品牌商
*
* @param string $brand_id
* @return ScanAwardStatisticsTask
*/
public function setBrandId( $brand_id )
{
$this->brand_id = $brand_id;
return $this;
}
public function execute()
{
$logger = di(LoggerFactory::class)->get('crontab', 'crontab');
if ($this->data_time) {
$date_time = Carbon::parse($this->data_time)->toDateString();
} else {
$date_time = Carbon::yesterday('Asia/shanghai')->toDateString();
}
$day = Carbon::parse( $date_time )->format('Ymd');
$brand_id = $this->brand_id;
try {
$scanAward = ScanAward::query();
if($brand_id) {
$scanAward = $scanAward->where('brand_id',$brand_id);
}
$scanAward->where('day', $day)
->groupBy('brand_id', 'activity_id', 'is_many_awards', 'province_id', 'product_id')
->select(
'brand_id',
'product_id',
'activity_id',
'province_id',
'province',
'is_many_awards',
Db::raw('count(*) as act_num'),
Db::raw("count(distinct(member_id)) as user_num"),
Db::raw("count(distinct(if(is_award=1,`member_id`,null))) as award_user_num"),
Db::raw("count(if(is_award=1,true,null)) as award_number"),
Db::raw("count(if(is_bonus=1,true,null)) as bonus_number"),
Db::raw("count(if(is_gift=1,true,null)) as gift_number"),
Db::raw("count(if(is_point=1,true,null)) as point_number"),
Db::raw("sum(if(is_bonus=1,bonus_num,0)) as money_num"),
Db::raw("sum(if(bonus_award_status=1,bonus_num,0)) as grant_bonus_num"),
Db::raw("sum(if(is_point=1,point_num,0)) as point_num"),
Db::raw("sum(if(point_award_status=1,point_num,0)) as grant_point_num"),
Db::raw("count(if(award_status=1,true,null)) as grant_award_number"),
Db::raw("count(if(bonus_award_status=1 and is_bonus=1,true,null)) as grant_bonus_number"),
Db::raw("count(if(gift_award_status=1 and is_gift=1,true,null)) as grant_gift_number"),
Db::raw("count(if(point_award_status=1 and is_point=1,true,null)) as grant_point_number"),
Db::raw("count(if(coupon_award_status=1 and is_coupon=1,true,null)) as grant_coupon_number"),
Db::raw("count(if(is_coupon=1,true,null)) as coupon_number"),
)
->chunk(100, function ($list) use ( $date_time, $day ) {
$created_time = Carbon::now('Asia/shanghai')->toDateTimeString();
foreach ($list as $item) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'activity_id' => $item->activity_id,
'product_id' => $item->product_id ?: 0,
'province_id' => $item->province_id ?: 0,
'is_many_awards' => $item->is_many_awards ?: 0,
];
// 参与的活动人数 重新去重
$scan_award = ScanAward::where('brand_id',$item->brand_id)
->where('is_many_awards',$item->is_many_awards)
->where('province_id', $where['province_id'] )
->where('activity_id',$item->activity_id);
// 产品
if( $where['product_id'] ) {
$scan_award = $scan_award->where('product_id', $where['product_id'] );
} else {
$scan_award = $scan_award->whereNull('product_id');
}
$user_ids = $scan_award->where('day', $day)
->select('member_id','is_award')
->groupBy('member_id')
->get();
$award_user_ids = collect($user_ids->toArray() ?? [] )->where('is_award',1)->pluck('member_id')->values()->toJson();
$user_ids = $user_ids->pluck('member_id')->values()->toJson();
$scan = [
'province' => $item->province,
'act_num' => $item->act_num ?? 0, // 活动次数
'user_num' => $item->user_num ?? 0, // 参与人数
'award_user_num' => $item->award_user_num ?? 0, // 中奖人数
'award_number' => $item->award_number ?? 0, // 中奖份数
'bonus_number' => $item->bonus_number ?? 0, // 红包中奖份数
'gift_number' => $item->gift_number ?? 0, // 礼品中奖份数
'point_number' => $item->point_number ?? 0, // 积分中奖份数
'grant_award_number' => $item->grant_award_number ?? 0, // 奖项发放份数
'grant_bonus_number' => $item->grant_bonus_number ?? 0, // 红包发放份数
'grant_gift_number' => $item->grant_gift_number ?? 0, // 礼品发放份数
'grant_point_number' => $item->grant_point_number ?? 0, // 积分发放份数
'bonus_num' => $item->bonus_num ?? 0,
'grant_bonus_num' => $item->grant_bonus_num ?? 0,
'point_num' => $item->point_num ?? 0,
'grant_point_num' => $item->grant_point_num ?? 0,
'user_ids' => $user_ids,
'award_user_ids' => $award_user_ids,
'created_time' => $created_time,
'coupon_number' => $item->coupon_number ?? 0, // 优惠券中奖份数
'grant_coupon_number' => $item->grant_coupon_number ?? 0, // 优惠券发放份数
];
StatisticsScanProvince::updateOrInsert($where, $scan);
usleep(100000); //睡眠 100 毫秒
}
});
// 市
$scanAward = ScanAward::query();
if($brand_id) {
$scanAward = $scanAward->where('brand_id',$brand_id);
}
$scanAward->where('day', $day)
->groupBy('brand_id', 'activity_id', 'is_many_awards', 'city_id', 'product_id')
->select(
'brand_id',
'product_id',
'activity_id',
'province_id',
'sn',
'city_id',
'province',
'city',
'is_many_awards',
Db::raw('count(*) as act_num'),
Db::raw("count(distinct(member_id)) as user_num"),
Db::raw("count(distinct(if(is_award=1,`member_id`,null))) as award_user_num"),
Db::raw("count(if(is_award=1,true,null)) as award_number"),
Db::raw("count(if(is_bonus=1,true,null)) as bonus_number"),
Db::raw("count(if(is_gift=1,true,null)) as gift_number"),
Db::raw("count(if(is_point=1,true,null)) as point_number"),
Db::raw("sum(if(is_bonus=1,bonus_num,0)) as money_num"),
Db::raw("sum(if(bonus_award_status=1,bonus_num,0)) as grant_bonus_num"),
Db::raw("sum(if(is_point=1,point_num,0)) as point_num"),
Db::raw("sum(if(point_award_status=1,point_num,0)) as grant_point_num"),
Db::raw("count(if(award_status=1,true,null)) as grant_award_number"),
Db::raw("count(if(bonus_award_status=1 and is_bonus=1,true,null)) as grant_bonus_number"),
Db::raw("count(if(gift_award_status=1 and is_gift=1,true,null)) as grant_gift_number"),
Db::raw("count(if(point_award_status=1 and is_point=1,true,null)) as grant_point_number"),
Db::raw("count(if(coupon_award_status=1 and is_coupon=1,true,null)) as grant_coupon_number"),
Db::raw("count(if(is_coupon=1,true,null)) as coupon_number"),
)
->chunk(100, function ($list) use ( $date_time, $day ) {
$created_time = Carbon::now('Asia/shanghai')->toDateTimeString();
foreach ($list as $item) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'activity_id' => $item->activity_id,
'product_id' => $item->product_id ?: 0,
'province_id' => $item->province_id ?: 0,
'city_id' => $item->city_id ?: 0,
'is_many_awards' => $item->is_many_awards ?: 0,
];
// 参与的活动人数 重新去重
$scan_award = ScanAward::where('brand_id',$item->brand_id)
->where('is_many_awards',$item->is_many_awards)
->where('province_id', $where['province_id'] )
->where('activity_id',$item->activity_id);
if( $item->product_id ) {
$scan_award = $scan_award->where('product_id',$item->product_id);
} else {
$scan_award = $scan_award->whereNull('product_id');
}
$user_ids = $scan_award->where('day', $day)
->groupBy('member_id')
->select('member_id')
->get();
$user_ids = $user_ids->pluck('member_id')->values()->toJson();
$scan = [
'province' => $item->province,
'city' => $item->city,
'act_num' => $item->act_num ?? 0, // 活动次数
'user_num' => $item->user_num ?? 0, // 参与人数
'award_user_num' => $item->award_user_num ?? 0, // 中奖人数
'award_number' => $item->award_number ?? 0, // 中奖份数
'bonus_number' => $item->bonus_number ?? 0, // 红包中奖份数
'gift_number' => $item->gift_number ?? 0, // 礼品中奖份数
'point_number' => $item->point_number ?? 0, // 积分中奖份数
'grant_award_number' => $item->grant_award_number ?? 0, // 奖项发放份数
'grant_bonus_number' => $item->grant_bonus_number ?? 0, // 红包发放份数
'grant_gift_number' => $item->grant_gift_number ?? 0, // 礼品发放份数
'grant_point_number' => $item->grant_point_number ?? 0, // 积分发放份数
'bonus_num' => $item->bonus_num ?? 0,
'grant_bonus_num' => $item->grant_bonus_num ?? 0,
'point_num' => $item->point_num ?? 0,
'grant_point_num' => $item->grant_point_num ?? 0,
'user_ids' => $user_ids,
'created_time' => $created_time,
'coupon_number' => $item->coupon_number ?? 0, // 优惠券中奖份数
'grant_coupon_number' => $item->grant_coupon_number ?? 0, // 优惠券发放份数
];
StatisticsScanCity::updateOrInsert($where, $scan);
}
});
// 区
$scanAward = ScanAward::query();
if($brand_id) {
$scanAward = $scanAward->where('brand_id',$brand_id);
}
$scanAward->where('day', $day)
->groupBy('brand_id', 'activity_id', 'is_many_awards', 'district_id', 'product_id')
->select(
'brand_id',
'product_id',
'activity_id',
'province_id',
'city_id',
'district_id',
'province',
'city',
'district',
'is_many_awards',
Db::raw('count(*) as act_num'),
Db::raw("count(distinct(member_id)) as user_num"),
Db::raw("count(distinct(if(is_award=1,`member_id`,null))) as award_user_num"),
Db::raw("count(if(is_award=1,true,null)) as award_number"),
Db::raw("count(if(is_bonus=1,true,null)) as bonus_number"),
Db::raw("count(if(is_gift=1,true,null)) as gift_number"),
Db::raw("count(if(is_point=1,true,null)) as point_number"),
Db::raw("sum(if(is_bonus=1,bonus_num,0)) as money_num"),
Db::raw("sum(if(bonus_award_status=1,bonus_num,0)) as grant_bonus_num"),
Db::raw("sum(if(is_point=1,point_num,0)) as point_num"),
Db::raw("sum(if(point_award_status=1,point_num,0)) as grant_point_num"),
Db::raw("count(if(award_status=1,true,null)) as grant_award_number"),
Db::raw("count(if(bonus_award_status=1 and is_bonus=1,true,null)) as grant_bonus_number"),
Db::raw("count(if(gift_award_status=1 and is_gift=1,true,null)) as grant_gift_number"),
Db::raw("count(if(point_award_status=1 and is_point=1,true,null)) as grant_point_number"),
Db::raw("count(if(coupon_award_status=1 and is_coupon=1,true,null)) as grant_coupon_number"),
Db::raw("count(if(is_coupon=1,true,null)) as coupon_number"),
)
->chunk(100, function ($list) use ( $date_time, $day ) {
$created_time = Carbon::now('Asia/shanghai')->toDateTimeString();
foreach ($list as $item) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'product_id' => $item->product_id ?? 0,
'activity_id' => $item->activity_id ?? 0,
'province_id' => $item->province_id ?? 0,
'city_id' => $item->city_id ?? 0,
'district_id' => $item->district_id ?? 0,
'is_many_awards' => $item->is_many_awards,
];
// 参与的活动人数 重新去重
$scan_award = ScanAward::where('brand_id',$item->brand_id)
->where('is_many_awards',$item->is_many_awards)
->where('province_id', $where['province_id'] )
->where('activity_id',$item->activity_id);
if( $item->product_id ) {
$scan_award = $scan_award->where('product_id',$item->product_id);
} else {
$scan_award = $scan_award->whereNull('product_id');
}
$user_ids = $scan_award->where('day', $day)
->groupBy('member_id')
->select('member_id')
->get();
$user_ids = $user_ids->pluck('member_id')->values()->toJson();
$scan = [
'province' => $item->province,
'city' => $item->city,
'district' => $item->district,
'act_num' => $item->act_num ?? 0, // 活动次数
'user_num' => $item->user_num ?? 0, // 参与人数
'award_user_num' => $item->award_user_num ?? 0, // 中奖人数
'award_number' => $item->award_number ?? 0, // 中奖份数
'bonus_number' => $item->bonus_number ?? 0, // 红包中奖份数
'gift_number' => $item->gift_number ?? 0, // 礼品中奖份数
'point_number' => $item->point_number ?? 0, // 积分中奖份数
'grant_award_number' => $item->grant_award_number ?? 0, // 奖项发放份数
'grant_bonus_number' => $item->grant_bonus_number ?? 0, // 红包发放份数
'grant_gift_number' => $item->grant_gift_number ?? 0, // 礼品发放份数
'grant_point_number' => $item->grant_point_number ?? 0, // 积分发放份数
'bonus_num' => $item->bonus_num ?? 0,
'grant_bonus_num' => $item->grant_bonus_num ?? 0,
'point_num' => $item->point_num ?? 0,
'grant_point_num' => $item->grant_point_num ?? 0,
'user_ids' => $user_ids,
'created_time' => $created_time,
'coupon_number' => $item->coupon_number ?? 0, // 优惠券中奖份数
'grant_coupon_number' => $item->grant_coupon_number ?? 0, // 优惠券发放份数
];
StatisticsScanDistrict::updateOrInsert($where, $scan);
}
});
} catch (\Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "活动奖项统计异常", [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
public function isEnable(): bool
{
return true;
}
}
<?php
declare(strict_types=1);
namespace App\Task;
use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use App\Model\Marketing\Scan;
use Hyperf\Logger\LoggerFactory;
use App\Model\Marketing\ScanStatistics;
use App\Model\Marketing\StatisticsScanCity;
use App\Model\Marketing\StatisticsScanDistrict;
use App\Model\Marketing\StatisticsScanProvince;
class ScanStatisticsTask
{
public $data_time = null;
public $brand_id = null;
/**
* 设置时间 便于指定时间统计
*
* @param string $data_time
* @return ScanStatisticsTask
*/
public function setDateTime($data_time)
{
$this->data_time = $data_time;
return $this;
}
/**
* 设置品牌商
*
* @param string $brand_id
* @return ScanStatisticsTask
*/
public function setBrandId( $brand_id )
{
$this->brand_id = $brand_id;
return $this;
}
public function execute()
{
$logger = di(LoggerFactory::class)->get('crontab', 'crontab');
try {
if ($this->data_time) {
$date_time = Carbon::parse($this->data_time)->toDateString();
} else {
$date_time = Carbon::yesterday('Asia/shanghai')->toDateString();
}
$day = Carbon::parse( $date_time )->format('Ymd');
$brand_id = $this->brand_id;
$scan = Scan::query();
if($brand_id) {
$scan = $scan->where('brand_id',$brand_id);
}
// 省级数据统计
$scan->where('day', $day)
->groupBy('brand_id', 'province_id', 'product_id', 'activity_id')
->select(
'brand_id',
'product_id',
'activity_id',
'province_id',
'province',
Db::raw('count(*) as scan_total'),
Db::raw("count(distinct(product_code)) as scan_number"),
Db::raw("count(if(is_first=1,true,null)) as first_scan_num"),
Db::raw("count(if(is_first=0,true,null)) as repeat_scan_num")
)
->chunk(100, function ($list) use ($date_time) {
$created_time = Carbon::now('Asia/shanghai')->toDateTimeString();
foreach ($list as $item) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'product_id' => $item->product_id ?: 0,
'activity_id' => $item->activity_id ?: 0,
'province_id' => $item->province_id ?: 0,
];
$scan = [
'province' => $item->province,
'scan_total' => $item->scan_total ?? 0,
'scan_number' => $item->scan_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0,
'repeat_scan_num' => $item->repeat_scan_num ?? 0,
'created_time' => $created_time
];
StatisticsScanProvince::updateOrInsert($where, $scan);
}
});
$scan = Scan::query();
if($brand_id) {
$scan = $scan->where('brand_id',$brand_id);
}
// 市级数据统计
$scan->where('day', $day)
->groupBy('brand_id', 'city_id', 'product_id', 'activity_id')
->select(
'brand_id',
'product_id',
'activity_id',
'province_id',
'city_id',
'province',
'city',
Db::raw('count(*) as scan_total'),
Db::raw("count(distinct(product_code)) as scan_number"),
Db::raw("count(if(is_first=1,true,null)) as first_scan_num"),
Db::raw("count(if(is_first=0,true,null)) as repeat_scan_num")
)
->chunk(100, function ($list) use ($date_time) {
foreach ($list as $item) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'product_id' => $item->product_id ?: 0,
'activity_id' => $item->activity_id ?: 0,
'province_id' => $item->province_id ?: 0,
'city_id' => $item->city_id ?: 0,
];
$scan = [
'province' => $item->province,
'city' => $item->city,
'scan_total' => $item->scan_total ?? 0,
'scan_number' => $item->scan_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0,
'repeat_scan_num' => $item->repeat_scan_num ?? 0
];
StatisticsScanCity::updateOrInsert($where, $scan);
}
});
$scan = Scan::query();
if($brand_id) {
$scan = $scan->where('brand_id',$brand_id);
}
// 区级数据统计
$scan->where('day', $day)
->groupBy('brand_id', 'district_id', 'product_id', 'activity_id')
->select(
'brand_id',
'product_id',
'activity_id',
'province_id',
'city_id',
'district_id',
'province',
'city',
'district',
Db::raw('count(*) as scan_total'),
Db::raw("count(distinct(product_code)) as scan_number"),
Db::raw("count(if(is_first=1,true,null)) as first_scan_num"),
Db::raw("count(if(is_first=0,true,null)) as repeat_scan_num")
)
->chunk(100, function ($list) use ($date_time) {
foreach ($list as $item) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'product_id' => $item->product_id ?: 0,
'activity_id' => $item->activity_id ?: 0,
'province_id' => $item->province_id ?: 0,
'city_id' => $item->city_id ?: 0,
'district_id' => $item->district_id ?: 0,
];
$scan = [
'province' => $item->province ?: '',
'city' => $item->city ?: '',
'district' => $item->district ?: '',
'scan_total' => $item->scan_total ?? 0,
'scan_number' => $item->scan_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0,
'repeat_scan_num' => $item->repeat_scan_num ?? 0
];
StatisticsScanDistrict::updateOrInsert($where, $scan);
}
});
} catch (\Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "活动扫码统计任务异常", [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
public function isEnable(): bool
{
return true;
}
}
<?php
declare ( strict_types=1 );
namespace App\Task;
use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use App\Model\Marketing\Scan;
use Hyperf\Logger\LoggerFactory;
use App\Model\Marketing\StatisticsScan;
use App\Model\Marketing\StatisticsScanStore;
use App\Model\Marketing\StatisticsScanProduct;
use App\Model\Marketing\StatisticsScanActivity;
use App\Model\Marketing\StatisticsScanActivityProduct;
class ScanTotalStatisticsTask
{
public $brand_id = null;
public $date_time;
public $day;
/**
* 设置时间 便于指定时间统计
* @param $date_time
* @return $this
*/
public function setDateTime( $date_time )
{
$this->date_time = $date_time;
return $this;
}
/**
* 设置品牌商
* @param $brand_id
* @return $this
*/
public function setBrandId( $brand_id )
{
$this->brand_id = $brand_id;
return $this;
}
public function execute()
{
$logger = di( LoggerFactory::class )->get( 'crontab', 'crontab' );
try {
if ( $this->date_time ) {
$this->date_time = Carbon::parse( $this->date_time )->toDateString();
} else {
$this->date_time = Carbon::yesterday( 'Asia/shanghai' )->toDateString();
}
$this->day = Carbon::parse( $this->date_time )->format('Ymd');
$this->total();
$this->store();
$this->product();
$this->activity();
$this->productActivity();
} catch ( \Throwable $exception ) {
$logger->error( date( 'Y-m-d H:i:s' ) . "活动扫码总统计任务异常", [
$exception->getMessage(),
$exception->getTrace()
] );
}
}
public function total()
{
$date_time = $this->date_time;
$brand_id = $this->brand_id;
$scan = Scan::query();
if ( $brand_id ) {
$scan->where( 'brand_id', $brand_id );
}
// 扫码次数
$scan->where( 'day', $this->day )
->groupBy( [ 'brand_id' ] )
->select(
'brand_id',
Db::raw( "count(id) as scan_number" ),
Db::raw( "count(DISTINCT code_sn) as scan_code_number" ),
Db::raw( "count(DISTINCT member_id) as user_number" ),
Db::raw( "count(DISTINCT(if(is_first=1,member_id,null))) as first_scan_num" ),
Db::raw( "count(DISTINCT(if(is_first=0,member_id,null))) as repeat_scan_num" ),
Db::raw( "count(if(is_first=1,true,null)) as code_first_scan_num" ),
)
->chunk( 100, function ( $list ) use ( $date_time ) {
$created_time = Carbon::now( 'Asia/shanghai' )->toDateTimeString();
foreach ( $list as $item ) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
];
$scan = [
'scan_number' => $item->scan_number ?? 0,
'scan_code_number' => $item->scan_code_number ?? 0,
'user_number' => $item->user_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0, // 首次扫码人数
'repeat_scan_num' => $item->repeat_scan_num ?? 0, // 重复扫码人数
'code_first_scan_num' => $item->code_first_scan_num ?? 0, // 首次扫码次数
'created_time' => $created_time
];
StatisticsScan::updateOrInsert( $where, $scan );
}
} );
}
public function store()
{
$date_time = $this->date_time;
$brand_id = $this->brand_id;
$scan = Scan::query()->where( 'store_id', '>', 0 );
if ( $brand_id ) {
$scan->where( 'brand_id', $brand_id );
}
// 扫码次数
$scan->where( 'day', $this->day )
->groupBy( [ 'brand_id', 'store_id' ] )
->select(
'brand_id',
'store_id',
Db::raw( "count(id) as scan_number" ),
Db::raw( "count(DISTINCT code_sn) as scan_code_number" ),
Db::raw( "count(DISTINCT member_id) as user_number" ),
Db::raw( "count(DISTINCT(if(is_first=1,member_id,null))) as first_scan_num" ),
Db::raw( "count(DISTINCT(if(is_first=0,member_id,null))) as repeat_scan_num" ),
Db::raw( "count(if(is_first=1,true,null)) as code_first_scan_num" ),
)
->chunk( 100, function ( $list ) use ( $date_time ) {
$created_time = Carbon::now( 'Asia/shanghai' )->toDateTimeString();
foreach ( $list as $item ) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'store_id' => $item->store_id ?? 0,
];
$scan = [
'scan_number' => $item->scan_number ?? 0,
'scan_code_number' => $item->scan_code_number ?? 0,
'user_number' => $item->user_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0, // 首次扫码人数
'repeat_scan_num' => $item->repeat_scan_num ?? 0, // 重复扫码人数
'code_first_scan_num' => $item->code_first_scan_num ?? 0, // 首次扫码次数
'created_time' => $created_time
];
StatisticsScanStore::updateOrInsert( $where, $scan );
}
} );
}
public function activity()
{
$date_time = $this->date_time;
$brand_id = $this->brand_id;
$scan = Scan::query()->where( 'activity_id', '>', 0 );
if ( $brand_id ) {
$scan->where( 'brand_id', $brand_id );
}
// 扫码次数
$scan->where( 'day', $this->day )
->groupBy( [ 'brand_id', 'activity_id' ] )
->select(
'brand_id',
'activity_id',
Db::raw( "count(id) as scan_number" ),
Db::raw( "count(DISTINCT code_sn) as scan_code_number" ),
Db::raw( "count(DISTINCT member_id) as user_number" ),
Db::raw( "count(DISTINCT(if(is_first=1,member_id,null))) as first_scan_num" ),
Db::raw( "count(DISTINCT(if(is_first=0,member_id,null))) as repeat_scan_num" ),
)
->chunk( 100, function ( $list ) use ( $date_time ) {
$created_time = Carbon::now( 'Asia/shanghai' )->toDateTimeString();
foreach ( $list as $item ) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'activity_id' => $item->activity_id ?? 0,
];
$scan = [
'scan_number' => $item->scan_number ?? 0,
'scan_code_number' => $item->scan_code_number ?? 0,
'user_number' => $item->user_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0, // 首次扫码人数
'repeat_scan_num' => $item->repeat_scan_num ?? 0, // 重复扫码人数
'created_time' => $created_time
];
StatisticsScanActivity::updateOrInsert( $where, $scan );
}
} );
}
public function product()
{
$date_time = $this->date_time;
$brand_id = $this->brand_id;
$scan = Scan::query()->where( 'product_id', '>', 0 );
if ( $brand_id ) {
$scan->where( 'brand_id', $brand_id );
}
// 扫码次数
$scan->where( 'day', $this->day )
->groupBy( [ 'brand_id', 'product_id' ] )
->select(
'brand_id',
'product_id',
Db::raw( "count(id) as scan_number" ),
Db::raw( "count(DISTINCT code_sn) as scan_code_number" ),
Db::raw( "count(DISTINCT member_id) as user_number" ),
Db::raw( "count(DISTINCT(if(is_first=1,member_id,null))) as first_scan_num" ),
Db::raw( "count(DISTINCT(if(is_first=0,member_id,null))) as repeat_scan_num" ),
Db::raw( "count(if(is_first=1,true,null)) as code_first_scan_num" ),
)
->chunk( 100, function ( $list ) use ( $date_time ) {
$created_time = Carbon::now( 'Asia/shanghai' )->toDateTimeString();
foreach ( $list as $item ) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'product_id' => $item->product_id ?? 0,
];
$scan = [
'scan_number' => $item->scan_number ?? 0,
'scan_code_number' => $item->scan_code_number ?? 0,
'user_number' => $item->user_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0, // 首次扫码人数
'repeat_scan_num' => $item->repeat_scan_num ?? 0, // 重复扫码人数
'code_first_scan_num' => $item->code_first_scan_num ?? 0, // 首次扫码次数
'created_time' => $created_time
];
StatisticsScanProduct::updateOrInsert( $where, $scan );
}
} );
}
public function productActivity()
{
$date_time = $this->date_time;
$brand_id = $this->brand_id;
$scan = Scan::query();
if ( $brand_id ) {
$scan->where( 'brand_id', $brand_id );
}
// 扫码次数
$scan->where( 'day', $this->day )
->groupBy( [ 'brand_id', 'product_id', 'activity_id' ] )
->select(
'brand_id',
'product_id',
'activity_id',
Db::raw( "count(id) as scan_number" ),
Db::raw( "count(DISTINCT code_sn) as scan_code_number" ),
Db::raw( "count(DISTINCT member_id) as user_number" ),
Db::raw( "count(DISTINCT(if(is_first=1,member_id,null))) as first_scan_num" ),
Db::raw( "count(DISTINCT(if(is_first=0,member_id,null))) as repeat_scan_num" ),
)
->chunk( 100, function ( $list ) use ( $date_time ) {
$created_time = Carbon::now( 'Asia/shanghai' )->toDateTimeString();
foreach ( $list as $item ) {
$where = [
'date_time' => $date_time,
'brand_id' => $item->brand_id,
'product_id' => $item->product_id ?? 0,
'activity_id' => $item->activity_id ?? 0,
];
$scan = [
'scan_number' => $item->scan_number ?? 0,
'scan_code_number' => $item->scan_code_number ?? 0,
'user_number' => $item->user_number ?? 0,
'first_scan_num' => $item->first_scan_num ?? 0, // 首次扫码人数
'repeat_scan_num' => $item->repeat_scan_num ?? 0, // 重复扫码人数
'created_time' => $created_time
];
StatisticsScanActivityProduct::updateOrInsert( $where, $scan );
}
} );
}
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Task;
use App\Model\Brand\SmsGroupSendDetail;
use App\Model\Brand\SmsGroupSendHistory;
use App\Model\Brand\SmsSystemTemplate;
use App\Model\Brand\SmsTemplate;
use Carbon\Carbon;
use Hyperf\Logger\LoggerFactory;
use YddOpen\EasyYdd;
class SmsGroupSendTask
{
public function execute()
{
$logger = di( LoggerFactory::class )->get( 'group_sms', 'group_sms' );
try {
$now = Carbon::now( 'Asia/shanghai' )->timestamp;
//查出满足群发条件的记录
$where = [
[ 'process_status', '=', 0 ],
[ 'send_time', '>', 0 ],
[ 'send_time', '<=', $now ]
];
$orWhere = [
[ 'process_status', '=', 0 ],
[ 'send_time', '=', 0 ],
[ 'create_time', '<=', date( 'Y-m-d H:i:s', $now - 60 ) ]
];
$logs = SmsGroupSendHistory::query()
->where( $where )
->orWhere( $orWhere )
->get();
if ( $logs ) {
$handel = make( EasyYdd::class, [ config( 'easy_ydd' ) ] );
// 获取码关联信息
foreach ( $logs as $log ) {
if ( $log[ 'delivery_times' ] >= 5 ) {
$logger->info( '投递次数已超过5次!' . $log[ 'brand_id' ] . ':' . $log[ 'id' ] );
continue;
}
$phones = SmsGroupSendDetail::query()
->where( 'brand_id', $log[ 'brand_id' ] )
->where( 'log_id', $log[ 'id' ] )
->pluck( 'phone' )
->toArray();
if ( empty( $phones ) ) {
$logger->info( '群发任务号码为空!' . $log[ 'brand_id' ] . ':' . $log[ 'id' ] );
continue;
}
if ( count( $phones ) != $log[ 'send_numbers' ] ) {
$logger->info( '群发任务号码不一致!' . $log[ 'brand_id' ] . ':' . $log[ 'id' ] );
continue;
}
//获取短信模板
if($log['template_type'] == 1){
$templateCode = SmsSystemTemplate::query()
->where( 'id', $log[ 'template_id' ] )
->value( 'template_code' );
}else{
$templateCode = SmsTemplate::query()
->where( 'brand_id', $log[ 'brand_id' ] )
->where( 'id', $log[ 'template_id' ] )
->value( 'template_code' );
}
if ( empty( $templateCode ) ) {
$logger->info( '不存在短信模板!' . $log[ 'brand_id' ] . ':' . $log[ 'id' ] );
continue;
}
if ( $phones && $templateCode ) {
$result = $handel->message->sendMsgGroup( $log[ 'brand_id' ], $templateCode, $log[ 'id' ] );
SmsGroupSendHistory::where( 'brand_id', $log[ 'brand_id' ] )
->where( 'id', $log[ 'id' ] )
->increment( 'delivery_times' );
$logger->info( '投递结果:', $result );
}
}
}
} catch ( \Throwable $exception ) {
$logger->error( date( 'Y-m-d H:i:s' ) . "群发短信异常", [
$exception->getMessage(),
$exception->getTrace()
] );
}
}
public function isEnable(): bool
{
return true;
}
}
<?php
declare ( strict_types=1 );
namespace App\Task;
use App\Model\Brand\Brand;
use App\Model\Brand\SmsGroupSendDetail;
use App\Model\Brand\SmsGroupSendHistory;
use App\Model\Brand\SmsSendHistory;
use App\Model\Brand\SmsStatistics;
use Carbon\Carbon;
use Hyperf\Logger\LoggerFactory;
class SmsStatisticsTask
{
public function execute()
{
$logger = di( LoggerFactory::class )->get( 'sms_statistics', 'sms_statistics' );
try {
$data = [];
$brandIds = Brand::query()->pluck( 'brand_no' )->toArray();
if ( $brandIds ) {
$yesterdayJob = Carbon::now( 'Asia/shanghai' )::yesterday();
$start = $yesterdayJob->timestamp;
$end = $start + 86400 - 1;
foreach ( $brandIds as $brandId ) {
$num1 = SmsSendHistory::query()
->where( 'brand_id', $brandId )
->where( 'status', 2 )
->whereBetween( 'create_time', [ $start, $end ] )
->count( 'id' );
$num2 = SmsGroupSendDetail::query()
->where( 'brand_id', $brandId )
->where( 'status', 1 )
->whereBetween( 'create_time', [ date( 'Y-m-d H:i:s', $start ), date( 'Y-m-d H:i:s', $end ) ] )
->count( 'id' );
if ( $num1 || $num2 ) {
$temp = [
'ordinary_number_sent' => $num1,
'group_number_sent' => $num2,
'brand_id' => $brandId,
'date' => $yesterdayJob->toDateString(),
];
$data[] = $temp;
}
}
}
if ( $data ) {
SmsStatistics::insert($data);
}
} catch ( \Throwable $exception ) {
$logger->error( date( 'Y-m-d H:i:s' ) . "短信统计切换任务异常", [
$exception->getMessage(),
$exception->getTrace()
] );
}
}
public function isEnable(): bool
{
return true;
}
}
\ No newline at end of file
<?php
declare ( strict_types=1 );
namespace App\Task;
use App\Model\Brand\SmsGroupSendDetail;
use Hyperf\Database\Model\Builder;
use Hyperf\Logger\LoggerFactory;
class SmsStatusChangeTask
{
public function execute()
{
$logger = di( LoggerFactory::class )->get( 'group_sms', 'group_sms' );
try {
$ids = SmsGroupSendDetail::query()->whereHas( 'history', function ( Builder $builder ) {
$builder->where( 'status', 2 );
} )->where( 'status', 0 )->pluck( 'id' )->toArray();
if ( $ids ) {
$logger->info( 'ids', $ids );
SmsGroupSendDetail::whereIn( 'id', $ids )->update( [
'status' => 2
] );
}
} catch ( \Throwable $exception ) {
$logger->error( date( 'Y-m-d H:i:s' ) . "群发失败状态任务异常", [
$exception->getMessage(),
$exception->getTrace()
] );
}
}
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Task;
use App\Model\Brand\Store;
use App\Model\Brand\StoreLevel;
use App\Model\Brand\StoreLevelDemoteConfig;
use App\Support\Guzzle;
use Hyperf\Logger\LoggerFactory;
class StoreLevelExpireTask
{
public function execute()
{
$logger = di( LoggerFactory::class )->get( 'crontab', 'crontab' );
try {
//门店降级有效期配置
$all_store_level_down_config = StoreLevelDemoteConfig::query()->get()->toArray();
$logger->info( '门店等级降级开始');
foreach ( $all_store_level_down_config as $config ) {
$brand_id = $config[ 'brand_id' ];
//demote_type 降级方式(1:扣除当前等级所需成长值,2:扣除全部成长值)
if ( $config[ 'is_open' ] == 1 ) {
$time = strtotime( '-' . $config[ 'day' ] . 'day' );
$start_time = date( 'Y-m-d 00:00:00', $time );
$end_time = date( 'Y-m-d 23:59:59', $time );
$store_lists = Store::query()->where( 'brand_id', $brand_id )
->whereBetween( 'store_level_change_time', [ $start_time, $end_time ] )
->get()->toArray();
foreach ( $store_lists as $store ) {
//有成长值时降级处理
if ( $store[ 'growth_value' ] > 0 ) {
if ( $config[ 'demote_type' ] == 1 ) {
//现在的等级
$now_level = StoreLevel::query()->where( 'brand_id', $brand_id )->where( 'id', $store[ 'level_id' ] )->first();
$level = $now_level[ 'level' ] - 1;
if ( $level < 1 ) {
//无等级可降,清除全部成长值
$growth_condition_value = $store[ 'growth_value' ];
} else {
//降级后的等级
$down_level = StoreLevel::query()->where( 'brand_id', $brand_id )->where( 'level', $level )->first();
$growth_condition_value = $store[ 'growth_value' ] - $down_level[ 'growth_value' ];
}
} else {
//扣除全部成长值
$growth_condition_value = $store[ 'growth_value' ];
}
//更新门店成长值,降级操作
$growth_data = [
'brand_id' => $brand_id,
'store_id' => $store[ 'id' ],
'growth_type' => 8,
'growth_condition_value' => (int) $growth_condition_value,
'is_increase' => 0,
'remark' => '扣除' . $growth_condition_value . '成长值,当前配置有效期' . $config[ 'day' ] . '天,降级方式demote_type=' . $config[ 'demote_type' ]
];
$logger->info( '更新门店成长值:', $growth_data);
$brand_business_config = config('guzzle.brand_business', []);
$client = Guzzle::getInstance([
'host' => $brand_business_config['host']
]);
$response = $client->post($brand_business_config['growth_update_url'], [
'headers' => ['sign' => Guzzle::md5Sign( $growth_data)],
'form_params' => $growth_data,
] );
if ($response->getStatusCode() == 200) {
$body = json_decode((string) $response->getBody()->getContents(), true );
if (isset($body['code']) && $body['code'] == 0) {
$logger->info( '更新门店成长值成功', $body);
}
}
$logger->error('更新门店成长值接口调用异常:', [ $response->getBody()]);
}
}
}
}
} catch ( \Throwable $exception ) {
$logger->error( date( 'Y-m-d H:i:s' ) . "门店等级降级处理异常", [
$exception->getMessage(),
$exception->getTrace()
] );
}
}
}
<?php
declare( strict_types=1 );
namespace App\Task;
use App\Model\Brand\Dealer;
use App\Model\Brand\Store;
use App\Model\Brand\StoreRebateLog;
use App\Model\Reimbursement\AssetsPointLog;
use App\Model\Reimbursement\AssetsStatistics;
use Hyperf\Logger\LoggerFactory;
class StoreRebatePointTask
{
public function execute()
{
$logger = di( LoggerFactory::class )->get( 'store_rebate_point', 'store_rebate_point' );
try {
$logger->info( '门店返利处理开始:' . date( 'Y-m-d' ) );
//门店返利记录
$rebate = StoreRebateLog::query()->where( [ 'is_implement' => 0 ] )->get();
foreach ( $rebate->toArray() as $key => $value ) {
$assets = AssetsStatistics::query()->where( [ 'brand_id' => $value[ 'brand_id' ], 'store_id' => $value[ 'store_id' ] ] )->first();
$store = Store::query()->where( [ 'brand_id' => $value[ 'brand_id' ], 'id' => $value[ 'store_id' ] ] )->first();
if ( $store[ 'store_belong' ] == 1 ) {
$parent_id = $store[ 'pid' ];
$parent_name = Dealer::query()->where( [ 'brand_id' => $value[ 'brand_id' ], 'id' => $store[ 'pid' ] ] )->value( 'dealer_name' );
} elseif ( $store[ 'store_belong' ] == 3 ) {
$parent_id = 0;
$parent_name = "总部";
}
if ( $assets ) {
AssetsStatistics::query()->where( [ 'brand_id' => $value[ 'brand_id' ], 'store_id' => $value[ 'store_id' ] ] )
->increment( 'point', $value[ 'rebate_point' ] );
} else {
$info = [
'brand_id' => $value[ 'brand_id' ],
'store_id' => $value[ 'store_id' ],
'type' => 1,
'point' => $value[ 'rebate_point' ],
];
AssetsStatistics::query()->create( $info );
}
$point_log = [
'brand_id' => $value[ 'brand_id' ],
'store_type' => 1,
'store_id' => $store[ 'id' ],
'store_name' => $store[ 'store_name' ],
'parent_id' => $parent_id ?? 0,
'parent_name' => $parent_name ?? "总部",
'point' => $value[ 'rebate_point' ],
'action' => 1,
'type' => $value[ 'type' ] == 1 ? 6 : 7,
'create_time' => time()
];
AssetsPointLog::query()->create( $point_log );
StoreRebateLog::query()->where( [ 'brand_id' => $value[ 'brand_id' ], 'id' => $value[ 'id' ] ] )->update( [ 'is_implement' => 1 ] );
}
$logger->info( '门店返利处理结束:' . date( 'Y-m-d' ) );
} catch ( \Throwable $exception ) {
$logger->error( date( 'Y-m-d H:i:s', time() ) . "门店返利处理异常,时间:" . date( 'Y-m-d' ), [
$exception->getMessage(),
$exception->getTrace()
] );
}
return true;
}
}
\ No newline at end of file
<?php
declare( strict_types=1 );
namespace App\Task;
use App\Queue\GroupQueue;
use App\Cache\TreasureCache;
use Hyperf\Logger\LoggerFactory;
use App\Model\Cloud\TreasureActivity;
class TreasureActivityEndTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('treasure', 'activity');
try {
$now_time = time();
$treasure_cache = make(TreasureCache::class);
$group_queue = make(GroupQueue::class);
TreasureActivity::query()
->where( 'end_time', '<=', $now_time)
->where( 'end_time', '>=', $now_time - 180 )
->select( [ 'id', 'brand_id', 'end_time', 'numbers' ] )
->chunkById( 100, function ( $list ) use ( $logger, $treasure_cache, $group_queue ) {
try {
foreach ( $list as $item ) {
$logger->info("item",$item->toArray());
$act_id = $item['id'];
$brand_id = $item['brand_id'];
//查出所有还在拼团的队伍
$all_groups = $treasure_cache->getAllTemporaryInfo( $brand_id, $act_id );
$logger->info( '所有未成团队伍:', $all_groups );
$group_size = $item[ 'numbers' ];
foreach ( $all_groups as $group_id => $time ) {
//处理所有未完成拼团的队伍
$params = [
'groupId' => $group_id,
'groupSize' => $group_size,
'brandId' => $brand_id,
'actId' => $act_id,
'orderType' => 6
];
$group_queue->pushGroupJob($params);
}
}
} catch ( \Exception $e ) {
$logger->error( $e->getMessage(), $e->getTrace() );
}
} );
} catch ( \Exception | \Throwable $ex ) {
$logger->error('夺宝活动结束异常'. $ex->getMessage(), [
$ex->getFile(),
$ex->getCode(),
$ex->getLine()
] );
}
return true;
}
}
<?php
declare( strict_types=1 );
namespace App\Task;
use Psr\Log\LoggerInterface;
use App\Model\Member\MemberTag;
use Hyperf\Logger\LoggerFactory;
use App\Kernel\Member\MemebrTagHandle;
/**
* 会员标签 自动打标签
*/
class UserTagAutoSetTask
{
/** @var LoggerInterface */
private $logger;
public function __construct()
{
$this->logger = di(LoggerFactory::class)->get('user_tag_auto_set', 'default');
}
public function execute()
{
try {
MemberTag::query()
->where( 'is_auto', 2 )
->chunkById( 100, function ( $list ) {
foreach ( $list as $item ) {
/** @var MemebrTagHandle $handle */
$handle = make( MemebrTagHandle::class );
$handle->execute( $item->toArray() );
}
} );
} catch ( \Exception | \Throwable $ex ) {
$this->logger->error('会员标签功能-自动打标签异常'. $ex->getMessage(), [
$ex->getCode(),
$ex->getFile(),
$ex->getLine()
] );
}
return true;
}
}
<?php
declare(strict_types=1);
namespace App\Task;
use Carbon\Carbon;
use App\Model\Vouchers;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
class VoucherStatusTask
{
public function execute()
{
$logger = ApplicationContext::getContainer()->get( LoggerFactory::class )->get( 'crontab', 'crontab' );
$now = Carbon::now('Asia/shanghai')->toDateString();
// 启用未开始的
try {
Vouchers::where( 'status', 0 )->where( 'start_time', '<=', $now )->where( 'end_time', '>=', $now )->update(['status'=>1]);
// 关闭已结束的
Vouchers::where( 'status', 1 )->where( 'end_time', '<', $now )->update(['status'=>2]);
} catch (\Throwable $exception) {
$logger->error(date('Y-m-d H:i:s') . "提货卷状态自动切换任务异常", [
$exception->getMessage(),
$exception->getTrace()
]);
}
}
public function isEnable(): bool
{
return true;
}
}
<?php
declare( strict_types=1 );
namespace App\Task;
use Hyperf\Logger\LoggerFactory;
use App\Repository\Reimbursement\WarehouseStatisticsRepository;
use Carbon\Carbon;
use App\Model\Brand\Brand;
// 每天 - 入库表统计
class WarehouseStatisticsTask
{
public function execute()
{
$logger = di(LoggerFactory::class)->get('WarehouseStatisticsTask', 'crontab');
$repository = new WarehouseStatisticsRepository();
try {
$date_time = Carbon::yesterday( 'Asia/shanghai' )->toDateString();
$start_time = date('Y-m-d 00:00:00', strtotime($date_time));
$end_time = date('Y-m-d 23:59:59', strtotime($date_time));
Brand::query()->where('status', 1)
->select('brand_no')
->chunkById(100, function($brand)use($repository, $start_time, $end_time){
foreach($brand as $v){
$brand_id = $v['brand_no'];
set_auth_brand_id($v['brand_no']);
$repository
->setBrandId($brand_id)
->setBeforeDayModel()
->setTime($start_time)
->entry();
}
}, 'brand_no');
} catch (\Exception | \Throwable $ex) {
$logger->error('入库表统计,异常'. $ex->getMessage(), [
$ex->getMessage(),
$ex->getTrace()
] );
}
}
}
#!/usr/bin/env php
<?php
ini_set('display_errors', 'on');
ini_set('display_startup_errors', 'on');
ini_set('memory_limit', '1G');
error_reporting(E_ALL);
date_default_timezone_set('Asia/Shanghai');
! defined('BASE_PATH') && define('BASE_PATH', dirname(__DIR__, 1));
! defined('SWOOLE_HOOK_FLAGS') && define('SWOOLE_HOOK_FLAGS', SWOOLE_HOOK_ALL);
require BASE_PATH . '/vendor/autoload.php';
// Self-called anonymous function that creates its own scope and keep the global namespace clean.
(function () {
Hyperf\Di\ClassLoader::init();
/** @var Psr\Container\ContainerInterface $container */
$container = require BASE_PATH . '/config/container.php';
$application = $container->get(Hyperf\Contract\ApplicationInterface::class);
$application->run();
})();
{
"name": "hyperf/hyperf-skeleton",
"type": "project",
"keywords": [
"php",
"swoole",
"framework",
"hyperf",
"microservice",
"middleware"
],
"description": "A coroutine framework that focuses on hyperspeed and flexible, specifically use for build microservices and middlewares.",
"license": "Apache-2.0",
"require": {
"php": ">=7.3",
"hyperf/async-queue": "^2.2",
"hyperf/cache": "^2.2",
"hyperf/command": "^2.2",
"hyperf/config": "~2.2.0",
"hyperf/constants": "~2.2.0",
"hyperf/crontab": "^2.2",
"hyperf/database": "~2.2.0",
"hyperf/db-connection": "~2.2.0",
"hyperf/framework": "~2.2.0",
"hyperf/guzzle": "~2.2.0",
"hyperf/http-server": "~2.2.0",
"hyperf/logger": "~2.2.0",
"hyperf/memory": "~2.2.0",
"hyperf/process": "~2.2.0",
"hyperf/redis": "^2.2",
"ydd-open/easy-ydd": "^1.2",
"ydd-open/common-cache-sdk": "v0.0.1",
"hyperf/xxl-job-incubator": "v0.1.3"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.0",
"hyperf/devtool": "~2.2.0",
"hyperf/ide-helper": "~2.2.0",
"hyperf/testing": "~2.2.0",
"hyperf/watcher": "v2.2.6.1",
"mockery/mockery": "^1.0",
"phpstan/phpstan": "^0.12",
"swoole/ide-helper": "^4.5"
},
"suggest": {
"ext-openssl": "Required to use HTTPS.",
"ext-json": "Required to use JSON.",
"ext-pdo": "Required to use MySQL Client.",
"ext-pdo_mysql": "Required to use MySQL Client.",
"ext-redis": "Required to use Redis Client."
},
"autoload": {
"psr-4": {
"App\\": "app/"
},
"files": [
"app\\Support\\Helps.php"
]
},
"autoload-dev": {
"psr-4": {
"HyperfTest\\": "./test/"
}
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
"optimize-autoloader": true,
"sort-packages": true,
"secure-http": false
},
"extra": [],
"scripts": {
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-autoload-dump": [
"rm -rf runtime/container"
],
"test": "co-phpunit --prepend test/bootstrap.php -c phpunit.xml --colors=always",
"cs-fix": "php-cs-fixer fix $1",
"analyse": "phpstan analyse --memory-limit 300M -l 0 -c phpstan.neon ./app ./config",
"start": [
"Composer\\Config::disableProcessTimeout",
"php ./bin/hyperf.php start"
]
},
"repositories": {
"packagist": {
"type": "composer",
"url": "https://mirrors.aliyun.com/composer/"
},
"common-cache-sdk": {
"type": "vcs",
"url": "http://gitlab.test.2vm.co/ydd-open/common-cache-sdk.git"
}
}
}
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
'scan' => [
'paths' => [
BASE_PATH . '/app',
],
'ignore_annotations' => [
'mixin',
],
],
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
];
<?php
declare(strict_types=1);
return [
'default' => [
'driver' => Hyperf\AsyncQueue\Driver\RedisDriver::class,
'redis' => [
'pool' => 'default'//redis 连接池
],
'channel' => 'queue',//队列前缀
'timeout' => 2,//pop 消息的超时时间
'retry_seconds' => 5,//失败后重新尝试间隔
'handle_timeout' => 10,//消息处理超时时间
'processes' => 1,//消费进程数
'concurrent' => [
'limit' => 5,//同时处理消息数
],
],
'activity' => [
'driver' => Hyperf\AsyncQueue\Driver\RedisDriver::class,
'redis' => [
'pool' => 'activity'
],
'channel' => 'queue.activity',
'timeout' => 2,
'retry_seconds' => [1, 5, 10, 20],
'handle_timeout' => 10,
'processes' => 1,
'concurrent' => [
'limit' => 5,
],
],
'order_refund' => [
'driver' => Hyperf\AsyncQueue\Driver\RedisDriver::class,
'redis' => [
'pool' => 'order'
],
'channel' => 'queue.order_refund',
'timeout' => 2,
'retry_seconds' => [1, 5, 10, 20],
'handle_timeout' => 10,
'processes' => 1,
'concurrent' => [
'limit' => 5,
],
],
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
'default' => [
'driver' => Hyperf\Cache\Driver\RedisDriver::class,
'packer' => Hyperf\Utils\Packer\PhpSerializerPacker::class,
'prefix' => 'c:',
],
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
];
<?php
declare(strict_types=1);
use Hyperf\Crontab\Crontab;
return [
'enable' => false,
'crontab' => [
// '* * * * *' 5位 分级 '* * * * * *' 6位 秒级
// 示例
//(new Crontab())->setName('Foo')->setRule('* * * * *')->setCallback([App\Task\FooTask::class, 'execute'])->setMemo('这是一个示例的定时任务'),
// 资产-提货卷 提货卷状态信息维护 每天00:01 执行
(new Crontab())->setName('voucher_status')->setRule('1 0 * * *')->setCallback([App\Task\VoucherStatusTask::class, 'execute'])->setMemo('提货卷状态信息维护'),
// // 商户-小额消费汇总 每天00:01 执行
// (new Crontab())->setName('VoucherStatus1')->setRule('1 0 * * *')->setCallback([App\Task\BrandConsumeTask::class, 'execute'])->setMemo('商户-小额消费汇总'),
// 智能营销-活动状态更新 每分钟更新一次
(new Crontab())->setName('activity_auto_switch')->setRule('* * * * *')->setCallback([App\Task\ActivityAutoSwitchTask::class, 'execute'])->setMemo('智能营销-营销活动的活动状态更新'),
// 智能营销-黑名单自动释放 每分钟更新一次
(new Crontab())->setName('blacklistautoclear')->setRule('* * * * *')->setCallback([App\Task\BlacklistAutoClearTask::class, 'execute'])->setMemo('自动释放黑名单人员'),
// 门店推荐返利,推荐门店订单返利 每30分钟更新一次
(new Crontab())->setName('StoreRebatePointTask')->setRule('*/30 * * * *')->setCallback([App\Task\StoreRebatePointTask::class, 'execute'])->setMemo('门店返利定时任务'),
// 智能营销-统计扫码
(new Crontab())->setName('act_scan_statistics')->setRule('2 0 * * *')->setCallback([App\Task\ScanStatisticsTask::class, 'execute'])->setMemo('每天00:02统计扫码信息'),
// 智能营销-总统计扫码
(new Crontab())->setName('act_scan_total_statistics')->setRule('4 0 * * *')->setCallback([App\Task\ScanTotalStatisticsTask::class, 'execute'])->setMemo('每天00:04统计扫码信息'),
// 智能营销-统计活动
(new Crontab())->setName('act_scan_award_statistics')->setRule('30 0 * * *')->setCallback([App\Task\ScanAwardStatisticsTask::class, 'execute'])->setMemo('每天00:03统计活动信息'),
// 优惠券-统计
(new Crontab())->setName('coupon_statistics')->setRule('1 1 * * *')->setCallback([App\Task\CouponStatisticsTask::class, 'execute'])->setMemo('每天01:01统计优惠券'),
// 会员卡到期处理
(new Crontab())->setName('user_vip_expire_time')->setRule('* * * * *')->setCallback([App\Task\MemberVipExpireTask::class, 'execute'])->setMemo('每分钟处理会员卡到期'),
//夺宝活动结束,处理未成团的订单
(new Crontab())->setName('treasure_activity_not_success')->setRule('*/3 * * * *')->setCallback([App\Task\TreasureActivityEndTask::class, 'execute'])->setMemo('每3分钟处理夺宝活动结束的订单'),
//删除夺宝活动缓存
(new Crontab())->setName('treasure_activity_del_cache')->setRule('30 1 * * *')->setCallback([App\Task\DelTreasureActivityCacheTask::class, 'execute'])->setMemo('每天1点30删除结束的夺宝活动缓存'),
// 群发短信任务推送,每3分钟更新一次
(new Crontab())->setName('SmsGroupSendTask')->setRule('* * * * *')->setCallback([App\Task\SmsGroupSendTask::class, 'execute'])->setMemo('营销短信群发任务'),
// 短信统计 每天00:10 执行
(new Crontab())->setName('SmsStatisticsTask')->setRule('10 0 * * *')->setCallback([App\Task\SmsStatisticsTask::class, 'execute'])->setMemo('短信统计任务'),
//群发短信状态同步任务 每天分钟 执行
(new Crontab())->setName('SmsStatusChangeTask')->setRule('* * * * *')->setCallback([App\Task\SmsStatusChangeTask::class, 'execute'])->setMemo('群发短信状态同步任务'),
// 删除过期导出文件任务 每天6点 执行
(new Crontab())->setName('DelExportFileTask')->setRule('0 6 * * *')->setCallback([App\Task\DelExportFileTask::class, 'execute'])->setMemo('删除过期导出文件'),
//扫码奖品核销超时任务 每天分钟 执行
(new Crontab())->setName('GiftVerificationTimeoutTask')->setRule('* * * * *')->setCallback([App\Task\GiftVerificationTimeoutTask::class, 'execute'])->setMemo('扫码奖品核销超时任务'),
//用户积分清理 每年 1月1日00:00:00 执行
(new Crontab())->setName('PointClearTask')->setRule('0 0 1 1 *')->setCallback([App\Task\PointClearTask::class, 'execute'])->setMemo('用户积分清理任务'),
// 会员标签功能 自动打标签 每天凌晨1点 执行
(new Crontab())->setName('user_tag_auto_set')->setRule('0 1 * * *')->setCallback([App\Task\UserTagAutoSetTask::class, 'execute'])->setMemo('会员标签-自动打标签'),
// 门店降级 每天凌晨2点 执行
(new Crontab())->setName('StoreLevelExpireTask')->setRule('0 2 * * *')->setCallback([App\Task\StoreLevelExpireTask::class, 'execute'])->setMemo('门店等级降级定时任务'),
// 泊然恩同步贝因美码数据 每天凌晨1点 执行
(new Crontab())->setName('BreSyncCodeBymTask')->setRule('0 1 * * *')->setCallback([App\Task\BreSyncCodeBymTask::class, 'execute'])->setMemo('泊然恩同步贝因美码数据'),
// 电商通订单统计数据 每天凌晨1:30点 执行
(new Crontab())->setName('EcpassOrderStatistics')->setRule('30 1 * * *')->setCallback([App\Task\EcpassOrderStatisticsTask::class, 'execute'])->setMemo('电商通订单统计数据'),
// 红包发放统计- 每天00:30 执行
(new Crontab())->setName('BonusSendCount')->setRule('30 0 * * *')->setCallback([App\Task\BonusSendCountTask::class, 'execute'])->setMemo('红包发放统计'),
// 入库统计 - 每天2点30分钟执行
(new Crontab())->setName('WarehouseStatisticsTask')->setRule('30 2 * * *')->setCallback([App\Task\WarehouseStatisticsTask::class, 'execute'])->setMemo('入库统计'),
// 出库统计 - 每天2点30分钟执行
(new Crontab())->setName('OutWarehouseStatisticsTask')->setRule('30 2 * * *')->setCallback([App\Task\OutWarehouseStatisticsTask::class, 'execute'])->setMemo('出库统计'),
// 退货统计 - 每天2点30分钟执行
(new Crontab())->setName('RefundWarehouseStatisticsTask')->setRule('30 2 * * *')->setCallback([App\Task\RefundWarehouseStatisticsTask::class, 'execute'])->setMemo('退货统计'),
// 总部商品批次库存统计 - 每天4点30分钟执行
(new Crontab())->setName('GeneralProductBatchStockStatisticsTask')->setRule('30 4 * * *')->setCallback([App\Task\GeneralProductBatchStockStatisticsTask::class, 'execute'])->setMemo('总部商品批次库存统计'),
// 总部商品库存统计 - 每天4点30分钟执行
(new Crontab())->setName('GeneralProductStockStatisticsTask')->setRule('30 4 * * *')->setCallback([App\Task\GeneralProductStockStatisticsTask::class, 'execute'])->setMemo('总部商品库存统计'),
]
];
<?php
declare( strict_types=1 );
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
$pool = [
'min_connections' => 1,
'max_connections' => 10,
'connect_timeout' => 10.0,
'wait_timeout' => 3.0,
'heartbeat' => -1,
'max_idle_time' => (float) env( 'DB_MAX_IDLE_TIME', 300 ),
];
$commands = [
'gen:model' => [
'path' => 'app/Model',
'force_casts' => true,
'inheritance' => 'Model',
],
];
return [
'default' => [
'driver' => env( 'DB_DRIVER', 'mysql' ),
'host' => env( 'DB_HOST', 'localhost' ),
'database' => env( 'DB_DATABASE', 'hyperf' ),
'port' => env( 'DB_PORT', 3306 ),
'username' => env( 'DB_USERNAME', 'root' ),
'password' => env( 'DB_PASSWORD', '' ),
'charset' => env( 'DB_CHARSET', 'utf8' ),
'collation' => env( 'DB_COLLATION', 'utf8_unicode_ci' ),
'prefix' => env( 'DB_PREFIX', '' ),
'pool' => [
'min_connections' => 1,
'max_connections' => 10,
'connect_timeout' => 10.0,
'wait_timeout' => 3.0,
'heartbeat' => -1,
'max_idle_time' => (float) env( 'DB_MAX_IDLE_TIME', 60 ),
],
'commands' => [
'gen:model' => [
'path' => 'app/Model',
'force_casts' => true,
'inheritance' => 'Model',
],
],
],
'brand' => [
'driver' => env( 'BRAND_DB_DRIVER', 'mysql' ),
'host' => env( 'BRAND_DB_HOST', 'localhost' ),
'database' => env( 'BRAND_DB_DATABASE', 'hyperf' ),
'port' => env( 'BRAND_DB_PORT', 3306 ),
'username' => env( 'BRAND_DB_USERNAME', 'root' ),
'password' => env( 'BRAND_DB_PASSWORD', '' ),
'charset' => env( 'BRAND_DB_CHARSET', 'utf8' ),
'collation' => env( 'BRAND_DB_COLLATION', 'utf8_unicode_ci' ),
'prefix' => env( 'BRAND_DB_PREFIX', '' ),
'pool' => $pool,
'commands' => $commands,
],
'r_brand' => [
'driver' => env( 'r_BRAND_DB_DRIVER', 'mysql' ),
'host' => env( 'r_BRAND_DB_HOST', 'localhost' ),
'database' => env( 'r_BRAND_DB_DATABASE', 'hyperf' ),
'port' => env( 'r_BRAND_DB_PORT', 3306 ),
'username' => env( 'r_BRAND_DB_USERNAME', 'root' ),
'password' => env( 'r_BRAND_DB_PASSWORD', '' ),
'charset' => env( 'r_BRAND_DB_CHARSET', 'utf8' ),
'collation' => env( 'r_BRAND_DB_COLLATION', 'utf8_unicode_ci' ),
'prefix' => env( 'r_BRAND_DB_PREFIX', '' ),
'pool' => $pool,
'commands' => $commands,
],
// 防窜货
'reimbursement' => [
'driver' => env( 'DB_REIMBURSEMENT_DRIVER', 'mysql' ),
'host' => env( 'DB_REIMBURSEMENT_HOST', 'localhost' ),
'database' => env( 'DB_REIMBURSEMENT_DATABASE', 'hyperf' ),
'port' => env( 'DB_REIMBURSEMENT_PORT', 3306 ),
'username' => env( 'DB_REIMBURSEMENT_USERNAME', 'root' ),
'password' => env( 'DB_REIMBURSEMENT_PASSWORD', '' ),
'charset' => env( 'DB_REIMBURSEMENT_CHARSET', 'utf8' ),
'collation' => env( 'DB_REIMBURSEMENT_COLLATION', 'utf8_unicode_ci' ),
'prefix' => env( 'DB_REIMBURSEMENT_PREFIX', '' ),
'pool' => [
'min_connections' => 1,
'max_connections' => 10,
'connect_timeout' => 10.0,
'wait_timeout' => 3.0,
'heartbeat' => -1,
'max_idle_time' => (float) env( 'DB_REIMBURSEMENT_MAX_IDLE_TIME', 60 ),
],
],
// 云店
'cloud' => [
'driver' => env( 'CLOUD_DB_DRIVER', 'mysql' ),
'host' => env( 'CLOUD_DB_HOST', 'localhost' ),
'database' => env( 'CLOUD_DB_DATABASE', 'hyperf' ),
'port' => env( 'CLOUD_DB_PORT', 3306 ),
'username' => env( 'CLOUD_DB_USERNAME', 'root' ),
'password' => env( 'CLOUD_DB_PASSWORD', '' ),
'charset' => env( 'CLOUD_DB_CHARSET', 'utf8' ),
'collation' => env( 'CLOUD_DB_COLLATION', 'utf8_unicode_ci' ),
'prefix' => env( 'CLOUD_DB_PREFIX', '' ),
'pool' => $pool,
],
// 营销
'marketing' => [
'driver' => env( 'MARKETING_DB_DRIVER', 'mysql' ),
'host' => env( 'MARKETING_DB_HOST', 'localhost' ),
'database' => env( 'MARKETING_DB_DATABASE', 'hyperf' ),
'port' => env( 'MARKETING_DB_PORT', 3306 ),
'username' => env( 'MARKETING_DB_USERNAME', 'root' ),
'password' => env( 'MARKETING_DB_PASSWORD', '' ),
'charset' => env( 'MARKETING_DB_CHARSET', 'utf8' ),
'collation' => env( 'MARKETING_DB_COLLATION', 'utf8_unicode_ci' ),
'prefix' => env( 'MARKETING_DB_PREFIX', '' ),
'pool' => $pool,
'commands' => $commands,
],
// 用户
'member' => [
'driver' => env( 'DB_MEMBER_DRIVER', 'mysql' ),
'host' => env( 'DB_MEMBER_HOST', 'localhost' ),
'database' => env( 'DB_MEMBER_DATABASE', 'hyperf' ),
'port' => env( 'DB_MEMBER_PORT', 3306 ),
'username' => env( 'DB_MEMBER_USERNAME', 'root' ),
'password' => env( 'DB_MEMBER_PASSWORD', '' ),
'charset' => env( 'DB_MEMBER_CHARSET', 'utf8' ),
'collation' => env( 'DB_MEMBER_COLLATION', 'utf8_unicode_ci' ),
'prefix' => env( 'DB_MEMBER_PREFIX', '' ),
'pool' => $pool,
'commands' => $commands,
],
'code' => [
'driver' => env('CODE_DB_DRIVER', 'mysql'),
'host' => env('CODE_DB_HOST', 'localhost'),
'database' => env('CODE_DB_DATABASE', 'hyperf'),
'port' => env('CODE_DB_PORT', 3306),
'username' => env('CODE_DB_USERNAME', 'root'),
'password' => env('CODE_DB_PASSWORD', ''),
'charset' => env('CODE_DB_CHARSET', 'utf8'),
'collation' => env('CODE_DB_COLLATION', 'utf8_unicode_ci'),
'prefix' => env('CODE_DB_PREFIX', ''),
'pool' => $pool,
'commands' => $commands,
'options' => [
PDO::MYSQL_ATTR_LOCAL_INFILE=>true
]
],
'ecpass' => [
'driver' => env( 'ECPASS_DB_DRIVER', 'mysql' ),
'host' => env( 'ECPASS_DB_HOST', 'localhost' ),
'database' => env( 'ECPASS_DB_DATABASE', 'hyperf' ),
'port' => env( 'ECPASS_DB_PORT', 3306 ),
'username' => env( 'ECPASS_DB_USERNAME', 'root' ),
'password' => env( 'ECPASS_DB_PASSWORD', '' ),
'charset' => env( 'ECPASS_DB_CHARSET', 'utf8' ),
'collation' => env( 'ECPASS_DB_COLLATION', 'utf8_unicode_ci' ),
'prefix' => env( 'ECPASS_DB_PREFIX', '' ),
'pool' => $pool,
'commands' => $commands,
],
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
\Hyperf\Contract\StdoutLoggerInterface::class => \App\Support\StdoutLogger::class,
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
'generator' => [
'amqp' => [
'consumer' => [
'namespace' => 'App\\Amqp\\Consumer',
],
'producer' => [
'namespace' => 'App\\Amqp\\Producer',
],
],
'aspect' => [
'namespace' => 'App\\Aspect',
],
'command' => [
'namespace' => 'App\\Command',
],
'controller' => [
'namespace' => 'App\\Controller',
],
'job' => [
'namespace' => 'App\\Job',
],
'listener' => [
'namespace' => 'App\\Listener',
],
'middleware' => [
'namespace' => 'App\\Middleware',
],
'Process' => [
'namespace' => 'App\\Processes',
],
],
];
<?php
declare(strict_types=1);
return [
'app_key' => env('YDD_OPEN_APP_KEY', ''),
'app_secret' => env('YDD_OPEN_APP_SECRET', ''),
'http' => [
'timeout' => 5.0,
'base_uri' => env('YDD_OPEN_APP_BASE_URI', 'https://open.2vm.co/'), //开放平台地址
'verify' => false
],
// 兼容用户中心的 JWT
'jwt' => [
'key' => env('YDD_OPEN_JWT_SECRET', ''),
'api' => env('YDD_OPEN_API_SECRET', '')
]
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
'handler' => [
'http' => [
Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
App\Exception\Handler\AppExceptionHandler::class,
],
],
];
<?php
declare( strict_types=1 );
return [
'brand_business' => [
'host' => env( 'GUZZLE_BRAND_BUSINESS_HOST', '' ),
'del_export_file' => '/v1/export/delMaturityFile', //删除导出到期文件
'growth_update_url' => '/v1/store/setGrowth', //更新门店成长值
]
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
'default' => [
'handler' => [
'class' => Monolog\Handler\StreamHandler::class,
'constructor' => [
'stream' => BASE_PATH . '/runtime/logs/default/default.log',
'level' => Monolog\Logger::DEBUG,
'maxFiles' => (int) env('LOG_MAX_FILES_DEFAULT', 7),
],
],
'formatter' => [
'class' => Monolog\Formatter\LineFormatter::class,
'constructor' => [
'format' => null,
'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => true,
],
],
],
'sql' => [
'handler' => [
'class' => Monolog\Handler\RotatingFileHandler::class,
'constructor' => [
'filename' => BASE_PATH . '/runtime/logs/sql/sql.log',
'level' => Monolog\Logger::toMonologLevel(env('LOG_LEVEL_DEFAULT', 'WARNING')),
'maxFiles' => (int) env('LOG_MAX_FILES_DEFAULT', 7),
],
],
'formatter' => [
'class' => env('LOG_FORMATTER_CLASS_SQL', Monolog\Formatter\JsonFormatter::class),
'constructor' => [
'format' => null,
'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => true,
],
],
],
'crontab' => [
'handler' => [
'class' => Monolog\Handler\RotatingFileHandler::class,
'constructor' => [
'filename' => BASE_PATH . '/runtime/logs/crontab/crontab.log',
'level' => Monolog\Logger::toMonologLevel(env('LOG_LEVEL_DEFAULT', 'WARNING')),
'maxFiles' => (int) env('LOG_MAX_FILES_DEFAULT', 7),
],
],
'formatter' => [
'class' => env('LOG_FORMATTER_CLASS_SQL', Monolog\Formatter\JsonFormatter::class),
'constructor' => [
'format' => null,
'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => true,
],
],
],
'store_rebate_point' => [
'handler' => [
'class' => Monolog\Handler\RotatingFileHandler::class,
'constructor' => [
'filename' => BASE_PATH . '/runtime/logs/store_rebate_point/store_rebate_point.log',
'level' => Monolog\Logger::toMonologLevel(env('LOG_LEVEL_DEFAULT', 'WARNING')),
'maxFiles' => (int) env('LOG_MAX_FILES_DEFAULT', 7),
],
],
'formatter' => [
'class' => env('LOG_FORMATTER_CLASS_SQL', Monolog\Formatter\JsonFormatter::class),
'constructor' => [
'format' => null,
'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => true,
],
],
],
'activity' => [
'handler' => [
'class' => Monolog\Handler\RotatingFileHandler::class,
'constructor' => [
'filename' => BASE_PATH . '/runtime/logs/activity/activity.log',
'level' => Monolog\Logger::toMonologLevel(env('LOG_LEVEL_DEFAULT', 'WARNING')),
'maxFiles' => (int) env('LOG_MAX_FILES_DEFAULT', 7),
],
],
'formatter' => [
'class' => env('LOG_FORMATTER_CLASS_SQL', Monolog\Formatter\JsonFormatter::class),
'constructor' => [
'format' => null,
'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => true,
],
],
],
'group_sms' => [
'handler' => [
'class' => Monolog\Handler\RotatingFileHandler::class,
'constructor' => [
'filename' => BASE_PATH . '/runtime/logs/group_sms/group_sms.log',
'level' => Monolog\Logger::toMonologLevel(env('LOG_LEVEL_DEFAULT', 'WARNING')),
'maxFiles' => (int) env('LOG_MAX_FILES_DEFAULT', 7),
],
],
'formatter' => [
'class' => env('LOG_FORMATTER_CLASS_SQL', Monolog\Formatter\JsonFormatter::class),
'constructor' => [
'format' => null,
'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => true,
],
],
],
'sms_statistics' => [
'handler' => [
'class' => Monolog\Handler\RotatingFileHandler::class,
'constructor' => [
'filename' => BASE_PATH . '/runtime/logs/sms_statistics/sms_statistics.log',
'level' => Monolog\Logger::toMonologLevel(env('LOG_LEVEL_DEFAULT', 'WARNING')),
'maxFiles' => (int) env('LOG_MAX_FILES_DEFAULT', 7),
],
],
'formatter' => [
'class' => env('LOG_FORMATTER_CLASS_SQL', Monolog\Formatter\JsonFormatter::class),
'constructor' => [
'format' => null,
'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => true,
],
],
],
'gift_timeout' => [
'handler' => [
'class' => Monolog\Handler\RotatingFileHandler::class,
'constructor' => [
'filename' => BASE_PATH . '/runtime/logs/gift_timeout/gift_timeout.log',
'level' => Monolog\Logger::toMonologLevel(env('LOG_LEVEL_DEFAULT', 'WARNING')),
'maxFiles' => (int) env('LOG_MAX_FILES_DEFAULT', 7),
],
],
'formatter' => [
'class' => env('LOG_FORMATTER_CLASS_SQL', Monolog\Formatter\JsonFormatter::class),
'constructor' => [
'format' => null,
'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => true,
],
],
],
'clear_point' => [
'handler' => [
'class' => Monolog\Handler\RotatingFileHandler::class,
'constructor' => [
'filename' => BASE_PATH . '/runtime/logs/clear_point/clear_point.log',
'level' => Monolog\Logger::toMonologLevel(env('LOG_LEVEL_DEFAULT', 'WARNING')),
'maxFiles' => (int) env('LOG_MAX_FILES_DEFAULT', 30),
],
],
'formatter' => [
'class' => env('LOG_FORMATTER_CLASS_SQL', Monolog\Formatter\JsonFormatter::class),
'constructor' => [
'format' => null,
'dateFormat' => 'Y-m-d H:i:s',
'allowInlineLineBreaks' => true,
],
],
],
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
'http' => [
],
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
return [
Hyperf\Crontab\Process\CrontabDispatcherProcess::class,
];
<?php
declare( strict_types=1 );
$poll = [
'min_connections' => 10,
'max_connections' => 500,
'connect_timeout' => 10.0,
'wait_timeout' => 3.0,
'heartbeat' => -1,
'max_idle_time' => (float) env( 'REDIS_MAX_IDLE_TIME', 30 ),
];
return [
'default' => [
'host' => env( 'REDIS_HOST', 'localhost' ),
'auth' => env( 'REDIS_AUTH', null ),
'port' => (int) env( 'REDIS_PORT', 6379 ),
'db' => (int) env( 'REDIS_DB', 0 ),
'pool' => $poll,
],
'order' => [
'host' => env( 'REDIS_HOST', 'localhost' ),
'auth' => env( 'REDIS_AUTH', null ),
'port' => (int) env( 'REDIS_PORT', 6379 ),
'db' => 5,
'pool' => $poll,
],
'activity' => [
'host' => env( 'REDIS_HOST', 'localhost' ),
'auth' => env( 'REDIS_AUTH', null ),
'port' => (int) env( 'REDIS_PORT', 6379 ),
'db' => 6,
'pool' => $poll,
],
'sharding' => [
'host' => env( 'REDIS_HOST', 'localhost' ),
'auth' => env( 'REDIS_AUTH', null ),
'port' => (int) env( 'REDIS_PORT', 6379 ),
'db' => 2,
'pool' => [
'min_connections' => 1,
'max_connections' => 10,
'connect_timeout' => 10.0,
'wait_timeout' => 3.0,
'heartbeat' => -1,
'max_idle_time' => (float) env( 'REDIS_MAX_IDLE_TIME', 60 ),
],
]
];
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
use Hyperf\Server\Event;
use Hyperf\Server\Server;
use Swoole\Constant;
$work_num = env('APP_WORKER_NUM', 1);
return [
'mode' => SWOOLE_PROCESS,
'servers' => [
[
'name' => 'http',
'type' => Server::SERVER_HTTP,
'host' => env( 'SWOOLE_HTTP_HOST', '0.0.0.0' ),
'port' => (int) env( 'SWOOLE_HTTP_PORT', 9501 ),
'sock_type' => SWOOLE_SOCK_TCP,
'callbacks' => [
Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
],
],
],
'settings' => [
Constant::OPTION_ENABLE_COROUTINE => true, // 开启内置协程
Constant::OPTION_WORKER_NUM => $work_num,
Constant::OPTION_PID_FILE => BASE_PATH . '/runtime/hyperf.pid',
Constant::OPTION_OPEN_TCP_NODELAY => true,
Constant::OPTION_MAX_COROUTINE => 100000,
Constant::OPTION_OPEN_HTTP2_PROTOCOL => true,
Constant::OPTION_MAX_REQUEST => 100000,
Constant::OPTION_SOCKET_BUFFER_SIZE => 2 * 1024 * 1024,
Constant::OPTION_BUFFER_OUTPUT_SIZE => 2 * 1024 * 1024,
],
'callbacks' => [
Event::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'],
Event::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'],
Event::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'],
],
];
<?php
declare( strict_types=1 );
/**
* 本系统自定义生成秘钥信息
*/
return [
// md5 加密的盐
"key" => "ywym20200.00",
// 公钥
"publicKey" => "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxx/ptWR8S56H4/HGTX0A
Z4IVUP4Bd7T2v0pT3oS+2w50ooEWqUBeND9PiDBK7lhUNT5Jc3qzfAUZyzMAip7t
xkKD2CF3pI0YqW7f65/5CZMWED1wQs7J9aMWTcYXX0NJccTNhSHdadA4Q6dwnPeu
rjSg9GH2BmpP4WnFbwBZzXpmxoMrEX1LgT9ISj19qiS1yZJ4LkLHkkxRTpXab1Nh
d0ueGIY5/WVVuyK70Ovhtn0/LM19n60l26LM+ESXglPy9btoWF0gpH8di+ZzOtmN
1DBbaMrK1hFwJcaF7zS3xHVs3CMT6n9XiHxfcsWzBTonORkit7shEKFaQhDeoNOt
CwIDAQAB
-----END PUBLIC KEY-----",
// 私钥
"privateKey" => "-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDHH+m1ZHxLnofj
8cZNfQBnghVQ/gF3tPa/SlPehL7bDnSigRapQF40P0+IMEruWFQ1PklzerN8BRnL
MwCKnu3GQoPYIXekjRipbt/rn/kJkxYQPXBCzsn1oxZNxhdfQ0lxxM2FId1p0DhD
p3Cc966uNKD0YfYGak/hacVvAFnNembGgysRfUuBP0hKPX2qJLXJknguQseSTFFO
ldpvU2F3S54Yhjn9ZVW7IrvQ6+G2fT8szX2frSXbosz4RJeCU/L1u2hYXSCkfx2L
5nM62Y3UMFtoysrWEXAlxoXvNLfEdWzcIxPqf1eIfF9yxbMFOic5GSK3uyEQoVpC
EN6g060LAgMBAAECggEBALxxGhZcyzgxBf8U/oq0gl5yf8PPLgpgSqcLK0XJMGlU
S9LCAXUZAk3FoHmM4kyfcMmWcaKEezkiBqADWz7UWscmiWlPes9R7AXkdKqjEOYb
uWSTEBtZYU1CEsh1cAbqQaYWDj0wqD4MHEMCQZN63mfkTHIaBt9ZWtFC7OI4XcQS
pIN1qMSAFUIfbgvrJ2Kw8KgwtVvjNuMX2birY37MZC9XFp/1mPI+afu/7VwuIo12
TJDn2tq0pQy9FYyMOHT4Dtn4kO4cKcoe8U8CPiByiox1/B/a6pzDcgi/7Hpy9MIw
Yblaed775ycrI6lDNu3zNWND3pHUOr6S5P7OB/CuTLECgYEA/0HMm4+qTgrlSUt0
y4cBt3fNthnSQ3BWr+XHQHav567U+h8wHd9DogzYhNlMOx3mbCaMtELnjq9UfbpT
DASuS2dru4YGBvBgysPaxyyO+Nae61tL7k4Mr+Q970J4KLTiw49O9ZELeNvDzz17
KbwQVtLvZdxcPr7qwIscxMFDovkCgYEAx7RJm0p1+Y+TqZ0bV5tDCwchlhsO0OOM
/dqX07p8MW5NafKO0M9GnUeLkjujAfRjaywcKLAS3W6clbXghLRGMgm0g3sIOdHN
JtOSYYlrh16KYZPoXKI+zHsyX602rI1bm3gxU+62gomPgJd3qsKeT556uxh9RgGp
1u7O/ZVrzSMCgYEAlJmwzQtJIR/0tcPI3cfd9vo29wF3SC15OfOyGNQ/ucgtUuOf
NnTIwelqj4SVfYD9qQ6UMUkV1xo5POyg9kkvUtSFgmkWzylXoBN/JR7KqREA+ZFv
1e74MdnVOJngrAoKTcD7PbjQDe8awmZPck96z6EDH7C2vwyUS71w5RaCErkCgYBV
UxlT6TeIviiIAqEpCCRX9N8LxFnLND4MRDY0d2wSrp8S0ljkrHruPiBLBYH7FtDX
fIw3citNQrJSYNghuuh2/qCKwKleEt7FZQYY+F7iAqm7UTepRITyVvzJ1jcS+H6Y
aX0h8E84bM/MUGsHoYmEWSD1CVyU6acINxZnUE0z4wKBgQD9SzWmI1XSn4iSclIu
B7dXjuM1ryoSrPAC0/P5F+k3RNA4jIbVOyMFDLbZMJ9K2Zj+p+D4uwJSqPzHxNo5
iixsJAcug83WjNYX/KT3B9CZLOcBmjtmQe8WQ24bFKEDq5frWhul9FXWdfviXOOk
3kmWN+BSsT82oS4qGmHYjt3u+g==
-----END PRIVATE KEY-----"
];
\ No newline at end of file
<?php
return [
// md5 加密的盐
"key" => "yddpointshop2000",
// 公钥
"publicKey" => "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCh5Nk2GLiyQFMIU+h3OEA4UeFb
u3dCH5sjd/sLTxxvwjXq7JLqJbt2rCIdzpAXOi4jL+FRGQnHaxUlHUBZsojnCcHv
hrz2knV6rXNogt0emL7f7ZMRo8IsQGV8mlKIC9xLnlOQQdRNUssmrROrCG99wpTR
RNZjOmLvkcoXdeuaCQIDAQAB
-----END PUBLIC KEY-----",
// 私钥
"privateKey" => "-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCh5Nk2GLiyQFMIU+h3OEA4UeFbu3dCH5sjd/sLTxxvwjXq7JLq
Jbt2rCIdzpAXOi4jL+FRGQnHaxUlHUBZsojnCcHvhrz2knV6rXNogt0emL7f7ZMR
o8IsQGV8mlKIC9xLnlOQQdRNUssmrROrCG99wpTRRNZjOmLvkcoXdeuaCQIDAQAB
AoGAUTcJ1H6QYTOts9bMHsrERLymzir8R9qtLBzrfp/gRxxpigHGLdph8cWmk8dl
N5HDRXmmkdV6t2S7xdOnzZen31lcWe0bIzg0SrFiUEOtg3Lwxzw2Pz0dKwg4ZUoo
GKpcIU6kEpbC2UkjBV4+2E6P1DXuhdgTyHoUA3ycxOdjCAUCQQCyjTzGPXFoHq5T
miJyVd4VXNyCXGU0ZuQayt6nPN8Gd5CcEb2S4kggzPXQcd90FO0kHfZV6+PGTrc2
ZUuz5uwPAkEA6B3lmEmiZsJS/decLzWR0T1CXaFGwTjBQbHXJ0RziAfkuy+VwSmh
vrW/ipk5xbREr5rKx3jVI2PzVOvLw7NgZwJAbUsvDFnH9WfyZZJPy5TsID97awCL
oovozM2phM0p55eAmUfyttp0ND/BqBpMIY49qoH8q5N9FYJRe6Z9tF2B2QJAQBEo
cw039xcB4zCk2l713YQEEmXWarSomuJkWWFKZiyPlJ8Ava0pCMOPl8jNKmWkY7fc
6ovOgJMw8aqXtm+HVwJAerJeUEDez2djG5pIF6aCV0bP3fhQUq8OQCgGF5Qzo9Cn
qvYreGpYKPJGVixAsEPCiLzJRhy1XfFona6VRXIIxw==
-----END RSA PRIVATE KEY-----"
];
\ No newline at end of file
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
use Hyperf\Watcher\Driver\ScanFileDriver;
return [
'driver' => ScanFileDriver::class,
'bin' => 'php',
'watch' => [
'dir' => ['app', 'config'],
'file' => ['.env'],
'scan_interval' => 2000,
],
];
<?php
return [
// 是否启用
'enable' => env('XXL_JOB_ENABLE', true),
// XXL-JOB 服务端地址
'admin_address' => env('XXL_JOB_ADMIN_ADDRESS', 'http://192.168.0.205:8080/xxl-job-admin'),
// 对应的 AppName
'app_name' => env('XXL_JOB_APP_NAME', 'xxl-job-demo'),
// 访问凭证
'access_token' => env('XXL_JOB_ACCESS_TOKEN', 'default_token'),
// 执行器心跳间隔(秒)
'heartbeat' => env('XXL_JOB_HEARTBEAT', 30),
// 日志文件保存天数 [选填]: 过期日志自动清理, 限制值大于等于3时生效; 否则, 如-1, 关闭自动清理功能;
'log_retention_days' => 30,
// 执行器 HTTP Server 相关配置
'executor_server' => [
// HTTP Server 路由前缀
'prefix_url' => env('XXL_JOB_PREFIX_URL', 'php-xxl-job'),
],
];
\ No newline at end of file
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
use Hyperf\Contract\StdoutLoggerInterface;
use Psr\Log\LogLevel;
return [
'app_name' => env('APP_NAME', 'skeleton'),
'app_env' => env('APP_ENV', 'dev'),
'scan_cacheable' => env('SCAN_CACHEABLE', false),
StdoutLoggerInterface::class => [
'log_level' => explode(',', env('STDOUT_LOG_LEVEL', 'info,notice,warning,error,critical,alert,emergency'))
],
];
<?php
/**
* Initialize a dependency injection container that implemented PSR-11 and return the container.
*/
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
use Hyperf\Di\Container;
use Hyperf\Di\Definition\DefinitionSourceFactory;
use Hyperf\Utils\ApplicationContext;
$container = new Container((new DefinitionSourceFactory(true))());
if (! $container instanceof \Psr\Container\ContainerInterface) {
throw new RuntimeException('The dependency injection container is invalid.');
}
return ApplicationContext::setContainer($container);
<?php
// declare(strict_types=1);
// /**
// * This file is part of Hyperf.
// *
// * @link https://www.hyperf.io
// * @document https://hyperf.wiki
// * @contact group@hyperf.io
// * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
// */
use Hyperf\HttpServer\Router\Router;
//Router::addRoute(['GET', 'POST', 'HEAD'], '/', 'App\Controller\IndexController@index');
// Router::get('/favicon.ico', function () {
// return '';
// });
version: '3.7'
services:
hyperf:
image: $REGISTRY_URL/$PROJECT_NAME:test
environment:
- "APP_PROJECT=hyperf"
- "APP_ENV=test"
ports:
- 9501:9501
deploy:
replicas: 1
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 5
update_config:
parallelism: 2
delay: 5s
order: start-first
networks:
- hyperf_net
configs:
- source: hyperf_v1.0
target: /opt/www/.env
configs:
hyperf_v1.0:
external: true
networks:
hyperf_net:
external: true
# Magic behaviour with __get, __set, __call and __callStatic is not exactly static analyser-friendly :)
# Fortunately, You can ingore it by the following config.
#
# vendor/bin/phpstan analyse app --memory-limit 200M -l 0
#
parameters:
reportUnmatchedIgnoredErrors: false
ignoreErrors:
- '#Static call to instance method Hyperf\\HttpServer\\Router\\Router::[a-zA-Z0-9\\_]+\(\)#'
- '#Static call to instance method Hyperf\\DbConnection\\Db::[a-zA-Z0-9\\_]+\(\)#'
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="./test/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Tests">
<directory suffix="Test.php">./test</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
</phpunit>
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace HyperfTest\Cases;
use HyperfTest\HttpTestCase;
/**
* @internal
* @coversNothing
*/
class ExampleTest extends HttpTestCase
{
public function testExample()
{
$this->assertTrue(true);
$this->assertTrue(is_array($this->get('/')));
}
}
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace HyperfTest;
use Hyperf\Testing\Client;
use PHPUnit\Framework\TestCase;
/**
* Class HttpTestCase.
* @method get($uri, $data = [], $headers = [])
* @method post($uri, $data = [], $headers = [])
* @method json($uri, $data = [], $headers = [])
* @method file($uri, $data = [], $headers = [])
* @method request($method, $path, $options = [])
*/
abstract class HttpTestCase extends TestCase
{
/**
* @var Client
*/
protected $client;
public function __construct($name = null, array $data = [], $dataName = '')
{
parent::__construct($name, $data, $dataName);
$this->client = make(Client::class);
}
public function __call($name, $arguments)
{
return $this->client->{$name}(...$arguments);
}
}
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
ini_set('display_errors', 'on');
ini_set('display_startup_errors', 'on');
error_reporting(E_ALL);
date_default_timezone_set('Asia/Shanghai');
! defined('BASE_PATH') && define('BASE_PATH', dirname(__DIR__, 1));
! defined('SWOOLE_HOOK_FLAGS') && define('SWOOLE_HOOK_FLAGS', SWOOLE_HOOK_ALL);
Swoole\Runtime::enableCoroutine(true);
require BASE_PATH . '/vendor/autoload.php';
Hyperf\Di\ClassLoader::init();
$container = require BASE_PATH . '/config/container.php';
$container->get(Hyperf\Contract\ApplicationInterface::class);
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论