> 演练模式下收集的下发/短信预览(供接口返回)
*/
protected $notifyDryRunPreview = [];
/** @var array>|null 单次请求内 Redis 列表缓存 */
protected $procuremenRedisCache = null;
/** @var array|null 单次请求内下发隐藏工序 ID 缓存 */
protected $pickHiddenScydgySetCache = null;
/** 邮件发送日志表结构已就绪缓存键 */
protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
/**
* 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
* @var array
*/
protected $noNeedRight = [
'pickreview', 'review', 'reviewcompanies',
// 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
'auditmanualpick',
// 与 rfqlist 同权,方法内校验
'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
];
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\Procuremen;
$this->maybeMigrateLegacyWflowStatusText();
$this->assignProcuremenAuthConfig();
try {
ProcuremenSchema::ensureAll();
} catch (\Throwable $e) {
}
if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
$this->ensurePurchaseEmailSendLogTableOnce();
}
}
/**
* 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
*/
protected function maybeMigrateLegacyWflowStatusText(): void
{
$flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
if (is_file($flagFile)) {
return;
}
$map = [
'0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
'1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
'2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
'3' => ProcuremenStatus::WFLOW_APPROVED,
];
try {
foreach ($map as $num => $text) {
Db::table('purchase_order')
->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
->update(['wflow_status' => $text]);
}
@file_put_contents($flagFile, date('c'));
} catch (\Throwable $e) {
Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
}
}
/**
* 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
*
* @param string[] $actions 如 pickreview、procuremen/picksubmit
*/
protected function hasProcuremenPerm(array $actions): bool
{
foreach ($actions as $action) {
$action = strtolower(trim((string)$action));
if ($action === '') {
continue;
}
if (strpos($action, 'procuremen/') !== 0) {
$action = 'procuremen/' . $action;
}
if ($this->auth->check($action)) {
return true;
}
}
$suffixes = [];
foreach ($actions as $action) {
$action = strtolower(trim((string)$action));
$action = preg_replace('#^procuremen/#', '', $action);
if ($action !== '') {
$suffixes[$action] = true;
}
}
if ($suffixes === []) {
return false;
}
try {
foreach ($this->auth->getRuleList() as $rule) {
$rule = strtolower((string)$rule);
if (strpos($rule, 'procuremen/') !== 0) {
continue;
}
foreach (array_keys($suffixes) as $suffix) {
if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
return true;
}
}
}
} catch (\Throwable $e) {
}
return false;
}
/**
* 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
*
* @param string[] $actions
*/
protected function hasProcuremenPermStrict(array $actions): bool
{
foreach ($actions as $action) {
$action = strtolower(trim((string)$action));
if ($action === '') {
continue;
}
if (strpos($action, 'procuremen/') !== 0) {
$action = 'procuremen/' . $action;
}
if ($this->auth->check($action)) {
return true;
}
}
return false;
}
/**
* 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
*
* @param string[] $titles
*/
protected function authHasAssignedRuleTitle(array $titles): bool
{
$titles = array_values(array_filter(array_map('trim', $titles)));
if ($titles === []) {
return false;
}
try {
$ids = $this->auth->getRuleIds();
if (in_array('*', $ids, true)) {
return true;
}
if ($ids === []) {
return false;
}
$rows = Db::name('auth_rule')
->where('status', 'normal')
->whereIn('id', $ids)
->column('title');
foreach ($rows as $title) {
$t = trim((string)$title);
if ($t !== '' && in_array($t, $titles, true)) {
return true;
}
}
} catch (\Throwable $e) {
}
return false;
}
protected function procuremenCanPickDelete(): bool
{
if ($this->hasProcuremenPermStrict(['pickdelete'])) {
return true;
}
return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
}
protected function procuremenCanComplete(): bool
{
if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
return true;
}
return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
}
protected function procuremenCanDispatch(): bool
{
return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
}
/**
* 前端按钮显隐(Config.procuremenAuth)
*/
protected function assignProcuremenAuthConfig(): void
{
$authMap = [
'pickreview' => $this->procuremenCanDispatch(),
'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
'pickdelete' => $this->procuremenCanPickDelete(),
'completedirectly' => $this->procuremenCanComplete(),
'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
'auditissue' => $this->hasProcuremenPerm(['auditissue']),
'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
'details' => $this->hasProcuremenPerm(['details']),
'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
'add' => $this->hasProcuremenPerm(['add']),
'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
// 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
// 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
];
$this->assignconfig('procuremenAuth', $authMap);
}
/**
* 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
* 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
*
* @param int $purchaseOrderDetailId purchase_order_detail 主键
*/
protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
{
static $mprocCfgLoaded = false;
if (!$mprocCfgLoaded) {
$mprocCfgLoaded = true;
if (is_file(APP_PATH . 'extra/mproc.php')) {
Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
}
}
$eid = (int)$purchaseOrderDetailId;
$base = $this->resolveMprocMobilePublicBaseUrl();
if ($base === '') {
throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
}
$path = trim((string)Config::get('mproc.mobile_index_path'));
if ($path === '') {
$path = '/index.php/index/index/index';
} else {
$path = '/' . ltrim($path, '/');
}
// 邮件 HTML 中多参数链接常被邮箱客户端错误解析(& 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
if ($eid > 0) {
return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
}
return $base . $path . '?main_tab=orders';
}
/**
* 邮件/短信外链:须为带点的公网域名
*/
protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
{
$u = trim((string)$baseUrl);
if ($u === '' || !preg_match('#^https?://#i', $u)) {
return false;
}
$host = parse_url($u, PHP_URL_HOST);
if (!is_string($host) || $host === '') {
return false;
}
if (strcasecmp($host, 'localhost') === 0) {
return false;
}
if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
return false;
}
if (strpos($host, '.') === false) {
return false;
}
return true;
}
/**
* 解析用于协助邮件/短信的手机端站点根
*/
protected function resolveMprocMobilePublicBaseUrl()
{
$candidates = [];
$candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
$candidates[] = trim((string)Config::get('site.indexurl'));
$cdn = trim((string)Config::get('site.cdnurl'));
if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
$candidates[] = rtrim($cdn, '/');
}
$reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
$candidates[] = $reqBase;
foreach ($candidates as $c) {
if ($c === '') {
continue;
}
$c = rtrim($c, '/');
if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
return $c;
}
}
// 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
$reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
return $reqBase;
}
Log::write('协助邮件手机链接:配置地址失效', 'warning');
return '';
}
/**
* 获取 Redis 中 procuremen_redis
*/
protected function ProcuremenRedis(): array
{
if ($this->procuremenRedisCache !== null) {
return $this->procuremenRedisCache;
}
try {
$redis = redis();
$raw = $redis->get('procuremen_redis');
if ($raw === false || $raw === '') {
$this->procuremenRedisCache = [];
return $this->procuremenRedisCache;
}
$decoded = json_decode($raw, true);
if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
$this->procuremenRedisCache = [];
return $this->procuremenRedisCache;
}
$this->procuremenRedisCache = $decoded['data'];
// 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
if ($this->loadProcuremenSidebarYmList() === []) {
$this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
}
return $this->procuremenRedisCache;
} catch (\Throwable $e) {
$this->procuremenRedisCache = [];
return $this->procuremenRedisCache;
}
}
/**
* 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
*
* @return array>
*/
protected function procuremenFetchErpPoolFromDb(): array
{
try {
$startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
$endTime = date('Y-m-d 23:59:59');
$list = Db::table('scydgy')
->alias('a')
->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
->where([
'a.bwjg' => 1,
'a.iEndBz' => 0,
'a.iType' => 0,
'a.iStatus' => 10,
])
->where('a.dStamp', '>=', $startTime)
->where('a.dStamp', '<=', $endTime)
->order('a.dStamp', 'desc')
->select();
if (!is_array($list)) {
return [];
}
try {
$redis = redis();
$payload = [
'code' => 200,
'msg' => 'success',
'data' => $list,
];
$redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
$this->procuremenRedisCache = $list;
$this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
$this->clearPickMonthPoolCaches();
$this->warmPickMonthPoolCachesFromPool($list);
} catch (\Throwable $e) {
}
return $list;
} catch (\Throwable $e) {
Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
return [];
}
}
/**
* Redis 为空时从库补一份缓存(同请求内只尝试一次)
*
* @return array>
*/
protected function procuremenEnsureRedisPool(): array
{
$pool = $this->ProcuremenRedis();
if (is_array($pool) && $pool !== []) {
return $pool;
}
static $warmed = false;
if ($warmed) {
return is_array($pool) ? $pool : [];
}
$warmed = true;
return $this->procuremenFetchErpPoolFromDb();
}
/**
* 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
*
* @param array $row
*/
protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
{
$t = $this->procuremenRowListSortTime($row, $primary);
if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
return null;
}
$mo = (int)$m[2];
if ($mo < 1 || $mo > 12) {
return null;
}
return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
}
/**
* @param array $sidebar
* @return array
*/
protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
{
$ym = trim($ym);
if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
return $sidebar;
}
foreach ($sidebar as $block) {
if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
continue;
}
foreach ($block['months'] as $item) {
if (is_array($item) && ($item['ym'] ?? '') === $ym) {
return $sidebar;
}
}
}
$y = substr($ym, 0, 4);
$mo = (int)substr($ym, 5, 2);
$sidebar[] = [
'year' => $y,
'months' => [['ym' => $ym, 'label' => $mo . '月']],
];
return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
}
/**
* @param array $sidebar
* @return string[]
*/
protected function flattenProcuremenSidebarYms(array $sidebar): array
{
$yms = [];
foreach ($sidebar as $block) {
if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
continue;
}
foreach ($block['months'] as $item) {
if (!is_array($item)) {
continue;
}
$ym = trim((string)($item['ym'] ?? ''));
if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
$yms[$ym] = true;
}
}
}
return array_keys($yms);
}
/**
* 左侧菜单(协助初选)
* 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
*/
protected function GetIndexYearMonths()
{
$ymList = $this->ensureProcuremenPickSidebarYmList();
if ($ymList === []) {
$def = date('Y-m');
$ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
}
return $this->buildYearMonthSidebar($ymList);
}
/**
* 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
*
* @return string[]
*/
protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
{
static $memo = null;
if (!$forceRefresh && is_array($memo)) {
return $memo;
}
$fromDb = $this->queryProcuremenPickSidebarYmListLight();
if ($fromDb !== []) {
$this->saveProcuremenSidebarYmList($fromDb);
$memo = $fromDb;
return $memo;
}
// 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
$cached = $this->loadProcuremenSidebarYmList();
if ($cached !== []) {
$memo = $cached;
return $memo;
}
$memo = [date('Y-m')];
return $memo;
}
/**
* @return string[] 形如 2026-07
*/
protected function loadProcuremenSidebarYmList(): array
{
try {
$raw = redis()->get('procuremen_redis_yms');
if ($raw === false || $raw === null || $raw === '') {
return [];
}
$decoded = json_decode((string)$raw, true);
if (!is_array($decoded)) {
return [];
}
$out = [];
foreach ($decoded as $ym) {
$ym = trim((string)$ym);
if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
$out[$ym] = true;
}
}
return array_keys($out);
} catch (\Throwable $e) {
return [];
}
}
/**
* @param string[] $ymList
*/
protected function saveProcuremenSidebarYmList(array $ymList): void
{
$out = [];
foreach ($ymList as $ym) {
$ym = trim((string)$ym);
if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
$out[$ym] = true;
}
}
if ($out === []) {
return;
}
try {
redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
} catch (\Throwable $e) {
}
}
/**
* @param array> $pool
* @return string[]
*/
protected function extractYearMonthsFromPoolRows(array $pool): array
{
$ymSet = [];
foreach ($pool as $r) {
if (!is_array($r)) {
continue;
}
if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
continue;
}
$ym = $this->procuremenRowYearMonth($r, 'dputrecord');
if ($ym !== null) {
$ymSet[$ym] = true;
}
}
return array_keys($ymSet);
}
/**
* 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
*
* @return string[]
*/
protected function queryProcuremenPickSidebarYmListLight(): array
{
try {
$startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
$endTime = date('Y-m-d 23:59:59');
$sql = 'SELECT DISTINCT DATE_FORMAT('
. 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
. ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
. ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
. ' FROM scydgy a'
. ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
. ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
. ' AND a.dStamp >= ? AND a.dStamp <= ?';
$rows = Db::query($sql, [$startTime, $endTime]);
if (!is_array($rows)) {
return [];
}
$out = [];
foreach ($rows as $r) {
$ym = trim((string)($r['ym'] ?? ''));
if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
$out[$ym] = true;
}
}
return array_keys($out);
} catch (\Throwable $e) {
Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
return [];
}
}
/**
* @return string[] 含当月在内的近 N 个自然月
*/
protected function buildRecentCalendarYmList(int $months = 12): array
{
$months = max(1, min(24, $months));
$out = [];
$base = strtotime(date('Y-m-01'));
for ($i = 0; $i < $months; $i++) {
$out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
}
return $out;
}
/**
* 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
* 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
*
* @return array>
*/
protected function loadPickPoolForYm(string $ym): array
{
$ym = trim($ym);
if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
return [];
}
$hit = $this->readPickMonthPoolCache($ym);
if ($hit !== null) {
return $hit;
}
return $this->queryPickPoolForYmFromDb($ym);
}
/**
* @return array>|null null=无有效缓存(含旧版空数组误缓存)
*/
protected function readPickMonthPoolCache(string $ym): ?array
{
try {
$raw = redis()->get('procuremen_pick_pool:' . $ym);
if ($raw === false || $raw === null || $raw === '') {
return null;
}
$decoded = json_decode((string)$raw, true);
if (!is_array($decoded)) {
return null;
}
// 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
return $decoded['rows'];
}
// 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
if ($decoded === []) {
try {
redis()->del('procuremen_pick_pool:' . $ym);
} catch (\Throwable $e) {
}
return null;
}
if (isset($decoded[0]) && is_array($decoded[0])) {
return $decoded;
}
return null;
} catch (\Throwable $e) {
return null;
}
}
/**
* @param array> $rows
*/
protected function writePickMonthPoolCache(string $ym, array $rows): void
{
try {
redis()->setex(
'procuremen_pick_pool:' . $ym,
600,
json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
);
} catch (\Throwable $e) {
}
}
/**
* @param array> $pool
* @return array>
*/
protected function filterPoolRowsByYm(array $pool, string $ym): array
{
$out = [];
foreach ($pool as $r) {
if (!is_array($r)) {
continue;
}
if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
continue;
}
if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
$out[] = $r;
}
}
return $out;
}
/**
* 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
*
* @return array>
*/
protected function queryPickPoolForYmFromDb(string $ym): array
{
$monthStart = $ym . '-01 00:00:00';
$monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
// 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
$queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
$queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
try {
$list = Db::table('scydgy')
->alias('a')
->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
->where([
'a.bwjg' => 1,
'a.iEndBz' => 0,
'a.iType' => 0,
'a.iStatus' => 10,
])
->where('a.dStamp', '>=', $queryStart)
->where('a.dStamp', '<=', $queryEnd)
->order('a.dStamp', 'desc')
->select();
} catch (\Throwable $e) {
Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
return [];
}
if (!is_array($list)) {
$list = [];
}
$out = $this->filterPoolRowsByYm($list, $ym);
// 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
$this->writePickMonthPoolCache($ym, $out);
try {
$yms = $this->loadProcuremenSidebarYmList();
if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
$yms[] = $ym;
$this->saveProcuremenSidebarYmList($yms);
}
} catch (\Throwable $e) {
}
return $out;
}
/**
* 整包写入后拆成按月小缓存,供初选列表秒开
*
* @param array> $pool
*/
protected function warmPickMonthPoolCachesFromPool(array $pool): void
{
if ($pool === []) {
return;
}
$byYm = [];
foreach ($pool as $r) {
if (!is_array($r)) {
continue;
}
if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
continue;
}
$rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
if ($rowYm === null) {
continue;
}
$byYm[$rowYm][] = $r;
}
if ($byYm === []) {
return;
}
try {
$redis = redis();
foreach ($byYm as $rowYm => $rows) {
$redis->setex(
'procuremen_pick_pool:' . $rowYm,
600,
json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
);
}
try {
$redis->del('procuremen_pick_hidden_scydgy_v1');
} catch (\Throwable $e) {
}
} catch (\Throwable $e) {
}
}
/**
* 刷新整包后清理近月缓存,避免脏读
*/
protected function clearPickMonthPoolCaches(int $months = 24): void
{
try {
$redis = redis();
foreach ($this->buildRecentCalendarYmList($months) as $ym) {
try {
$redis->del('procuremen_pick_pool:' . $ym);
} catch (\Throwable $e) {
}
}
} catch (\Throwable $e) {
}
$this->invalidatePickHiddenScydgyCache();
}
/**
* 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
*/
protected function invalidatePickHiddenScydgyCache(): void
{
$this->pickHiddenScydgySetCache = null;
try {
redis()->del('procuremen_pick_hidden_scydgy_v1');
} catch (\Throwable $e) {
}
}
/** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
protected function procuremenReleaseSessionLock(): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
@session_write_close();
}
}
/**
* @param string[] $ymList 形如 2026-06
* @return array
*/
protected function buildYearMonthSidebar(array $ymList): array
{
rsort($ymList, SORT_STRING);
$byYear = [];
foreach ($ymList as $ym) {
$y = substr($ym, 0, 4);
$mo = (int)substr($ym, 5, 2);
if (!isset($byYear[$y])) {
$byYear[$y] = [];
}
$byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
}
krsort($byYear, SORT_NUMERIC);
foreach ($byYear as $y => $items) {
usort($byYear[$y], function ($a, $b) {
return strcmp($b['ym'], $a['ym']);
});
}
$sidebar = [];
foreach ($byYear as $y => $months) {
$sidebar[] = ['year' => $y, 'months' => $months];
}
return $sidebar;
}
/**
* 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
*/
protected function GetIssuedOrderYearMonths(string $stage): array
{
$ymSet = [];
try {
$query = Db::table('purchase_order');
$this->applyPurchaseOrderNotDeletedWhere($query);
if ($stage === 'audit') {
$query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
} elseif ($stage === 'confirm') {
$this->applyPurchaseOrderConfirmStageWhere($query);
} else {
return $this->GetIndexYearMonths();
}
$rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
if (is_array($rows)) {
foreach ($rows as $r) {
if (!is_array($r)) {
continue;
}
$ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
if ($ym !== null) {
$ymSet[$ym] = true;
}
}
}
} catch (\Throwable $e) {
$ymSet = [];
}
$ymList = array_keys($ymSet);
if ($ymList === []) {
$def = $this->resolveProcuremenDefaultYm($stage);
$ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
}
return $this->buildYearMonthSidebar($ymList);
}
/**
* 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
*/
protected function resolveProcuremenDefaultYm(string $stage): string
{
if ($stage === 'pick') {
$yms = $this->ensureProcuremenPickSidebarYmList();
if ($yms !== []) {
rsort($yms, SORT_STRING);
return $yms[0];
}
return date('Y-m');
}
try {
$query = Db::table('purchase_order');
$this->applyPurchaseOrderNotDeletedWhere($query);
if ($stage === 'audit') {
$query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
} elseif ($stage === 'confirm') {
$this->applyPurchaseOrderConfirmStageWhere($query);
} else {
return date('Y-m');
}
$latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
if ($latest === null || $latest === '') {
$latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
}
$t = $this->formatProcuremenDetailTime($latest);
if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
return $m[1] . '-' . $m[2];
}
} catch (\Throwable $e) {
}
return date('Y-m');
}
protected function applyPurchaseOrderNotDeletedWhere($query): void
{
$query->whereRaw(
'(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
);
}
/**
* 审批列表:wflow_status = 待审批(兼容旧值 2)
*/
protected function applyPurchaseOrderConfirmStageWhere($query): void
{
$vals = ProcuremenStatus::wflowPendingApprovalValues();
$quoted = [];
foreach ($vals as $v) {
$quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
}
if ($quoted === []) {
$query->whereRaw('1 = 0');
return;
}
$query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
$query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
}
/**
* 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
*
* @param array $row
* @return array
*/
protected function normalizePurchaseOrderListTimeRow(array $row): array
{
$row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
$pick = trim((string)($row['pick_time'] ?? ''));
if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
$t = trim((string)($row[$key] ?? ''));
if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
$row['pick_time'] = $t;
break;
}
}
}
return $row;
}
/**
* 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
*/
protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
{
if (!in_array($stage, ['audit', 'confirm'], true)) {
return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
}
if ($pool === []) {
$def = $this->resolveProcuremenDefaultYm($stage);
return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
}
$tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
return false;
}
$monthStart = $ym . '-01 00:00:00';
$monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
$probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
return $probe !== [];
};
if ($tryYm($requestedYm)) {
return $requestedYm;
}
$fallback = $this->resolveProcuremenDefaultYm($stage);
if ($tryYm($fallback)) {
return $fallback;
}
$bestYm = '';
$bestTime = '';
foreach ($pool as $row) {
if (!is_array($row)) {
continue;
}
$t = $this->procuremenRowListSortTime($row, $listTimePrimary);
if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
continue;
}
$ymRow = $m[1];
if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
$bestTime = $t;
$bestYm = $ymRow;
}
}
if ($bestYm !== '') {
return $bestYm;
}
return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
}
protected function isPurchaseOrderDetailVoid(array $row): bool
{
if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
return true;
}
return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
}
/**
* 仅当前有效下发明细(排除废弃归档)
*/
protected function applyActivePurchaseOrderDetailWhere($query): void
{
$query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
}
/**
* @param array $detailRow
*/
protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
{
if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
return false;
}
$statusName = trim((string)($detailRow['status_name'] ?? ''));
return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
}
/**
* 废弃退回初选:下发明细标记归档,不物理删除
*
* @param array $scydgyIds
*/
protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
{
$ids = [];
foreach ($scydgyIds as $sid) {
$n = (int)$sid;
if ($this->isValidScydgyRowId($n) || $n < 0) {
$ids[$n] = true;
}
}
if ($ids === []) {
return;
}
$void = ProcuremenStatus::POD_VOID;
Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($ids))
->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
->update([
'status' => $void,
'status_name' => $void,
]);
}
/**
* 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
*/
protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
{
$p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
$norm = function (string $col) use ($p): string {
return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
};
$createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
$parts = [];
foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
if ($key === 'createtime') {
$parts[] = $createtime;
} else {
$parts[] = $norm($key);
}
}
return 'COALESCE(' . implode(', ', $parts) . ')';
}
protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
{
$expr = $this->procuremenListTimeSqlExpr($primary, $alias);
$query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
}
/**
* @return array>
*/
protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
{
$this->ensurePurchaseOrderCzlyqColumn();
$fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
. 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
try {
$query = Db::table('purchase_order')->field($fields);
$this->applyPurchaseOrderNotDeletedWhere($query);
if ($stage === 'audit') {
$query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
} elseif ($stage === 'confirm') {
$this->applyPurchaseOrderConfirmStageWhere($query);
} else {
return [];
}
$query->order('pick_time', 'desc')->order('id', 'desc');
if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
$monthStart = $ym . '-01 00:00:00';
$monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
$this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
}
$rows = $query->select();
} catch (\Throwable $e) {
Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
$rows = [];
}
return is_array($rows) ? $rows : [];
}
/**
* 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
*/
protected function resolveProcuremenListStage(): string
{
$tab = trim((string)$this->request->request('wff_tab', ''));
if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
return $tab;
}
$action = strtolower((string)$this->request->action());
if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
return $action;
}
return 'pick';
}
protected function assignProcuremenListPage(string $stage, string $pageTitle): void
{
$this->procuremenReleaseSessionLock();
$rootTrue = rtrim((string)$this->request->root(true), '/');
$indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
$indexPhpRoot = $rootTrue . '/index.php';
}
$this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
$defaultYm = $this->resolveProcuremenDefaultYm($stage);
$sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
$sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
$this->view->assign('defaultYm', $defaultYm);
$this->view->assign('sidebarYearMonths', $sidebar);
$this->view->assign('procuremenStage', $stage);
$this->view->assign('procuremenPageTitle', $pageTitle);
$this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
$this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
$this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
$this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
$this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
}
/**
* 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
*
* @return array{czlyq:array,CCLBMMC:array,cywyxm:array,CGYMC:array}
*/
protected function buildProcuremenFilterOptions(string $stage): array
{
$buckets = [
'czlyq' => [],
'CCLBMMC' => [],
'cywyxm' => [],
'CGYMC' => [],
];
$maxPerField = 300;
try {
if ($stage === 'pick') {
// 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
return $buckets;
}
if (in_array($stage, ['audit', 'confirm'], true)) {
$this->ensurePurchaseOrderCzlyqColumn();
foreach (array_keys($buckets) as $field) {
try {
$query = Db::table('purchase_order')->field($field);
$this->applyPurchaseOrderNotDeletedWhere($query);
if ($stage === 'audit') {
$query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
} else {
$this->applyPurchaseOrderConfirmStageWhere($query);
}
$query->where($field, '<>', '')->whereNotNull($field);
$vals = $query->distinct(true)->limit($maxPerField)->column($field);
if (!is_array($vals)) {
continue;
}
foreach ($vals as $v) {
$v = trim((string)$v);
if ($v !== '') {
$buckets[$field][$v] = $v;
}
}
} catch (\Throwable $e) {
// 单字段失败不影响其它
}
}
}
} catch (\Throwable $e) {
Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
}
foreach ($buckets as &$set) {
if ($set !== []) {
ksort($set, SORT_STRING);
}
}
unset($set);
return $buckets;
}
/**
* filter JSON 是否含有效条件
*
* @param array $filterArr
*/
protected function procuremenFilterArrHasValue(array $filterArr): bool
{
foreach ($filterArr as $v) {
if (is_array($v)) {
if (array_filter($v, function ($x) {
return $x !== '' && $x !== null;
})) {
return true;
}
} elseif ($v !== '' && $v !== null) {
return true;
}
}
return false;
}
/**
* 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
*
* @param array $filterArr
* @param array $opArr
*/
protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
{
if ($search !== '') {
return false;
}
foreach ($filterArr as $fk => $fv) {
if (is_array($fv)) {
continue;
}
if ($fv === '' && $fv !== '0' && $fv !== 0) {
continue;
}
if ($fv === null) {
continue;
}
$sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
$sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
if ($sym === '' || $sym === '=') {
continue;
}
return false;
}
return true;
}
/**
* 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
*
* @param array $rows
* @return array{czlyq:array,CCLBMMC:array,cywyxm:array,CGYMC:array}
*/
protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
{
$buckets = [
'czlyq' => [],
'CCLBMMC' => [],
'cywyxm' => [],
'CGYMC' => [],
];
foreach ($rows as $r) {
if (!is_array($r)) {
continue;
}
foreach ($buckets as $field => &$set) {
if (count($set) >= $maxPerField) {
continue;
}
$v = trim((string)($r[$field] ?? ''));
if ($v !== '') {
$set[$v] = $v;
}
}
unset($set);
$full = true;
foreach ($buckets as $set) {
if (count($set) < $maxPerField) {
$full = false;
break;
}
}
if ($full) {
break;
}
}
foreach ($buckets as &$set) {
if ($set !== []) {
// 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
$normalized = [];
foreach ($set as $k => $v) {
$s = trim((string)(is_scalar($v) ? $v : $k));
if ($s === '') {
continue;
}
$normalized[$s] = $s;
}
ksort($normalized, SORT_STRING);
$set = $normalized;
}
}
unset($set);
return $buckets;
}
/** 协助下发(选工序+供应商,发短信邮件通知报价) */
public function pick()
{
$this->request->filter(['strip_tags', 'trim']);
if (!$this->request->isAjax()) {
$this->assignProcuremenListPage('pick', '协助下发');
return $this->view->fetch('procuremen/index');
}
return $this->index();
}
/** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
public function audit()
{
$this->request->filter(['strip_tags', 'trim']);
if (!$this->request->isAjax()) {
$this->assignProcuremenListPage('audit', '确认供应商');
return $this->view->fetch('procuremen/index');
}
return $this->index();
}
/** 采购确认(定标) */
public function confirm()
{
$this->request->filter(['strip_tags', 'trim']);
if (!$this->request->isAjax()) {
$this->assignProcuremenListPage('confirm', '采购确认');
return $this->view->fetch('procuremen/index');
}
return $this->index();
}
/**
* 列表页(兼容旧菜单 procuremen/index,等同协助下发)
*/
public function index()
{
$this->request->filter(['strip_tags', 'trim']);
if (!$this->request->isAjax()) {
$this->assignProcuremenListPage('pick', '协助下发');
return $this->view->fetch('procuremen/index');
}
if ($this->request->request('keyField')) {
return $this->selectpage();
}
$this->procuremenReleaseSessionLock();
list(, $sort, $order, $offset, $limit) = $this->buildparams();
$limit = max(10, min(500, (int)$limit));
$ym = $this->request->request('ym', '');
$ym = is_string($ym) ? trim($ym) : '';
/* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
$wffTab = $this->resolveProcuremenListStage();
if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
$ym = in_array($wffTab, ['audit', 'confirm'], true)
? $this->resolveProcuremenDefaultYm($wffTab)
: date('Y-m');
}
if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
$ym = date('Y-m');
}
$monthStart = $ym . '-01 00:00:00';
$monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
$search = trim((string)$this->request->get('search', ''));
$filterArr = (array)json_decode($this->request->get('filter', ''), true);
$opArr = (array)json_decode($this->request->get('op', ''), true);
if (!is_array($filterArr)) {
$filterArr = [];
}
if (!is_array($opArr)) {
$opArr = [];
}
// 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
$bidOpenStatusFilter = '';
foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
if (!array_key_exists($bidFk, $filterArr)) {
continue;
}
$bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
unset($filterArr[$bidFk], $opArr[$bidFk]);
}
// 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
$applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
$hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
try {
$listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
if ($wffTab === 'audit') {
$pool = $this->procuremenPoolFromPurchaseOrderDbRows(
$this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
);
} elseif ($wffTab === 'confirm') {
$dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
if ($dbRows === []) {
try {
$dbRows = Db::table('purchase_order')
->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
. 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
->order('pick_time', 'desc')->order('id', 'desc')
->select();
} catch (\Throwable $e) {
Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
$dbRows = [];
}
}
$pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
if ($pool === []) {
Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
}
} else {
// 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
if ($applyMonthRange) {
$pool = $this->loadPickPoolForYm($ym);
} else {
$pool = $this->procuremenEnsureRedisPool();
}
if (!is_array($pool)) {
$pool = [];
}
// 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
$hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
if ($pool !== [] && $hideSet !== []) {
$pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
if (!is_array($r)) {
return false;
}
$id = (int)($r['ID'] ?? $r['id'] ?? 0);
return $id <= 0 || !isset($hideSet[$id]);
}));
}
// 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
if ($pool === []) {
return json([
'total' => 0,
'rows' => [],
'activeYm' => $ym,
'filterOptions' => (
(int)$offset === 0
&& !$hasActiveSearch
&& (string)$this->request->get('need_filter_options', '1') !== '0'
)
? $this->extractProcuremenFilterOptionsFromRows([])
: new \stdClass(),
]);
}
}
if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
$ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
$monthStart = $ym . '-01 00:00:00';
$monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
}
$filtered = $this->filterProcuremenIndexPool(
$pool,
$monthStart,
$monthEnd,
$applyMonthRange,
$search,
$filterArr,
$opArr,
$listTimePrimary
);
/* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
if (in_array($wffTab, ['audit', 'confirm'], true)) {
$filtered = $this->collapseProcuremenPoolByOrder($filtered);
}
if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
$filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
}
$sortField = 'ID';
if (is_string($sort) && $sort !== '') {
$parts = explode(',', $sort);
$sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
if ($sortField === '') {
$sortField = 'ID';
}
}
$ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
$nFiltered = count($filtered);
if ($nFiltered > 1) {
if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
usort($filtered, function ($a, $b) use ($sortField, $ord) {
$ta = $this->procuremenRowListSortTime($a, $sortField);
$tb = $this->procuremenRowListSortTime($b, $sortField);
if ($ta === $tb) {
return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
}
if ($ta === '') {
return 1;
}
if ($tb === '') {
return -1;
}
return strcmp($ta, $tb) * $ord;
});
} elseif ($sortField === 'ID') {
$sortKeys = [];
foreach ($filtered as $i => $row) {
$sortKeys[$i] = (int)($row['ID'] ?? 0);
}
$dir = $ord === 1 ? SORT_ASC : SORT_DESC;
array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
} elseif ($sortField === 'CCYDH') {
usort($filtered, function ($a, $b) use ($ord) {
$sa = trim((string)($a['CCYDH'] ?? ''));
$sb = trim((string)($b['CCYDH'] ?? ''));
if ($sa === $sb) {
return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
}
if ($sa === '') {
return 1;
}
if ($sb === '') {
return -1;
}
return strcmp($sa, $sb) * $ord;
});
} else {
usort($filtered, function ($a, $b) use ($sortField, $ord) {
$va = $a[$sortField] ?? null;
$vb = $b[$sortField] ?? null;
$sa = (string)$va;
$sb = (string)$vb;
if ($sa === $sb) {
return 0;
}
return strcmp($sa, $sb) * $ord;
});
}
}
$offset = max(0, (int)$offset);
$limit = max(1, (int)$limit);
$rows = array_slice($filtered, $offset, $limit);
foreach ($rows as &$rw) {
if (!is_array($rw)) {
continue;
}
$rid = (int)($rw['ID'] ?? 0);
$rw['_iss_out'] = ($wffTab !== 'pick');
}
unset($rw);
if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
$idList = [];
foreach ($rows as $rw) {
if (!is_array($rw)) {
continue;
}
if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
foreach ($rw['_order_merge_rows'] as $mr) {
$mid = (int)($mr['ID'] ?? 0);
if ($this->isValidScydgyRowId($mid)) {
$idList[$mid] = true;
}
}
}
$id = (int)($rw['ID'] ?? 0);
if ($this->isValidScydgyRowId($id)) {
$idList[$id] = true;
}
}
$detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
foreach ($rows as &$rw) {
if (!is_array($rw)) {
continue;
}
$mergeIds = [];
if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
foreach ($rw['_order_merge_rows'] as $mr) {
$mid = (int)($mr['ID'] ?? 0);
if ($this->isValidScydgyRowId($mid)) {
$mergeIds[$mid] = true;
}
}
}
$rid = (int)($rw['ID'] ?? 0);
if ($this->isValidScydgyRowId($rid)) {
$mergeIds[$rid] = true;
}
$s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
$rw['po_detail_count'] = $s['cnt'];
$rw['po_amount_fill_cnt'] = $s['amt'];
$rw['po_delivery_fill_cnt'] = $s['deliv'];
}
unset($rw);
}
if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
$idList = [];
foreach ($rows as $rw) {
if (!is_array($rw)) {
continue;
}
if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
foreach ($rw['_order_merge_rows'] as $mr) {
$mid = (int)($mr['ID'] ?? 0);
if ($this->isValidScydgyRowId($mid)) {
$idList[$mid] = true;
}
}
}
$id = (int)($rw['ID'] ?? 0);
if ($this->isValidScydgyRowId($id)) {
$idList[$id] = true;
}
}
$quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
$bidOpenSet = [];
$manualPickSet = [];
if ($wffTab === 'audit') {
$ccydhList = [];
foreach ($rows as $rw0) {
if (!is_array($rw0)) {
continue;
}
$c0 = trim((string)($rw0['CCYDH'] ?? ''));
if ($c0 !== '') {
$ccydhList[] = $c0;
}
}
$bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
$manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
}
foreach ($rows as &$rw) {
if (!is_array($rw)) {
continue;
}
$mergeIds = [];
if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
foreach ($rw['_order_merge_rows'] as $mr) {
$mid = (int)($mr['ID'] ?? 0);
if ($this->isValidScydgyRowId($mid)) {
$mergeIds[$mid] = true;
}
}
}
$rid = (int)($rw['ID'] ?? 0);
if ($this->isValidScydgyRowId($rid)) {
$mergeIds[$rid] = true;
}
$buckets = [];
foreach (array_keys($mergeIds) as $mid) {
if (isset($quoteBucket[$mid])) {
$buckets[] = $quoteBucket[$mid];
}
}
$supplierText = $buckets !== []
? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
: '';
if ($wffTab === 'confirm') {
$picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
if ($picked === '') {
// 兜底:从合并工序行取
if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
foreach ($rw['_order_merge_rows'] as $mr) {
if (!is_array($mr)) {
continue;
}
$pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
if ($pn !== '') {
$picked = $pn;
break;
}
}
}
}
$rw['picked_supplier_name'] = $picked;
} else {
$rw['notify_supplier_text'] = $supplierText;
$ccydh = trim((string)($rw['CCYDH'] ?? ''));
$verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
$manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
$rw['bid_open_verified'] = $verified ? 1 : 0;
$rw['manual_picked'] = $manualPicked ? 1 : 0;
if ($verified) {
$rw['bid_open_status_text'] = '已开标';
} elseif ($manualPicked) {
$rw['bid_open_status_text'] = '已指定供应商';
} else {
$rw['bid_open_status_text'] = '待开标';
}
}
}
unset($rw);
}
if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
$this->enrichProcuremenListMilestoneTimes($rows);
$this->syncCollapsedOrderQtyPriceForList($rows);
}
if ($wffTab === 'all' && count($rows) > 0) {
$this->mergePurchaseOrder($rows);
}
if ($wffTab === 'pick' && count($rows) > 0) {
$this->mergePurchaseOrder($rows);
}
foreach ($rows as &$rwClean) {
if (is_array($rwClean)) {
unset($rwClean['_order_merge_rows']);
if (array_key_exists('NGZL', $rwClean)) {
$rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
}
}
}
unset($rwClean);
return json([
'total' => count($filtered),
'rows' => $rows,
'activeYm' => $ym,
// 初选:把有数据的月份带回,替换「空月份日历」侧栏
'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
? $this->ensureProcuremenPickSidebarYmList()
: [],
// 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
'filterOptions' => (
(int)$offset === 0
&& !$hasActiveSearch
&& (string)$this->request->get('need_filter_options', '1') !== '0'
)
? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
: new \stdClass(),
]);
} catch (\Throwable $e) {
Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
return json([
'total' => 0,
'rows' => [],
]);
}
}
/**
* @param array> $pool
* @return int[]
*/
protected function extractScydgyIdsFromPool(array $pool): array
{
$ids = [];
foreach ($pool as $r) {
if (!is_array($r)) {
continue;
}
$id = (int)($r['ID'] ?? $r['id'] ?? 0);
if ($id > 0) {
$ids[$id] = $id;
}
}
return array_values($ids);
}
/**
* 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
*
* @param int[] $scydgyIds
* @return array
*/
protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
{
$hideSet = [];
$scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
return $id > 0;
}));
if ($scydgyIds === []) {
return $hideSet;
}
// 分批,避免 whereIn 过长
foreach (array_chunk($scydgyIds, 500) as $chunk) {
try {
$poIds = Db::table('purchase_order')
->where('scydgy_id', 'in', $chunk)
->where(function ($q) {
$q->whereIn('wflow_status', array_merge(
ProcuremenStatus::wflowPendingConfirmValues(),
ProcuremenStatus::wflowPendingApprovalValues()
))
->whereOr(function ($q1) {
$q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
})
->whereOr(function ($q2) {
$q2->whereNotNull('pick_time')
->where('pick_time', '<>', '')
->where('pick_time', '<>', '0000-00-00 00:00:00');
})
->whereOr(function ($q3) {
$q3->whereNotNull('mod_rq')
->where('mod_rq', '<>', '')
->where('mod_rq', 'not like', '0000-00-00%');
});
})
->column('scydgy_id');
if (is_array($poIds)) {
foreach ($poIds as $pid) {
$k = (int)$pid;
if ($k !== 0) {
$hideSet[$k] = true;
}
}
}
} catch (\Throwable $e) {
}
try {
$detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
$this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
$detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
if (is_array($detIds)) {
foreach ($detIds as $pid) {
$k = (int)$pid;
if ($this->isValidScydgyRowId($k)) {
$hideSet[$k] = true;
}
}
}
} catch (\Throwable $e) {
}
}
return $hideSet;
}
/**
* 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
*
* @return array
*/
protected function loadPickHiddenScydgySet(): array
{
if ($this->pickHiddenScydgySetCache !== null) {
return $this->pickHiddenScydgySetCache;
}
$cacheKey = 'procuremen_pick_hidden_scydgy_v1';
try {
$raw = redis()->get($cacheKey);
if ($raw !== false && $raw !== null && $raw !== '') {
$ids = json_decode((string)$raw, true);
if (is_array($ids)) {
$hideSet = [];
foreach ($ids as $pid) {
$k = (int)$pid;
if ($k !== 0) {
$hideSet[$k] = true;
}
}
$this->pickHiddenScydgySetCache = $hideSet;
return $hideSet;
}
}
} catch (\Throwable $e) {
}
$hideSet = [];
try {
$poIds = Db::table('purchase_order')
->where(function ($q) {
$q->whereIn('wflow_status', array_merge(
ProcuremenStatus::wflowPendingConfirmValues(),
ProcuremenStatus::wflowPendingApprovalValues()
))
->whereOr(function ($q1) {
$q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
})
->whereOr(function ($q2) {
$q2->whereNotNull('pick_time')
->where('pick_time', '<>', '')
->where('pick_time', '<>', '0000-00-00 00:00:00');
})
->whereOr(function ($q3) {
$q3->whereNotNull('mod_rq')
->where('mod_rq', '<>', '')
->where('mod_rq', 'not like', '0000-00-00%');
});
})
->column('scydgy_id');
if (is_array($poIds)) {
foreach ($poIds as $pid) {
$k = (int)$pid;
if ($k !== 0) {
$hideSet[$k] = true;
}
}
}
} catch (\Throwable $e) {
}
try {
$detIdsQuery = Db::table('purchase_order_detail');
$this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
$detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
if (is_array($detIds)) {
foreach ($detIds as $pid) {
$k = (int)$pid;
if ($this->isValidScydgyRowId($k)) {
$hideSet[$k] = true;
}
}
}
} catch (\Throwable $e) {
}
$this->pickHiddenScydgySetCache = $hideSet;
try {
redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
} catch (\Throwable $e) {
}
return $hideSet;
}
/**
* 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
*
* @return array>
*/
protected function loadPickManualOrderRows(): array
{
try {
$dbRows = Db::table('purchase_order')
->where('scydgy_id', '<', 0)
->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
->order('scydgy_id', 'asc')
->select();
} catch (\Throwable $e) {
try {
$dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
} catch (\Throwable $e2) {
return [];
}
}
if (!is_array($dbRows) || $dbRows === []) {
return [];
}
$detailSidSet = [];
try {
$negIds = [];
foreach ($dbRows as $dbRow) {
if (!is_array($dbRow)) {
continue;
}
$sid = (int)($dbRow['scydgy_id'] ?? 0);
if ($sid < 0) {
$negIds[$sid] = true;
}
}
if ($negIds !== []) {
$detQuery = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($negIds));
$this->applyActivePurchaseOrderDetailWhere($detQuery);
$detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
if (is_array($detRows)) {
foreach ($detRows as $did) {
$detailSidSet[(int)$did] = true;
}
}
}
} catch (\Throwable $e) {
}
$pool = [];
foreach ($dbRows as $dbRow) {
if (!is_array($dbRow)) {
continue;
}
$sid = (int)($dbRow['scydgy_id'] ?? 0);
if ($sid >= 0) {
continue;
}
// 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
continue;
}
// 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
continue;
}
if (isset($detailSidSet[$sid])) {
continue;
}
$r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
$r['_is_manual'] = 1;
$pool[] = $r;
}
return $pool;
}
/**
* 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
*/
protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
{
$keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
foreach ($keys as $k) {
$t = trim((string)($row[$k] ?? ''));
if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
return $t;
}
}
return '';
}
/**
* 分配手工新增工序行 ID(负数递减)
*/
protected function allocateManualScydgyId(): int
{
try {
$min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
$min = (int)$min;
return $min < 0 ? $min - 1 : -1;
} catch (\Throwable $e) {
return -1;
}
}
/**
* 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
*/
protected function allocateManualOrderCcydh(): string
{
$prefix = 'YW' . date('Ymd');
$maxSeq = 0;
try {
$rows = Db::table('purchase_order')
->where('CCYDH', 'like', $prefix . '%')
->column('CCYDH');
if (is_array($rows)) {
foreach ($rows as $ccydh) {
$ccydh = trim((string)$ccydh);
if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
$maxSeq = max($maxSeq, (int)$m[1]);
}
}
}
} catch (\Throwable $e) {
}
return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
}
/**
* purchase_order.mod_rq 是否有有效软删除时间
*/
protected function isPurchaseOrderSoftDeleted($modRq): bool
{
$t = trim((string)$modRq);
return $t !== '' && stripos($t, '0000-00-00') !== 0;
}
/**
* 列表行 → purchase_order 写入字段
*
* @return array
*/
protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
{
return [
'scydgy_id' => $scydgyId,
'CCYDH' => $row['CCYDH'] ?? null,
'CYJMC' => $row['CYJMC'] ?? null,
'CCLBMMC' => $row['CCLBMMC'] ?? null,
'CDXMC' => $row['CDXMC'] ?? null,
'CGYBH' => $row['CGYBH'] ?? null,
'CGYMC' => $row['CGYMC'] ?? null,
'CDW' => $row['CDW'] ?? null,
'czlyq' => $row['czlyq'] ?? null,
'NGZL' => $row['NGZL'] ?? null,
'CDF' => $row['CDF'] ?? null,
'cGzzxMc' => $row['cGzzxMc'] ?? null,
'MBZ' => $row['MBZ'] ?? null,
'bwjg' => $row['bwjg'] ?? null,
'iStatus' => $row['iStatus'] ?? null,
'dStamp' => $row['dStamp'] ?? null,
'dputrecord' => $row['dputrecord'] ?? null,
'cywyxm' => $row['cywyxm'] ?? null,
'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
];
}
/**
* 初选行对应的 purchase_order 与是否应从初选列表隐藏
*
* @return array{po:?array, hidden:bool}
*/
protected function resolvePickRowPoContext(int $sid): array
{
$po = null;
try {
$found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
if (is_array($found)) {
$po = $found;
}
} catch (\Throwable $e) {
}
$hideSet = $this->loadPickHiddenScydgySet();
return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
}
/**
* 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
*/
protected function assertPickRowCanDelete(int $sid, array $row): void
{
$ctx = $this->resolvePickRowPoContext($sid);
$po = $ctx['po'];
if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
return;
}
if (is_array($po)) {
if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
throw new \InvalidArgumentException('该工序已完结,无法删除');
}
if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
}
}
if ($ctx['hidden']) {
$ccydh = trim((string)($row['CCYDH'] ?? ''));
$label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
}
}
/**
* 初选直接完结前校验
*/
protected function assertPickRowCanComplete(int $sid, array $row): void
{
$ctx = $this->resolvePickRowPoContext($sid);
$po = $ctx['po'];
if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
}
if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
}
if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
}
}
/**
* 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
*/
protected function softDeleteProcuremenPickRow(array $row): void
{
$sid = $this->extractScydgyRowId($row);
if (!$this->isValidScydgyRowId($sid)) {
throw new \InvalidArgumentException('无效的行主键');
}
$this->assertPickRowCanDelete($sid, $row);
$po = $this->resolvePickRowPoContext($sid)['po'];
if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
return;
}
if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
}
$now = date('Y-m-d H:i:s');
$exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
if (is_array($exists)) {
Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
$poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
} else {
$data = $this->purchaseOrderPayloadFromListRow($row, $sid);
$data['mod_rq'] = $now;
$data['createtime'] = $now;
Db::table('purchase_order')->insert($data);
$poIdLog = (int)Db::getLastInsID();
}
$ccydhLog = trim((string)($row['CCYDH'] ?? ''));
$gymcLog = trim((string)($row['CGYMC'] ?? ''));
$logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
if ($gymcLog !== '') {
$logTail .= ' / ' . $gymcLog;
}
$this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
}
/**
* 手工新增协助工序(写入 purchase_order)
*
* @param array $params
* @return int scydgy_id
*/
protected function saveManualPickOrder(array $params): int
{
$cyjmc = trim((string)($params['CYJMC'] ?? ''));
$cgymc = trim((string)($params['CGYMC'] ?? ''));
$ccydh = trim((string)($params['CCYDH'] ?? ''));
if ($ccydh === '') {
$ccydh = $this->allocateManualOrderCcydh();
}
$now = date('Y-m-d H:i:s');
$sid = $this->allocateManualScydgyId();
$this->ensurePurchaseOrderNotifySalesmanColumn();
$this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
// 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
$supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
$notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
$data = [
'scydgy_id' => $sid,
'CCYDH' => $ccydh,
'CYJMC' => $cyjmc,
'CGYMC' => $cgymc,
'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
'CDW' => trim((string)($params['CDW'] ?? '')),
'NGZL' => trim((string)($params['NGZL'] ?? '')),
'CDF' => trim((string)($params['CDF'] ?? '')),
'cGzzxMc' => $supplierName,
'MBZ' => trim((string)($params['MBZ'] ?? '')),
'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
'notify_salesman' => $notifySalesman,
'rfq_salesman_notified' => 0,
'rfq_salesman_notify_time' => null,
'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
'status' => ProcuremenStatus::PO_IN_PROGRESS,
'createtime' => $now,
'dStamp' => $now,
'dputrecord' => $now,
];
Db::table('purchase_order')->insert($data);
$poId = (int)Db::getLastInsID();
$this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
return $sid;
}
protected function formatProcuremenRowLabel(array $row): string
{
$dh = trim((string)($row['CCYDH'] ?? ''));
$gymc = trim((string)($row['CGYMC'] ?? ''));
if ($dh !== '' && $gymc !== '') {
return '订单「' . $dh . '」、工序「' . $gymc . '」';
}
if ($dh !== '') {
return '订单「' . $dh . '」';
}
if ($gymc !== '') {
return '工序「' . $gymc . '」';
}
$id = $this->extractScydgyRowId($row);
return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
}
/**
* 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
*/
protected function extractScydgyRowId(array $row): int
{
// 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
return (int)$row['scydgy_id'];
}
if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
return (int)$row['SCYDGY_ID'];
}
return (int)($row['ID'] ?? $row['id'] ?? 0);
}
protected function isValidScydgyRowId(int $id): bool
{
return ProcuremenGuard::isValidScydgyId($id);
}
protected function isManualScydgyRowId(int $id): bool
{
return $id < 0;
}
/**
* 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
*
* @param int[] $scydgyIds
* @return array
*/
protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
{
$out = [];
$scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
if ($scydgyIds === []) {
return $out;
}
try {
$rows = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', $scydgyIds)
->field('scydgy_id,company_name')
->order('company_name', 'asc')
->select();
} catch (\Throwable $e) {
$rows = [];
}
if (!is_array($rows)) {
return $out;
}
foreach ($rows as $r) {
if (!is_array($r)) {
continue;
}
$sid = (int)($r['scydgy_id'] ?? 0);
$cn = trim((string)($r['company_name'] ?? ''));
if (!$this->isValidScydgyRowId($sid) || $cn === '') {
continue;
}
if (!isset($out[$sid])) {
$out[$sid] = [];
}
if (!in_array($cn, $out[$sid], true)) {
$out[$sid][] = $cn;
}
}
return $out;
}
/**
* 列表展示通知供应商(完整列表,前端单行省略展开)
*
* @param string[] $names
*/
protected function formatNotifySupplierDisplay(array $names): string
{
$names = array_values(array_unique(array_filter(array_map(function ($n) {
return trim((string)$n);
}, $names))));
if ($names === []) {
return '';
}
sort($names, SORT_STRING);
return implode("\n", $names);
}
/**
* 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
*
* @param int[] $scydgyIds
* @return array, quoted: array}>
*/
protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
{
$out = [];
$scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
if ($scydgyIds === []) {
return $out;
}
try {
$rows = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', $scydgyIds)
->field('scydgy_id,company_name,amount')
->select();
} catch (\Throwable $e) {
$rows = [];
}
if (!is_array($rows)) {
return $out;
}
foreach ($rows as $r) {
if (!is_array($r)) {
continue;
}
$sid = (int)($r['scydgy_id'] ?? 0);
$cn = trim((string)($r['company_name'] ?? ''));
if (!$this->isValidScydgyRowId($sid) || $cn === '') {
continue;
}
if (!isset($out[$sid])) {
$out[$sid] = ['all' => [], 'quoted' => []];
}
$out[$sid]['all'][$cn] = true;
$am = trim((string)($r['amount'] ?? ''));
if ($am !== '' && $am !== '0' && $am !== '0.00') {
$out[$sid]['quoted'][$cn] = true;
}
}
return $out;
}
/**
* @param array, quoted: array}> $buckets
* @return array{all: array, quoted: array}
*/
protected function mergeQuotedSupplierBuckets(array $buckets): array
{
$merged = ['all' => [], 'quoted' => []];
foreach ($buckets as $b) {
if (!is_array($b)) {
continue;
}
foreach ($b['all'] ?? [] as $cn => $_) {
$merged['all'][$cn] = true;
}
foreach ($b['quoted'] ?? [] as $cn => $_) {
$merged['quoted'][$cn] = true;
}
}
return $merged;
}
/**
* @param array{all: array, quoted: array} $bucket
*/
protected function formatQuotedSupplierLines(array $bucket): string
{
$all = array_keys($bucket['all'] ?? []);
if ($all === []) {
return '';
}
sort($all, SORT_STRING);
$lines = [];
foreach ($all as $cn) {
$status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
$lines[] = $cn . '(' . $status . ')';
}
return implode("\n", $lines);
}
/**
* 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
*/
protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
{
$restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
$this->view->engine->layout(false);
try {
$bodyHtml = $this->view->fetch($view);
$this->view->assign('dialogBody', $bodyHtml);
$this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
return $this->view->fetch('procuremen/dialog_lite_shell');
} finally {
if ($restoreLayout) {
$this->view->engine->layout($restoreLayout);
}
}
}
/**
* 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
*/
protected function resolveBundleSysRq(array $bundle): string
{
foreach ($bundle['pos'] ?? [] as $po) {
if (!is_array($po)) {
continue;
}
$sr = trim((string)($po['sys_rq'] ?? ''));
if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
return $sr;
}
}
return '';
}
/**
* 报价截止时间是否已到(未设置截止时间则视为可查看报价)
*/
protected function isProcuremenQuoteDeadlineReached($sysRq): bool
{
$raw = trim((string)$sysRq);
if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
return true;
}
$ts = strtotime(str_replace('T', ' ', $raw));
if ($ts === false || $ts <= 0) {
return true;
}
return time() >= $ts;
}
/**
* 开标前校验:必须已过报价截止时间
*
* @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
*/
protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
{
$sysRq = $this->resolveBundleSysRq($bundle);
if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
$this->error('未到招标截止日期');
}
}
/**
* 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
*
* @param array $d
* @param string $deliveryYmd
*/
protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
{
if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
return max(0, (int)$d['lead_days']);
}
if ($deliveryYmd === '') {
$deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
}
if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
return null;
}
$t1 = strtotime(date('Y-m-d') . ' 00:00:00');
$t2 = strtotime($m[1] . ' 00:00:00');
if ($t1 === false || $t2 === false) {
return null;
}
return max(0, (int)round(($t2 - $t1) / 86400));
}
/**
* @param int|null $days
*/
protected function formatProcuremenLeadDaysText($days): string
{
if ($days === null || $days === '') {
return '未填写';
}
if (!is_numeric($days)) {
return '未填写';
}
return ((int)$days) . '天';
}
/**
* 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
*
* @param array $line
*/
protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
{
$amountFilled = !empty($line['amount_filled']);
$deliveryFilled = !empty($line['delivery_filled']);
$leadFilled = !empty($line['lead_days_filled']);
$operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
$line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
$line['amount_show'] = '';
if (array_key_exists('amount_text', $line)) {
$line['amount_text'] = $line['unit_price_text'];
}
$deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
$line['delivery_show'] = $deliveryText;
if (array_key_exists('delivery_text', $line)) {
$line['delivery_text'] = $deliveryText;
}
$line['delivery_ymd'] = '';
$leadText = $leadFilled ? '开标验证后查看' : '未填写';
$line['lead_days_show'] = $leadText;
$line['lead_days_text'] = $leadText;
$line['lead_days'] = '';
// 小计、操作时间与单价等同属报价信息,开标前不可见
$line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
$line['subtotal_num'] = null;
$line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
$line['amount_quote_pending'] = $amountFilled ? 1 : 0;
$line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
$line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
$line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
$line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
$line['amount_filled'] = false;
$line['delivery_filled'] = false;
$line['lead_days_filled'] = false;
$line['is_quoted'] = false;
if (array_key_exists('quote_label', $line)) {
$line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
}
}
protected function ensurePurchaseOrderBidOpenTable(): void
{
static $ready = false;
if ($ready) {
return;
}
$cacheKey = 'procuremen_bid_open_table_ok_v1';
try {
if (Cache::get($cacheKey)) {
$ready = true;
return;
}
} catch (\Throwable $e) {
}
try {
Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
$ready = true;
try {
Cache::set($cacheKey, 1, 86400);
} catch (\Throwable $e) {
}
} catch (\Throwable $e) {
Db::execute(
"CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
`verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
`verifier1_name` varchar(64) NOT NULL DEFAULT '',
`verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
`verifier2_name` varchar(64) NOT NULL DEFAULT '',
`operator_id` int(10) unsigned NOT NULL DEFAULT 0,
`operator_name` varchar(64) NOT NULL DEFAULT '',
`createtime` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_ccydh` (`ccydh`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
);
$ready = true;
try {
Cache::set($cacheKey, 1, 86400);
} catch (\Throwable $e2) {
}
}
}
protected function isProcuremenBidOpenVerified(string $ccydh): bool
{
$ccydh = trim($ccydh);
if ($ccydh === '') {
return false;
}
$this->ensurePurchaseOrderBidOpenTable();
try {
$row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
return is_array($row);
} catch (\Throwable $e) {
return false;
}
}
/**
* 批量查询订单是否已开标验证
*
* @param array $ccydhs
* @return array ccydh => true
*/
protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
{
$set = [];
$list = [];
foreach ($ccydhs as $c) {
$c = trim((string)$c);
if ($c !== '') {
$list[$c] = true;
}
}
if ($list === []) {
return $set;
}
$this->ensurePurchaseOrderBidOpenTable();
try {
$rows = Db::table('purchase_order_bid_open')
->where('ccydh', 'in', array_keys($list))
->field('ccydh')
->select();
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$c = trim((string)($row['ccydh'] ?? ''));
if ($c !== '') {
$set[$c] = true;
}
}
} catch (\Throwable $e) {
return [];
}
return $set;
}
/**
* 批量查询订单是否已指定供应商(免开标)
*
* @param array $ccydhs
* @return array ccydh => true
*/
protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
{
$set = [];
$list = [];
foreach ($ccydhs as $c) {
$c = trim((string)$c);
if ($c !== '') {
$list[$c] = true;
}
}
if ($list === []) {
return $set;
}
$this->ensurePurchaseOrderManualPickColumns();
try {
$rows = Db::table('purchase_order')
->where('CCYDH', 'in', array_keys($list))
->where('manual_pick', 1)
->field('CCYDH')
->select();
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$c = trim((string)($row['CCYDH'] ?? ''));
if ($c !== '') {
$set[$c] = true;
}
}
} catch (\Throwable $e) {
return [];
}
return $set;
}
/**
* 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
*
* @param array> $pool
* @return array>
*/
protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
{
$status = trim($status);
if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
return $pool;
}
$ccydhList = [];
foreach ($pool as $rw) {
if (!is_array($rw)) {
continue;
}
$c = trim((string)($rw['CCYDH'] ?? ''));
if ($c !== '') {
$ccydhList[] = $c;
}
}
$bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
$manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
$out = [];
foreach ($pool as $rw) {
if (!is_array($rw)) {
continue;
}
$c = trim((string)($rw['CCYDH'] ?? ''));
if ($c !== '' && isset($bidOpenSet[$c])) {
$t = '已开标';
} elseif ($c !== '' && isset($manualPickSet[$c])) {
$t = '已指定供应商';
} else {
$t = '待开标';
}
if ($t === $status) {
$out[] = $rw;
}
}
return $out;
}
/**
* 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
*
* @param array $group
*/
protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
{
if ($quoteVisible) {
$group['remark_quote_pending'] = 0;
return;
}
$group['remark'] = '';
$group['remark_quote_pending'] = 0;
}
/**
* @param array{ccydh?:string} $bundle
*/
protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
{
return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
}
protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
{
if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
return true;
}
return $this->isProcuremenManualPickedForBundle($bundle);
}
/**
* 确保 purchase_order 自选供应商字段
*/
protected function ensurePurchaseOrderManualPickColumns(): void
{
static $done = false;
if ($done) {
return;
}
$done = true;
$adds = [
'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
];
foreach ($adds as $col => $ddl) {
try {
$cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
if (!is_array($cols) || $cols === []) {
Db::execute("ALTER TABLE `purchase_order` {$ddl}");
}
} catch (\Throwable $e) {
Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
}
}
}
/**
* 是否已自选供应商(免开标查看报价)
*
* @param array{pos?:array} $bundle
*/
protected function isProcuremenManualPickedForBundle(array $bundle): bool
{
$this->ensurePurchaseOrderManualPickColumns();
foreach ($bundle['pos'] ?? [] as $poRow) {
if (!is_array($poRow)) {
continue;
}
if ((int)($poRow['manual_pick'] ?? 0) === 1) {
return true;
}
}
$ccydh = trim((string)($bundle['ccydh'] ?? ''));
if ($ccydh === '') {
return false;
}
try {
$v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
return $v !== null && $v !== false && (int)$v > 0;
} catch (\Throwable $e) {
return false;
}
}
/**
* @param array{pos?:array} $bundle
* @return array{company:string,reason:string}
*/
protected function resolveProcuremenManualPickInfo(array $bundle): array
{
$this->ensurePurchaseOrderManualPickColumns();
foreach ($bundle['pos'] ?? [] as $poRow) {
if (!is_array($poRow)) {
continue;
}
if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
continue;
}
$cn = trim((string)($poRow['pick_company_name'] ?? ''));
$reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
return ['company' => $cn, 'reason' => $reason];
}
$ccydh = trim((string)($bundle['ccydh'] ?? ''));
if ($ccydh === '') {
return ['company' => '', 'reason' => ''];
}
try {
$row = Db::table('purchase_order')
->where('CCYDH', $ccydh)
->where('manual_pick', 1)
->field('pick_company_name,manual_pick_reason')
->order('id', 'asc')
->find();
} catch (\Throwable $e) {
$row = null;
}
if (!is_array($row)) {
return ['company' => '', 'reason' => ''];
}
return [
'company' => trim((string)($row['pick_company_name'] ?? '')),
'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
];
}
protected function loadBidOpenAdminUser(int $adminId): ?array
{
if ($adminId <= 0) {
return null;
}
try {
$row = Db::name('admin')->where('id', $adminId)->find();
} catch (\Throwable $e) {
return null;
}
if (!is_array($row)) {
return null;
}
$status = strtolower(trim((string)($row['status'] ?? '')));
if ($status !== '' && $status !== 'normal') {
return null;
}
if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
return null;
}
$phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
if (!preg_match('/^1\d{10}$/', $phone)) {
return null;
}
$name = trim((string)($row['nickname'] ?? ''));
if ($name === '') {
$name = trim((string)($row['username'] ?? ''));
}
return [
'id' => (int)$row['id'],
'username' => trim((string)($row['username'] ?? '')),
'nickname' => $name,
'mobile' => $phone,
];
}
/**
* 开标验证人可选范围:auth_group 根组 id(含其全部子组)
*/
protected function bidOpenVerifierAuthGroupRootId(): int
{
$id = (int)Config::get('mproc.bid_open_auth_group_root_id');
return $id > 0 ? $id : 10;
}
/**
* @return int[]
*/
protected function loadBidOpenVerifierAuthGroupIds(): array
{
static $memo = [];
$rootId = $this->bidOpenVerifierAuthGroupRootId();
if (isset($memo[$rootId])) {
return $memo[$rootId];
}
try {
$groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
} catch (\Throwable $e) {
$memo[$rootId] = [$rootId];
return $memo[$rootId];
}
if (!is_array($groups) || $groups === []) {
$memo[$rootId] = [$rootId];
return $memo[$rootId];
}
$groupList = [];
foreach ($groups as $g) {
if (is_array($g)) {
$groupList[] = $g;
}
}
if ($groupList === []) {
$memo[$rootId] = [$rootId];
return $memo[$rootId];
}
$tree = \fast\Tree::instance();
$tree->init($groupList);
$ids = $tree->getChildrenIds($rootId, true);
if (!is_array($ids) || $ids === []) {
$memo[$rootId] = [$rootId];
return $memo[$rootId];
}
$memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
return $memo[$rootId];
}
protected function isBidOpenVerifierAdmin(int $adminId): bool
{
if ($adminId <= 0) {
return false;
}
$groupIds = $this->loadBidOpenVerifierAuthGroupIds();
if ($groupIds === []) {
return false;
}
try {
return (bool)Db::name('auth_group_access')
->where('uid', $adminId)
->where('group_id', 'in', $groupIds)
->count();
} catch (\Throwable $e) {
return false;
}
}
/**
* @return array>
*/
protected function listBidOpenVerifierCandidates(): array
{
$groupIds = $this->loadBidOpenVerifierAuthGroupIds();
if ($groupIds === []) {
return [];
}
try {
$adminIds = Db::name('auth_group_access')
->where('group_id', 'in', $groupIds)
->column('uid');
} catch (\Throwable $e) {
$adminIds = [];
}
$adminIds = is_array($adminIds)
? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
: [];
if ($adminIds === []) {
return [];
}
try {
$rows = Db::name('admin')
->where('status', 'normal')
->where('id', 'in', $adminIds)
->where('mobile', '<>', '')
->order('id', 'asc')
->select();
} catch (\Throwable $e) {
return [];
}
if (!is_array($rows)) {
return [];
}
$groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
$out = [];
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
if ($one === null) {
continue;
}
$out[] = [
'id' => $one['id'],
'username' => $one['username'],
'nickname' => $one['nickname'],
'group_name' => $groupNameMap[$one['id']] ?? '',
'mobile' => mask_phone($one['mobile']),
'mobile_plain' => (string)$one['mobile'],
];
}
return $out;
}
/**
* @param int[] $adminIds
* @return array
*/
protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
{
$adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
if ($adminIds === []) {
return [];
}
$groupIds = $this->loadBidOpenVerifierAuthGroupIds();
try {
$rows = Db::name('auth_group_access')
->alias('aga')
->join('auth_group ag', 'aga.group_id = ag.id')
->where('aga.uid', 'in', $adminIds)
->where('aga.group_id', 'in', $groupIds)
->field('aga.uid,ag.name')
->order('aga.uid', 'asc')
->order('aga.group_id', 'asc')
->select();
} catch (\Throwable $e) {
return [];
}
if (!is_array($rows)) {
return [];
}
$out = [];
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$uid = (int)($row['uid'] ?? 0);
$name = trim((string)($row['name'] ?? ''));
if ($uid <= 0 || $name === '' || isset($out[$uid])) {
continue;
}
$out[$uid] = $name;
}
return $out;
}
protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
{
return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
}
protected function bidOpenSmsWaitCacheKey(int $adminId): string
{
return 'procuremen_bidopen_wait_' . $adminId;
}
protected function renderBidOpenVerifySms(string $code): string
{
$tpl = '';
try {
$row = $this->loadNotifyTemplateRow('bid_open');
if (is_array($row)) {
$tpl = trim((string)($row['content'] ?? ''));
}
} catch (\Throwable $e) {
$tpl = '';
}
if ($tpl === '') {
$tpl = '【可集达】您的短信验证码是{code}';
}
return str_replace('{code}', $code, $tpl);
}
protected function sendBidOpenVerifySms(string $phone, string $code): void
{
$this->smsbao($phone, $this->renderBidOpenVerifySms($code));
}
protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
{
$code = trim($code);
if (!preg_match('/^\d{6}$/', $code)) {
return false;
}
$mock = Config::get('mproc.mock_sms_code');
if ($mock !== null && $mock !== '' && (string)$mock === $code) {
Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
return true;
}
$cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
if ($cached === false || $cached === null || (string)$cached !== $code) {
return false;
}
Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
return true;
}
/**
* @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
*/
protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
{
$ccydh = trim((string)($bundle['ccydh'] ?? ''));
if ($ccydh === '') {
throw new \InvalidArgumentException('订单号无效');
}
$this->ensurePurchaseOrderBidOpenTable();
list($operatorId, $operatorName) = $this->GetUseName();
$now = date('Y-m-d H:i:s');
$exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
$payload = [
'ccydh' => $ccydh,
'verifier1_id' => (int)($verifier1['id'] ?? 0),
'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
'verifier2_id' => (int)($verifier2['id'] ?? 0),
'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
'operator_id' => (int)$operatorId,
'operator_name' => trim((string)$operatorName),
'createtime' => $now,
];
if (is_array($exists)) {
Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
} else {
Db::table('purchase_order_bid_open')->insert($payload);
}
$name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
$name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
$labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
(int)$payload['verifier1_id'],
(int)$payload['verifier2_id'],
]);
if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
$name1 = $labelMap[(int)$payload['verifier1_id']];
}
if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
$name2 = $labelMap[(int)$payload['verifier2_id']];
}
$logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
$seenSid = [];
foreach ($bundle['pos'] ?? [] as $poRow) {
if (!is_array($poRow)) {
continue;
}
$sid = (int)($poRow['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
continue;
}
$seenSid[$sid] = true;
$poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
$this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
}
if ($seenSid === []) {
$anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
if ($this->isValidScydgyRowId($anchor)) {
$this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
}
}
// 开标通过后计算并写入供应商服务评分
try {
$quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
} catch (\Throwable $e) {
Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
}
}
/**
* 报价行展示字段默认值(模板安全访问)
*
* @param array $line
* @return array
*/
protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
{
if (!array_key_exists('amount_quote_pending', $line)) {
$line['amount_quote_pending'] = 0;
}
if (!array_key_exists('delivery_quote_pending', $line)) {
$line['delivery_quote_pending'] = 0;
}
if (!array_key_exists('quote_before_deadline', $line)) {
$line['quote_before_deadline'] = 0;
}
if (!array_key_exists('amount_filled', $line)) {
$line['amount_filled'] = 0;
}
if (!array_key_exists('delivery_filled', $line)) {
$line['delivery_filled'] = 0;
}
if (!array_key_exists('lead_days_filled', $line)) {
$line['lead_days_filled'] = 0;
}
if (!array_key_exists('lead_days_quote_pending', $line)) {
$line['lead_days_quote_pending'] = 0;
}
if (!array_key_exists('lead_days_show', $line)) {
$line['lead_days_show'] = '未填写';
}
if (!array_key_exists('lead_days_text', $line)) {
$line['lead_days_text'] = $line['lead_days_show'];
}
return $line;
}
/**
* 审核弹窗:按供应商汇总报价明细
*
* @param array{ccydh:string, pos:array, merge_rows:array} $bundle
* @return array>
*/
protected function loadAuditSupplierQuoteGroups(array $bundle): array
{
$sids = [];
foreach ($bundle['pos'] ?? [] as $po) {
if (!is_array($po)) {
continue;
}
$sid = (int)($po['scydgy_id'] ?? 0);
if ($this->isValidScydgyRowId($sid)) {
$sids[$sid] = true;
}
}
if ($sids === []) {
return [];
}
$quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
$gymcMap = [];
$qtyBySid = [];
$orderedSids = [];
foreach ($bundle['merge_rows'] ?? [] as $mr) {
if (!is_array($mr)) {
continue;
}
$gid = $this->extractScydgyRowId($mr);
if ($this->isValidScydgyRowId($gid)) {
$gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
$orderedSids[] = $gid;
$qty = trim((string)($mr['This_quantity'] ?? ''));
if ($qty === '') {
$qty = trim((string)($mr['NGZL'] ?? ''));
}
$qtyBySid[$gid] = $qty;
}
}
foreach ($bundle['pos'] ?? [] as $po) {
if (!is_array($po)) {
continue;
}
$gid = (int)($po['scydgy_id'] ?? 0);
if ($this->isValidScydgyRowId($gid)) {
$nm = trim((string)($po['CGYMC'] ?? ''));
if ($nm !== '') {
$gymcMap[$gid] = $nm;
}
if (!in_array($gid, $orderedSids, true)) {
$orderedSids[] = $gid;
}
}
}
try {
$detailsQuery = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($sids));
$this->applyActivePurchaseOrderDetailWhere($detailsQuery);
$details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
} catch (\Throwable $e) {
try {
$detailsQuery = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($sids));
$this->applyActivePurchaseOrderDetailWhere($detailsQuery);
$details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
} catch (\Throwable $e2) {
$details = [];
}
}
if (!is_array($details)) {
$details = [];
}
$byCompany = [];
foreach ($details as $d) {
if (!is_array($d)) {
continue;
}
$cn = trim((string)($d['company_name'] ?? ''));
if ($cn === '') {
continue;
}
if (!isset($byCompany[$cn])) {
$ph = trim((string)($d['phone'] ?? ''));
$username = trim((string)($d['username'] ?? ''));
if ($username === '') {
$username = $this->resolveCustomerContactName($ph, $cn);
}
$byCompany[$cn] = [
'name' => $cn,
'email' => trim((string)($d['email'] ?? '')),
'phone' => $ph,
'username' => $username,
'remark' => '',
'has_quote' => false,
'lines_map' => [],
];
}
if ($byCompany[$cn]['remark'] === '') {
$rm = '';
foreach (['remark', 'Remark', 'REMARK'] as $rk) {
if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
$rm = trim((string)$d[$rk]);
break;
}
}
if ($rm !== '') {
$byCompany[$cn]['remark'] = $rm;
}
}
$sid = (int)($d['scydgy_id'] ?? 0);
$am = trim((string)($d['amount'] ?? ''));
$gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
if ($gymc === '') {
$gymc = '工序';
}
$deliveryRaw = trim((string)($d['delivery'] ?? ''));
$deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
if ($deliveryShow === '' && $deliveryRaw !== '') {
$deliveryShow = $deliveryRaw;
}
$amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
$deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
$amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
$subtotal = null;
if ($amountNum !== null) {
$subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
}
$unitPriceText = $amountFilled
? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
: '未填写';
$leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
$leadFilled = ($leadDays !== null);
$leadText = $this->formatProcuremenLeadDaysText($leadDays);
$lineRow = [
'cgymc' => $gymc,
'amount' => $am,
'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
'amount_filled' => $amountFilled,
'unit_price_text' => $unitPriceText,
'delivery' => $deliveryRaw,
'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
'delivery_filled' => $deliveryFilled,
'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
'lead_days' => $leadFilled ? $leadDays : '',
'lead_days_filled'=> $leadFilled,
'lead_days_show' => $leadText,
'lead_days_text' => $leadText,
'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
'subtotal_num' => $subtotal,
'status_name' => trim((string)($d['status_name'] ?? '')),
'is_quoted' => $amountFilled,
'quote_label' => $amountFilled ? '已报价' : '未报价',
'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
];
if (!$quoteVisible) {
$this->maskSupplierQuoteLineBeforeDeadline($lineRow);
}
// 按工序 id 暂存,下面再按上方工序表顺序输出
$byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
}
foreach ($byCompany as $cn => $g) {
$linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
$lines = [];
$usedSids = [];
foreach ($orderedSids as $sid) {
if (!isset($linesMap[$sid])) {
continue;
}
$lines[] = $linesMap[$sid];
$usedSids[$sid] = true;
}
foreach ($linesMap as $sid => $ln) {
if (isset($usedSids[$sid])) {
continue;
}
$lines[] = $ln;
}
$total = count($lines);
$quoted = 0;
$groupTotal = 0.0;
$groupHasTotal = false;
if ($quoteVisible) {
foreach ($lines as $ln) {
$am = trim((string)($ln['amount'] ?? ''));
if ($am !== '' && $am !== '0' && $am !== '0.00') {
$quoted++;
}
if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
$groupTotal += (float)$ln['subtotal_num'];
$groupHasTotal = true;
}
}
}
unset($byCompany[$cn]['lines_map']);
$byCompany[$cn]['lines'] = $lines;
$byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
$byCompany[$cn]['line_count'] = $total;
$byCompany[$cn]['has_total'] = $total > 0;
$byCompany[$cn]['has_remark'] = $total > 0;
$this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
$byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
// 工序行 + 备注行 + 总计行
$byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
}
$groups = array_values($byCompany);
$ccydh = trim((string)($bundle['ccydh'] ?? ''));
return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
}
/**
* 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
*
* @param array{ccydh:string, pos:array, merge_rows:array} $bundle
* @return array>
*/
protected function loadConfirmSupplierPickGroups(array $bundle): array
{
$sids = [];
$poIdMap = [];
foreach ($bundle['pos'] ?? [] as $po) {
if (!is_array($po)) {
continue;
}
$sid = (int)($po['scydgy_id'] ?? 0);
if ($this->isValidScydgyRowId($sid)) {
$sids[$sid] = true;
$poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
}
}
if ($sids === []) {
return [];
}
$quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
$gymcMap = [];
$qtyBySid = [];
$orderedSids = [];
foreach ($bundle['merge_rows'] ?? [] as $mr) {
if (!is_array($mr)) {
continue;
}
$gid = $this->extractScydgyRowId($mr);
if ($this->isValidScydgyRowId($gid)) {
$gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
$orderedSids[] = $gid;
$qty = trim((string)($mr['This_quantity'] ?? ''));
if ($qty === '') {
$qty = trim((string)($mr['NGZL'] ?? ''));
}
$qtyBySid[$gid] = $qty;
}
}
foreach ($bundle['pos'] ?? [] as $po) {
if (!is_array($po)) {
continue;
}
$gid = (int)($po['scydgy_id'] ?? 0);
if ($this->isValidScydgyRowId($gid)) {
$nm = trim((string)($po['CGYMC'] ?? ''));
if ($nm !== '') {
$gymcMap[$gid] = $nm;
}
}
}
try {
$details = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($sids))
->order('company_name', 'asc')
->order('id', 'asc')
->select();
} catch (\Throwable $e) {
try {
$details = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($sids))
->order('company_name', 'asc')
->order('ID', 'asc')
->select();
} catch (\Throwable $e2) {
$details = [];
}
}
if (!is_array($details)) {
$details = [];
}
$byCompany = [];
foreach ($details as $d) {
if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
continue;
}
$cn = trim((string)($d['company_name'] ?? ''));
if ($cn === '') {
continue;
}
$detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
$sid = (int)($d['scydgy_id'] ?? 0);
if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
continue;
}
if (!isset($byCompany[$cn])) {
$ph = trim((string)($d['phone'] ?? ''));
$username = trim((string)($d['username'] ?? ''));
if ($username === '') {
$username = $this->resolveCustomerContactName($ph, $cn);
}
$byCompany[$cn] = [
'name' => $cn,
'email' => trim((string)($d['email'] ?? '')),
'phone' => $ph,
'username' => $username,
'remark' => '',
'pick_lines' => [],
'detail_picks' => [],
];
}
if ($byCompany[$cn]['remark'] === '') {
$rm = '';
foreach (['remark', 'Remark', 'REMARK'] as $rk) {
if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
$rm = trim((string)$d[$rk]);
break;
}
}
if ($rm !== '') {
$byCompany[$cn]['remark'] = $rm;
}
}
$gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
if ($gymc === '') {
$gymc = '工序';
}
$am = trim((string)($d['amount'] ?? ''));
$amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
$deliveryRaw = trim((string)($d['delivery'] ?? ''));
$deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
if ($deliveryShow === '' && $deliveryRaw !== '') {
$deliveryShow = $deliveryRaw;
}
$deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
$amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
$subtotal = null;
if ($amountNum !== null) {
$subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
}
$unitPriceText = $amountFilled
? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
: '未填写';
$leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
$leadFilled = ($leadDays !== null);
$leadText = $this->formatProcuremenLeadDaysText($leadDays);
$pickLine = [
'cgymc' => $gymc,
'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
'amount_filled' => $amountFilled,
'delivery_filled' => $deliveryFilled,
'unit_price_text' => $unitPriceText,
'lead_days' => $leadFilled ? $leadDays : '',
'lead_days_filled'=> $leadFilled,
'lead_days_show' => $leadText,
'lead_days_text' => $leadText,
'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
'subtotal_num' => $subtotal,
'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
'is_quoted' => $amountFilled,
];
if (!$quoteVisible) {
$this->maskSupplierQuoteLineBeforeDeadline($pickLine);
}
$byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
$byCompany[$cn]['detail_picks'][$sid] = [
'scydgy_id' => $sid,
'detail_id' => $detailId,
'purchase_order_id' => $poIdMap[$sid] ?? 0,
'cgymc' => $gymc,
];
}
$out = [];
foreach ($byCompany as $g) {
$pickLinesMap = $g['pick_lines'] ?? [];
if (!is_array($pickLinesMap) || $pickLinesMap === []) {
continue;
}
$pickLines = [];
$usedLineSids = [];
foreach ($orderedSids as $sid) {
if (!isset($pickLinesMap[$sid])) {
continue;
}
$pickLines[] = $pickLinesMap[$sid];
$usedLineSids[$sid] = true;
}
foreach ($pickLinesMap as $sid => $ln) {
if (isset($usedLineSids[$sid])) {
continue;
}
$pickLines[] = $ln;
}
$groupTotal = 0.0;
$groupHasTotal = false;
if ($quoteVisible) {
foreach ($pickLines as $ln) {
if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
$groupTotal += (float)$ln['subtotal_num'];
$groupHasTotal = true;
}
}
}
$lineCount = count($pickLines);
$g['pick_lines'] = $pickLines;
$g['line_count'] = $lineCount;
$g['has_total'] = $lineCount > 0;
$g['has_remark'] = $lineCount > 0;
$this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
$g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
// 工序行 + 备注行 + 总计行
$g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
$detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
$detailPicks = [];
$usedPickSids = [];
foreach ($orderedSids as $sid) {
if (!isset($detailPicksMap[$sid])) {
continue;
}
$detailPicks[] = $detailPicksMap[$sid];
$usedPickSids[$sid] = true;
}
foreach ($detailPicksMap as $sid => $dp) {
if (isset($usedPickSids[$sid])) {
continue;
}
$detailPicks[] = $dp;
}
$g['detail_picks'] = $detailPicks;
$g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
unset($g['detail_picks']);
$out[] = $g;
}
$ccydh = trim((string)($bundle['ccydh'] ?? ''));
return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
}
/**
* @param array> $details purchase_order_detail 行
* @return array scydgy_id => detail_id[]
*/
protected function mapDetailIdsByScydgyId(array $details): array
{
$out = [];
foreach ($details as $d) {
if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
continue;
}
$sid = (int)($d['scydgy_id'] ?? 0);
$pk = (int)($d['id'] ?? $d['ID'] ?? 0);
if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
continue;
}
if (!isset($out[$sid])) {
$out[$sid] = [];
}
$out[$sid][] = $pk;
}
foreach ($out as $sid => $ids) {
$out[$sid] = array_values(array_unique($ids));
}
return $out;
}
/**
* purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
*
* @param array $dbRow
* @param array $dStampMap scydgy_id => dStamp
*/
protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
{
$sid = (int)($dbRow['scydgy_id'] ?? 0);
$r = [
'ID' => $sid,
'scydgy_id' => $sid,
'CCYDH' => $dbRow['CCYDH'] ?? '',
'CYJMC' => $dbRow['CYJMC'] ?? '',
'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
'CDXMC' => $dbRow['CDXMC'] ?? '',
'CGYBH' => $dbRow['CGYBH'] ?? '',
'CGYMC' => $dbRow['CGYMC'] ?? '',
'CDW' => $dbRow['CDW'] ?? '',
'czlyq' => $dbRow['czlyq'] ?? '',
'NGZL' => $dbRow['NGZL'] ?? '',
'CDF' => $dbRow['CDF'] ?? '',
'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
'MBZ' => $dbRow['MBZ'] ?? '',
'bwjg' => $dbRow['bwjg'] ?? '',
'iStatus' => $dbRow['iStatus'] ?? '',
'dputrecord' => $dbRow['dputrecord'] ?? '',
'cywyxm' => $dbRow['cywyxm'] ?? '',
'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
'dStamp' => $dbRow['dStamp'] ?? '',
'pick_time' => $dbRow['pick_time'] ?? '',
];
$r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
$r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
if ($sid > 0 && isset($dStampMap[$sid])) {
$t = trim((string)$dStampMap[$sid]);
if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
$r['dStamp'] = $dStampMap[$sid];
}
}
$dsOut = trim((string)($r['dStamp'] ?? ''));
if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
$ct = $dbRow['createtime'];
if (is_numeric($ct) && (int)$ct > 946684800) {
$r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
} elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
$r['dStamp'] = trim($ct);
}
}
// 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
$dpOut = trim((string)($r['dputrecord'] ?? ''));
if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
$fallback = trim((string)($r['dStamp'] ?? ''));
if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
$r['dputrecord'] = $fallback;
}
}
if (array_key_exists('id', $dbRow)) {
$r['purchase_order_id'] = (int)$dbRow['id'];
}
if ($sid < 0) {
$r['_is_manual'] = 1;
}
$r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
$pickOut = trim((string)($r['pick_time'] ?? ''));
if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
$pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
$r['pick_time'] = $pickFallback;
break;
}
}
}
$pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
if ($pickNm !== '') {
$r['pick_company_name'] = $pickNm;
$r['picked_supplier_name'] = $pickNm;
}
return $r;
}
/**
* 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
*
* @return array>
*/
protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
{
$pool = [];
if (!is_array($dbRows) || $dbRows === []) {
return $pool;
}
$dStampMap = [];
$sidList = [];
foreach ($dbRows as $tmpRow) {
if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
$sid = (int)$tmpRow['scydgy_id'];
if ($sid > 0) {
$ds = trim((string)($tmpRow['dStamp'] ?? ''));
if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
$sidList[$sid] = true;
}
}
}
}
if ($sidList !== []) {
try {
$dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
} catch (\Throwable $e) {
$dStampMap = [];
}
}
foreach ($dbRows as $dbRow) {
if (!is_array($dbRow)) {
continue;
}
$pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
}
// 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
$needCcydh = [];
foreach ($pool as $row) {
if (!is_array($row)) {
continue;
}
if (trim((string)($row['czlyq'] ?? '')) !== '') {
continue;
}
$ccydh = trim((string)($row['CCYDH'] ?? ''));
if ($ccydh !== '') {
$needCcydh[$ccydh] = true;
}
}
if ($needCcydh !== []) {
$czMap = [];
try {
$czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
} catch (\Throwable $e) {
$czMap = [];
}
if (is_array($czMap) && $czMap !== []) {
foreach ($pool as &$row) {
if (!is_array($row)) {
continue;
}
if (trim((string)($row['czlyq'] ?? '')) !== '') {
continue;
}
$ccydh = trim((string)($row['CCYDH'] ?? ''));
if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
$row['czlyq'] = trim((string)$czMap[$ccydh]);
}
}
unset($row);
}
}
return $pool;
}
/**
* 批量读取 purchase_order_detail(确认/审批列表统计用)
*
* @param int[] $scydgyIds
* @return array>
*/
protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
{
$scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
if ($scydgyIds === []) {
return [];
}
try {
$list = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', $scydgyIds)
->field('scydgy_id,company_name,amount,delivery')
->select();
} catch (\Throwable $e) {
$list = [];
}
return is_array($list) ? $list : [];
}
/**
* 合并工序行后按公司去重统计:已下发、已填单价、已填货期
*
* @param int[] $scydgyIds
* @param array> $allRows
* @return array{cnt:int, amt:int, deliv:int}
*/
protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
{
$out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
$scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
if ($scydgyIds === [] || $allRows === []) {
return $out;
}
$idSet = array_flip($scydgyIds);
$all = [];
$withAmt = [];
$withDeliv = [];
foreach ($allRows as $r) {
if (!is_array($r)) {
continue;
}
$sid = (int)($r['scydgy_id'] ?? 0);
if (!isset($idSet[$sid])) {
continue;
}
$cn = trim((string)($r['company_name'] ?? ''));
if ($cn === '') {
continue;
}
$all[$cn] = true;
$am = $r['amount'] ?? null;
if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
$withAmt[$cn] = true;
}
$dv = $r['delivery'] ?? null;
if ($dv !== null && trim((string)$dv) !== '') {
$withDeliv[$cn] = true;
}
}
return [
'cnt' => count($all),
'amt' => count($withAmt),
'deliv' => count($withDeliv),
];
}
/**
* 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
*
* @param array $row
*/
protected function resolveProcuremenThisQuantity(array $row): string
{
$q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
if ($q !== '') {
return $q;
}
$ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
if (!is_scalar($ngzl)) {
return '';
}
$s = trim((string)$ngzl);
if ($s === '') {
return '';
}
if (is_numeric($s) && (float)$s === 0.0) {
return '';
}
return $s;
}
/**
* @param array $row
*/
protected function resolveProcuremenCeilingPrice(array $row): string
{
return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
}
/**
* 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
*
* @param array $parts
*/
protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
{
$out = [];
foreach ($parts as $p) {
$s = trim((string)$p);
if ($s !== '') {
$out[] = $s;
}
}
return $out === [] ? '' : implode($sep, $out);
}
/**
* 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
*
* @param array> $rows
*/
protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
{
if ($rows === []) {
return;
}
$idList = [];
foreach ($rows as $rw) {
if (!is_array($rw)) {
continue;
}
if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
foreach ($rw['_order_merge_rows'] as $mr) {
if (!is_array($mr)) {
continue;
}
$mid = (int)($mr['ID'] ?? 0);
if ($this->isValidScydgyRowId($mid)) {
$idList[$mid] = true;
}
}
}
$id = (int)($rw['ID'] ?? 0);
if ($this->isValidScydgyRowId($id)) {
$idList[$id] = true;
}
}
if ($idList === []) {
return;
}
try {
$list = Db::table('purchase_order')
->where('scydgy_id', 'in', array_keys($idList))
->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
->select();
} catch (\Throwable $e) {
return;
}
if (!is_array($list)) {
return;
}
$byId = [];
foreach ($list as $dbRow) {
if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
continue;
}
$byId[(int)$dbRow['scydgy_id']] = $dbRow;
}
foreach ($rows as &$rw) {
if (!is_array($rw)) {
continue;
}
$mergeRows = [];
if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
$mergeRows = $rw['_order_merge_rows'];
} else {
$mergeRows = [$rw];
}
$qtyList = [];
$priceList = [];
$picked = '';
foreach ($mergeRows as $mr) {
if (!is_array($mr)) {
continue;
}
$sid = (int)($mr['ID'] ?? 0);
$db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
$src = $mr;
if (is_array($db)) {
$qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
$pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
$ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
if ($qDb !== '') {
$src['This_quantity'] = $qDb;
}
if ($pDb !== '') {
$src['ceilingPrice'] = $pDb;
}
if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
$src['NGZL'] = $ngzlDb;
}
if ($picked === '') {
$picked = trim((string)($db['pick_company_name'] ?? ''));
}
}
if ($picked === '') {
$picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
}
$qtyList[] = $this->resolveProcuremenThisQuantity($src);
$priceList[] = $this->resolveProcuremenCeilingPrice($src);
}
$rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
$rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
if ($picked !== '') {
$rw['pick_company_name'] = $picked;
$rw['picked_supplier_name'] = $picked;
}
}
unset($rw);
}
/**
* 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
*
* @param int[] $scydgyIds
* @return array
* @deprecated 合并工序展示请用 summarizeMergedOrderDetails
*/
protected function OrderDetailSummary(array $scydgyIds)
{
$out = [];
$scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
if ($scydgyIds === []) {
return $out;
}
$list = [];
try {
$list = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', $scydgyIds)
->field('id,scydgy_id,amount,delivery')
->select();
} catch (\Throwable $e) {
$list = [];
}
if (!is_array($list)) {
return $out;
}
foreach ($list as $r) {
if (!is_array($r)) {
continue;
}
$ids = (int)($r['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($ids)) {
continue;
}
if (!isset($out[$ids])) {
$out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
}
$out[$ids]['cnt']++;
$am = $r['amount'] ?? null;
if ($am !== null && $am !== '') {
if (!(is_string($am) && trim($am) === '')) {
$out[$ids]['amt']++;
}
}
$dv = $r['delivery'] ?? null;
if ($dv !== null && trim((string)$dv) !== '') {
$out[$ids]['deliv']++;
}
}
return $out;
}
/**
* 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
*
* @return array
*/
protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
{
$strContains = function ($haystack, $needle) {
if ($needle === '') {
return false;
}
$haystack = (string)$haystack;
if (function_exists('mb_stripos')) {
return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
}
return stripos($haystack, $needle) !== false;
};
$stripAlias = function ($f) {
return preg_replace('/^[ab]\./i', '', (string)$f);
};
$searchColNames = [];
foreach (explode(',', $this->searchFields) as $colRaw) {
$c = $stripAlias(trim($colRaw));
if ($c !== '') {
$searchColNames[] = $c;
}
}
// 等值条件先行(表头下拉),减少后续日期解析量
$eqFilters = [];
$otherFilters = [];
foreach ($filterArr as $fk => $fv) {
if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
continue;
}
if (is_array($fv)) {
continue;
}
if ($fv === '' && $fv !== '0' && $fv !== 0) {
continue;
}
$sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
$sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
$field = $stripAlias($fk);
if ($sym === '=' || $sym === '') {
$eqFilters[$field] = trim((string)$fv);
} else {
$otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
}
}
$ymTarget = '';
if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
$ymTarget = $ymM[1];
}
$filtered = [];
foreach ($pool as $r) {
if (!is_array($r)) {
continue;
}
foreach ($eqFilters as $field => $fv) {
if (trim((string)($r[$field] ?? '')) !== $fv) {
continue 2;
}
}
$isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
// 初选池不应含手工单;若混入则直接剔除
if ($isManual) {
continue;
}
$listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
|| !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
continue;
}
if ($applyMonthRange) {
$mo = (int)$m[2];
if ($mo < 1 || $mo > 12) {
continue;
}
if ($ymTarget !== '') {
$ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
if ($ymRow !== $ymTarget) {
continue;
}
} else {
$ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
$rowMonthStart = $ymRow . '-01 00:00:00';
$rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
continue;
}
}
}
if ($search !== '') {
$hitSearch = false;
foreach ($searchColNames as $c) {
$cell = isset($r[$c]) ? (string)$r[$c] : '';
if ($cell !== '' && $strContains($cell, $search)) {
$hitSearch = true;
break;
}
}
if (!$hitSearch) {
continue;
}
}
foreach ($otherFilters as $item) {
$fv = $item['fv'];
$sym = $item['sym'];
$field = $item['field'];
$cell = array_key_exists($field, $r) ? $r[$field] : null;
$cellStr = trim((string)$cell);
switch ($sym) {
case '<>':
if ((string)$cell === (string)$fv) {
continue 3;
}
break;
case 'LIKE':
case 'NOT LIKE':
$needle = trim((string)$fv);
$hit = ($needle !== '' && $strContains($cellStr, $needle));
if ($sym === 'LIKE' && !$hit) {
continue 3;
}
if ($sym === 'NOT LIKE' && $hit) {
continue 3;
}
break;
case 'BETWEEN':
case 'RANGE':
$parts = is_string($fv) ? explode(' - ', $fv) : [];
if (count($parts) < 2) {
$parts = is_string($fv) ? explode(',', $fv) : [];
}
$begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
$end = isset($parts[1]) ? trim((string)$parts[1]) : '';
if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
continue 3;
}
if ($end !== '' && strcmp($cellStr, $end) > 0) {
continue 3;
}
break;
case '>':
if (!(strcmp($cellStr, (string)$fv) > 0)) {
continue 3;
}
break;
case '>=':
if (!(strcmp($cellStr, (string)$fv) >= 0)) {
continue 3;
}
break;
case '<':
if (!(strcmp($cellStr, (string)$fv) < 0)) {
continue 3;
}
break;
case '<=':
if (!(strcmp($cellStr, (string)$fv) <= 0)) {
continue 3;
}
break;
default:
if ((string)$cell !== (string)$fv) {
continue 3;
}
break;
}
}
$filtered[] = $r;
}
return $filtered;
}
/**
* 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
*/
public function snapshotToProcure()
{
if (!$this->request->isPost() || !$this->request->isAjax()) {
$this->error(__('Invalid parameters'));
}
$row = json_decode($this->request->post('row_json', ''), true);
if (!is_array($row)) {
$this->error(__('Invalid parameters'));
}
try {
$ids = $this->extractScydgyRowId($row);
if (!$this->isValidScydgyRowId($ids)) {
throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
}
$exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
$data = [
'scydgy_id' => $ids,
'CCYDH' => $row['CCYDH'] ?? null,
'CYJMC' => $row['CYJMC'] ?? null,
'CCLBMMC' => $row['CCLBMMC'] ?? null,
'CDXMC' => $row['CDXMC'] ?? null,
'CGYBH' => $row['CGYBH'] ?? null,
'CGYMC' => $row['CGYMC'] ?? null,
'CDW' => $row['CDW'] ?? null,
'czlyq' => $row['czlyq'] ?? null,
'NGZL' => $row['NGZL'] ?? null,
'CDF' => $row['CDF'] ?? null,
'cGzzxMc' => $row['cGzzxMc'] ?? null,
'MBZ' => $row['MBZ'] ?? null,
'bwjg' => $row['bwjg'] ?? null,
'iStatus' => $row['iStatus'] ?? null,
'dStamp' => $row['dStamp'] ?? null,
'dputrecord' => $row['dputrecord'] ?? null,
'cywyxm' => $row['cywyxm'] ?? null,
'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
];
$qtySnap = trim((string)($data['This_quantity'] ?? ''));
$priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
if (!$exists && $qtySnap === '' && $priceSnap === '') {
$this->success('操作成功');
return;
}
if ($exists) {
$upd = $data;
unset($upd['scydgy_id'], $upd['status']);
Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
} else {
// 新增:不写 status(空/走库默认);仅写创建时间
$data['createtime'] = date('Y-m-d H:i:s');
Db::table('purchase_order')->insert($data);
}
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
// 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
$this->success('操作成功');
}
/**
* 未发列表
* 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
* POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
*/
public function completeDirectly()
{
if (!$this->request->isPost() || !$this->request->isAjax()) {
$this->error(__('参数错误'));
}
if (!$this->procuremenCanComplete()) {
$this->error(__('You have no permission'));
}
$row = json_decode($this->request->post('row_json', ''), true);
if (!is_array($row)) {
$this->error(__('Invalid parameters'));
}
$finishRaw = $this->request->post('finish', '1');
$asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
$poIdLog = null;
try {
// 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
$ids = $this->extractScydgyRowId($row);
if (!$this->isValidScydgyRowId($ids)) {
throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
}
if ($asComplete) {
$this->assertPickRowCanComplete($ids, $row);
}
$exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
$data = [
'scydgy_id' => $ids,
'CCYDH' => $row['CCYDH'] ?? null,
'CYJMC' => $row['CYJMC'] ?? null,
'CCLBMMC' => $row['CCLBMMC'] ?? null,
'CDXMC' => $row['CDXMC'] ?? null,
'CGYBH' => $row['CGYBH'] ?? null,
'CGYMC' => $row['CGYMC'] ?? null,
'CDW' => $row['CDW'] ?? null,
'czlyq' => $row['czlyq'] ?? null,
'NGZL' => $row['NGZL'] ?? null,
'CDF' => $row['CDF'] ?? null,
'cGzzxMc' => $row['cGzzxMc'] ?? null,
'MBZ' => $row['MBZ'] ?? null,
'bwjg' => $row['bwjg'] ?? null,
'iStatus' => $row['iStatus'] ?? null,
'dStamp' => $row['dStamp'] ?? null,
'dputrecord' => $row['dputrecord'] ?? null,
'cywyxm' => $row['cywyxm'] ?? null,
'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
];
if ($asComplete) {
$data['status'] = ProcuremenStatus::PO_COMPLETED;
$data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
}
$qtyCd = trim((string)($data['This_quantity'] ?? ''));
$priceCd = trim((string)($data['ceilingPrice'] ?? ''));
if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
$this->success('操作成功');
return;
}
if ($exists) {
$upd = $data;
unset($upd['scydgy_id']);
if (!$asComplete) {
unset($upd['status']);
}
Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
} else {
// 新增:不写 status;完结时 $data 已含 status=1
$data['createtime'] = date('Y-m-d H:i:s');
Db::table('purchase_order')->insert($data);
}
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
try {
$rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
if (is_array($rpo)) {
$tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
$poIdLog = $tid > 0 ? $tid : null;
}
} catch (\Throwable $e) {
$poIdLog = null;
}
$q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
$p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
if ($asComplete) {
$this->addOrderLog(
$ids,
'mark_complete',
'点击「完结」,已标记为已完结',
$poIdLog
);
try {
$pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
if ($pdfPublicPath === '') {
Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
}
} catch (\Throwable $e) {
Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
}
} else {
$gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
$qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
$pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
$detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
$this->addOrderLog(
$ids,
'save_qty_price',
'保存本次数量、最高限价:' . $detail,
$poIdLog
);
}
$this->pickHiddenScydgySetCache = null;
$this->success("操作成功");
}
/**
* 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
*
* @param array $rows 引用传递当前页行
*/
protected function mergePurchaseOrder(array &$rows)
{
if ($rows === []) {
return;
}
$ids = [];
foreach ($rows as $rw) {
if (!is_array($rw)) {
continue;
}
$id = (int)($rw['ID'] ?? 0);
// 含手工新增负数 scydgy_id,避免限价/数量不同步
if ($this->isValidScydgyRowId($id)) {
$ids[$id] = true;
}
}
$idList = array_keys($ids);
if ($idList === []) {
return;
}
try {
$list = Db::table('purchase_order')
->where('scydgy_id', 'in', $idList)
->field('scydgy_id,This_quantity,ceilingPrice')
->select();
} catch (\Throwable $e) {
return;
}
if (!is_array($list)) {
return;
}
$byId = [];
foreach ($list as $dbRow) {
if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
continue;
}
$byId[(int)$dbRow['scydgy_id']] = $dbRow;
}
foreach ($rows as &$rw) {
if (!is_array($rw)) {
continue;
}
$sid = (int)($rw['ID'] ?? 0);
if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
continue;
}
$db = $byId[$sid];
// 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
if (array_key_exists('This_quantity', $db)) {
$rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
}
if (array_key_exists('ceilingPrice', $db)) {
$rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
} elseif (array_key_exists('ceiling_price', $db)) {
$rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
}
}
unset($rw);
}
/**
* 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
*/
public function purchaseConfirmPick()
{
if (!$this->request->isPost() || !$this->request->isAjax()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
$this->error(__('You have no permission'));
}
$batchRaw = trim((string)$this->request->post('order_picks_json', ''));
if ($batchRaw !== '') {
$this->handlePurchaseConfirmOrderBatch($batchRaw);
return;
}
$scydgyId = trim((string)$this->request->post('scydgy_id', ''));
$sid = (int)$scydgyId;
if (!$this->isValidScydgyRowId($sid)) {
$this->error('参数无效');
}
$parseIdList = function ($raw) {
if (is_array($raw)) {
$arr = $raw;
} else {
$decoded = json_decode((string)$raw, true);
$arr = is_array($decoded) ? $decoded : [];
}
return array_values(array_unique(array_filter(array_map('intval', $arr))));
};
$selectedRaw = $this->request->post('selected_ids', null);
if ($selectedRaw === null || $selectedRaw === '') {
$legacy = (int)$this->request->post('selected_id', 0);
$selectedIds = $legacy > 0 ? [$legacy] : [];
} else {
$selectedIds = $parseIdList($selectedRaw);
}
$unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
$purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
try {
$result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
} catch (\InvalidArgumentException $e) {
$this->error($e->getMessage());
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
$this->pickHiddenScydgySetCache = null;
$this->success('操作成功', '', $result);
}
/**
* 整单采购确认(多道工序一次提交)
*/
protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
{
$decoded = json_decode($batchRaw, true);
if (!is_array($decoded) || $decoded === []) {
$this->error('提交数据无效');
}
$picks = [];
foreach ($decoded as $item) {
if (!is_array($item)) {
continue;
}
$sid = (int)($item['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid)) {
continue;
}
$sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
if (!is_array($sel)) {
$sel = [(int)$sel];
}
$unsel = $item['unselected_ids'] ?? [];
if (!is_array($unsel)) {
$unsel = json_decode((string)$unsel, true);
$unsel = is_array($unsel) ? $unsel : [];
}
$picks[] = [
'scydgy_id' => $sid,
'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
];
}
if ($picks === []) {
$this->error('提交数据无效');
}
Db::startTrans();
$results = [];
try {
foreach ($picks as $pick) {
$results[] = $this->runPurchaseConfirmPick(
(int)$pick['scydgy_id'],
$pick['selected_ids'],
$pick['unselected_ids'],
(int)$pick['purchase_order_id'],
false,
false
);
}
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$msg = $e->getMessage();
$this->error($msg !== '' ? $msg : '提交失败');
}
try {
$bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
$this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
} catch (\Throwable $e) {
Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
}
$this->pickHiddenScydgySetCache = null;
$this->success('操作成功', '', ['batch' => $results]);
}
/**
* @return array
*/
protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
{
$poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
ProcuremenGuard::assertWflowPendingApproval($poRow);
ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
$scydgyId = (string)$sid;
if ($selectedIds === []) {
throw new \InvalidArgumentException('请至少勾选一条明细');
}
$inter = array_intersect($selectedIds, $unselectedIds);
if ($inter !== []) {
throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
}
$allIds = $this->purchaseOrderDetail($sid);
if ($allIds === []) {
throw new \InvalidArgumentException('未找到该工序行的下发明细');
}
foreach ($selectedIds as $id) {
if (!in_array($id, $allIds, true)) {
throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
}
}
foreach ($unselectedIds as $id) {
if (!in_array($id, $allIds, true)) {
throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
}
}
$union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
sort($union, SORT_NUMERIC);
$expect = $allIds;
sort($expect, SORT_NUMERIC);
if ($union !== $expect) {
throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
}
if ($manageTransaction) {
Db::startTrans();
}
try {
Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
$aff = 0;
try {
$aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
} catch (\Throwable $e) {
$aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
}
if ($aff < 1) {
throw new \Exception('更新选中状态失败');
}
$poPayload = [
// 审核通过后进入「待入库评分」;合格/不合格后才置已完结
'status' => ProcuremenStatus::PO_IN_PROGRESS,
'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
];
if ($purchaseOrderId > 0) {
$poAff = (int)Db::table('purchase_order')
->where('id', $purchaseOrderId)
->where('scydgy_id', $sid)
->update($poPayload);
if ($poAff < 1) {
throw new \Exception('主表订单不存在或与工序行不匹配');
}
} else {
$poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
if ($poAff < 1) {
throw new \Exception('未找到');
}
}
$this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
$this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
if ($manageTransaction) {
Db::commit();
}
} catch (\Throwable $e) {
if ($manageTransaction) {
Db::rollback();
}
throw $e;
}
$poIdFinal = $purchaseOrderId;
if ($poIdFinal <= 0) {
try {
$rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
if (is_array($rpo)) {
$poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
}
} catch (\Throwable $e) {
$poIdFinal = 0;
}
}
$pickNames = [];
foreach ($selectedIds as $pid) {
$dr = $this->purchaseOrderDetai($sid, $pid);
$nm = trim((string)($dr['company_name'] ?? ''));
$pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
}
$this->addOrderLog(
$sid,
'purchase_confirm',
'审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
$poIdFinal > 0 ? $poIdFinal : null
);
if ($sendNotifications) {
try {
$bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
$this->dispatchPurchaseConfirmPickNotifications($bundle, [[
'scydgy_id' => $sid,
'selected_ids' => $selectedIds,
'unselected_ids' => $unselectedIds,
'purchase_order_id' => $purchaseOrderId,
]]);
} catch (\Throwable $e) {
Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
}
}
Log::write(sprintf(
'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
$scydgyId,
$purchaseOrderId,
json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
), 'notice');
$pdfPublicPath = '';
try {
$pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
} catch (\Throwable $e) {
Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
}
return [
'scydgy_id' => $scydgyId,
'purchase_order_id' => $purchaseOrderId,
'selected_ids' => $selectedIds,
'unselected_ids' => $unselectedIds,
'purchase_confirm_pdf' => $pdfPublicPath,
];
}
/**
* 审批通过短信:按本次涉及的工序汇总 process_lines
*
* @param int[]|string[] $scydgyIds
* @return array{ccydh:string, pos:array, merge_rows:array}
*/
protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
{
$empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
$scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
if ($scydgyIds === []) {
return $empty;
}
$pos = [];
try {
$rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
} catch (\Throwable $e) {
$rows = [];
}
if (is_array($rows)) {
foreach ($rows as $po) {
if (is_array($po)) {
$pos[] = $po;
}
}
}
if ($pos === []) {
return $empty;
}
$ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
return [
'ccydh' => $ccydh,
'pos' => $pos,
'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
];
}
/**
* 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
*
* @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
* @param array> $picks
*/
protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
{
if ($picks === []) {
return;
}
$fallbackDetailId = 0;
$winners = [];
$losers = [];
foreach ($picks as $pick) {
if (!is_array($pick)) {
continue;
}
$sid = (int)($pick['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid)) {
continue;
}
$selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
$unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
if ($fallbackDetailId <= 0 && $selectedIds !== []) {
$fallbackDetailId = (int)$selectedIds[0];
}
foreach ($selectedIds as $pid) {
$dr = $this->purchaseOrderDetai($sid, $pid);
if (!is_array($dr)) {
continue;
}
$winners[$this->notifySupplierDedupeKey($dr)] = $dr;
}
foreach ($unselectedIds as $pid) {
$dr = $this->purchaseOrderDetai($sid, $pid);
if (!is_array($dr)) {
continue;
}
$key = $this->notifySupplierDedupeKey($dr);
if (!isset($winners[$key])) {
$losers[$key] = $dr;
}
}
}
if ($winners === [] && $losers === []) {
return;
}
$confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
$sendSmsSafe = function ($phone, $content) {
$phone = trim((string)$phone);
if ($phone === '') {
return;
}
try {
$this->smsbao($phone, $content);
} catch (\Throwable $e) {
Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
}
};
foreach ($winners as $dr) {
$cname = trim((string)($dr['company_name'] ?? ''));
$ph = trim((string)($dr['phone'] ?? ''));
$sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
'company_name' => $cname,
'contact_name' => $this->resolveCustomerContactName($ph, $cname),
'phone' => $ph,
]));
$sendSmsSafe($ph, $sms);
}
foreach ($losers as $dr) {
$cname = trim((string)($dr['company_name'] ?? ''));
$ph = trim((string)($dr['phone'] ?? ''));
$sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
'company_name' => $cname,
'contact_name' => $this->resolveCustomerContactName($ph, $cname),
'phone' => $ph,
]));
$sendSmsSafe($ph, $sms);
}
}
/**
* 短信去重键:优先手机号,否则公司名
*/
protected function notifySupplierDedupeKey(array $detailRow): string
{
$ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
if ($ph !== '') {
return 'p:' . $ph;
}
$cn = trim((string)($detailRow['company_name'] ?? ''));
return 'c:' . $cn;
}
/**
* 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
*
* @param int[] $detailIds
*/
protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
{
$detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
if ($detailIds === []) {
return;
}
$payload = ['status_name' => $statusName];
try {
Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
} catch (\Throwable $e) {
Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
}
}
/**
* 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
*/
protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
{
try {
$rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
} catch (\Throwable $e) {
return;
}
if (!is_array($rows)) {
return;
}
foreach ($rows as $dr) {
if (!is_array($dr)) {
continue;
}
$id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
if ($id <= 0) {
continue;
}
$sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
$pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
try {
Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
} catch (\Throwable $e) {
}
}
}
/**
* @param array $detailRow
*/
protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
{
$am = $detailRow['amount'] ?? null;
$dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
$amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
$deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
}
/**
* @return int[]
*/
protected function purchaseOrderDetail(int $scydgyId): array
{
if (!$this->isValidScydgyRowId($scydgyId)) {
return [];
}
try {
$listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
$this->applyActivePurchaseOrderDetailWhere($listQuery);
$list = $listQuery->select();
} catch (\Throwable $e) {
return [];
}
if (!is_array($list)) {
return [];
}
$ids = [];
foreach ($list as $r) {
if (!is_array($r)) {
continue;
}
$pk = (int)($r['id'] ?? $r['ID'] ?? 0);
if ($pk > 0) {
$ids[] = $pk;
}
}
return array_values(array_unique($ids));
}
/**
* 获取当前登录用户信息 [id, 展示名]
*/
protected function GetUseName(): array
{
$id = 0;
$name = '';
try {
if ($this->auth && $this->auth->isLogin()) {
$u = $this->auth->getUserInfo();
if (is_array($u)) {
$id = (int)($u['id'] ?? 0);
$name = trim((string)($u['nickname'] ?? ''));
if ($name === '') {
$name = trim((string)($u['username'] ?? ''));
}
}
}
} catch (\Throwable $e) {
}
if ($name === '') {
$name = '未知用户';
}
return [$id, $name];
}
/**
* 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
*/
protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
{
ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
}
/**
* 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
*
* @param array> $rows
*/
protected function enrichProcuremenListMilestoneTimes(array &$rows): void
{
$sidList = [];
foreach ($rows as $rw) {
if (!is_array($rw)) {
continue;
}
if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
foreach ($rw['_order_merge_rows'] as $mr) {
$mid = (int)($mr['ID'] ?? 0);
if ($this->isValidScydgyRowId($mid)) {
$sidList[$mid] = true;
}
}
}
$id = (int)($rw['ID'] ?? 0);
if ($this->isValidScydgyRowId($id)) {
$sidList[$id] = true;
}
}
$sids = array_keys($sidList);
$issueBySid = [];
$confirmBySid = [];
$approveBySid = [];
if ($sids !== []) {
$issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
$confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
$approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
$allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
try {
$logs = Db::table('purchase_order_oper_log')
->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
->order('id', 'asc')
->select();
} catch (\Throwable $e) {
$logs = [];
}
if (is_array($logs)) {
$issueSet = array_fill_keys($issueActs, true);
$confirmSet = array_fill_keys($confirmActs, true);
$approveSet = array_fill_keys($approveActs, true);
foreach ($logs as $lg) {
if (!is_array($lg)) {
continue;
}
$lg = ProcuremenOperLog::normalizeRow($lg);
$sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
if ($sid === 0) {
continue;
}
$action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
$t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
if ($t === '') {
continue;
}
if (isset($issueSet[$action])) {
if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
$issueBySid[$sid] = $t;
}
}
if (isset($confirmSet[$action])) {
if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
$confirmBySid[$sid] = $t;
}
}
if (isset($approveSet[$action])) {
if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
$approveBySid[$sid] = $t;
}
}
}
}
}
foreach ($rows as &$rw) {
if (!is_array($rw)) {
continue;
}
$mergeSids = [];
if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
foreach ($rw['_order_merge_rows'] as $mr) {
$mid = (int)($mr['ID'] ?? 0);
if ($this->isValidScydgyRowId($mid)) {
$mergeSids[] = $mid;
}
}
}
$rid = (int)($rw['ID'] ?? 0);
if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
$mergeSids[] = $rid;
}
$pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
$issue = $pick;
$confirm = '';
$approve = '';
foreach ($mergeSids as $sid) {
if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
$issue = $issueBySid[$sid];
}
if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
$confirm = $confirmBySid[$sid];
}
if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
$approve = $approveBySid[$sid];
}
}
if ($issue === '' && $pick !== '') {
$issue = $pick;
}
$rw['issue_time'] = $issue;
$rw['confirm_time'] = $confirm;
$rw['approve_time'] = $approve;
}
unset($rw);
}
/**
* 按主键取一条
*/
protected function purchaseOrderDetai(int $scydgyId, int $pk): array
{
if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
return [];
}
try {
$one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
if (is_array($one)) {
return $one;
}
} catch (\Throwable $e) {
}
try {
$one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
if (is_array($one)) {
return $one;
}
} catch (\Throwable $e) {
}
return [];
}
/**
* 主表/明细时间字段统一为可读字符串(用于详情进度)
*/
protected function formatProcuremenDetailTime($v): string
{
if ($v === null || $v === '') {
return '';
}
if (is_numeric($v) && (int)$v > 946684800) {
return date('Y-m-d H:i:s', (int)$v);
}
return ProcuremenTime::formatDisplayDateTime($v);
}
/**
* 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
*/
protected function formatDeliveryYmd($v): string
{
if ($v === null || $v === '') {
return '';
}
$s = trim((string)$v);
if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
return '';
}
if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
return $m[1];
}
$ts = strtotime($s);
return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
}
/**
* 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
*/
protected function detailRowSupplierOperated(array $r): bool
{
$am = $r['amount'] ?? null;
$okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
$dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
$okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
return $okAmt || $okDel;
}
/**
* 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
*/
protected function resolveDetailSupplierOperTime(array $r): string
{
if (!$this->detailRowSupplierOperated($r)) {
return '';
}
$t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
if ($t !== '') {
return $t;
}
foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
continue;
}
$t = $this->formatProcuremenDetailTime($r[$col]);
if ($t !== '') {
return $t;
}
}
return '';
}
/**
* 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
*/
protected function detailRowSupplierAccepted(array $r): bool
{
$am = $r['amount'] ?? null;
$okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
$dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
$okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
return $okAmt && $okDel;
}
/**
* 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
*/
protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
{
if ($detailCount > 0) {
return true;
}
if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
return true;
}
$pickTime = trim((string)($main['pick_time'] ?? ''));
if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
return true;
}
return false;
}
/**
* 下发时间:优先 pick_time,其次首条下发明细时间
*/
protected function resolveProcuremenIssueTime(array $main, array $details): string
{
$issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
if ($issueTime !== '') {
return $issueTime;
}
foreach ($details as $dr) {
if (!is_array($dr)) {
continue;
}
$t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
$issueTime = $t;
}
}
if ($issueTime !== '') {
return $issueTime;
}
return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
}
/**
* 直接点「完结」时间:优先操作记录 mark_complete
*/
protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
{
return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
}
/**
* 操作记录时间(取指定 action 最近一条)
*
* @param string|array $actions
*/
protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
{
return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
}
/**
* 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
*
* @param array $main purchase_order 一行
* @param array $details purchase_order_detail 多行(已预处理 createtime_text)
* @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
*/
protected function buildProcuremenDetailsViewData(array $main, array $details): array
{
$issueCnt = count($details);
$acceptCnt = 0;
$pickedName = '';
$pickedTime = '';
foreach ($details as $dr) {
if (!is_array($dr)) {
continue;
}
if ($this->detailRowSupplierAccepted($dr)) {
$acceptCnt++;
}
if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
if ($pickedName === '') {
$pickedName = trim((string)($dr['company_name'] ?? ''));
}
if ($pickedTime === '') {
$pickedTime = trim((string)($dr['createtime_text'] ?? ''));
if ($pickedTime === '') {
$pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
}
}
}
}
$hasMain = $main !== [];
$poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
if ($poTime === '') {
$poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
}
$mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
$wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
$wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
$issued = $this->isProcuremenOrderIssued($main, $issueCnt);
$issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
$scydgyId = (int)($main['scydgy_id'] ?? 0);
$auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
$confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
$inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
$inboundResult = '';
if ($scydgyId > 0) {
try {
$inRow = Db::table('purchase_order_inbound_score')
->where('scydgy_id', $scydgyId)
->field('result,updatetime,createtime')
->find();
} catch (\Throwable $e) {
$inRow = null;
}
if (is_array($inRow) && $inRow !== []) {
$inboundResult = trim((string)($inRow['result'] ?? ''));
if ($inboundScoreTime === '') {
$inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
}
}
}
$inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
$supplierTime = '';
if ($acceptCnt > 0) {
foreach ($details as $dr) {
if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
continue;
}
$t = $this->resolveDetailSupplierOperTime($dr);
if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
$supplierTime = $t;
}
}
}
$directComplete = ($mainCompleted && !$issued);
$doneTime = '';
if ($mainCompleted) {
if ($directComplete) {
$doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
}
if ($doneTime === '' && $inboundScoreTime !== '') {
$doneTime = $inboundScoreTime;
}
if ($doneTime === '') {
$doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
}
if ($doneTime === '') {
foreach ($details as $dr) {
if (!is_array($dr)) {
continue;
}
$t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
$doneTime = $t;
}
}
}
if ($doneTime === '') {
$doneTime = $poTime;
}
// 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
if ($doneTime === '' && $confirmApproveTime !== '') {
$doneTime = $confirmApproveTime;
}
}
if ($directComplete) {
// 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
$step1Done = $hasMain;
$step2Done = false;
$step3Done = false;
$step4Done = false;
$step5Done = false;
$stepInboundDone = $inboundScored;
$step6Done = $mainCompleted && $inboundScored;
} else {
$step1Done = $issued;
$step2Done = $issued;
$step3Done = $acceptCnt > 0;
$step4Done = $wflowPendingApproval;
if (!$step4Done) {
foreach ($details as $dr) {
if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
$step4Done = true;
break;
}
}
}
$step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
$stepInboundDone = $inboundScored;
// 未确认合格/不合格时,「已完结」保持未点亮(灰色)
$step6Done = $mainCompleted && $inboundScored;
// 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
if ($mainCompleted && $issued) {
$step3Done = true;
$step4Done = true;
$step5Done = true;
// 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
if ($supplierTime === '') {
$fillT = $doneTime !== '' ? $doneTime : $poTime;
if ($fillT !== '') {
$supplierTime = $fillT;
}
}
if ($pickedTime === '') {
$fillT = $doneTime !== '' ? $doneTime : $poTime;
if ($fillT !== '') {
$pickedTime = $fillT;
}
}
if ($auditSelectTime === '') {
$fillT = $doneTime !== '' ? $doneTime : $poTime;
if ($fillT !== '') {
$auditSelectTime = $fillT;
}
}
if ($confirmApproveTime === '') {
$fillT = $doneTime !== '' ? $doneTime : $poTime;
if ($fillT !== '') {
$confirmApproveTime = $fillT;
}
}
}
}
$poTime = ProcuremenTime::formatDisplayDateTime($poTime);
$issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
$supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
$pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
$auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
$confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
$inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
$doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
$deadlineLines = [];
$sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
$deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
$deadlineLines[] = '招标截止日期:' . $deadlineDisp;
}
}
$deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
$deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
if ($deliveryDisp === '') {
$deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
}
if ($deliveryDisp !== '') {
$deadlineLines[] = '交货截止日期:' . $deliveryDisp;
}
}
$issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
$deadlineText = implode("\n", $deadlineLines);
$prefixOperTime = static function (string $t): string {
$t = trim($t);
if ($t === '' || $t === '—') {
return $t;
}
if (strpos($t, '操作时间') === 0) {
return $t;
}
return '操作时间:' . $t;
};
$step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
$step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
$step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
$stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
$step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
$steps = [
[
'title' => '未发',
'subtitle' => '',
'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
'done' => $step1Done,
],
[
'title' => '下发',
'subtitle' => $deadlineText,
'time' => $prefixOperTime($step2Time),
'done' => $step2Done,
],
[
'title' => '供应商接单',
'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
'time' => '',
'done' => $step3Done,
],
[
'title' => '待确认',
'subtitle' => $step4Done
? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
: ($issued ? '待选供应商' : ''),
'time' => $prefixOperTime($step4Time),
'done' => $step4Done,
],
[
'title' => '待审批',
'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
'time' => $prefixOperTime($step5Time),
'done' => $step5Done,
],
[
'title' => '是否合格',
'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
'time' => $prefixOperTime($stepInboundTime),
'done' => $stepInboundDone,
],
[
'title' => '已完结',
'subtitle' => '',
'time' => $prefixOperTime($step6Time),
'done' => $step6Done,
],
];
$currentIdx = count($steps) - 1;
if ($directComplete) {
// 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
if (!$step6Done) {
foreach ($steps as $i => $s) {
if (($s['title'] ?? '') === '是否合格') {
$currentIdx = $i;
break;
}
}
}
} else {
foreach ($steps as $i => $s) {
if (!$s['done']) {
$currentIdx = $i;
break;
}
}
}
$nSteps = count($steps);
foreach ($steps as $idx => &$s) {
$s['current'] = ($idx === $currentIdx);
if ($idx === 0) {
$s['pdf_left_bg'] = '';
} else {
$s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
}
if ($idx >= $nSteps - 1) {
$s['pdf_right_bg'] = '';
} else {
$s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
}
}
unset($s);
$labelMap = [
'CCYDH' => '订单号',
'CYJMC' => '印件名称',
'CCLBMMC' => '承揽部门',
'CGYMC' => '工序名称',
'CDW' => '单位',
'czlyq' => '类型',
'NGZL' => '工作量',
'CDF' => '单价',
'cGzzxMc' => '工作中心',
'MBZ' => '备注',
'This_quantity' => '本次数量',
'ceilingPrice' => '最高限价',
];
$orderSummary = [];
foreach ($labelMap as $key => $lab) {
if (!array_key_exists($key, $main)) {
continue;
}
$val = $main[$key];
if ($val === null) {
$val = '';
} elseif (!is_scalar($val)) {
$val = json_encode($val, JSON_UNESCAPED_UNICODE);
} else {
$val = (string)$val;
}
$orderSummary[] = ['label' => $lab, 'value' => $val];
}
$orderSummary[] = [
'label' => '是否合格',
'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
];
$orderSummaryGrid = [];
$n = count($orderSummary);
for ($i = 0; $i < $n; $i += 2) {
$left = $orderSummary[$i];
$hasRight = ($i + 1) < $n;
$orderSummaryGrid[] = [
'l1' => $left['label'],
'v1' => $left['value'],
'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
];
}
return [
'steps' => $steps,
'orderSummary' => $orderSummary,
'orderSummaryGrid' => $orderSummaryGrid,
'inbound_result' => $inboundResult,
'inbound_score_time'=> $inboundScoreTime,
'detailRows' => $details,
];
}
/**
* 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
*
* @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
*/
protected function prepareProcuremenDetailsView(string $ids): array
{
$main = [];
try {
$one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
$main = is_array($one) ? $one : [];
} catch (\Throwable $e) {
$main = [];
}
$details = [];
$mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
if ($mergeRows === []) {
$mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
if ($mergeRows === [] && $main !== []) {
$mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
}
}
$detailSidList = [];
$anchorSid = (int)$ids;
if ($anchorSid !== 0) {
$detailSidList[$anchorSid] = true;
}
foreach ($mergeRows as $mr) {
if (!is_array($mr)) {
continue;
}
$sid = $this->extractScydgyRowId($mr);
if ($sid !== 0) {
$detailSidList[$sid] = true;
}
}
try {
if ($detailSidList !== []) {
$details = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($detailSidList))
->order('id', 'asc')
->select();
}
} catch (\Throwable $e) {
$details = [];
}
if (!is_array($details)) {
$details = [];
}
foreach ($details as &$r) {
if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
$r['id'] = $r['ID'];
}
if (isset($r['createtime'])) {
if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
$r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
} else {
$r['createtime_text'] = (string)$r['createtime'];
}
} else {
$r['createtime_text'] = '';
}
$r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
$r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
$r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
$r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
if (is_array($r)) {
$r = $this->maskSupplierContactFields($r);
}
}
unset($r);
$activeDetails = [];
foreach ($details as $r) {
if (is_array($r) && empty($r['is_void'])) {
$activeDetails[] = $r;
}
}
$operLogs = [];
try {
$operSidList = array_keys($detailSidList);
if ($operSidList === [] && (int)$ids !== 0) {
$operSidList = [(int)$ids];
}
if ($operSidList !== []) {
$operLogs = Db::table('purchase_order_oper_log')
->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
->order('id', 'asc')
->select();
}
// 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
$poId = (int)($main['id'] ?? $main['ID'] ?? 0);
if ($poId > 0) {
$operLogs = Db::table('purchase_order_oper_log')
->where(ProcuremenOperLog::COL_PO_ID, $poId)
->order('id', 'asc')
->select();
}
}
} catch (\Throwable $e) {
$operLogs = [];
}
if (!is_array($operLogs)) {
$operLogs = [];
}
$operLogsRaw = $operLogs;
$processNameBySid = [];
foreach ($mergeRows as $mr) {
if (!is_array($mr)) {
continue;
}
$psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
$gymc = trim((string)($mr['CGYMC'] ?? ''));
if ($psid !== 0 && $gymc !== '') {
$processNameBySid[$psid] = $gymc;
}
}
$operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
$bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
$quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
$ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
if ($ccydh === '') {
foreach ($details as $r) {
if (!is_array($r)) {
continue;
}
$ccydh = trim((string)($r['CCYDH'] ?? ''));
if ($ccydh !== '') {
break;
}
}
}
$this->view->assign('ccydh', $ccydh);
$this->view->assign('steps', $bundle['steps']);
$this->view->assign('orderSummary', $bundle['orderSummary']);
$this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
$this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
$this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
$this->view->assign('processDisplayRows', $quoteView['process_rows']);
$this->view->assign('processCount', count($mergeRows));
$this->view->assign('detailRows', $details);
$this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
$this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
$this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
$this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
// 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
$showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
|| ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
$this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
$this->view->assign('operLogs', $operLogs);
$sg = $quoteView['supplier_groups'] ?? [];
$orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
$this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
$this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
$this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
return [
'ok' => $main !== [] || $details !== [],
'ccydh' => $ccydh,
];
}
/**
* 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
*/
public function details()
{
$ids = $this->request->param('ids', $this->request->param('id', ''));
if (is_array($ids)) {
$ids = isset($ids[0]) ? $ids[0] : '';
}
$ids = trim((string)$ids);
if ($ids === '') {
$this->error(__('Invalid parameters'));
}
$this->assertManualOrderDetailsViewable((int)$ids);
$this->prepareProcuremenDetailsView($ids);
/* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
$restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
$this->view->engine->layout(false);
try {
return $this->view->fetch('procuremen/details_dialog_shell');
} finally {
if ($restoreLayout) {
$this->view->engine->layout($restoreLayout);
}
}
}
/**
* 解析合并审核工序行(订单号须一致,且均未协助)
*
* @return array>
*/
protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
{
$primary = json_decode($rowJson, true);
if (!is_array($primary)) {
$this->error(__('Invalid parameters'));
}
$merge = json_decode($mergeRowsJson, true);
if (!is_array($merge) || $merge === []) {
$merge = [$primary];
}
$seen = [];
$out = [];
foreach ($merge as $r) {
if (!is_array($r)) {
continue;
}
$id = $this->extractScydgyRowId($r);
if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
continue;
}
$seen[$id] = true;
$out[] = $r;
}
if ($out === []) {
$this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
}
$ccydh = null;
foreach ($out as $r) {
$dh = trim((string)($r['CCYDH'] ?? ''));
if ($ccydh === null) {
$ccydh = $dh;
} elseif ($dh !== $ccydh) {
$this->error('合并审核要求所选行的订单号一致');
}
}
$ids = [];
foreach ($out as $r) {
$id = $this->extractScydgyRowId($r);
if ($this->isValidScydgyRowId($id)) {
$ids[$id] = true;
}
}
$poBySid = [];
$detCntBySid = [];
if ($ids !== []) {
$idList = array_keys($ids);
try {
$poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
if (is_array($poList)) {
foreach ($poList as $po) {
if (!is_array($po)) {
continue;
}
$sid = (int)($po['scydgy_id'] ?? 0);
if ($this->isValidScydgyRowId($sid)) {
$poBySid[$sid] = $po;
}
}
}
} catch (\Throwable $e) {
}
try {
$detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
$this->applyActivePurchaseOrderDetailWhere($detQuery);
$detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
if (is_array($detRows)) {
foreach ($detRows as $dr) {
if (!is_array($dr)) {
continue;
}
$sid = (int)($dr['scydgy_id'] ?? 0);
if ($this->isValidScydgyRowId($sid)) {
$detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
}
}
}
} catch (\Throwable $e) {
}
}
foreach ($out as $r) {
$id = $this->extractScydgyRowId($r);
if (!$this->isValidScydgyRowId($id)) {
continue;
}
$po = $poBySid[$id] ?? null;
if (!is_array($po)) {
continue;
}
if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
$gymc = trim((string)($r['CGYMC'] ?? ''));
$this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
}
$detCnt = (int)($detCntBySid[$id] ?? 0);
if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
$gymc = trim((string)($r['CGYMC'] ?? ''));
$this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
}
}
return $out;
}
/**
* 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
*/
protected function maskSupplierContactFields(array $item): array
{
if (array_key_exists('email', $item)) {
$item['email'] = mask_email((string)$item['email']);
}
if (array_key_exists('phone', $item)) {
$item['phone'] = mask_phone((string)$item['phone']);
}
return $item;
}
/**
* @param array> $list
* @return array>
*/
protected function maskSupplierContactList(array $list): array
{
$out = [];
foreach ($list as $item) {
$out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
}
return $out;
}
/**
* 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
*
* @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
* @return array|null
*/
protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
{
if (!is_array($row)) {
return null;
}
$norm = [];
foreach ($row as $k => $v) {
$norm[is_string($k) ? strtolower($k) : $k] = $v;
}
$row = $norm;
$st = $row['status'] ?? '';
if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
return null;
}
$companyName = '';
foreach (['company_name', 'name'] as $nk) {
if (!empty($row[$nk])) {
$companyName = trim((string)$row[$nk]);
break;
}
}
if ($companyName === '') {
return null;
}
$username = '';
foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
$username = trim((string)$row[$uk]);
break;
}
}
$email = isset($row['email']) ? trim((string)$row['email']) : '';
$phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
if ($phone === '' && isset($row['account'])) {
$phone = trim((string)$row['account']);
}
if ($phone === '' && isset($row['mobile'])) {
$phone = trim((string)$row['mobile']);
}
if ($requireContactChannels && $email === '' && $phone === '') {
return null;
}
$category = '';
foreach (['company_type', 'category', 'type_name'] as $ck) {
if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
$category = trim((string)$row[$ck]);
break;
}
}
return [
'id' => isset($row['id']) ? (string)$row['id'] : '',
'name' => $companyName,
'company_name' => $companyName,
'username' => $username,
'email' => $email,
'phone' => $phone,
'category' => $category,
'company_type' => $category,
];
}
/**
* 按 customer.id 解析供应商联系信息(服务端下发/通知用)
*/
protected function resolveCustomerContactById(string $id): ?array
{
$id = trim($id);
if ($id === '' || !ctype_digit($id)) {
return null;
}
try {
$row = Db::table('customer')->where('id', (int)$id)->find();
} catch (\Throwable $e) {
return null;
}
return $this->buildCustomerContactPayloadFromRow($row);
}
/**
* 按供应商名称解析联系信息(兼容旧提交数据)
*
* @param bool $requireContactChannels true 时须有邮箱或手机
*/
protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
{
$name = trim($name);
if ($name === '') {
return null;
}
try {
// customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
$row = Db::table('customer')
->where('company_name', $name)
->order('id', 'desc')
->find();
} catch (\Throwable $e) {
return null;
}
return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
}
/**
* 规范化下发/确认时勾选的供应商
*
* @param array $companies
* @return array>
*/
protected function normalizePickCompanies(array $companies): array
{
$out = [];
foreach ($companies as $c) {
if (!is_array($c)) {
continue;
}
$resolved = null;
$cid = trim((string)($c['id'] ?? ''));
if ($cid !== '') {
$resolved = $this->resolveCustomerContactById($cid);
}
$name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
if ($resolved === null && $name !== '') {
$resolved = $this->resolveCustomerContactByCompanyName($name);
}
if ($resolved === null) {
continue;
}
$out[] = $resolved;
}
return $out;
}
/**
* 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
*
* @param array> $pool
* @return array>
*/
protected function collapseProcuremenPoolByOrder(array $pool): array
{
if ($pool === []) {
return [];
}
$groups = [];
foreach ($pool as $row) {
if (!is_array($row)) {
continue;
}
$dh = trim((string)($row['CCYDH'] ?? ''));
$key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
if (!isset($groups[$key])) {
$groups[$key] = [];
}
$groups[$key][] = $row;
}
$out = [];
foreach ($groups as $ccydh => $rows) {
if ($rows === []) {
continue;
}
usort($rows, function ($a, $b) {
return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
});
$head = $rows[0];
$gymcList = [];
foreach ($rows as $r) {
$g = trim((string)($r['CGYMC'] ?? ''));
if ($g !== '' && !in_array($g, $gymcList, true)) {
$gymcList[] = $g;
}
}
$merged = $head;
$merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
$merged['process_count'] = count($rows);
$merged['_order_merge_rows'] = $rows;
$qtyList = [];
$priceList = [];
foreach ($rows as $r) {
if (!is_array($r)) {
continue;
}
$qtyList[] = $this->resolveProcuremenThisQuantity($r);
$priceList[] = $this->resolveProcuremenCeilingPrice($r);
}
if (count($rows) > 1) {
$merged['CGYMC'] = implode('、', $gymcList);
// 多工序:数量/限价按有值项顿号间隔(空值不占位)
$merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
$merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
} else {
$merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
$merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
}
// 已选供应商:取合并行中首个非空 pick_company_name
$pickedName = '';
foreach ($rows as $r) {
if (!is_array($r)) {
continue;
}
$pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
if ($pn !== '') {
$pickedName = $pn;
break;
}
}
if ($pickedName !== '') {
$merged['pick_company_name'] = $pickedName;
$merged['picked_supplier_name'] = $pickedName;
}
$mergedPickTime = '';
foreach ($rows as $r) {
$t = $this->procuremenRowListSortTime($r, 'pick_time');
if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
$mergedPickTime = $t;
}
}
if ($mergedPickTime !== '') {
$merged['pick_time'] = $mergedPickTime;
}
$out[] = $merged;
}
usort($out, function ($a, $b) {
$ta = $this->procuremenRowListSortTime($a, 'pick_time');
$tb = $this->procuremenRowListSortTime($b, 'pick_time');
if ($ta === $tb) {
$ida = (int)($a['purchase_order_id'] ?? 0);
$idb = (int)($b['purchase_order_id'] ?? 0);
if ($ida !== $idb) {
return $idb <=> $ida;
}
return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
}
if ($ta === '') {
return 1;
}
if ($tb === '') {
return -1;
}
return strcmp($tb, $ta);
});
return $out;
}
/**
* 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
*
* @return array{ccydh:string, pos:array, merge_rows:array}
*/
protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
{
$scydgyId = trim($scydgyId);
$empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
if ($scydgyId === '') {
return $empty;
}
try {
$anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
} catch (\Throwable $e) {
$anchor = null;
}
if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
return $empty;
}
$ccydh = trim((string)($anchor['CCYDH'] ?? ''));
if ($ccydh === '') {
return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
}
try {
$pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
} catch (\Throwable $e) {
$pos = [$anchor];
}
if (!is_array($pos) || $pos === []) {
$pos = [$anchor];
}
return [
'ccydh' => $ccydh,
'pos' => $pos,
'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
];
}
/**
* 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
*/
protected function purchaseOrderRowInConfirmStage(array $po): bool
{
if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
return false;
}
if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
return false;
}
if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
return true;
}
if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
$sid = (int)($po['scydgy_id'] ?? 0);
return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
}
return false;
}
/**
* 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
*
* @return array{ccydh:string, pos:array, merge_rows:array}
*/
protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
{
$scydgyId = trim($scydgyId);
$empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
if ($scydgyId === '') {
return $empty;
}
try {
$anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
} catch (\Throwable $e) {
$anchor = null;
}
if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
return $empty;
}
$ccydh = trim((string)($anchor['CCYDH'] ?? ''));
if ($ccydh === '') {
return [
'ccydh' => '',
'pos' => [$anchor],
'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
];
}
try {
$posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
$this->applyPurchaseOrderConfirmStageWhere($posQuery);
$pos = $posQuery->order('scydgy_id', 'asc')->select();
} catch (\Throwable $e) {
$pos = [$anchor];
}
if (!is_array($pos) || $pos === []) {
$pos = [$anchor];
}
$pos = array_values(array_filter($pos, function ($po) {
return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
}));
if ($pos === []) {
$pos = [$anchor];
}
return [
'ccydh' => $ccydh,
'pos' => $pos,
'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
];
}
/**
* @param array> $purchaseOrders
* @return array>
*/
protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
{
$pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
$byId = [];
foreach ($pool as $r) {
if (!is_array($r)) {
continue;
}
$sid = (int)($r['ID'] ?? $r['id'] ?? 0);
if ($this->isValidScydgyRowId($sid)) {
$byId[$sid] = $r;
}
}
$out = [];
foreach ($purchaseOrders as $po) {
if (!is_array($po)) {
continue;
}
$sid = (int)($po['scydgy_id'] ?? 0);
if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
$out[] = $byId[$sid];
}
}
return $out;
}
/**
* 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
*
* @return array>
*/
protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
{
$scydgyId = trim($scydgyId);
if ($scydgyId === '') {
return [];
}
try {
$anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
} catch (\Throwable $e) {
$anchor = null;
}
if (!is_array($anchor)) {
return [];
}
if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
return [];
}
$ccydh = trim((string)($anchor['CCYDH'] ?? ''));
$pickTime = trim((string)($anchor['pick_time'] ?? ''));
$isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
try {
$q = Db::table('purchase_order');
if ($ccydh !== '') {
$q->where('CCYDH', $ccydh);
} else {
$q->where('scydgy_id', $scydgyId);
}
if ($isValidPick) {
$q->where('pick_time', $pickTime);
}
$pos = $q->order('scydgy_id', 'asc')->select();
} catch (\Throwable $e) {
$pos = [$anchor];
}
if (!is_array($pos) || $pos === []) {
$pos = [$anchor];
}
$pos = array_values(array_filter($pos, function ($po) {
if (!is_array($po)) {
return false;
}
$mr = $po['mod_rq'] ?? null;
if ($mr === null || $mr === '') {
return true;
}
$mrs = trim((string)$mr);
return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
}));
if ($pos === []) {
$pos = [$anchor];
}
$rows = $this->scydgyRowsForPurchaseOrders($pos);
if ($rows === []) {
$rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
}
return $rows;
}
/**
* 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
*
* @param array> $mergeRows
* @return array>
*/
protected function buildAuditProcessDisplayRows(array $mergeRows): array
{
$list = array_values($mergeRows);
$n = count($list);
$orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
$nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
$mergeSame = $n > 1 && $orderKey0 !== '';
if ($mergeSame) {
foreach ($list as $rr) {
if (!is_array($rr)) {
$mergeSame = false;
break;
}
if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
|| trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
$mergeSame = false;
break;
}
}
}
$out = [];
foreach ($list as $idx => $r) {
if (!is_array($r)) {
continue;
}
$qty = $this->resolveProcuremenThisQuantity($r);
$price = $this->resolveProcuremenCeilingPrice($r);
$sid = $this->extractScydgyRowId($r);
$out[] = [
'seq' => $idx + 1,
'scydgy_id' => $sid,
'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
'CDW' => trim((string)($r['CDW'] ?? '')),
'czlyq' => trim((string)($r['czlyq'] ?? '')),
'NGZL' => $r['NGZL'] ?? '',
'This_quantity' => $qty,
'ceilingPrice' => $price,
'CDF' => trim((string)($r['CDF'] ?? '')),
'MBZ' => trim((string)($r['MBZ'] ?? '')),
'show_order_cells' => !$mergeSame || $idx === 0,
'order_rowspan' => $mergeSame ? $n : 1,
];
}
return $out;
}
/**
* 解析金额/数量(去千分位等非数字字符)
*/
protected function parseProcuremenMoneyNumber($value): ?float
{
if ($value === null || $value === '') {
return null;
}
if (is_numeric($value)) {
return (float)$value;
}
$v = preg_replace('/[^\d\.\-]/', '', (string)$value);
return ($v !== '' && is_numeric($v)) ? (float)$v : null;
}
protected function formatProcuremenMoneyDisplay(?float $amount): string
{
if ($amount === null) {
return '';
}
// 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
$s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
return $s === '' ? '0' : $s;
}
/**
* 列表/详情展示:工作量为 0 时显示空
*/
protected function formatProcuremenWorkloadDisplay($value): string
{
if ($value === null || $value === '') {
return '';
}
$s = trim((string)$value);
if ($s === '') {
return '';
}
if (is_numeric($s) && (float)$s == 0) {
return '';
}
return $s;
}
/**
* 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
*/
protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
{
foreach ($details as $d) {
if (!is_array($d)) {
continue;
}
if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
$cn = trim((string)($d['company_name'] ?? ''));
if ($cn !== '') {
return $cn;
}
}
}
return trim((string)($main['pick_company_name'] ?? ''));
}
/**
* 详情报价小计:单价 × 本工序本次数量
*/
protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
{
$unit = $this->parseProcuremenMoneyNumber($amountRaw);
if ($unit === null) {
return null;
}
$qty = $this->parseProcuremenMoneyNumber($qtyStr);
if ($qty === null || $qty <= 0) {
return null;
}
return $unit * $qty;
}
/**
* 详情页:工序小计 + 供应商分组报价与总计
*
* @param array> $mergeRows
* @param array> $details 含有效与历史明细
* @return array{
* process_rows: array,
* supplier_groups: array,
* order_total_text: string,
* order_total_has: bool,
* selected_company: string
* }
*/
protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
{
$processRows = $this->buildAuditProcessDisplayRows($mergeRows);
$ccydh = trim((string)($main['CCYDH'] ?? ''));
$quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
|| ((int)($main['manual_pick'] ?? 0) === 1);
$qtyBySid = [];
$gymcBySid = [];
$orderedSids = [];
foreach ($mergeRows as $mr) {
if (!is_array($mr)) {
continue;
}
$sid = $this->extractScydgyRowId($mr);
if ($this->isValidScydgyRowId($sid)) {
$orderedSids[] = $sid;
}
$qty = trim((string)($mr['This_quantity'] ?? ''));
if ($qty === '') {
$qty = trim((string)($mr['NGZL'] ?? ''));
}
$qtyBySid[$sid] = $qty;
$gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
}
$selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
$detailByCompanySid = [];
foreach ($details as $d) {
if (!is_array($d)) {
continue;
}
$cn = trim((string)($d['company_name'] ?? ''));
$sid = (int)($d['scydgy_id'] ?? 0);
if ($cn === '' || $sid === 0) {
continue;
}
if (!isset($detailByCompanySid[$cn])) {
$detailByCompanySid[$cn] = [];
}
$detailByCompanySid[$cn][$sid] = $d;
}
$supplierGroups = [];
foreach ($detailByCompanySid as $cn => $bySid) {
$lines = [];
$groupTotal = 0.0;
$groupHas = false;
$groupVoid = true;
$usedSids = [];
$appendLine = function (int $sid, array $d) use (
&$lines,
&$groupTotal,
&$groupHas,
&$groupVoid,
$qtyBySid,
$gymcBySid,
$quoteVisible
) {
$isVoid = $this->isPurchaseOrderDetailVoid($d);
if (!$isVoid) {
$groupVoid = false;
}
$qtyStr = $qtyBySid[$sid] ?? '';
$amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
$am = trim((string)($d['amount'] ?? ''));
$amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
$deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
$deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
$sub = null;
if (!$isVoid && $amountNum !== null) {
$sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
}
$ct = $this->resolveDetailSupplierOperTime($d);
$leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
$leadFilled = ($leadDays !== null);
$leadText = $this->formatProcuremenLeadDaysText($leadDays);
$line = [
'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
'amount' => $am,
'unit_price_text' => $amountFilled
? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
: '未填写',
'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
'delivery_ymd' => $deliveryYmd,
'amount_filled' => $amountFilled,
'delivery_filled' => $deliveryFilled,
'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
'lead_days' => $leadFilled ? $leadDays : '',
'lead_days_filled'=> $leadFilled,
'lead_days_show' => $leadText,
'lead_days_text' => $leadText,
'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
'is_void' => $isVoid,
'oper_time_text' => $ct,
];
if (!$quoteVisible && !$isVoid) {
$this->maskSupplierQuoteLineBeforeDeadline($line);
} elseif ($sub !== null) {
$groupTotal += $sub;
$groupHas = true;
}
$lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
};
foreach ($orderedSids as $sid) {
if (!isset($bySid[$sid])) {
continue;
}
$usedSids[$sid] = true;
$appendLine($sid, $bySid[$sid]);
}
foreach ($bySid as $sid => $d) {
if (isset($usedSids[$sid])) {
continue;
}
$appendLine((int)$sid, $d);
}
$firstDetail = null;
foreach ($bySid as $d) {
if (is_array($d)) {
$firstDetail = $d;
break;
}
}
$ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
$username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
if ($username === '' && $ph !== '') {
$username = $this->resolveCustomerContactName($ph, $cn);
}
$remark = '';
foreach ($bySid as $d) {
if (!is_array($d)) {
continue;
}
$rm = '';
foreach (['remark', 'Remark', 'REMARK'] as $rk) {
if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
$rm = trim((string)$d[$rk]);
break;
}
}
if ($rm !== '') {
$remark = $rm;
break;
}
}
$lineCount = count($lines);
$hasRemark = $lineCount > 0;
$supplierGroup = [
'company_name' => $cn,
'username' => $username,
'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
'phone' => $ph,
'remark' => $remark,
'has_remark' => $hasRemark,
'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
'is_void' => $groupVoid,
'lines' => $lines,
'line_count' => $lineCount,
'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
'has_total' => $lineCount > 0,
];
$this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
$supplierGroups[] = $supplierGroup;
}
usort($supplierGroups, function ($a, $b) {
if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
return ($a['is_void'] ?? false) ? 1 : -1;
}
if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
return ($a['is_selected'] ?? false) ? -1 : 1;
}
return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
});
$supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
return [
'process_rows' => $processRows,
'supplier_groups' => $supplierGroups,
'order_total_text' => '',
'order_total_has' => false,
'selected_company' => $selectedCompany,
];
}
/**
* 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
*/
protected function buildProcessLinesPlain(array $mergeRows): string
{
$lines = [];
$i = 1;
foreach ($mergeRows as $r) {
if (!is_array($r)) {
continue;
}
$gymc = trim((string)($r['CGYMC'] ?? ''));
$dw = trim((string)($r['CDW'] ?? ''));
$gzl = trim((string)($r['NGZL'] ?? ''));
$qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
$parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
if ($dw !== '') {
$parts[] = '单位:' . $dw;
}
if ($gzl !== '') {
$parts[] = '工作量:' . $gzl;
}
if ($qty !== '') {
$parts[] = '本次数量:' . $qty;
}
$lines[] = implode(' ', $parts);
$i++;
}
return implode("\n", $lines);
}
/**
* 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
*
* @return array
*/
protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
{
if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
$bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
}
$mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
$pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
$ccydh = trim((string)($bundle['ccydh'] ?? ''));
$cyjmc = '';
foreach ($mergeRows as $mr) {
if (!is_array($mr)) {
continue;
}
if ($ccydh === '') {
$ccydh = trim((string)($mr['CCYDH'] ?? ''));
}
if ($cyjmc === '') {
$cyjmc = trim((string)($mr['CYJMC'] ?? ''));
}
}
if ($pos !== []) {
$firstPo = $pos[0];
if (is_array($firstPo)) {
if ($ccydh === '') {
$ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
}
if ($cyjmc === '') {
$cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
}
}
}
if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
$any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
if (is_array($any)) {
if ($ccydh === '') {
$ccydh = trim((string)($any['CCYDH'] ?? ''));
}
if ($cyjmc === '') {
$cyjmc = trim((string)($any['CYJMC'] ?? ''));
}
}
}
$processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
$processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
$cgymc = '';
if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
$cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
}
return [
'ccydh' => $ccydh,
'cyjmc' => $cyjmc,
'cgymc' => $cgymc,
'process_lines' => $processLines,
'process_lines_html' => '',
];
}
/**
* 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
*/
protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
{
$lines = [];
if ($ccydh !== '') {
$lines[] = '订单号:' . $ccydh;
}
if ($cyjmc !== '') {
$lines[] = '印件名称:' . $cyjmc;
}
if ($processPlain !== '') {
$lines[] = $processPlain;
}
return implode("\n", $lines);
}
/**
* 各工序手机端链接(纯文本,供短信模版 {platform_links})
*
* @param array $detailLinks
*/
protected function buildPlatformLinksPlain(array $detailLinks): string
{
$lines = [];
$i = 1;
foreach ($detailLinks as $lk) {
if (!is_array($lk)) {
continue;
}
$url = trim((string)($lk['url'] ?? ''));
if ($url === '') {
continue;
}
$label = trim((string)($lk['cgymc'] ?? ''));
if ($label === '') {
$label = '工序' . $i;
}
$lines[] = $label . ':' . $url;
$i++;
}
return implode("\n", $lines);
}
/**
* 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
*
* @param array $detailLinks
*/
protected function buildPlatformLinksHtml(array $detailLinks): string
{
$parts = [];
$i = 1;
foreach ($detailLinks as $lk) {
if (!is_array($lk)) {
continue;
}
$url = trim((string)($lk['url'] ?? ''));
if ($url === '') {
continue;
}
$label = trim((string)($lk['cgymc'] ?? ''));
if ($label === '') {
$label = '工序' . $i;
}
$urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
$parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
. ' — 点击查看';
$i++;
}
return implode("
\n", $parts);
}
/**
* 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
*
* @return array
*/
protected function loadMailerConfig(): array
{
try {
$cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
} catch (\Throwable $e) {
$cfg = [];
}
return is_array($cfg) ? $cfg : [];
}
protected function loadNotifyTemplateRow(string $scene): ?array
{
try {
$row = Db::table('purchase_sms_template')
->where('scene', $scene)
->where(function ($q) {
$q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
})
->order('id', 'asc')
->find();
} catch (\Throwable $e) {
return null;
}
if (!is_array($row) || $row === []) {
return null;
}
return [
'title' => trim((string)($row['title'] ?? '')),
'content' => trim((string)($row['content'] ?? '')),
];
}
/**
* 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
*/
protected function buildProcessLinesHtml(array $mergeRows): string
{
if (count($mergeRows) <= 1) {
$r = $mergeRows[0] ?? [];
if (!is_array($r)) {
return '';
}
$gymc = trim((string)($r['CGYMC'] ?? ''));
$dw = trim((string)($r['CDW'] ?? ''));
$gzl = trim((string)($r['NGZL'] ?? ''));
$qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
$html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '
';
if ($dw !== '') {
$html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '
';
}
if ($gzl !== '') {
$html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '
';
}
if ($qty !== '') {
$html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '
';
}
return $html;
}
$rows = '';
$i = 1;
foreach ($mergeRows as $r) {
if (!is_array($r)) {
continue;
}
$gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
$dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
$gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
$qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
$rows .= '| ' . $i . ' | '
. '' . ($gymc !== '' ? $gymc : '—') . ' | '
. '' . ($dw !== '' ? $dw : '—') . ' | '
. '' . ($gzl !== '' ? $gzl : '—') . ' | '
. '' . ($qty !== '' ? $qty : '—') . ' |
';
$i++;
}
if ($rows === '') {
return '';
}
return ''
. ''
. '| 序号 | '
. '工序名称 | '
. '单位 | '
. '工作量 | '
. '本次数量 | '
. '
' . $rows . '
';
}
protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
{
$sysRq = trim($sysRq);
if ($sysRq === '') {
if ($required) {
$this->error('请选择招标截止日期');
}
return '';
}
$ts = strtotime($sysRq);
if ($ts === false || $ts <= 0) {
$this->error('招标截止日期格式无效');
}
// 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
if (!$allowPast) {
$ymd = date('Y-m-d', $ts);
if ($ymd < date('Y-m-d')) {
$this->error('招标截止日期不能早于今天');
}
if ($ts <= time()) {
$this->error('招标截止时间不能早于当前时间');
}
}
return date('Y-m-d H:i:s', $ts);
}
/**
* 确保 purchase_order.czlyq(类型)存在
*/
protected function ensurePurchaseOrderCzlyqColumn(): void
{
static $done = false;
if ($done) {
return;
}
$done = true;
try {
$cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
if (empty($cols)) {
Db::execute(
"ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
);
}
} catch (\Throwable $e) {
// ignore
}
}
/**
* 确保 purchase_order.delivery_deadline 存在
*/
protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
{
static $done = false;
if ($done) {
return;
}
$done = true;
try {
$cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
if (empty($cols)) {
Db::execute(
"ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
);
}
} catch (\Throwable $e) {
// ignore
}
}
/**
* 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
*/
protected function ensurePurchaseOrderScoreRuleIdColumn(): void
{
static $done = false;
if ($done) {
return;
}
$done = true;
// 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
$adds = [
'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
];
$changed = false;
foreach ($adds as $col => $ddl) {
try {
$cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
if (!is_array($cols) || $cols === []) {
Db::execute("ALTER TABLE `purchase_order` {$ddl}");
$changed = true;
}
} catch (\Throwable $e) {
Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
}
}
if ($changed) {
$this->clearPurchaseOrderTableFieldsCache();
}
}
/**
* ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
*/
protected function clearPurchaseOrderTableFieldsCache(): void
{
try {
$db = (string)Config::get('database.database');
$key = $db . '.purchase_order';
$ref = new \ReflectionProperty(\think\db\Query::class, 'info');
$ref->setAccessible(true);
$info = $ref->getValue();
if (is_array($info) && isset($info[$key])) {
unset($info[$key]);
$ref->setValue(null, $info);
}
} catch (\Throwable $e) {
}
try {
$db = (string)Config::get('database.database');
$schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
if (is_file($schemaFile)) {
@unlink($schemaFile);
}
} catch (\Throwable $e) {
}
}
/**
* @return array
*/
protected function loadPurchaseOrderColumnSet(): array
{
static $set = null;
if (is_array($set)) {
return $set;
}
$set = [];
try {
$cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
} catch (\Throwable $e) {
return $set;
}
if (!is_array($cols)) {
return $set;
}
foreach ($cols as $c) {
if (!is_array($c)) {
continue;
}
$f = (string)($c['Field'] ?? $c['field'] ?? '');
if ($f !== '') {
$set[$f] = true;
}
}
return $set;
}
/**
* 解析交货截止日期(仅年月日)
*/
protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
{
$raw = trim($raw);
if ($raw === '') {
if ($required) {
$this->error('请选择交货截止日期');
}
return '';
}
if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
$ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
} else {
$ts = strtotime(str_replace('/', '-', $raw));
if ($ts === false || $ts <= 0) {
$this->error('交货截止日期格式无效');
}
$ymd = date('Y-m-d', $ts);
}
if ($ymd < date('Y-m-d')) {
$this->error('交货截止日期不能早于今天');
}
return $ymd;
}
protected function formatProcuremenDeliveryDeadlineForInput($value): string
{
$s = trim((string)$value);
if ($s === '' || stripos($s, '0000-00-00') === 0) {
return '';
}
if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
return $m[1];
}
$ts = strtotime(str_replace('/', '-', $s));
return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
}
/**
* @param array{pos?:array} $bundle
*/
protected function resolveBundleDeliveryDeadline(array $bundle): string
{
foreach ($bundle['pos'] ?? [] as $po) {
if (!is_array($po)) {
continue;
}
$d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
if ($d !== '') {
return $d;
}
}
return '';
}
protected function formatProcuremenSysRqForInput($sysRq): string
{
$sr = trim((string)$sysRq);
if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
return '';
}
$ts = strtotime($sr);
return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
}
protected function formatProcuremenSysRqForDisplay($sysRq): string
{
$sr = $this->formatProcuremenSysRqForInput($sysRq);
if ($sr === '') {
return '—';
}
$ts = strtotime($sr);
return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
}
/**
* 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
*
* @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
* @return array{ccydh?:string,pos:array,merge_rows:array}
*/
protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
{
return $bundle;
}
/**
* 写入/更新 purchase_order(单道工序行)
*
* @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
*/
protected function upsertPurchaseOrderFromRow(
array $row,
string $sysRqDb,
$wflowStatus = null,
?string $pickTime = null,
?array $exists = null,
?string $deliveryDeadline = null,
$scoreRuleId = null
): void {
$ids = $this->extractScydgyRowId($row);
if (!$this->isValidScydgyRowId($ids)) {
throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
}
if ($exists === null) {
$exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
}
$this->ensurePurchaseOrderDeliveryDeadlineColumn();
$this->ensurePurchaseOrderScoreRuleIdColumn();
$this->ensurePurchaseOrderCzlyqColumn();
$data = [
'scydgy_id' => $ids,
'CCYDH' => $row['CCYDH'] ?? null,
'CYJMC' => $row['CYJMC'] ?? null,
'CCLBMMC' => $row['CCLBMMC'] ?? null,
'CDXMC' => $row['CDXMC'] ?? null,
'CGYBH' => $row['CGYBH'] ?? null,
'CGYMC' => $row['CGYMC'] ?? null,
'CDW' => $row['CDW'] ?? null,
'czlyq' => $row['czlyq'] ?? null,
'NGZL' => $row['NGZL'] ?? null,
'CDF' => $row['CDF'] ?? null,
'cGzzxMc' => $row['cGzzxMc'] ?? null,
'MBZ' => $row['MBZ'] ?? null,
'bwjg' => $row['bwjg'] ?? null,
'iStatus' => $row['iStatus'] ?? null,
'dStamp' => $row['dStamp'] ?? null,
'dputrecord' => $row['dputrecord'] ?? null,
'cywyxm' => $row['cywyxm'] ?? null,
'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
'status' => ProcuremenStatus::PO_IN_PROGRESS,
'sys_rq' => $sysRqDb,
];
// 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
$qtyUp = trim((string)($data['This_quantity'] ?? ''));
if ($qtyUp === '') {
$qtyFallback = $this->resolveProcuremenThisQuantity([
'This_quantity' => '',
'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
]);
if ($qtyFallback !== '') {
$data['This_quantity'] = $qtyFallback;
}
}
if ($deliveryDeadline !== null) {
$data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
}
// 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
$scoreRule = null;
if (is_array($scoreRuleId)) {
$scoreRule = $scoreRuleId;
$scoreRuleId = (int)($scoreRule['id'] ?? 0);
} else {
$scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
}
if ($scoreRuleId !== null && $scoreRuleId > 0) {
$poCols = $this->loadPurchaseOrderColumnSet();
if (!empty($poCols['score_rule_id'])) {
$data['score_rule_id'] = $scoreRuleId;
if (is_array($scoreRule)) {
if (!empty($poCols['score_rule_name'])) {
$data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
}
if (!empty($poCols['score_quality_weight'])) {
$data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
}
if (!empty($poCols['score_price_weight'])) {
$data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
}
if (!empty($poCols['score_lead_weight'])) {
$data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
}
}
}
}
if ($wflowStatus !== null && $wflowStatus !== '') {
$data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
}
if ($pickTime !== null && $pickTime !== '') {
$data['pick_time'] = $pickTime;
$data['pick_company_name'] = '';
}
if ($exists) {
$upd = $data;
unset($upd['scydgy_id']);
Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
} else {
$data['createtime'] = date('Y-m-d H:i:s');
Db::table('purchase_order')->insert($data);
}
}
/**
* 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
*
* @return array
*/
protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
{
$toDb = function ($value) {
if ($value === null) {
return null;
}
if (is_scalar($value)) {
return $value;
}
return json_encode($value, JSON_UNESCAPED_UNICODE);
};
$toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
$companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
$phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
$username = isset($c['username']) ? trim((string)$c['username']) : '';
if ($username === '') {
$username = $this->resolveCustomerContactName($phone, $companyName);
}
if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
}
if ($requirePhone && $phone === '') {
throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
}
$detailLinks = [];
foreach ($mergeRows as $row) {
if (!is_array($row)) {
continue;
}
$sid = $this->extractScydgyRowId($row);
$detailId = 0;
if ($skipExisting) {
try {
$existsQuery = Db::table('purchase_order_detail')
->where('scydgy_id', $sid)
->where('company_name', $companyName);
$this->applyActivePurchaseOrderDetailWhere($existsQuery);
$exists = $existsQuery->find();
} catch (\Throwable $e) {
$exists = null;
}
if (is_array($exists)) {
$detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
}
}
if ($detailId <= 0) {
$one = [
'scydgy_id' => $toDb($sid),
'CCYDH' => $toDb($row['CCYDH'] ?? null),
'CYJMC' => $toDb($row['CYJMC'] ?? null),
'company_name' => isset($c['name']) ? (string)$c['name'] : null,
'username' => $username !== '' ? $username : null,
'email' => isset($c['email']) ? (string)$c['email'] : null,
'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
'createtime' => date('Y-m-d H:i:s'),
'status' => ProcuremenStatus::POD_UNPICKED,
'status_name' => '未提交',
];
Db::table('purchase_order_detail')->insert($one);
$detailId = (int)Db::getLastInsID();
}
$mprocUrl = '';
if ($buildMobileLinks && $detailId > 0) {
$mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
}
$detailLinks[] = [
'detail_id' => $detailId,
'cgymc' => trim((string)($row['CGYMC'] ?? '')),
'url' => $mprocUrl,
];
}
$this->invalidatePickHiddenScydgyCache();
return $detailLinks;
}
/**
* @param array $detailLinks
* @return array
*/
protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
{
$toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
$companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
$phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
$platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
$platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
$platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
$isMerge = !empty($ctx['is_merge']);
$contactName = trim((string)($c['username'] ?? ''));
if ($contactName === '') {
$contactName = $this->resolveCustomerContactName($phone, $companyName);
}
$notifyVars = [
'company_name' => $companyName,
'contact_name' => $contactName,
'phone' => $phone,
'email' => $toEmail,
'ccydh' => (string)($ctx['ccydh'] ?? ''),
'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
'deadline' => (string)($ctx['deadline'] ?? ''),
'process_lines' => (string)($ctx['process_plain'] ?? ''),
'process_lines_html' => (string)($ctx['process_html'] ?? ''),
'platform_url' => $platformUrl,
'platform_links' => $platformLinksPlain,
'platform_links_html' => $platformLinksHtml,
];
$smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
$emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
$mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
$mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
return [
'company_name' => $companyName,
'phone' => $phone,
'email' => $toEmail,
'sms_content' => $smsContent,
'mail_plain' => $mailPlain,
'mail_body' => $mailBody,
'notify_vars' => $notifyVars,
'detail_links' => $detailLinks,
];
}
/**
* @param array $chosen
* @param array> $mergeRows
* @param array{ccydh:string, pos:array} $bundle
*/
protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
{
if (!$sendSms && !$sendEmail) {
return;
}
$companyName = trim((string)($chosen['name'] ?? ''));
$phone = trim((string)($chosen['phone'] ?? ''));
$toEmail = trim((string)($chosen['email'] ?? ''));
if ($companyName === '') {
throw new \Exception('供应商名称无效');
}
if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
}
if ($sendSms && $phone === '') {
throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
}
$sids = [];
foreach ($mergeRows as $mr) {
if (!is_array($mr)) {
continue;
}
$sid = $this->extractScydgyRowId($mr);
if ($this->isValidScydgyRowId($sid)) {
$sids[$sid] = true;
}
}
if ($sids === []) {
throw new \Exception('未找到工序行,无法发送通知');
}
$sysRqNotify = '';
$pos = $bundle['pos'] ?? [];
if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
$sr = trim((string)($pos[0]['sys_rq'] ?? ''));
if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
$ts = strtotime($sr);
$sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
}
}
try {
$detailsQuery = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($sids))
->where('company_name', $companyName);
$this->applyActivePurchaseOrderDetailWhere($detailsQuery);
$details = $detailsQuery->order('id', 'asc')->select();
} catch (\Throwable $e) {
$details = [];
}
if (!is_array($details) || $details === []) {
$this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
try {
$detailsQuery = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($sids))
->where('company_name', $companyName);
$this->applyActivePurchaseOrderDetailWhere($detailsQuery);
$details = $detailsQuery->order('id', 'asc')->select();
} catch (\Throwable $e) {
$details = [];
}
}
if (!is_array($details) || $details === []) {
throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
}
$detailLinks = [];
foreach ($details as $d) {
if (!is_array($d)) {
continue;
}
$detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
if ($detailId <= 0) {
continue;
}
$sid = (int)($d['scydgy_id'] ?? 0);
$gymc = '';
foreach ($mergeRows as $mr) {
if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
$gymc = trim((string)($mr['CGYMC'] ?? ''));
break;
}
}
$detailLinks[] = [
'detail_id' => $detailId,
'cgymc' => $gymc,
'url' => $this->buildMprocMobileOrderUrl($detailId),
];
}
if ($detailLinks === []) {
throw new \Exception('未找到有效的手机端链接,无法发送通知');
}
$emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
$ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
$notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
$notifyBundle['email_log_scene'] = $emailLogScene;
$notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
$poIdLog = 0;
$pos = $bundle['pos'] ?? [];
if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
$poIdLog = (int)($pos[0]['id'] ?? 0);
}
$notifyBundle['email_log_purchase_order_id'] = $poIdLog;
if ($sendEmail) {
$mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
}
$mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
$mailConfig = $this->loadMailerConfig();
if (!$this->isProcuremenNotifyDryRun()) {
if (empty($mailConfig['host'])) {
throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
}
if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
}
}
$this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
}
if ($sendSms) {
$this->issueSendSupplierSms($notifyBundle);
}
}
/**
* @param array> $quoteGroups
* @return array>
*/
protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
{
$names = [];
if (is_string($companiesJson) && $companiesJson !== '') {
$decoded = json_decode($companiesJson, true);
if (is_array($decoded)) {
foreach ($decoded as $nm) {
$nm = trim((string)$nm);
if ($nm !== '') {
$names[] = $nm;
}
}
}
}
$names = array_values(array_unique($names));
if ($names === [] && $selectedCompany !== '') {
$names = [$selectedCompany];
}
if ($names === []) {
return $quoteGroups;
}
$targets = [];
foreach ($quoteGroups as $g) {
if (!is_array($g)) {
continue;
}
$cn = trim((string)($g['name'] ?? ''));
if ($cn !== '' && in_array($cn, $names, true)) {
$targets[] = $g;
}
}
return $targets;
}
/**
* @return array{pos:array, merge_rows:array, bundle:array}
*/
protected function loadAuditResendBundle(string $scydgyId): array
{
$bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
$pos = $bundle['pos'];
$mergeRows = $bundle['merge_rows'];
if ($pos === [] || $mergeRows === []) {
$this->error('该订单不在待确认供应商状态');
}
$sysRqDb = '';
if (isset($pos[0]) && is_array($pos[0])) {
$sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
}
foreach ($pos as $i => $poRow) {
if (is_array($pos[$i]) && $sysRqDb !== '') {
$pos[$i]['sys_rq'] = $sysRqDb;
}
}
$bundle['pos'] = $pos;
return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
}
/**
* @param array> $targets
*/
protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
{
if ($targets === []) {
$this->error('未找到可通知的供应商');
}
$notifyErrors = [];
try {
$this->notifyDryRunPreview = [];
foreach ($targets as $g) {
if (!is_array($g)) {
continue;
}
$cname = trim((string)($g['name'] ?? ''));
if ($cname === '') {
continue;
}
$chosen = [
'name' => $cname,
'company_name' => $cname,
'email' => trim((string)($g['email'] ?? '')),
'phone' => trim((string)($g['phone'] ?? '')),
'username' => trim((string)($g['username'] ?? '')),
];
try {
$this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
} catch (\Throwable $e) {
$notifyErrors[] = $cname . ':' . $e->getMessage();
}
}
} catch (\Throwable $e) {
$this->error('通知发送失败:' . $e->getMessage());
}
if ($notifyErrors !== []) {
$this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
}
if ($this->isProcuremenNotifyDryRun()) {
$this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
'notify_dry_run' => true,
'notify_preview' => $this->notifyDryRunPreview,
]);
}
$nameLabels = [];
foreach ($targets as $g) {
if (!is_array($g)) {
continue;
}
$n = trim((string)($g['name'] ?? ''));
if ($n !== '') {
$nameLabels[] = $n;
}
}
$logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
$logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
. ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
$seenLogSid = [];
foreach ($bundle['pos'] ?? [] as $poRow) {
if (!is_array($poRow)) {
continue;
}
$sid = (int)($poRow['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
continue;
}
$seenLogSid[$sid] = true;
$poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
$this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
}
if ($seenLogSid === []) {
foreach ($mergeRows as $mr) {
if (!is_array($mr)) {
continue;
}
$sid = $this->extractScydgyRowId($mr);
if ($this->isValidScydgyRowId($sid)) {
$this->addOrderLog($sid, $logAction, $logMsg, null);
break;
}
}
}
$this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
}
/**
* 协助下发 — 发送短信(一家供应商)
*
* @param array $bundle composeSupplierNotifyBundle 返回值
*/
protected function issueSendSupplierSms(array $bundle): void
{
$companyName = (string)($bundle['company_name'] ?? '');
$phone = (string)($bundle['phone'] ?? '');
$smsContent = (string)($bundle['sms_content'] ?? '');
$this->logIssueNotifyDebug('短信', [
'company' => $companyName,
'phone' => $phone,
'sms_content' => $smsContent,
]);
if ($this->isProcuremenNotifyDryRun()) {
$this->recordNotifyDryRunPreview([
'scene' => 'issue_sms',
'company_name' => $companyName,
'phone' => $phone,
'sms_content' => $smsContent,
]);
return;
}
$this->smsbao($phone, $smsContent);
}
/**
* 协助下发 — 发送邮件(一家供应商)
*
* @param array $bundle
* @param array $mailConfig
*/
protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
{
$companyName = (string)($bundle['company_name'] ?? '');
$toEmail = (string)($bundle['email'] ?? '');
$mailPlain = (string)($bundle['mail_plain'] ?? '');
$mailBody = (string)($bundle['mail_body'] ?? '');
$this->logIssueNotifyDebug('邮件', [
'company' => $companyName,
'email' => $toEmail,
'mail_subject' => $mailSubject,
'mail_body' => $mailPlain,
]);
if ($this->isProcuremenNotifyDryRun()) {
$this->recordNotifyDryRunPreview([
'scene' => 'issue_email',
'company_name' => $companyName,
'email' => $toEmail,
'mail_subject' => $mailSubject,
'mail_body' => $mailPlain,
'sms_content' => (string)($bundle['sms_content'] ?? ''),
'notify_vars' => $bundle['notify_vars'] ?? [],
'detail_links' => $bundle['detail_links'] ?? [],
]);
return;
}
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = $mailConfig['host'];
$mail->SMTPAuth = true;
$mail->Username = $mailConfig['addr'];
$mail->Password = $mailConfig['pass'];
$mail->SMTPSecure = $mailConfig['security'];
$mail->Port = $mailConfig['port'];
$mail->CharSet = $mailConfig['charset'];
$mail->setFrom($mailConfig['addr'], $mailConfig['name']);
$mail->addAddress($toEmail, $companyName);
$mail->isHTML(true);
$mail->Subject = $mailSubject;
$mail->Body = $mailBody;
$fromEmail = trim((string)($mailConfig['addr'] ?? ''));
$sendOk = true;
$failReason = '';
try {
$mail->send();
} catch (\Throwable $e) {
$sendOk = false;
$failReason = $e->getMessage();
$this->persistEmailSendLog([
'from_email' => $fromEmail,
'to_email' => $toEmail,
'send_time' => date('Y-m-d H:i:s'),
'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
'company_name' => $companyName,
'mail_subject' => $mailSubject,
'status' => 0,
'fail_reason' => $failReason,
'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
]);
throw $e;
}
$this->persistEmailSendLog([
'from_email' => $fromEmail,
'to_email' => $toEmail,
'send_time' => date('Y-m-d H:i:s'),
'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
'company_name' => $companyName,
'mail_subject' => $mailSubject,
'status' => 1,
'fail_reason' => '',
'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
]);
}
/**
* 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
*
* @param array> $mergeRows
* @return array
*/
protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
{
$head = $mergeRows[0] ?? [];
$isMerge = count($mergeRows) > 1;
return [
'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
'is_merge' => $isMerge,
'process_plain' => $this->buildProcessLinesPlain($mergeRows),
'process_html' => $this->buildProcessLinesHtml($mergeRows),
'deadline' => $sysRqNotify,
];
}
/**
* 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
*
* @param array $data
*/
protected function logIssueNotifyDebug(string $type, array $data): void
{
if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
return;
}
Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
}
protected function ensurePurchaseEmailSendLogTableOnce(): void
{
try {
Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
return;
} catch (\Throwable $e) {
}
$sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
if (is_file($sqlFile)) {
$sql = file_get_contents($sqlFile);
if (is_string($sql) && $sql !== '') {
foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
$stmt = trim($stmt);
if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
continue;
}
try {
Db::execute($stmt);
} catch (\Throwable $ignore) {
}
}
}
}
Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
}
/**
* @param array $row
*/
protected function persistEmailSendLog(array $row): void
{
try {
$this->ensurePurchaseEmailSendLogTableOnce();
} catch (\Throwable $e) {
return;
}
list($adminId, $adminName) = $this->GetUseName();
$cut = function ($s, $max) {
$s = (string)$s;
if (function_exists('mb_substr')) {
return mb_substr($s, 0, $max, 'UTF-8');
}
return strlen($s) <= $max ? $s : substr($s, 0, $max);
};
$data = [
'from_email' => $cut($row['from_email'] ?? '', 128),
'to_email' => $cut($row['to_email'] ?? '', 128),
'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
'ccydh' => $cut($row['ccydh'] ?? '', 64),
'company_name' => $cut($row['company_name'] ?? '', 128),
'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
'status' => !empty($row['status']) ? 1 : 0,
'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
'admin_id' => (int)$adminId,
'admin_name' => $cut($adminName, 64),
'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
'createtime' => date('Y-m-d H:i:s'),
];
try {
Db::table('purchase_email_send_log')->insert($data);
} catch (\Throwable $e) {
Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
}
}
protected function formatEmailLogSceneText(string $scene): string
{
$map = [
'pick_issue' => '初选下发',
'audit_resend' => '确认页重发',
'rfq_salesman' => '询价通知业务员',
'rfq_supplier' => '供应商询价通知',
];
return $map[$scene] ?? $scene;
}
/**
* 邮件发送日志列表
*/
public function emailLog()
{
$this->relationSearch = false;
$this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
$this->request->filter(['strip_tags', 'trim']);
$bakModel = $this->model;
$this->model = new \app\admin\model\Purchaseemailsendlog;
if ($this->request->isAjax()) {
$this->ensurePurchaseEmailSendLogTableOnce();
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
$orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
$list = $this->model
->where($where)
->order($sortField, $orderDir)
->paginate($limit);
$rows = [];
foreach ($list->items() as $item) {
$row = is_array($item) ? $item : $item->toArray();
$scene = trim((string)($row['scene'] ?? ''));
$row['scene_text'] = $this->formatEmailLogSceneText($scene);
$row['status_text'] = !empty($row['status']) ? '成功' : '失败';
$row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
$row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
$rows[] = $row;
}
$this->model = $bakModel;
return json(['total' => $list->total(), 'rows' => $rows]);
}
$this->model = $bakModel;
return $this->view->fetch('procuremen/emaillog');
}
/**
* 协助下发弹窗(选多家供应商并通知)
*/
public function pickReview()
{
if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
$this->error(__('You have no permission'));
}
if ($this->request->isPost()) {
$this->error('请使用弹窗内「确认下发」提交');
}
$this->view->assign('pickMode', 1);
$this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
}
/**
* 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
*/
protected function ensurePurchaseOrderNotifySalesmanColumn(): void
{
static $done = false;
if ($done) {
return;
}
$done = true;
try {
$cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
if (empty($cols)) {
Db::execute(
"ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
);
} else {
$type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
Db::execute(
"ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
);
}
}
} catch (\Throwable $e) {
// ignore
}
}
/**
* 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
*/
protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
{
static $done = false;
if ($done) {
return;
}
$done = true;
try {
$cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
if (empty($cols)) {
Db::execute(
"ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
);
}
} catch (\Throwable $e) {
// ignore
}
try {
$cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
if (empty($cols2)) {
Db::execute(
"ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
);
}
} catch (\Throwable $e) {
// ignore
}
}
/**
* 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
*/
protected function ensureRfqSupplierEmailTemplate(): void
{
static $done = false;
if ($done) {
return;
}
$done = true;
$content = "您好,{company_name}:\n\n"
. "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
. "需求编号:{ccydh}\n"
. "印件名称:{cyjmc}\n"
. "{process_lines}\n\n"
. "请在 {deadline} 前完成回复。\n\n"
. "平台链接:{platform_url}\n";
try {
$row = Db::table('purchase_sms_template')
->where('scene', 'rfq_supplier_email')
->find();
} catch (\Throwable $e) {
return;
}
$now = date('Y-m-d H:i:s');
if (is_array($row) && $row !== []) {
return;
}
try {
$data = [
'scene' => 'rfq_supplier_email',
'title' => '供应商询价通知',
'content' => $content,
'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
'status' => 1,
];
try {
$cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
} catch (\Throwable $e) {
$cols = [];
}
$colNames = [];
foreach ($cols as $c) {
if (!is_array($c)) {
continue;
}
$n = (string)($c['Field'] ?? $c['field'] ?? '');
if ($n !== '') {
$colNames[$n] = true;
}
}
if (isset($colNames['updatetime'])) {
$data['updatetime'] = $now;
}
if (isset($colNames['createtime'])) {
$data['createtime'] = $now;
}
Db::table('purchase_sms_template')->insert($data);
} catch (\Throwable $e) {
// ignore
}
}
/**
* 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
*/
protected function ensureRfqSalesmanEmailTemplate(): void
{
static $done = false;
if ($done) {
return;
}
$done = true;
$content = "您好,{contact_name}:\n\n"
. "有新的协助采购询价需求,请知悉。\n"
. "印件名称:{cyjmc}\n"
. "工序名称:{cgymc}\n"
. "本次数量:{this_quantity}\n"
. "供应商报价:\n{supplier_quotes}\n"
. "需求发起人:{cywyxm}\n";
try {
$row = Db::table('purchase_sms_template')
->where('scene', 'rfq_salesman_email')
->find();
} catch (\Throwable $e) {
return;
}
$now = date('Y-m-d H:i:s');
if (is_array($row) && $row !== []) {
$old = (string)($row['content'] ?? '');
// 仍用旧的「供应商:{supplier_name}」或没有报价占位符时,补上单价表格
$needMigrate = (strpos($old, '{supplier_quotes}') === false)
|| (strpos($old, '供应商:{supplier_name}') !== false);
if ($needMigrate) {
$data = ['content' => $content];
if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
$data['title'] = '业务员询价通知';
}
try {
$cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
if (!empty($cols)) {
$data['updatetime'] = $now;
}
} catch (\Throwable $e) {
}
try {
Db::table('purchase_sms_template')
->where('id', (int)($row['id'] ?? 0))
->update($data);
} catch (\Throwable $e) {
}
}
return;
}
try {
$data = [
'scene' => 'rfq_salesman_email',
'title' => '业务员询价通知',
'content' => $content,
'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
'status' => 1,
];
try {
$cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
} catch (\Throwable $e) {
$cols = [];
}
$colNames = [];
foreach ($cols as $c) {
if (!is_array($c)) {
continue;
}
$n = (string)($c['Field'] ?? $c['field'] ?? '');
if ($n !== '') {
$colNames[$n] = true;
}
}
if (isset($colNames['updatetime'])) {
$data['updatetime'] = $now;
}
if (isset($colNames['createtime'])) {
$data['createtime'] = $now;
}
Db::table('purchase_sms_template')->insert($data);
} catch (\Throwable $e) {
// ignore
}
}
/**
* 通知业务员邮件:供应商报价明细行(仅名称+单价)
*
* @return array
*/
protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
{
$list = [];
$seen = [];
try {
$rows = Db::table('purchase_order_detail')
->where('scydgy_id', $sid)
->field('company_name,amount')
->order('id', 'asc')
->select();
if (is_array($rows)) {
foreach ($rows as $r) {
if (!is_array($r)) {
continue;
}
$cn = trim((string)($r['company_name'] ?? ''));
if ($cn === '' || isset($seen[$cn])) {
continue;
}
$seen[$cn] = true;
$amount = trim((string)($r['amount'] ?? ''));
$list[] = [
'name' => $cn,
'amount' => $amount !== '' ? $amount : '未报价',
];
}
}
} catch (\Throwable $e) {
}
if ($list === [] && $supplierRaw !== '') {
foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
if ($cn === '' || isset($seen[$cn])) {
continue;
}
$seen[$cn] = true;
$list[] = [
'name' => $cn,
'amount' => '未报价',
];
}
}
return $list;
}
/**
* 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
*/
protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
{
$rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
if ($rows === []) {
return '暂无报价
';
}
$html = ''
. ''
. '| 序号 | '
. '供应商名称 | '
. '单价 | '
. '
';
foreach ($rows as $i => $row) {
$html .= ''
. '| ' . ($i + 1) . ' | '
. '' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . ' | '
. '' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . ' | '
. '
';
}
$html .= '
';
return $html;
}
/**
* 询价多选字段:数组或字符串统一为顿号拼接
*
* @param mixed $raw
*/
protected function joinRfqMultiSelectValues($raw): string
{
$parts = [];
if (is_array($raw)) {
foreach ($raw as $item) {
if (is_array($item)) {
continue;
}
$v = trim((string)$item);
if ($v !== '') {
$parts[] = $v;
}
}
} else {
$s = trim((string)$raw);
if ($s !== '') {
foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
$v = trim((string)$piece);
if ($v !== '') {
$parts[] = $v;
}
}
}
}
$parts = array_values(array_unique($parts));
return implode('、', $parts);
}
/**
* 新增询价:可选供应商名称(仅落库记录,不发通知)
*
* @return string[]
*/
protected function loadRfqSupplierNameOptions(): array
{
$out = [];
try {
$rows = Db::table('customer')
->where(function ($q) {
$q->where('status', 1)
->whereOr('status', '1')
->whereOr('status', '')
->whereNull('status');
})
->order('id', 'desc')
->column('company_name');
} catch (\Throwable $e) {
return [];
}
if (!is_array($rows)) {
return [];
}
foreach ($rows as $name) {
$name = trim((string)$name);
if ($name === '' || isset($out[$name])) {
continue;
}
$out[$name] = $name;
}
return array_values($out);
}
/**
* 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
*/
protected function rfqNotifySalesmanAuthGroupId(): int
{
$id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
if ($id > 0) {
return $id;
}
try {
$found = Db::name('auth_group')
->where('name', '业务员')
->where('status', 'normal')
->order('id', 'asc')
->value('id');
$id = (int)$found;
} catch (\Throwable $e) {
$id = 0;
}
return $id > 0 ? $id : 12;
}
/**
* 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
*
* @return string[]
*/
protected function loadRfqSalesmanNameOptions(): array
{
$out = [];
foreach ($this->loadRfqSalesmanContactOptions() as $row) {
$name = trim((string)($row['name'] ?? ''));
if ($name !== '') {
$out[] = $name;
}
}
return $out;
}
/**
* 业务员角色组下管理员:姓名、邮箱、手机
*
* @return array
*/
protected function loadRfqSalesmanContactOptions(): array
{
$out = [];
$seen = [];
$groupId = $this->rfqNotifySalesmanAuthGroupId();
if ($groupId <= 0) {
return [];
}
try {
$adminIds = Db::name('auth_group_access')
->where('group_id', $groupId)
->column('uid');
} catch (\Throwable $e) {
return [];
}
$adminIds = is_array($adminIds)
? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
: [];
if ($adminIds === []) {
return [];
}
try {
$rows = Db::name('admin')
->where('status', 'normal')
->where('id', 'in', $adminIds)
->order('id', 'asc')
->field('id,nickname,username,email,mobile')
->select();
} catch (\Throwable $e) {
return [];
}
if (!is_array($rows)) {
return [];
}
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$name = trim((string)($row['nickname'] ?? ''));
if ($name === '') {
$name = trim((string)($row['username'] ?? ''));
}
if ($name === '' || isset($seen[$name])) {
continue;
}
$seen[$name] = true;
$out[] = [
'name' => $name,
'email' => trim((string)($row['email'] ?? '')),
'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
];
}
return $out;
}
/**
* 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
*
* @return string[]
*/
protected function loadRfqDeptNameOptions(): array
{
$out = [];
// ERP 承揽部门(主来源)
try {
$vals = Db::table('mcyd')
->where('CCLBMMC', '<>', '')
->whereNotNull('CCLBMMC')
->distinct(true)
->limit(300)
->column('CCLBMMC');
} catch (\Throwable $e) {
$vals = [];
}
if (is_array($vals)) {
foreach ($vals as $v) {
$v = trim((string)$v);
if ($v === '' || isset($out[$v])) {
continue;
}
$out[$v] = $v;
}
}
// 手工询价历史部门补全
try {
$poVals = Db::table('purchase_order')
->where('CCLBMMC', '<>', '')
->whereNotNull('CCLBMMC')
->distinct(true)
->limit(200)
->column('CCLBMMC');
} catch (\Throwable $e) {
$poVals = [];
}
if (is_array($poVals)) {
foreach ($poVals as $v) {
$v = trim((string)$v);
if ($v === '' || isset($out[$v])) {
continue;
}
$out[$v] = $v;
}
}
foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
if (!isset($out[$preset])) {
$out[$preset] = $preset;
}
}
$list = array_values($out);
// 常用部门靠前
usort($list, static function ($a, $b) {
$weight = [
'营销中心' => 1,
'业务部' => 2,
'市场部' => 3,
'外贸部' => 4,
'新华技术业务部' => 5,
];
$wa = $weight[$a] ?? 100;
$wb = $weight[$b] ?? 100;
if ($wa !== $wb) {
return $wa <=> $wb;
}
return strcmp((string)$a, (string)$b);
});
return $list;
}
/**
* 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post('row/a');
if (!is_array($params)) {
$this->error(__('Parameter %s can not be empty', ''));
}
[, $adminName] = $this->GetUseName();
$params['cywyxm'] = $adminName;
try {
$sid = $this->saveManualPickOrder($params);
} catch (\InvalidArgumentException $e) {
$this->error($e->getMessage());
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
$this->success('新增成功', '', [
'scydgy_id' => $sid,
'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
]);
}
$this->ensurePurchaseOrderNotifySalesmanColumn();
[, $adminName] = $this->GetUseName();
$this->view->assign('adminNickname', $adminName);
$this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
$this->view->assign('defaultCclbmmc', '营销中心');
$this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
$this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
$this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
return $this->view->fetch();
}
/**
* 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
*/
public function rfqlist()
{
$this->relationSearch = false;
$this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
$this->request->filter(['strip_tags', 'trim']);
$this->ensurePurchaseOrderNotifySalesmanColumn();
$this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
$this->ensureRfqSalesmanEmailTemplate();
$this->ensureRfqSupplierEmailTemplate();
if ($this->request->isAjax()) {
try {
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$limit = max(10, min(500, (int)$limit));
$filterYm = trim((string)$this->request->param('filter_ym', ''));
if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
$filterYm = date('Y-m');
}
$applyFilters = function ($query) use ($where, $filterYm) {
$query->where('scydgy_id', '<', 0);
$this->applyPurchaseOrderNotDeletedWhere($query);
// 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
$this->applyRfqListMonthFilter($query, $filterYm);
if (!empty($where)) {
// 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
$safeWhere = [];
$skipFields = [
'supplier_name' => true,
'progress_text' => true,
'createtime_text' => true,
'notify_time_text' => true,
'can_notify_salesman' => true,
'has_issued' => true,
'has_quoted' => true,
];
foreach ((array)$where as $cond) {
if (!is_array($cond) || !isset($cond[0])) {
continue;
}
$field = (string)$cond[0];
$fieldBase = (string)preg_replace('/\|.*$/', '', $field);
$fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
if (isset($skipFields[$fieldBase])) {
continue;
}
if ($fieldBase === 'supplier_name') {
continue;
}
$safeWhere[] = $cond;
}
if ($safeWhere !== []) {
$query->where($safeWhere);
}
}
};
$countQuery = Db::table('purchase_order');
$applyFilters($countQuery);
$total = (int)$countQuery->count();
$sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
$orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
$listQuery = Db::table('purchase_order');
$applyFilters($listQuery);
$rows = $listQuery
->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,CDW,CDF,This_quantity,ceilingPrice,cGzzxMc,pick_company_name,cywyxm,notify_salesman,rfq_salesman_notified,rfq_salesman_notify_time,MBZ,createtime,dStamp,status,wflow_status')
->order($sortField, $orderDir)
->limit($offset, $limit)
->select();
if (!is_array($rows)) {
$rows = [];
}
$sidList = [];
foreach ($rows as $r) {
if (!is_array($r)) {
continue;
}
$sid = (int)($r['scydgy_id'] ?? 0);
if ($sid < 0) {
$sidList[$sid] = true;
}
}
$issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
$quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
$out = [];
foreach ($rows as $r) {
if (!is_array($r)) {
continue;
}
$sid = (int)($r['scydgy_id'] ?? 0);
if ($sid >= 0) {
continue;
}
$createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
if ($createdText === '') {
$createdText = trim((string)($r['dStamp'] ?? ''));
}
$notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
$supplier = trim((string)($r['cGzzxMc'] ?? ''));
if ($supplier === '') {
$supplier = trim((string)($r['pick_company_name'] ?? ''));
}
$hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
|| isset($issuedSidSet[$sid]);
$hasQuoted = isset($quotedSidSet[$sid]);
$salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
$canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
$out[] = [
'id' => (int)($r['id'] ?? 0),
'scydgy_id' => $sid,
'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
'CDW' => trim((string)($r['CDW'] ?? '')),
'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
'CDF' => trim((string)($r['CDF'] ?? '')),
'supplier_name' => $supplier,
'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
'notify_time_text' => $notifyTimeText,
'MBZ' => trim((string)($r['MBZ'] ?? '')),
'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
'has_issued' => $hasIssued ? 1 : 0,
'has_quoted' => $hasQuoted ? 1 : 0,
'can_notify_salesman' => $canNotifySalesman,
'createtime' => $r['createtime'] ?? null,
'createtime_text' => $createdText,
];
}
return json(['total' => $total, 'rows' => $out]);
} catch (\Throwable $e) {
Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
}
}
$sidebar = $this->loadRfqSidebarYearMonths();
$defaultYm = $this->resolveRfqListDefaultYm($sidebar);
$sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
[, $adminName] = $this->GetUseName();
$this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
$this->view->assign('adminNickname', $adminName);
$this->view->assign('defaultYm', $defaultYm);
$this->view->assign('sidebarYearMonths', $sidebar);
return $this->view->fetch('procuremen/rfqlist');
}
/**
* 列表默认月份:当月有数据用当月,否则取最近有数据的月份
*
* @param array $sidebar
*/
protected function resolveRfqListDefaultYm(array $sidebar): string
{
$current = date('Y-m');
$yms = $this->flattenProcuremenSidebarYms($sidebar);
if (in_array($current, $yms, true)) {
return $current;
}
if ($yms !== []) {
rsort($yms, SORT_STRING);
return (string)$yms[0];
}
return $current;
}
/**
* 手工询价列表左侧月份(按 createtime / dStamp)
*
* @return array
*/
protected function loadRfqSidebarYearMonths(): array
{
$ymSet = [];
try {
$q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
$this->applyPurchaseOrderNotDeletedWhere($q);
$rows = $q->field('createtime,dStamp')->limit(5000)->select();
} catch (\Throwable $e) {
$rows = [];
}
if (!is_array($rows)) {
$rows = [];
}
foreach ($rows as $r) {
if (!is_array($r)) {
continue;
}
$t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
if ($t === '') {
$t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
}
if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
$ymSet[$m[1] . '-' . $m[2]] = true;
}
}
return $this->buildYearMonthSidebar(array_keys($ymSet));
}
/**
* 手工询价可见范围(用于详情/操作校验):
* 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
* 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
*/
protected function applyManualRfqViewerWhere($query): void
{
if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
return;
}
[, $adminName] = $this->GetUseName();
$adminName = trim((string)$adminName);
if ($adminName === '') {
$query->whereRaw('1 = 0');
return;
}
// 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
$query->where(function ($q) use ($adminName) {
$q->where('cywyxm', $adminName)
->whereOr('notify_salesman', $adminName)
->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
->whereOr('notify_salesman', 'like', $adminName . '、%')
->whereOr('notify_salesman', 'like', '%、' . $adminName)
->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
->whereOr('notify_salesman', 'like', $adminName . ',%')
->whereOr('notify_salesman', 'like', '%,' . $adminName);
});
}
/**
* 当前用户是否可查看/操作该手工询价单
*/
protected function canViewManualRfqOrder(array $po): bool
{
if ($this->auth->isSuperAdmin()) {
return true;
}
// 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
if ($this->hasProcuremenPerm(['rfqlist'])) {
return true;
}
[, $adminName] = $this->GetUseName();
$adminName = trim((string)$adminName);
if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
return true;
}
if ($adminName !== '') {
foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
if ($n === $adminName) {
return true;
}
}
}
return false;
}
/**
* 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
*/
protected function applyRfqListMonthFilter($query, string $ym): void
{
if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
$ym = date('Y-m');
}
$ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
// 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
$query->whereRaw(
"("
. "CASE "
. "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
. "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
. "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
. "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
. "THEN TRIM(CAST(createtime AS CHAR(32))) "
. "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
. "END"
. ") LIKE '{$ymEsc}-%'"
);
}
/**
* 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
*/
public function rfqlistDetails()
{
return $this->details();
}
/**
* 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
*/
public function rfqnotifysalesmen()
{
if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
$this->error(__('You have no permission'));
}
$this->ensurePurchaseOrderNotifySalesmanColumn();
$this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
$sid = (int)$this->request->param('scydgy_id', 0);
if ($sid >= 0) {
$this->error('仅支持手工新增询价单');
}
$po = $this->loadManualRfqOrderForNotify($sid);
$selectedMap = [];
foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
$selectedMap[$n] = true;
}
$list = [];
foreach ($this->loadRfqSalesmanContactOptions() as $row) {
$name = trim((string)($row['name'] ?? ''));
if ($name === '') {
continue;
}
$email = trim((string)($row['email'] ?? ''));
$mobile = trim((string)($row['mobile'] ?? ''));
$hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
$list[] = [
'name' => $name,
'email' => $email,
'mobile' => $mobile,
'can_select' => $hasEmail ? 1 : 0,
'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
];
}
$canNotify = $this->canRfqNotifySalesman($po);
$this->success('', null, [
'scydgy_id' => $sid,
'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
'can_notify_salesman' => $canNotify ? 1 : 0,
'list' => $list,
]);
}
/**
* 查询询价 — 补加通知业务员可选名单
*/
public function rfqsalesmanoptions()
{
if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
$this->error(__('You have no permission'));
}
$out = [];
foreach ($this->loadRfqSalesmanContactOptions() as $row) {
$email = trim((string)($row['email'] ?? ''));
$mobile = trim((string)($row['mobile'] ?? ''));
$hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
$out[] = [
'name' => (string)($row['name'] ?? ''),
'email' => $email,
'mobile' => $mobile,
'can_select' => $hasEmail ? 1 : 0,
];
}
$this->success('', null, ['list' => $out]);
}
/**
* 查询询价 — 补加通知业务员(合并更新 notify_salesman)
*/
public function rfqappendsalesmen()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
$this->error(__('You have no permission'));
}
$this->ensurePurchaseOrderNotifySalesmanColumn();
$sid = (int)$this->request->post('scydgy_id', 0);
if ($sid >= 0) {
$this->error('仅支持手工新增询价单');
}
$po = $this->loadManualRfqOrderForNotify($sid);
if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
$this->error('订单已完结,无法添加业务员');
}
$raw = $this->request->post('salesmen/a', []);
if (!is_array($raw) || $raw === []) {
$salesmenJson = $this->request->post('salesmen_json', '');
if (is_string($salesmenJson) && $salesmenJson !== '') {
$decoded = json_decode($salesmenJson, true);
$raw = is_array($decoded) ? $decoded : [];
}
}
$addNames = [];
foreach ((array)$raw as $item) {
if (is_array($item)) {
$n = trim((string)($item['name'] ?? ''));
} else {
$n = trim((string)$item);
}
if ($n !== '') {
$addNames[] = $n;
}
}
$addNames = array_values(array_unique($addNames));
if ($addNames === []) {
$this->error('请选择要添加的业务员');
}
$allowedOptions = $this->loadRfqSalesmanContactOptions();
$allowedMap = [];
foreach ($allowedOptions as $opt) {
$n = trim((string)($opt['name'] ?? ''));
if ($n === '') {
continue;
}
$email = trim((string)($opt['email'] ?? ''));
$allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
}
foreach ($addNames as $n) {
if (!array_key_exists($n, $allowedMap)) {
$this->error('业务员不在可选名单中:' . $n);
}
if (!$allowedMap[$n]) {
$this->error('业务员未填写有效邮箱,无法添加:' . $n);
}
}
$existingRaw = trim((string)($po['notify_salesman'] ?? ''));
$merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
$mergedStr = $this->joinRfqMultiSelectValues($merged);
try {
Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
} catch (\Throwable $e) {
$this->error('保存失败:' . $e->getMessage());
}
$poId = (int)($po['id'] ?? $po['ID'] ?? 0);
$this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
$this->success('已添加业务员', null, [
'scydgy_id' => $sid,
'notify_salesman' => $mergedStr,
'added_count' => count($addNames),
]);
}
/**
* 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
*/
public function rfqnotifysalesman()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
$this->error(__('You have no permission'));
}
$this->ensurePurchaseOrderNotifySalesmanColumn();
$this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
$sid = (int)$this->request->post('scydgy_id', 0);
if ($sid >= 0) {
$this->error('仅支持手工新增询价单');
}
$po = $this->loadManualRfqOrderForNotify($sid);
$this->assertRfqCanNotifySalesman($po);
$raw = $this->request->post('salesmen/a', []);
if (!is_array($raw) || $raw === []) {
$salesmenJson = $this->request->post('salesmen_json', '');
if (is_string($salesmenJson) && $salesmenJson !== '') {
$decoded = json_decode($salesmenJson, true);
$raw = is_array($decoded) ? $decoded : [];
}
}
// 兼容旧参数:notify_all / 单人 name
if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
$raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
}
if ((!is_array($raw) || $raw === [])) {
$oneName = trim((string)$this->request->post('name', ''));
if ($oneName !== '') {
$raw = [$oneName];
}
}
$selectedNames = [];
foreach ((array)$raw as $item) {
if (is_array($item)) {
$n = trim((string)($item['name'] ?? ''));
} else {
$n = trim((string)$item);
}
if ($n !== '') {
$selectedNames[] = $n;
}
}
$selectedNames = array_values(array_unique($selectedNames));
if ($selectedNames === []) {
$this->error('请选择要通知的业务员');
}
$optionMap = [];
foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
$n = trim((string)($opt['name'] ?? ''));
if ($n === '') {
continue;
}
$optionMap[$n] = $opt;
}
$targets = [];
foreach ($selectedNames as $n) {
if (!isset($optionMap[$n])) {
$this->error('业务员不在可选名单中:' . $n);
}
$email = trim((string)($optionMap[$n]['email'] ?? ''));
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->error('业务员未填写有效邮箱,无法通知:' . $n);
}
$resolved = $this->resolveRfqSalesmanContactRows([$n]);
$targets[] = $resolved[0] ?? [
'admin_id' => 0,
'name' => $n,
'email' => $email,
];
}
$mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
try {
Db::table('purchase_order')->where('scydgy_id', $sid)->update([
'notify_salesman' => $mergedStr,
]);
} catch (\Throwable $e) {
$this->error('保存通知业务员失败:' . $e->getMessage());
}
$po['notify_salesman'] = $mergedStr;
$mailConfig = $this->loadMailerConfig();
if (empty($mailConfig['host'])) {
$this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
}
if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
$this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
}
$this->ensureRfqSalesmanEmailTemplate();
$ccydh = trim((string)($po['CCYDH'] ?? ''));
$cyjmc = trim((string)($po['CYJMC'] ?? ''));
$cgymc = trim((string)($po['CGYMC'] ?? ''));
$cdw = trim((string)($po['CDW'] ?? ''));
$qty = trim((string)$this->resolveProcuremenThisQuantity($po));
$ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
$mbz = trim((string)($po['MBZ'] ?? ''));
$cywyxm = trim((string)($po['cywyxm'] ?? ''));
$supplier = trim((string)($po['cGzzxMc'] ?? ''));
if ($supplier === '') {
$supplier = trim((string)($po['pick_company_name'] ?? ''));
}
$supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
try {
$mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
$okNames = [];
$failMsgs = [];
foreach ($targets as $contact) {
$toEmail = trim((string)($contact['email'] ?? ''));
$toName = trim((string)($contact['name'] ?? ''));
$notifyVars = [
'contact_name' => $toName,
'salesman_name' => $toName,
'company_name' => $toName,
'email' => $toEmail,
'ccydh' => $ccydh,
'cyjmc' => $cyjmc,
'cgymc' => $cgymc,
'cdw' => $cdw,
'this_quantity' => $qty,
'ceilingPrice' => $ceiling,
'MBZ' => $mbz,
'supplier_name' => $supplier,
// 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
'cywyxm' => $cywyxm,
];
try {
$mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
$mailSubject = $mailSubjectTpl;
foreach ($notifyVars as $k => $v) {
if ($k === 'supplier_quotes') {
continue;
}
$mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
}
$mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
$mailSubject = trim((string)$mailSubject);
if ($mailSubject === '') {
$mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
}
$mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
$mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
$mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['', '
'], "\n", $supplierQuotesHtml)), $mailPlain);
$bundle = [
'company_name' => $toName,
'email' => $toEmail,
'mail_plain' => $mailPlainForLog,
'mail_body' => $mailBody,
'ccydh' => $ccydh,
'email_log_scene' => 'rfq_salesman',
'email_log_scydgy_id' => $sid,
'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
'notify_vars' => $notifyVars,
];
$this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
$okNames[] = $toName . '(' . $toEmail . ')';
} catch (\Throwable $e) {
$failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
}
}
if ($okNames === []) {
$this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
}
$now = date('Y-m-d H:i:s');
try {
Db::table('purchase_order')->where('scydgy_id', $sid)->update([
'rfq_salesman_notified' => 1,
'rfq_salesman_notify_time' => $now,
]);
} catch (\Throwable $e) {
// ignore
}
$this->addOrderLog(
$sid,
'rfq_notify_salesman',
'邮箱通知业务员:' . implode('、', $okNames),
(int)($po['id'] ?? 0)
);
$msg = '已通知 ' . count($okNames) . ' 人';
if ($failMsgs !== []) {
$msg .= ';部分失败:' . implode(';', $failMsgs);
}
$this->success($msg, null, [
'scydgy_id' => $sid,
'notify_salesman' => $mergedStr,
'rfq_salesman_notified' => 1,
'rfq_salesman_notify_time' => $now,
'notify_time_text' => $now,
'ok_count' => count($okNames),
'fail_count' => count($failMsgs),
]);
}
/**
* 查询询价 — 下发前:返回将通知的供应商表格数据
*/
public function rfqissuesuppliers()
{
if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
$this->error(__('You have no permission'));
}
$sid = (int)$this->request->param('scydgy_id', 0);
if ($sid >= 0) {
$this->error('仅支持手工新增询价单');
}
$po = $this->loadManualRfqOrderForNotify($sid);
$supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
if ($supplierRaw === '') {
$supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
}
$names = $this->splitRfqSalesmanNames($supplierRaw);
// 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
$notifiedMap = [];
try {
$this->ensurePurchaseEmailSendLogTableOnce();
$logRows = Db::table('purchase_email_send_log')
->where('scydgy_id', $sid)
->where('status', 1)
->where('scene', 'in', ['rfq_supplier', 'pick_issue'])
->field('company_name')
->select();
if (is_array($logRows)) {
foreach ($logRows as $lr) {
if (!is_array($lr)) {
continue;
}
$cn = trim((string)($lr['company_name'] ?? ''));
if ($cn !== '') {
$notifiedMap[$cn] = true;
}
}
}
} catch (\Throwable $e) {
}
// 兼容:明细已生成(曾下发)也视为已通知
try {
$detRows = Db::table('purchase_order_detail')
->where('scydgy_id', $sid)
->field('company_name')
->select();
if (is_array($detRows)) {
foreach ($detRows as $dr) {
if (!is_array($dr)) {
continue;
}
$cn = trim((string)($dr['company_name'] ?? ''));
if ($cn !== '') {
$notifiedMap[$cn] = true;
}
}
}
} catch (\Throwable $e) {
}
$list = [];
foreach ($names as $name) {
// 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
$contact = $this->resolveCustomerContactByCompanyName($name, false);
$email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
$phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
$username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
$okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
$notified = !empty($notifiedMap[$name]) ? 1 : 0;
$list[] = [
'name' => $name,
'username' => $username,
'email' => $email,
'phone' => $phone,
'can_notify' => $okEmail ? 1 : 0,
'found' => is_array($contact) ? 1 : 0,
'notified' => $notified,
'notify_status_text' => $notified ? '已通知' : '未通知',
];
}
$this->success('', null, [
'scydgy_id' => $sid,
'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
'CDW' => trim((string)($po['CDW'] ?? '')),
'This_quantity' => $this->resolveProcuremenThisQuantity($po),
'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
'CDF' => trim((string)($po['CDF'] ?? '')),
'MBZ' => trim((string)($po['MBZ'] ?? '')),
'list' => $list,
]);
}
/**
* 查询询价 — 补加供应商可选名单
*/
public function rfqsupplieroptions()
{
if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
$this->error(__('You have no permission'));
}
$names = array_values($this->loadRfqSupplierNameOptions());
$out = [];
foreach ($names as $name) {
$out[] = ['name' => $name];
}
$this->success('', null, ['list' => $out]);
}
/**
* 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
*/
public function rfqappendsuppliers()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
$this->error(__('You have no permission'));
}
$sid = (int)$this->request->post('scydgy_id', 0);
if ($sid >= 0) {
$this->error('仅支持手工新增询价单');
}
$po = $this->loadManualRfqOrderForNotify($sid);
if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
$this->error('订单已完结,无法补加供应商');
}
$raw = $this->request->post('suppliers/a', []);
if (!is_array($raw) || $raw === []) {
$suppliersJson = $this->request->post('suppliers_json', '');
if (is_string($suppliersJson) && $suppliersJson !== '') {
$decoded = json_decode($suppliersJson, true);
$raw = is_array($decoded) ? $decoded : [];
}
}
$addNames = [];
foreach ((array)$raw as $item) {
if (is_array($item)) {
$n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
} else {
$n = trim((string)$item);
}
if ($n !== '') {
$addNames[] = $n;
}
}
$addNames = array_values(array_unique($addNames));
if ($addNames === []) {
$this->error('请选择要补加的供应商');
}
$existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
if ($existingRaw === '') {
$existingRaw = trim((string)($po['pick_company_name'] ?? ''));
}
$merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
$mergedStr = $this->joinRfqMultiSelectValues($merged);
try {
Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
} catch (\Throwable $e) {
$this->error('保存失败:' . $e->getMessage());
}
$poId = (int)($po['id'] ?? $po['ID'] ?? 0);
$this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
$this->success('已补加供应商', null, [
'scydgy_id' => $sid,
'cGzzxMc' => $mergedStr,
'added_count' => count($addNames),
]);
}
/**
* 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
*/
public function rfqissue()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPerm(['rfqissue'])) {
$this->error(__('You have no permission'));
}
$this->ensureRfqSupplierEmailTemplate();
$sid = (int)$this->request->post('scydgy_id', 0);
if ($sid >= 0) {
$this->error('仅支持手工新增询价单');
}
$po = $this->loadManualRfqOrderForNotify($sid);
if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
$this->error('订单已完结,无法下发');
}
if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
&& !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
$this->error('订单已进入后续流程,无法再下发');
}
$supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
if ($supplierRaw === '') {
$supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
}
$supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
if ($supplierNames === []) {
$this->error('请先在新增询价时选择供应商');
}
$companies = [];
$missing = [];
$noEmail = [];
foreach ($supplierNames as $name) {
$contact = $this->resolveCustomerContactByCompanyName($name, false);
if ($contact === null) {
$missing[] = $name;
continue;
}
$em = trim((string)($contact['email'] ?? ''));
if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
$noEmail[] = $name;
continue;
}
$companies[] = $contact;
}
if ($missing !== []) {
$this->error('未找到供应商档案:' . implode('、', $missing));
}
if ($noEmail !== []) {
$this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
}
if ($companies === []) {
$this->error('没有可通知的供应商');
}
$mailConfig = $this->loadMailerConfig();
if (empty($mailConfig['host'])) {
$this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
}
if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
$this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
}
$mergeRow = $po;
$mergeRow['ID'] = $sid;
$mergeRow['id'] = $sid;
$mergeRows = [$mergeRow];
$sysRqDb = trim((string)($po['sys_rq'] ?? ''));
if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
$sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
}
$scoreRule = ProcuremenSupplierScore::getDefaultRule();
$issueTime = date('Y-m-d H:i:s');
$nameLabels = [];
foreach ($companies as $c) {
$nameLabels[] = trim((string)($c['name'] ?? ''));
}
$logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
Db::startTrans();
try {
$this->upsertPurchaseOrderFromRow(
$mergeRow,
$sysRqDb,
ProcuremenStatus::WFLOW_PENDING_CONFIRM,
$issueTime,
$po,
null,
$scoreRule
);
foreach ($companies as $c) {
$this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
}
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$this->error($e->getMessage());
}
$poId = (int)($po['id'] ?? $po['ID'] ?? 0);
if ($poId <= 0) {
try {
$poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
} catch (\Throwable $e) {
$poId = 0;
}
}
$this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
$posNotify = [];
try {
$fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
if (is_array($fresh)) {
$fresh['sys_rq'] = $sysRqDb;
$posNotify = [$fresh];
}
} catch (\Throwable $e) {
$posNotify = [$po];
$posNotify[0]['sys_rq'] = $sysRqDb;
}
$notifyBundle = [
'ccydh' => trim((string)($po['CCYDH'] ?? '')),
'pos' => $posNotify,
'merge_rows' => $mergeRows,
];
$notifyErrors = [];
foreach ($companies as $c) {
$cname = trim((string)($c['name'] ?? ''));
try {
// 询价下发:仅邮箱通知供应商
$this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
} catch (\Throwable $e) {
$notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
}
}
if ($notifyErrors !== []) {
$this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
}
$this->success('已询价并邮件通知供应商', null, [
'scydgy_id' => $sid,
'progress_text' => '待报价',
'supplier_count' => count($companies),
]);
}
/**
* 查询询价 — 弹窗内向单个供应商发送询价邮件
*/
public function rfqissuesendmail()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
$this->error(__('You have no permission'));
}
$this->ensureRfqSupplierEmailTemplate();
$sid = (int)$this->request->post('scydgy_id', 0);
$companyName = trim((string)$this->request->post('company_name', ''));
if ($sid >= 0) {
$this->error('仅支持手工新增询价单');
}
if ($companyName === '') {
$this->error('请选择供应商');
}
$po = $this->loadManualRfqOrderForNotify($sid);
if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
$this->error('订单已完结,无法发送');
}
if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
&& !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
$this->error('订单已进入后续流程,无法再发送');
}
$contact = $this->resolveCustomerContactByCompanyName($companyName, false);
if ($contact === null) {
$this->error('未找到供应商档案:' . $companyName);
}
$email = trim((string)($contact['email'] ?? ''));
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->error('该供应商未填写有效邮箱');
}
$mailConfig = $this->loadMailerConfig();
if (empty($mailConfig['host'])) {
$this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
}
if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
$this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
}
$mergeRow = $po;
$mergeRow['ID'] = $sid;
$mergeRow['id'] = $sid;
$mergeRows = [$mergeRow];
$sysRqDb = trim((string)($po['sys_rq'] ?? ''));
if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
$sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
}
$scoreRule = ProcuremenSupplierScore::getDefaultRule();
$issueTime = date('Y-m-d H:i:s');
Db::startTrans();
try {
$this->upsertPurchaseOrderFromRow(
$mergeRow,
$sysRqDb,
ProcuremenStatus::WFLOW_PENDING_CONFIRM,
$issueTime,
$po,
null,
$scoreRule
);
$this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$this->error($e->getMessage());
}
$posNotify = [];
try {
$fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
if (is_array($fresh)) {
$fresh['sys_rq'] = $sysRqDb;
$posNotify = [$fresh];
}
} catch (\Throwable $e) {
$posNotify = [$po];
$posNotify[0]['sys_rq'] = $sysRqDb;
}
$notifyBundle = [
'ccydh' => trim((string)($po['CCYDH'] ?? '')),
'pos' => $posNotify,
'merge_rows' => $mergeRows,
];
try {
$this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
} catch (\Throwable $e) {
$this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
}
$poId = (int)($po['id'] ?? $po['ID'] ?? 0);
if ($poId <= 0) {
try {
$poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
} catch (\Throwable $e) {
$poId = 0;
}
}
$this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
$this->success('已向「' . $companyName . '」发送询价邮件', null, [
'scydgy_id' => $sid,
'company_name' => $companyName,
]);
}
/**
* 查询询价 — 查看各供应商报价(单价)
*/
public function rfqquotes()
{
if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
$this->error(__('You have no permission'));
}
$sid = (int)$this->request->param('scydgy_id', 0);
if ($sid >= 0) {
$this->error('仅支持手工新增询价单');
}
$po = $this->loadManualRfqOrderForNotify($sid);
$rows = [];
try {
// 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
$q = Db::table('purchase_order_detail')
->where('scydgy_id', $sid)
->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
->order('id', 'asc');
$this->applyActivePurchaseOrderDetailWhere($q);
$rows = $q->select();
} catch (\Throwable $e) {
try {
$q = Db::table('purchase_order_detail')
->where('scydgy_id', $sid)
->order('id', 'asc');
$this->applyActivePurchaseOrderDetailWhere($q);
$rows = $q->select();
} catch (\Throwable $e2) {
$rows = [];
}
}
if (!is_array($rows)) {
$rows = [];
}
$list = [];
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$amount = trim((string)($row['amount'] ?? ''));
$isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
// 未报价不显示时间(createtime 是下发时间,不是报价时间)
$oper = '';
if ($isQuoted) {
$oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
if ($oper === '') {
$oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
}
}
$list[] = [
'id' => (int)($row['id'] ?? 0),
'company_name' => trim((string)($row['company_name'] ?? '')),
'amount' => $amount,
'amount_text' => $isQuoted ? $amount : '',
'is_quoted' => $isQuoted,
'quote_label' => $isQuoted ? '已报价' : '未报价',
'status_name' => trim((string)($row['status_name'] ?? '')),
'oper_time' => $oper,
];
}
$this->success('', null, [
'scydgy_id' => $sid,
'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
'CDW' => trim((string)($po['CDW'] ?? '')),
'This_quantity' => $this->resolveProcuremenThisQuantity($po),
'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
'CDF' => trim((string)($po['CDF'] ?? '')),
'MBZ' => trim((string)($po['MBZ'] ?? '')),
'list' => $list,
]);
}
/**
* 手工询价是否已下发(有下发明细或已进入待确认及之后)
*/
protected function isRfqOrderIssued(array $po): bool
{
if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
return true;
}
$sid = (int)($po['scydgy_id'] ?? 0);
if ($sid >= 0) {
return false;
}
try {
$q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
$this->applyActivePurchaseOrderDetailWhere($q);
return (int)$q->count() > 0;
} catch (\Throwable $e) {
return false;
}
}
/**
* 批量:已有下发明细的手工询价 scydgy_id
*
* @param int[] $scydgyIds
* @return array
*/
protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
{
$set = [];
$ids = [];
foreach ($scydgyIds as $sid) {
$sid = (int)$sid;
if ($sid < 0) {
$ids[$sid] = true;
}
}
if ($ids === []) {
return $set;
}
try {
$q = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($ids))
->field('scydgy_id');
$this->applyActivePurchaseOrderDetailWhere($q);
$rows = $q->select();
} catch (\Throwable $e) {
return $set;
}
if (!is_array($rows)) {
return $set;
}
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$sid = (int)($row['scydgy_id'] ?? 0);
if ($sid < 0) {
$set[$sid] = true;
}
}
return $set;
}
/**
* 批量:已填单价(已报价)的手工询价 scydgy_id
*
* @param int[] $scydgyIds
* @return array
*/
protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
{
$set = [];
$ids = [];
foreach ($scydgyIds as $sid) {
$sid = (int)$sid;
if ($sid < 0) {
$ids[$sid] = true;
}
}
if ($ids === []) {
return $set;
}
try {
$q = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($ids))
->field('scydgy_id,amount');
$this->applyActivePurchaseOrderDetailWhere($q);
$rows = $q->select();
} catch (\Throwable $e) {
return $set;
}
if (!is_array($rows)) {
return $set;
}
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$amount = trim((string)($row['amount'] ?? ''));
if ($amount === '' || $amount === '0' || $amount === '0.00') {
continue;
}
$sid = (int)($row['scydgy_id'] ?? 0);
if ($sid < 0) {
$set[$sid] = true;
}
}
return $set;
}
/**
* 已下发且至少一家供应商已报价,才允许通知业务员
*/
protected function canRfqNotifySalesman(array $po): bool
{
if (!$this->isRfqOrderIssued($po)) {
return false;
}
$sid = (int)($po['scydgy_id'] ?? 0);
if ($sid >= 0) {
return false;
}
$quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
return isset($quoted[$sid]);
}
protected function assertRfqCanNotifySalesman(array $po): void
{
if (!$this->isRfqOrderIssued($po)) {
$this->error('请先询价并等待供应商报价后再通知业务员');
}
if (!$this->canRfqNotifySalesman($po)) {
$this->error('供应商尚未报价,暂不能通知业务员');
}
}
/**
* 加载手工询价单(含可见性校验)
*
* @return array
*/
protected function loadManualRfqOrderForNotify(int $scydgyId): array
{
try {
$po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
} catch (\Throwable $e) {
$po = null;
}
if (!is_array($po)) {
$this->error('订单不存在');
}
$modRq = trim((string)($po['mod_rq'] ?? ''));
if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
$this->error('订单不存在');
}
if ($this->auth->isSuperAdmin()) {
return $po;
}
if ($this->canViewManualRfqOrder($po)) {
return $po;
}
$this->error('无权操作该订单');
}
/**
* @return string[]
*/
protected function splitRfqSalesmanNames(string $raw): array
{
$parts = [];
$raw = trim($raw);
if ($raw === '') {
return [];
}
foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
$v = trim((string)$piece);
if ($v !== '' && !in_array($v, $parts, true)) {
$parts[] = $v;
}
}
return $parts;
}
/**
* 按姓名匹配 fa_admin 邮箱
*
* @param string[] $names
* @return array
*/
protected function resolveRfqSalesmanContactRows(array $names): array
{
$out = [];
foreach ($names as $name) {
$name = trim((string)$name);
if ($name === '') {
continue;
}
$adminId = 0;
$email = '';
try {
$row = Db::name('admin')
->where(function ($q) use ($name) {
$q->where('nickname', $name)->whereOr('username', $name);
})
->where('status', 'normal')
->order('id', 'asc')
->field('id,nickname,username,email')
->find();
} catch (\Throwable $e) {
$row = null;
}
if (is_array($row)) {
$adminId = (int)($row['id'] ?? 0);
$email = trim((string)($row['email'] ?? ''));
$disp = trim((string)($row['nickname'] ?? ''));
if ($disp === '') {
$disp = trim((string)($row['username'] ?? ''));
}
if ($disp !== '') {
$name = $disp;
}
}
$out[] = [
'admin_id' => $adminId,
'name' => $name,
'email' => $email,
];
}
return $out;
}
/**
* 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
*/
protected function assertManualOrderDetailsViewable(int $scydgyId): void
{
if ($scydgyId >= 0) {
return;
}
try {
$po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
} catch (\Throwable $e) {
$po = null;
}
if (!is_array($po)) {
$this->error('订单不存在');
}
$modRq = trim((string)($po['mod_rq'] ?? ''));
if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
$this->error('订单不存在');
}
if ($this->auth->isSuperAdmin()) {
return;
}
[, $adminName] = $this->GetUseName();
$cywy = trim((string)($po['cywyxm'] ?? ''));
if ($cywy !== '' && $cywy === $adminName) {
return;
}
foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
try {
if ($this->auth->check($rule)) {
return;
}
} catch (\Throwable $e) {
}
}
$this->error('无权查看该订单');
}
/**
* 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
*/
protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
{
if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
return ProcuremenStatus::PO_COMPLETED;
}
$sid = (int)($row['scydgy_id'] ?? 0);
if ($sid < 0) {
if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
return '已通知业务员';
}
if ($hasQuoted) {
return '供应商已报价';
}
if ($hasIssued
|| ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
|| ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
return '待报价';
}
try {
$detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
$this->applyActivePurchaseOrderDetailWhere($detCntQuery);
if ((int)$detCntQuery->count() > 0) {
return '待报价';
}
} catch (\Throwable $e) {
}
return '待询价';
}
if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
return '待入库评分';
}
if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
return '待采购确认';
}
if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
return '待确认供应商';
}
return '待协助下发';
}
/**
* 协助初选列表 — 批量软删除
*/
public function pickDelete()
{
if (!$this->request->isPost() || !$this->request->isAjax()) {
$this->error(__('Invalid parameters'));
}
if (!$this->procuremenCanPickDelete()) {
$this->error(__('You have no permission'));
}
$rowsRaw = $this->request->post('rows_json', '[]');
$rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
if (!is_array($rows) || $rows === []) {
$this->error('请至少勾选一条工序');
}
$done = 0;
Db::startTrans();
try {
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$this->softDeleteProcuremenPickRow($row);
$done++;
}
if ($done < 1) {
throw new \Exception('没有可删除的工序');
}
Db::commit();
} catch (\InvalidArgumentException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (\Throwable $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->pickHiddenScydgySetCache = null;
$this->success('已删除 ' . $done . ' 条工序');
}
/**
* 下发 — 手工新增工序(弹窗)
*/
public function pickAdd()
{
if ($this->request->isPost()) {
$params = $this->request->post('row/a');
if (!is_array($params)) {
$this->error(__('Parameter %s can not be empty', ''));
}
try {
$sid = $this->saveManualPickOrder($params);
} catch (\InvalidArgumentException $e) {
$this->error($e->getMessage());
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
$this->success('新增成功', '', ['scydgy_id' => $sid]);
}
return $this->view->fetch('procuremen/pick_add');
}
/**
* 下发提交 — 通知供应商 → POST procuremen/picksubmit
*/
public function pickSubmit()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
// ---------- 接口订单数据 ----------
$rowJson = $this->request->post('row_json', '');
$mergeRowsJson = $this->request->post('merge_rows_json', '');
$companiesJson = $this->request->post('companies_json', '[]');
$mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
$companies = json_decode($companiesJson, true);
if (!is_array($companies)) {
$this->error('供应商数据无效');
}
$issueCompanies = $this->normalizePickCompanies($companies);
if ($issueCompanies === []) {
$this->error('请至少选择一家合作供应商');
}
$issueNameLabels = [];
foreach ($issueCompanies as $pc) {
$issueNameLabels[] = $pc['name'];
}
$issueNamesSummary = implode('、', $issueNameLabels);
$sysRq = trim((string)$this->request->post('sys_rq', ''));
if ($sysRq === '') {
$this->error('请选择招标截止日期');
}
$sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
$deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
(string)$this->request->post('delivery_deadline', ''),
true
);
$scoreRuleId = (int)$this->request->post('score_rule_id', 0);
if ($scoreRuleId <= 0) {
$this->error('请选择订单类型');
}
$scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
if ((int)($scoreRule['id'] ?? 0) <= 0) {
$this->error('订单类型无效,请刷新后重选');
}
$scoreRuleId = (int)$scoreRule['id'];
$this->ensurePurchaseOrderScoreRuleIdColumn();
$isMerge = count($mergeRows) > 1;
$procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
$logMsg = '下发' . $procPart
. '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
$issueTime = date('Y-m-d H:i:s');
$logSidList = [];
foreach ($mergeRows as $row) {
if (!is_array($row)) {
continue;
}
$sid = $this->extractScydgyRowId($row);
if ($this->isValidScydgyRowId($sid)) {
$logSidList[$sid] = true;
}
}
$existingBySid = [];
if ($logSidList !== []) {
try {
$existingRows = Db::table('purchase_order')
->where('scydgy_id', 'in', array_keys($logSidList))
->select();
if (is_array($existingRows)) {
foreach ($existingRows as $poRow) {
if (!is_array($poRow)) {
continue;
}
$sid = (int)($poRow['scydgy_id'] ?? 0);
if ($this->isValidScydgyRowId($sid)) {
$existingBySid[$sid] = $poRow;
}
}
}
} catch (\Throwable $e) {
$existingBySid = [];
}
}
Db::startTrans();
try {
// ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
foreach ($mergeRows as $row) {
if (!is_array($row)) {
continue;
}
$sid = $this->extractScydgyRowId($row);
$this->upsertPurchaseOrderFromRow(
$row,
$sysRqDb,
ProcuremenStatus::WFLOW_PENDING_CONFIRM,
$issueTime,
$this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
$deliveryDeadlineDb,
$scoreRule
);
}
foreach ($issueCompanies as $c) {
$this->issuePersistSupplierDetails($c, $mergeRows, false, true);
}
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$this->error($e->getMessage());
}
$poIdBySid = [];
if ($logSidList !== []) {
try {
$poIdBySid = Db::table('purchase_order')
->where('scydgy_id', 'in', array_keys($logSidList))
->column('id', 'scydgy_id');
} catch (\Throwable $e) {
$poIdBySid = [];
}
}
// ---------- 操作日志记录(批量写入,减少提交等待) ----------
if ($logSidList !== []) {
list($adminId, $adminName) = $this->GetUseName();
$logRows = [];
$seenLogSid = [];
foreach ($mergeRows as $row) {
if (!is_array($row)) {
continue;
}
$ids = $this->extractScydgyRowId($row);
if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
continue;
}
$seenLogSid[$ids] = true;
$poIdLog = null;
if (isset($poIdBySid[$ids])) {
$tid = (int)$poIdBySid[$ids];
$poIdLog = $tid > 0 ? $tid : null;
}
$logRows[] = ProcuremenOperLog::buildInsertRow(
$ids,
'issue_submit',
$logMsg,
$poIdLog,
(int)$adminId,
(string)$adminName
);
}
if ($logRows !== []) {
try {
Db::table('purchase_order_oper_log')->insertAll($logRows);
} catch (\Throwable $e) {
Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
}
}
}
$notifyErrors = [];
$posNotify = [];
if ($logSidList !== []) {
try {
$posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
} catch (\Throwable $e) {
$posNotify = [];
}
}
if (!is_array($posNotify)) {
$posNotify = [];
}
foreach ($posNotify as $i => $prow) {
if (is_array($posNotify[$i])) {
$posNotify[$i]['sys_rq'] = $sysRqDb;
}
}
$ccydhPick = '';
foreach ($mergeRows as $row) {
if (!is_array($row)) {
continue;
}
$ccydhPick = trim((string)($row['CCYDH'] ?? ''));
if ($ccydhPick !== '') {
break;
}
}
$notifyBundleBase = [
'ccydh' => $ccydhPick,
'pos' => $posNotify,
'merge_rows' => $mergeRows,
];
try {
$this->notifyDryRunPreview = [];
foreach ($issueCompanies as $c) {
if (!is_array($c)) {
continue;
}
$cname = trim((string)($c['name'] ?? ''));
if ($cname === '') {
continue;
}
try {
$this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
} catch (\Throwable $e) {
$notifyErrors[] = $cname . ':' . $e->getMessage();
}
}
} catch (\Throwable $e) {
$this->error('通知发送失败:' . $e->getMessage());
}
if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
$this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
}
if ($this->isProcuremenNotifyDryRun()) {
$this->success('【演练模式】已保存并生成通知预览', '', [
'notify_dry_run' => true,
'notify_preview' => $this->notifyDryRunPreview,
]);
}
$this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
}
/**
* 确认供应商弹窗
*/
public function auditIssue()
{
$ids = $this->request->param('ids', $this->request->param('id', ''));
if (is_array($ids)) {
$ids = isset($ids[0]) ? $ids[0] : '';
}
$ids = trim((string)$ids);
if ($ids === '') {
$this->error(__('Invalid parameters'));
}
if ($this->request->isPost()) {
$this->error('请使用弹窗内「确认」提交');
}
$bundle = $this->loadAuditOrderBundleByScydgyId($ids);
$pos = $bundle['pos'];
if ($pos === []) {
$this->error('该订单不在待确认供应商状态');
}
$po = $pos[0];
$quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
if ($quoteGroups === []) {
$this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
}
$pickedName = '';
foreach ($pos as $poRow) {
if (!is_array($poRow)) {
continue;
}
$pn = trim((string)($poRow['pick_company_name'] ?? ''));
if ($pn !== '') {
$pickedName = $pn;
break;
}
}
$this->view->assign('po', $po);
$this->view->assign('scydgyId', $ids);
$this->view->assign('orderCcydh', $bundle['ccydh']);
$mergeRows = $bundle['merge_rows'];
$this->view->assign('processRows', $mergeRows);
$this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
$this->view->assign('processCount', count($mergeRows));
$this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
$this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
$this->view->assign('pickedCompanyName', $pickedName);
$sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
if ($sysRqForView === '') {
$sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
}
$this->view->assign('sysRq', $sysRqForView);
$deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
if ($deliveryDeadlineForView === '') {
$deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
}
$this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
$this->ensurePurchaseOrderManualPickColumns();
$bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
$manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
$manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
$quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
$pickedName = $manualPickInfo['company'];
$this->view->assign('pickedCompanyName', $pickedName);
}
$this->view->assign('bidOpenVerified', $bidOpenVerified);
$this->view->assign('manualPicked', $manualPicked);
$this->view->assign('manualPickReason', $manualPickInfo['reason']);
$this->view->assign('quoteVisible', $quoteVisible);
$orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
$this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
$this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
$this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
$quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
$this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
$this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
$this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
return $this->view->fetch('procuremen/audit_issue');
}
/**
* 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
*
* @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
*/
protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
{
if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
return false;
}
if ($this->isProcuremenManualPickedForBundle($bundle)) {
return false;
}
return true;
}
/**
* 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
*
* @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
*/
protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
{
if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
return false;
}
if ($this->isProcuremenManualPickedForBundle($bundle)) {
return false;
}
$sysRq = trim((string)$this->resolveBundleSysRq($bundle));
if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
return true;
}
return !$this->isProcuremenQuoteDeadlineReached($sysRq);
}
/**
* 确认页 — 补加供应商弹窗
*/
public function auditAppend()
{
if (!$this->hasProcuremenPermStrict(['auditappend'])) {
$this->error(__('You have no permission'));
}
$ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
if (is_array($ids)) {
$ids = isset($ids[0]) ? $ids[0] : '';
}
$ids = trim((string)$ids);
if ($ids === '') {
$this->error(__('Invalid parameters'));
}
if ($this->request->isPost()) {
$this->error('请使用弹窗内「确认」提交');
}
$bundle = $this->loadAuditOrderBundleByScydgyId($ids);
if (($bundle['pos'] ?? []) === []) {
$this->error('该订单不在待确认供应商状态');
}
if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
$this->error('已开标验证,不能再补加供应商');
}
if ($this->isProcuremenManualPickedForBundle($bundle)) {
$this->error('已指定供应商,不能再补加供应商');
}
$this->error('已经超过了招标截止日期,不可操作');
}
$quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
$existingNames = [];
foreach ($quoteGroups as $g) {
if (!is_array($g)) {
continue;
}
$n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
if ($n !== '') {
$existingNames[$n] = true;
}
}
$po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
$mergeRows = $bundle['merge_rows'] ?? [];
$this->view->assign('scydgyId', $ids);
$this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
$this->view->assign('po', $po);
$this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
$this->view->assign('existingCompanyNames', array_keys($existingNames));
$this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
$sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
if ($sysRqForView === '') {
$sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
}
$this->view->assign('sysRq', $sysRqForView);
$deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
if ($deliveryDeadlineForView === '') {
$deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
}
$this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
}
/**
* 确认页 — 补加供应商提交
*/
public function auditAppendSubmit()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
$this->error(__('You have no permission'));
}
$ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
if ($ids === '') {
$this->error(__('Invalid parameters'));
}
$bundle = $this->loadAuditOrderBundleByScydgyId($ids);
if (($bundle['pos'] ?? []) === []) {
$this->error('该订单不在待确认供应商状态');
}
if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
$this->error('已开标验证,不能再补加供应商');
}
if ($this->isProcuremenManualPickedForBundle($bundle)) {
$this->error('已指定供应商,不能再补加供应商');
}
$this->error('已经超过了招标截止日期,不可操作');
}
$companiesJson = $this->request->post('companies_json', '[]');
$companies = json_decode((string)$companiesJson, true);
if (!is_array($companies)) {
$this->error('供应商数据无效');
}
$issueCompanies = $this->normalizePickCompanies($companies);
if ($issueCompanies === []) {
$this->error('请至少选择一家合作供应商');
}
$mergeRows = $bundle['merge_rows'] ?? [];
if (!is_array($mergeRows) || $mergeRows === []) {
$this->error('未找到工序行,无法补加');
}
$existingNames = [];
foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
if (!is_array($g)) {
continue;
}
$n = trim((string)($g['company_name'] ?? ''));
if ($n !== '') {
$existingNames[$n] = true;
}
}
$toAdd = [];
foreach ($issueCompanies as $c) {
if (!is_array($c)) {
continue;
}
$n = trim((string)($c['name'] ?? ''));
if ($n === '' || isset($existingNames[$n])) {
continue;
}
$toAdd[] = $c;
}
if ($toAdd === []) {
$this->error('所选供应商均已在本单中,请选择新的供应商');
}
$addedNames = [];
Db::startTrans();
try {
foreach ($toAdd as $c) {
$this->issuePersistSupplierDetails($c, $mergeRows, false, true);
$addedNames[] = trim((string)($c['name'] ?? ''));
}
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$this->error($e->getMessage());
}
$notifyErrors = [];
$notifyBundleBase = [
'ccydh' => $bundle['ccydh'] ?? '',
'pos' => $bundle['pos'] ?? [],
'merge_rows' => $mergeRows,
];
foreach ($toAdd as $c) {
if (!is_array($c)) {
continue;
}
$cname = trim((string)($c['name'] ?? ''));
if ($cname === '') {
continue;
}
try {
$this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
} catch (\Throwable $e) {
$notifyErrors[] = $cname . ':' . $e->getMessage();
}
}
$logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
$seenLogSid = [];
foreach ($bundle['pos'] ?? [] as $poRow) {
if (!is_array($poRow)) {
continue;
}
$sid = (int)($poRow['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
continue;
}
$seenLogSid[$sid] = true;
$poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
$this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
}
if ($seenLogSid === []) {
$logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
if ($this->isValidScydgyRowId($logSid)) {
$this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
}
}
if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
$this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
}
$this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
}
/**
* 开标双重验证 — 可选验证人列表
*/
public function bidOpenUsers()
{
if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
$this->error('无权限');
}
$scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
if ($scydgyId !== '') {
$bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
$this->success('已完成开标验证', null, [
'verified' => 1,
'users' => [],
]);
}
if ($this->isProcuremenManualPickedForBundle($bundle)) {
$this->error('本单已指定供应商,无需再开标');
}
$this->assertProcuremenBidOpenAfterDeadline($bundle);
}
$this->success('', null, [
'verified' => 0,
'users' => $this->listBidOpenVerifierCandidates(),
]);
}
/**
* 开标双重验证 — 向指定管理员发送短信验证码
*/
public function bidOpenSendCode()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
$this->error('无权限');
}
$scydgyId = trim((string)$this->request->post('scydgy_id', ''));
$adminId = (int)$this->request->post('admin_id', 0);
if ($scydgyId === '' || $adminId <= 0) {
$this->error('参数无效');
}
$bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
if ($bundle['pos'] === []) {
$this->error('该订单不在待确认供应商状态');
}
if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
$this->success('已完成开标验证,无需重复发送');
}
if ($this->isProcuremenManualPickedForBundle($bundle)) {
$this->error('本单已指定供应商,无需再开标');
}
$this->assertProcuremenBidOpenAfterDeadline($bundle);
$ccydh = trim((string)($bundle['ccydh'] ?? ''));
if ($ccydh === '') {
$this->error('订单号无效');
}
$admin = $this->loadBidOpenAdminUser($adminId);
if ($admin === null) {
$this->error('验证人无效或未绑定手机号');
}
$cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
$cd = max(30, min(120, $cd));
if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
$this->error('发送过于频繁,请稍后再试');
}
$code = (string)random_int(100000, 999999);
$ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
$ttl = max(60, min(600, $ttl));
Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
try {
$this->sendBidOpenVerifySms($admin['mobile'], $code);
} catch (\Throwable $e) {
Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
$this->error($e->getMessage());
}
$this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
}
/**
* 开标双重验证 — 两人验证码校验并记录
*/
public function bidOpenVerify()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
$this->error('无权限');
}
$scydgyId = trim((string)$this->request->post('scydgy_id', ''));
$verifier1Id = (int)$this->request->post('verifier1_id', 0);
$verifier2Id = (int)$this->request->post('verifier2_id', 0);
$code1 = trim((string)$this->request->post('code1', ''));
$code2 = trim((string)$this->request->post('code2', ''));
if ($scydgyId === '') {
$this->error('参数无效');
}
if ($verifier1Id <= 0 || $verifier2Id <= 0) {
$this->error('请选择两位验证人');
}
if ($verifier1Id === $verifier2Id) {
$this->error('两位验证人不能相同');
}
if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
$this->error('请输入6位短信验证码');
}
$bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
if ($bundle['pos'] === []) {
$this->error('该订单不在待确认供应商状态');
}
$ccydh = trim((string)($bundle['ccydh'] ?? ''));
if ($ccydh === '') {
$this->error('订单号无效');
}
if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
$this->success('已完成开标验证');
}
if ($this->isProcuremenManualPickedForBundle($bundle)) {
$this->error('本单已指定供应商,无需再开标');
}
$this->assertProcuremenBidOpenAfterDeadline($bundle);
$verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
$verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
if ($verifier1 === null || $verifier2 === null) {
$this->error('验证人无效或未绑定手机号');
}
if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
$this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
}
if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
$this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
}
try {
$this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
} catch (\Throwable $e) {
$this->error($e->getMessage());
}
$this->success('开标验证成功,可查看供应商报价与交货日期');
}
/**
* 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
*/
public function auditManualPick()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
$this->error('无权限');
}
$scydgyId = trim((string)$this->request->post('scydgy_id', ''));
if ($scydgyId === '') {
$this->error('参数无效');
}
$companyName = trim((string)$this->request->post('selected_company', ''));
$reason = trim((string)$this->request->post('pick_reason', ''));
if ($companyName === '') {
$this->error('请选择一家供应商');
}
if ($reason === '') {
$this->error('请填写选择说明');
}
if (mb_strlen($reason) > 500) {
$this->error('选择说明不能超过500字');
}
$this->ensurePurchaseOrderManualPickColumns();
$bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
$pos = $bundle['pos'];
if ($pos === []) {
$this->error('该订单不在待确认供应商状态');
}
if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
$this->error('本单已开标验证,请直接在列表中选定供应商后确认');
}
$quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
if ($quoteGroups === []) {
$this->error('暂无供应商,请确认已完成协助初选通知');
}
$matched = null;
foreach ($quoteGroups as $g) {
if (!is_array($g)) {
continue;
}
if (trim((string)($g['name'] ?? '')) === $companyName) {
$matched = $g;
break;
}
}
if ($matched === null) {
$this->error('所选供应商不在本单报价列表中');
}
$logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
Db::startTrans();
try {
foreach ($pos as $poRow) {
if (!is_array($poRow)) {
continue;
}
$sid = (int)($poRow['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid)) {
continue;
}
Db::table('purchase_order')->where('scydgy_id', $sid)->update([
'pick_company_name' => $companyName,
'manual_pick' => 1,
'manual_pick_reason' => $reason,
]);
}
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$this->error($e->getMessage());
}
foreach ($pos as $poRow) {
if (!is_array($poRow)) {
continue;
}
$sid = (int)($poRow['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid)) {
continue;
}
$poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
$this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
}
// 自选后可见报价:按本单规则计算评分(与开标后一致)
try {
$ccydh = trim((string)($bundle['ccydh'] ?? ''));
if ($ccydh !== '') {
// 重新加载以拿到未掩码报价参与计分
$bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
$groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
}
} catch (\Throwable $e) {
Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
}
$this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
}
/**
* 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
*/
public function auditSubmit()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
$scydgyId = trim((string)$this->request->post('scydgy_id', ''));
if ($scydgyId === '') {
$this->error('参数无效');
}
$bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
$pos = $bundle['pos'];
$mergeRows = $bundle['merge_rows'];
if ($pos === [] || $mergeRows === []) {
$this->error('该订单不在待确认供应商状态');
}
$quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
if ($quoteGroups === []) {
$this->error('暂无供应商报价,请确认已完成协助初选通知');
}
$companyName = trim((string)$this->request->post('selected_company', ''));
if ($companyName === '') {
$this->error('请选择一家供应商');
}
$matched = null;
foreach ($quoteGroups as $g) {
if (!is_array($g)) {
continue;
}
if (trim((string)($g['name'] ?? '')) === $companyName) {
$matched = $g;
break;
}
}
if ($matched === null) {
$this->error('所选供应商不在本单报价列表中');
}
$sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
if ($sysRqDb === '') {
$sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
} else {
// 确认供应商须已过招标截止,允许解析已过期的截止时间
$sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
}
if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
$this->error('未到招标截止日期,暂不可确认');
}
if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
&& !$this->isProcuremenManualPickedForBundle($bundle)
) {
$this->error('请先完成开标双重验证或指定供应商后再确认');
}
$procCnt = count($mergeRows);
$procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
$logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
Db::startTrans();
try {
foreach ($pos as $poRow) {
if (!is_array($poRow)) {
continue;
}
$sid = (int)($poRow['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid)) {
continue;
}
Db::table('purchase_order')->where('scydgy_id', $sid)->update([
'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
'status' => ProcuremenStatus::PO_IN_PROGRESS,
'pick_company_name' => $companyName,
'sys_rq' => $sysRqDb,
]);
}
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$this->error($e->getMessage());
}
foreach ($pos as $poRow) {
if (!is_array($poRow)) {
continue;
}
$sid = (int)($poRow['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid)) {
continue;
}
$poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
$this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
}
$this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
}
/**
* 确认供应商 — 二次发送短信(可选单家/批量/全部)
*/
public function auditResendSms()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
$scydgyId = trim((string)$this->request->post('scydgy_id', ''));
if ($scydgyId === '') {
$this->error('参数无效');
}
$loaded = $this->loadAuditResendBundle($scydgyId);
$mergeRows = $loaded['merge_rows'];
$bundle = $loaded['bundle'];
$bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
$quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
if ($quoteGroups === []) {
$this->error('暂无可通知的供应商');
}
$selectedCompany = trim((string)$this->request->post('selected_company', ''));
$companiesJson = (string)$this->request->post('companies_json', '');
$targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
$this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
}
/**
* 确认供应商 — 二次发送邮件(可选单家/批量)
*/
public function auditResendEmail()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
$scydgyId = trim((string)$this->request->post('scydgy_id', ''));
if ($scydgyId === '') {
$this->error('参数无效');
}
$loaded = $this->loadAuditResendBundle($scydgyId);
$mergeRows = $loaded['merge_rows'];
$bundle = $loaded['bundle'];
$bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
$quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
if ($quoteGroups === []) {
$this->error('暂无可通知的供应商');
}
$companiesJson = (string)$this->request->post('companies_json', '');
$selectedCompany = trim((string)$this->request->post('selected_company', ''));
$targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
if ($companiesJson === '' && $selectedCompany === '') {
$this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
}
$this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
}
/**
* 废弃单个订单 bundle(退回协助初选,明细归档留痕)
*
* @param array{ccydh:string, pos:array, merge_rows:array} $bundle
* @return array 已处理的 scydgy_id 集合
*/
protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
{
$pos = $bundle['pos'] ?? [];
if (!is_array($pos) || $pos === []) {
return [];
}
$sids = [];
$poIdBySid = [];
foreach ($pos as $poRow) {
if (!is_array($poRow)) {
continue;
}
$sid = (int)($poRow['scydgy_id'] ?? 0);
if ($this->isValidScydgyRowId($sid)) {
$sids[$sid] = true;
$poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
if ($poId > 0) {
$poIdBySid[$sid] = $poId;
}
}
}
if ($sids === []) {
return [];
}
$logMsg = '重新下发';
$suffix = trim((string)$logSuffix, ',, ');
if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
$logMsg .= ':从历史存证退回协助初选';
} else {
$logMsg .= ':退回协助初选';
}
Db::table('purchase_order')
->where('scydgy_id', 'in', array_keys($sids))
->update([
'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
'status' => ProcuremenStatus::PO_IN_PROGRESS,
'pick_company_name' => '',
'pick_time' => null,
'sys_rq' => null,
'mod_rq' => null,
]);
$this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
foreach (array_keys($sids) as $sid) {
$poIdLog = (int)($poIdBySid[$sid] ?? 0);
$this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
}
return $sids;
}
/**
* 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
*
* @return array{ccydh:string, pos:array, merge_rows:array}
*/
protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
{
$scydgyId = trim($scydgyId);
$empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
if ($scydgyId === '') {
return $empty;
}
try {
$anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
} catch (\Throwable $e) {
$anchor = null;
}
if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
return $empty;
}
$ccydh = trim((string)($anchor['CCYDH'] ?? ''));
if ($ccydh === '') {
return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
}
try {
$query = Db::table('purchase_order')->where('CCYDH', $ccydh);
$query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
$pos = $query->order('scydgy_id', 'asc')->select();
} catch (\Throwable $e) {
$pos = [$anchor];
}
if (!is_array($pos) || $pos === []) {
$pos = [$anchor];
}
return [
'ccydh' => $ccydh,
'pos' => $pos,
'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
];
}
protected function purchaseOrderRowIsCompleted(array $po): bool
{
return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
}
/**
* 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
*
* @return array{ccydh:string, pos:array, merge_rows:array}
*/
protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
{
$scydgyId = trim($scydgyId);
$empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
if ($scydgyId === '') {
return $empty;
}
try {
$anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
} catch (\Throwable $e) {
$anchor = null;
}
if (!is_array($anchor)) {
return $empty;
}
$ccydh = trim((string)($anchor['CCYDH'] ?? ''));
if ($ccydh === '') {
return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
}
try {
$pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
} catch (\Throwable $e) {
$pos = [$anchor];
}
if (!is_array($pos) || $pos === []) {
$pos = [$anchor];
}
return [
'ccydh' => $ccydh,
'pos' => $pos,
'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
];
}
/**
* 废弃订单 — 退回协助初选重新询价(支持单条或批量)
* 统一入口:待确认 / 已完结 / 其它状态均可重新下发
*/
public function auditAbandon()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
$anchorIds = [];
$batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
if ($batchRaw !== '') {
$decoded = json_decode($batchRaw, true);
if (is_array($decoded)) {
foreach ($decoded as $id) {
$s = trim((string)$id);
if ($s !== '') {
$anchorIds[] = $s;
}
}
}
}
if ($anchorIds === []) {
$single = trim((string)$this->request->post('scydgy_id', ''));
if ($single !== '') {
$anchorIds[] = $single;
}
}
if ($anchorIds === []) {
$this->error('请至少选择一条订单');
}
$processedCcydh = [];
$doneOrders = 0;
$allSids = [];
Db::startTrans();
try {
foreach ($anchorIds as $anchorId) {
$fromArchive = false;
$bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
if (($bundle['pos'] ?? []) === []) {
$bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
$fromArchive = ($bundle['pos'] ?? []) !== [];
}
if (($bundle['pos'] ?? []) === []) {
$bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
$fromArchive = ($bundle['pos'] ?? []) !== [];
}
if (($bundle['pos'] ?? []) === []) {
continue;
}
$ccydh = trim((string)($bundle['ccydh'] ?? ''));
$dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
if (isset($processedCcydh[$dedupeKey])) {
continue;
}
$processedCcydh[$dedupeKey] = true;
$sids = $fromArchive
? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
: $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
if ($sids === []) {
continue;
}
$doneOrders++;
foreach (array_keys($sids) as $sid) {
$allSids[(int)$sid] = true;
}
}
if ($doneOrders < 1) {
throw new \Exception('未找到可重新下发的订单,请刷新后重试');
}
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->pickHiddenScydgySetCache = null;
$msg = $doneOrders > 1
? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
: '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
$this->success($msg);
}
/**
* @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
*/
public function archiveAbandon()
{
return $this->auditAbandon();
}
/**
* 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
*/
public function purchaseApprovalReject()
{
if (!$this->request->isPost() || !$this->request->isAjax()) {
$this->error(__('Invalid parameters'));
}
if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
$this->error(__('You have no permission'));
}
$batchRaw = trim((string)$this->request->post('order_picks_json', ''));
$decoded = json_decode($batchRaw, true);
if (!is_array($decoded) || $decoded === []) {
$this->error('提交数据无效');
}
$done = 0;
Db::startTrans();
try {
foreach ($decoded as $item) {
if (!is_array($item)) {
continue;
}
$sid = (int)($item['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid)) {
continue;
}
$this->runPurchaseApprovalRejectForSid($sid);
$done++;
}
if ($done < 1) {
throw new \Exception('所选订单均不在待审批状态');
}
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
$this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
}
$this->pickHiddenScydgySetCache = null;
$this->success('已驳回并退回「协助审批下发」');
}
/**
* @throws \Exception
*/
protected function runPurchaseApprovalRejectForSid(int $sid): void
{
$poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
$allIds = $this->purchaseOrderDetail($sid);
if ($allIds === []) {
throw new \Exception('未找到下发明细');
}
Db::table('purchase_order')->where('scydgy_id', $sid)->update([
'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
'status' => ProcuremenStatus::PO_IN_PROGRESS,
'pick_company_name' => '',
]);
Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
$this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
$poId = 0;
try {
$po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
if (is_array($po)) {
$poId = (int)($po['id'] ?? $po['ID'] ?? 0);
}
} catch (\Throwable $e) {
}
$this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
}
/**
* 审核弹窗(旧入口,POST 已关闭)
*/
public function review()
{
if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
$this->error(__('You have no permission'));
}
if ($this->request->isPost()) {
$this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
}
$this->view->assign('pickMode', 0);
return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
}
/**
* 审核弹窗获取公司列表
*/
public function reviewCompanies()
{
if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
$this->error(__('You have no permission'));
}
if (!$this->request->isAjax()) {
$this->error(__('Invalid parameters'));
}
$list = [];
try {
// 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
$rows = Db::table('customer')
->where(function ($q) {
$q->where('status', 1)
->whereOr('status', '1')
->whereOr('status', '')
->whereNull('status');
})
->order('id', 'desc')
->select();
} catch (\Throwable $e) {
$this->success('', '', []);
return;
}
if (!is_array($rows)) {
$this->success('', '', []);
return;
}
$detailColCandidates = [
'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
'company_detail', 'company_desc', 'address',
];
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$norm = [];
foreach ($row as $k => $v) {
$norm[is_string($k) ? strtolower($k) : $k] = $v;
}
$row = $norm;
$st = $row['status'] ?? '';
if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
continue;
}
$payload = $this->buildCustomerContactPayloadFromRow($row);
if ($payload === null) {
continue;
}
$detail = '';
foreach ($detailColCandidates as $dk) {
if (!isset($row[$dk])) {
continue;
}
$dv = trim((string)$row[$dk]);
if ($dv !== '') {
$detail = $dv;
break;
}
}
$payload['detail'] = $detail;
$list[] = $this->maskSupplierContactFields($payload);
}
$this->success('', '', $list);
}
/**
* 采购确认-下发明细弹窗:
* 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
*/
public function outward_detail()
{
$ids = $this->request->param('ids', $this->request->param('id', ''));
if (is_array($ids)) {
$ids = isset($ids[0]) ? $ids[0] : '';
}
$ids = trim((string)$ids);
if ($ids === '') {
$this->error(__('Invalid parameters'));
}
$wffTab = trim((string)$this->request->param('wff_tab', 'all'));
if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
$wffTab = 'all';
}
$isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
$purchaseOrderId = 0;
$po = null;
try {
$po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
if (is_array($po)) {
$purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
}
} catch (\Throwable $e) {
$purchaseOrderId = 0;
$po = null;
}
if (!$isPurchaseConfirm && is_array($po)) {
$isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
$isPurchaseConfirm = true;
}
}
$headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
$confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
$confirmProcessCount = 1;
$confirmPickGroups = [];
$processDisplayRows = [];
$allDetailsBySid = [];
$requiredSidList = [];
$sidList = [$ids];
if ($isPurchaseConfirm) {
$confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
$mergeRows = $confirmBundle['merge_rows'] ?? [];
if ($mergeRows !== []) {
$processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
}
$confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
if ($confirmBundle['pos'] !== []) {
$sidList = [];
foreach ($confirmBundle['pos'] as $poRow) {
if (!is_array($poRow)) {
continue;
}
$sid = (int)($poRow['scydgy_id'] ?? 0);
if (!$this->isValidScydgyRowId($sid)) {
continue;
}
$sidList[] = (string)$sid;
$requiredSidList[] = $sid;
}
}
if ($sidList === []) {
$sidList = [$ids];
$requiredSidList = [(int)$ids];
}
$confirmProcessCount = max(1, count($requiredSidList));
if (is_array($po) && $purchaseOrderId <= 0) {
$purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
}
}
$rows = [];
try {
if (count($sidList) === 1) {
$rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
} else {
$rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
}
} catch (\Throwable $e) {
$rows = [];
}
if ($isPurchaseConfirm) {
$allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
}
foreach ($rows as &$r) {
if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
$r['id'] = $r['ID'];
}
if (isset($r['createtime'])) {
if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
$r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
} else {
$r['createtime_text'] = (string)$r['createtime'];
}
} else {
$r['createtime_text'] = '';
}
if (is_array($r)) {
$r = $this->maskSupplierContactFields($r);
}
}
unset($r);
$pickedCompanyName = '';
$manualPicked = 0;
$manualPickReason = '';
$quoteVisible = 0;
$bidOpenVerified = 0;
if ($isPurchaseConfirm) {
// 确认包为空时,用当前主单兜底,避免指定说明读不到
if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
$confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
}
if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
$confirmBundle['pos'] = [$po];
}
$manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
$manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
$manualPickReason = (string)($manualPickInfo['reason'] ?? '');
if ($manualPickInfo['company'] !== '') {
$pickedCompanyName = $manualPickInfo['company'];
}
if ($pickedCompanyName === '') {
foreach ($confirmBundle['pos'] ?? [] as $poRow) {
if (!is_array($poRow)) {
continue;
}
$pn = trim((string)($poRow['pick_company_name'] ?? ''));
if ($pn !== '') {
$pickedCompanyName = $pn;
break;
}
}
}
// 再兜底:直接读当前主单字段
if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
$manualPicked = 1;
if ($manualPickReason === '') {
$manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
}
if ($pickedCompanyName === '') {
$pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
}
}
$bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
$quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
}
$this->view->assign('rows', $rows ?: []);
$this->view->assign('rowCount', count($rows ?: []));
$this->view->assign('scydgyId', $ids);
$this->view->assign('purchaseOrderId', $purchaseOrderId);
$this->view->assign('headTitle', $headTitle);
$this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
$this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
$this->view->assign('confirmProcessCount', $confirmProcessCount);
$this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
$this->view->assign('processDisplayRows', $processDisplayRows);
$this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
$this->view->assign('confirmPickCount', count($confirmPickGroups));
$this->view->assign('pickedCompanyName', $pickedCompanyName);
$this->view->assign('manualPicked', $manualPicked);
$this->view->assign('manualPickReason', $manualPickReason);
$this->view->assign('bidOpenVerified', $bidOpenVerified);
$this->view->assign('quoteVisible', $quoteVisible);
$orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
$this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
$this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
$this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
$sysRqDisplay = '—';
if ($isPurchaseConfirm) {
$sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
$this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
);
}
$this->view->assign('sysRqDisplay', $sysRqDisplay);
$this->view->assign('sysRq', $isPurchaseConfirm
? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
: '');
$this->view->assign('deliveryDeadline', $isPurchaseConfirm
? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
: '');
$this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
$this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
/* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
if ($isPurchaseConfirm) {
return $this->view->fetch();
}
$restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
$this->view->engine->layout(false);
try {
$bodyHtml = $this->view->fetch('procuremen/outward_detail');
$this->view->assign('dialogBody', $bodyHtml);
return $this->view->fetch('procuremen/outward_detail_lite_shell');
} finally {
if ($restoreLayout) {
$this->view->engine->layout($restoreLayout);
}
}
}
/**
* 月度导出记录表(不存在时自动创建)
*/
protected function ensurePurchaseMonthExportLogTable(): void
{
try {
Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
} catch (\Throwable $e) {
Db::execute(
"CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`ym` char(7) NOT NULL COMMENT 'YYYY-MM',
`admin_id` int(10) unsigned NOT NULL DEFAULT 0,
`admin_name` varchar(64) NOT NULL DEFAULT '',
`row_count` int(10) unsigned NOT NULL DEFAULT 0,
`total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
`createtime` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_ym` (`ym`),
KEY `idx_ct` (`createtime`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
);
}
}
/**
* 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
*
* @param array $dbRows
* @return array>
*/
protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
{
$keyword = trim((string)$this->request->get('search', ''));
if ($keyword === '') {
$keyword = trim((string)$this->request->request('search', ''));
}
$filter = $this->request->get('filter', '');
$op = $this->request->get('op', '');
if (is_string($filter) && $filter !== '') {
$filterArr = (array)json_decode($filter, true);
} else {
$filterArr = is_array($filter) ? $filter : [];
}
if (is_string($op) && $op !== '') {
$opArr = (array)json_decode($op, true);
} else {
$opArr = is_array($op) ? $op : [];
}
if ($keyword === '' && $filterArr === []) {
return array_values(array_filter($dbRows, 'is_array'));
}
$searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
$out = [];
foreach ($dbRows as $row) {
if (!is_array($row)) {
continue;
}
if ($keyword !== '') {
$hit = false;
foreach ($searchFields as $f) {
if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
$hit = true;
break;
}
}
if (!$hit) {
continue;
}
}
$passFilter = true;
foreach ($filterArr as $field => $val) {
$field = (string)$field;
$val = trim((string)$val);
if ($field === '' || $val === '') {
continue;
}
if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
continue;
}
$cell = (string)($row[$field] ?? '');
$mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
if ($mode === '=' || $mode === 'EQUAL') {
if (strcasecmp($cell, $val) !== 0) {
$passFilter = false;
break;
}
} elseif (mb_stripos($cell, $val) === false) {
$passFilter = false;
break;
}
}
if (!$passFilter) {
continue;
}
$out[] = $row;
}
return $out;
}
/**
* 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
* 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
*/
public function export_month_outward()
{
if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
$this->error(__('You have no permission'));
}
$bundle = $this->prepareMonthOutwardExportBundle();
$ym = (string)($bundle['ym'] ?? date('Y-m'));
$exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
$groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('外协加工明细');
$mon = (int)substr($ym, 5, 2);
$sheet->mergeCells('A1:H1');
$sheet->setCellValue('A1', $mon . '月份外协加工明细');
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
$sheet->getStyle('A1')->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER)
->setVertical(Alignment::VERTICAL_CENTER);
$headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
$col = 'A';
foreach ($headers as $h) {
$sheet->setCellValue($col . '2', $h);
$col++;
}
$sheet->getStyle('A2:H2')->getFont()->setBold(true);
$sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$rowNum = 3;
$sumSubtotalCounts = 0;
$grandAmount = 0.0;
$globalSeq = 0;
if ($groups === []) {
$sheet->mergeCells('A3:H3');
$sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
$sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$rowNum = 4;
} else {
foreach ($groups as $items) {
if ($items === []) {
continue;
}
$groupLineCount = count($items);
$subAmount = 0.0;
foreach ($items as $line) {
$globalSeq++;
$dr = $line['detail'];
$amt = $this->procuremenExportAmount($dr);
$subAmount += $amt;
$sheet->setCellValue('A' . $rowNum, $globalSeq);
$sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
$sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
$sheet->setCellValue('D' . $rowNum, $line['company_name']);
$sheet->setCellValue('E' . $rowNum, $line['CDF']);
$sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
$sheet->setCellValue('G' . $rowNum, $line['gx']);
$sheet->setCellValue('H' . $rowNum, $amt);
$sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
$rowNum++;
}
$sumSubtotalCounts += $groupLineCount;
$grandAmount += $subAmount;
$sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
$sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
$sheet->getStyle('G' . $rowNum)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_LEFT)
->setVertical(Alignment::VERTICAL_CENTER);
$rowNum++;
}
}
$sheet->setCellValue('A' . $rowNum, '总计');
$sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
$sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
$sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
$sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
$sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
$lastRow = $rowNum;
$sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => '000000'],
],
],
]);
$sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
if ($lastRow >= 3) {
$sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
$sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
$sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
$sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
}
$this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
$sheet->getColumnDimension('A')->setWidth(7);
$sheet->getColumnDimension('B')->setWidth(16);
$sheet->getColumnDimension('C')->setWidth(52);
$sheet->getColumnDimension('D')->setWidth(32);
$sheet->getColumnDimension('E')->setWidth(12);
$sheet->getColumnDimension('F')->setWidth(44);
$sheet->getColumnDimension('G')->setWidth(26);
$sheet->getColumnDimension('H')->setWidth(13);
$sheet->getRowDimension(1)->setRowHeight(28);
$ymCompact = str_replace('-', '', $ym);
$fileBase = $mon . '月份外协加工明细_' . $ymCompact;
$filename = $fileBase . '.xlsx';
try {
$this->ensurePurchaseMonthExportLogTable();
list($adminId, $adminName) = $this->GetUseName();
Db::table('purchase_month_export_log')->insert([
'ym' => $ym,
'admin_id' => (int)$adminId,
'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
'row_count' => count($exportLines),
'total_amount' => round($grandAmount, 2),
'createtime' => time(),
]);
} catch (\Throwable $e) {
Log::write('month export log: ' . $e->getMessage(), 'error');
}
if (ob_get_length()) {
ob_end_clean();
}
$asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
exit;
}
/**
* 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
*/
public function export_month_quote()
{
if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
$this->error(__('You have no permission'));
}
$bundle = $this->prepareMonthOutwardExportBundle();
$ym = (string)($bundle['ym'] ?? date('Y-m'));
$detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
$mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
$quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('供应商报价明细');
$mon = (int)substr($ym, 5, 2);
$quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
$sheet->getColumnDimension('A')->setWidth(7);
$sheet->getColumnDimension('B')->setWidth(16);
$sheet->getColumnDimension('C')->setWidth(52);
$sheet->getColumnDimension('D')->setWidth(26);
$sheet->getColumnDimension('E')->setWidth(32);
$sheet->getColumnDimension('F')->setWidth(12);
$sheet->getColumnDimension('G')->setWidth(14);
$sheet->getColumnDimension('H')->setWidth(12);
if ($quoteLastRow < 1) {
$quoteLastRow = 3;
}
$ymCompact = str_replace('-', '', $ym);
$filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
if (ob_get_length()) {
ob_end_clean();
}
$asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
exit;
}
/**
* 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
*
* @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
*/
protected function prepareMonthOutwardExportBundle(): array
{
$this->request->filter(['strip_tags', 'trim']);
$ym = trim((string)$this->request->get('ym', date('Y-m')));
if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
$ym = date('Y-m');
}
$dbRows = [];
try {
$query = Db::table('purchase_order');
$query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
$dbRows = $query->select();
} catch (\Throwable $e) {
$dbRows = [];
}
if (!is_array($dbRows)) {
$dbRows = [];
}
$completeTsMap = [];
$sidList = [];
foreach ($dbRows as $dbRow) {
if (!is_array($dbRow)) {
continue;
}
$sid = (int)($dbRow['scydgy_id'] ?? 0);
if ($sid > 0) {
$sidList[$sid] = true;
}
}
if ($sidList !== []) {
$completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
}
$searchKw = trim((string)$this->request->get('search', ''));
if ($searchKw === '') {
$searchKw = trim((string)$this->request->request('search', ''));
}
$filterRaw = $this->request->get('filter', '');
$filterArrTmp = [];
if (is_string($filterRaw) && $filterRaw !== '') {
$filterArrTmp = (array)json_decode($filterRaw, true);
} elseif (is_array($filterRaw)) {
$filterArrTmp = $filterRaw;
}
$hasSearch = ($searchKw !== '');
if (!$hasSearch) {
foreach ($filterArrTmp as $fv) {
if (trim((string)$fv) !== '') {
$hasSearch = true;
break;
}
}
}
$dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
if (!is_array($dbRow)) {
return false;
}
$done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
if ($done['ts'] <= 0) {
return false;
}
if ($hasSearch) {
return true;
}
return date('Y-m', $done['ts']) === $ym;
}));
$dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
$pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
$mainBySid = [];
foreach ($pool as $rw) {
if (!is_array($rw)) {
continue;
}
$rid = (int)($rw['ID'] ?? 0);
if ($rid > 0) {
$mainBySid[$rid] = $rw;
}
}
if ($mainBySid === []) {
$detailRows = [];
} else {
try {
$detailRows = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($mainBySid))
->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
->order('status', 'desc')
->order('CCYDH', 'asc')
->order('company_name', 'asc')
->order('id', 'asc')
->select();
} catch (\Throwable $e) {
try {
$detailRows = Db::table('purchase_order_detail')
->where('scydgy_id', 'in', array_keys($mainBySid))
->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
->order('status', 'desc')
->order('CCYDH', 'asc')
->order('company_name', 'asc')
->order('ID', 'asc')
->select();
} catch (\Throwable $e2) {
$detailRows = [];
}
}
}
if (!is_array($detailRows)) {
$detailRows = [];
}
$exportLines = [];
$detailSidSeen = [];
foreach ($detailRows as $dr) {
if (!is_array($dr)) {
continue;
}
$sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
if ($sid <= 0 || !isset($mainBySid[$sid])) {
continue;
}
if (isset($detailSidSeen[$sid])) {
continue;
}
if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
continue;
}
$detailSidSeen[$sid] = true;
$m = $mainBySid[$sid];
$exportLines[] = [
'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
'company_name' => (string)($dr['company_name'] ?? ''),
'CDF' => (string)($m['CDF'] ?? ''),
'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
'gx' => $this->procuremenExportGxText($m),
'detail' => $dr,
];
}
foreach ($detailRows as $dr) {
if (!is_array($dr)) {
continue;
}
$sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
continue;
}
$detailSidSeen[$sid] = true;
$m = $mainBySid[$sid];
$exportLines[] = [
'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
'company_name' => (string)($dr['company_name'] ?? ''),
'CDF' => (string)($m['CDF'] ?? ''),
'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
'gx' => $this->procuremenExportGxText($m),
'detail' => $dr,
];
}
foreach ($mainBySid as $sid => $m) {
if (isset($detailSidSeen[$sid])) {
continue;
}
$company = trim((string)($m['pick_company_name'] ?? ''));
$exportLines[] = [
'CCYDH' => (string)($m['CCYDH'] ?? ''),
'CYJMC' => (string)($m['CYJMC'] ?? ''),
'company_name' => $company,
'CDF' => (string)($m['CDF'] ?? ''),
'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
'gx' => $this->procuremenExportGxText($m),
'detail' => [],
];
}
$groups = [];
foreach ($exportLines as $line) {
$k = $line['CCYDH'] . "\x1f" . $line['company_name'];
if (!isset($groups[$k])) {
$groups[$k] = [];
}
$groups[$k][] = $line;
}
ksort($groups, SORT_STRING);
return [
'ym' => $ym,
'mainBySid' => $mainBySid,
'detailRows' => $detailRows,
'exportLines' => $exportLines,
'groups' => $groups,
];
}
/**
* 导出用:工序列文案
*/
protected function procuremenExportGxText(array $r)
{
$a = trim((string)($r['CDXMC'] ?? ''));
$b = trim((string)($r['CGYMC'] ?? ''));
if ($a !== '' && $b !== '') {
return $a . ':' . $b;
}
return $a !== '' ? $a : $b;
}
/**
* 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
*/
protected function procuremenExportAmount(array $r)
{
foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
if (!array_key_exists($k, $r)) {
continue;
}
$v = $r[$k];
if ($v === null || $v === '') {
continue;
}
if (is_numeric($v)) {
return (float)$v;
}
$v = preg_replace('/[^\d\.\-]/', '', (string)$v);
if ($v !== '' && is_numeric($v)) {
return (float)$v;
}
}
return 0.0;
}
/**
* 月度导出:各工序下所有下发供应商的报价明细(含未中标)
*
* @param array> $detailRows
* @param array> $mainBySid
* @return array>
*/
protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
{
$lines = [];
foreach ($detailRows as $dr) {
if (!is_array($dr)) {
continue;
}
$sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
if ($sid <= 0 || !isset($mainBySid[$sid])) {
continue;
}
if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
continue;
}
$cn = trim((string)($dr['company_name'] ?? ''));
if ($cn === '') {
continue;
}
$m = $mainBySid[$sid];
$am = trim((string)($dr['amount'] ?? ''));
$amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
$amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
$amountText = $amountFilled
? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
: '未填写';
$deliveryRaw = trim((string)($dr['delivery'] ?? ''));
$deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
if ($deliveryShow === '' && $deliveryRaw !== '') {
$deliveryShow = $deliveryRaw;
}
$deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
? $deliveryShow
: '未填写';
$picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
$lines[] = [
'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
'gx' => $this->procuremenExportGxText($m),
'company_name' => $cn,
'amount_text' => $amountText,
'amount_num' => $amountFilled ? $amountNum : null,
'delivery_text' => $deliveryText,
'picked_text' => $picked ? '中标' : '未中标',
'picked' => $picked,
];
}
$winnerSupplierByOrder = [];
foreach ($lines as $line) {
$dh = trim((string)($line['CCYDH'] ?? ''));
$cn = trim((string)($line['company_name'] ?? ''));
if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
$winnerSupplierByOrder[$dh][$cn] = true;
}
}
usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
$c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
if ($c !== 0) {
return $c;
}
$dh = trim((string)($a['CCYDH'] ?? ''));
$aCn = trim((string)($a['company_name'] ?? ''));
$bCn = trim((string)($b['company_name'] ?? ''));
$aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
$bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
if ($aSupplierWin !== $bSupplierWin) {
return $aSupplierWin ? -1 : 1;
}
$c = strcmp($aCn, $bCn);
if ($c !== 0) {
return $c;
}
if (!empty($a['picked']) !== !empty($b['picked'])) {
return !empty($a['picked']) ? -1 : 1;
}
$c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
if ($c !== 0) {
return $c;
}
return 0;
});
return $lines;
}
/**
* 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
*
* @param array> $quoteLines
*/
protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
{
$mon = (int)substr($ym, 5, 2);
$titleRow = $startRow;
$headerRow = $startRow + 1;
$dataStartRow = $startRow + 2;
$sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
$sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
$sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
$sheet->getStyle('A' . $titleRow)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER)
->setVertical(Alignment::VERTICAL_CENTER);
$headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
$col = 'A';
foreach ($headers as $h) {
$sheet->setCellValue($col . $headerRow, $h);
$col++;
}
$sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
$sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$rowNum = $dataStartRow;
if ($quoteLines === []) {
$sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
$sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
$sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$rowNum = $dataStartRow + 1;
} else {
$i = 0;
foreach ($quoteLines as $line) {
$i++;
$sheet->setCellValue('A' . $rowNum, $i);
$sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
$sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
$sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
$sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
if ($line['amount_num'] !== null) {
$sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
$sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
} else {
$sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
}
$sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
$sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
if (!empty($line['picked'])) {
$sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
}
$rowNum++;
}
}
$lastRow = $rowNum - 1;
if ($lastRow >= $headerRow) {
$sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => '000000'],
],
],
]);
$sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
$sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
$sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
$sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
$sheet->getRowDimension($titleRow)->setRowHeight(28);
if ($lastRow >= $dataStartRow) {
$this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
}
}
return $lastRow;
}
/**
* 月度导出表格对齐:表头居中、序号列居中、其余列居左
*/
protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
{
if ($lastRow < $dataStartRow || $headerRow < 1) {
return;
}
$sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER)
->setVertical(Alignment::VERTICAL_CENTER);
$sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER)
->setVertical(Alignment::VERTICAL_CENTER);
if ($lastCol > 'B') {
$sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_LEFT)
->setVertical(Alignment::VERTICAL_CENTER);
}
}
/**
* 订单号等用于 PDF 文件名片段(去掉路径非法字符)
*/
protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
{
$s = trim($ccydh);
if ($s === '') {
return 'ORDER';
}
$s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
$s = trim($s, '._-');
if ($s === '') {
return 'ORDER';
}
if (function_exists('mb_substr')) {
return mb_substr($s, 0, 80, 'UTF-8');
}
return strlen($s) <= 80 ? $s : substr($s, 0, 80);
}
/**
* 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
* xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
*
* @return array{objectKey: string, webPath: string}
*/
protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
{
$sid = (int)$scydgyId;
$safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
$y = date('Y');
$m = date('m');
$d = date('d');
$basename = $safeOrder . '_' . $sid . '.pdf';
$objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
return [
'objectKey' => $objectKey,
'webPath' => '/' . $objectKey,
];
}
/**
* 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
* 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
* 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
*
* @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
*/
protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
{
if (!$this->isValidScydgyRowId($scydgyId)) {
return '';
}
$ids = trim((string)$scydgyId);
$prep = $this->prepareProcuremenDetailsView($ids);
if (!$prep['ok']) {
return '';
}
$ccydh = $prep['ccydh'];
$paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
$objectKey = $paths['objectKey'];
$webPath = $paths['webPath'];
$meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
$this->view->assign([
'pdf_export' => 1,
'pdfMetaLine' => $meta,
]);
// 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
$restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
$this->view->engine->layout(false);
try {
$html = $this->view->fetch('procuremen/details_pdf_shell');
} catch (\Throwable $e) {
if ($restoreLayout) {
$this->view->engine->layout($restoreLayout);
}
Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
$this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
return '';
}
if ($restoreLayout) {
$this->view->engine->layout($restoreLayout);
}
$this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
$tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
if (!is_dir($tempDir)) {
@mkdir($tempDir, 0755, true);
}
$tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
try {
$mpdf = new \Mpdf\Mpdf([
'mode' => 'utf-8',
'format' => 'A4',
'margin_left' => 12,
'margin_right' => 12,
'margin_top' => 14,
'margin_bottom' => 14,
'tempDir' => $tempDir,
'autoScriptToLang' => true,
'autoLangToFont' => true,
]);
// 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
// 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
$mpdf->SetBasePath('http://127.0.0.1/');
$mpdf->WriteHTML($html);
$mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
} catch (\Throwable $e) {
Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
if (is_file($tempPdf)) {
@unlink($tempPdf);
}
return '';
}
$ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
if ($ossUrl !== '') {
@unlink($tempPdf);
$this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
return $ossUrl;
}
$pi = pathinfo($objectKey);
$dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
$baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
if ($baseFile === '') {
@unlink($tempPdf);
return '';
}
$dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
@unlink($tempPdf);
return '';
}
$fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
if (!@copy($tempPdf, $fullPath)) {
Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
@unlink($tempPdf);
return '';
}
@unlink($tempPdf);
$this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
return $webPath;
}
/**
* 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
*/
protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
{
if ($scydgyId <= 0 || $webPath === '') {
return;
}
try {
Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
} catch (\Throwable $e) {
Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
}
}
/**
* 整理短信变量:去空格;联系人姓名为空时用公司名称
*
* @param array $vars
* @return array
*/
protected function normalizeSmsTemplateVars(array $vars): array
{
$out = [];
foreach ($vars as $k => $v) {
$out[(string)$k] = trim((string)$v);
}
if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
$out['contact_name'] = $out['company_name'];
}
return $out;
}
/**
* 按手机号或公司名称查 customer 表联系人姓名
*/
protected function resolveCustomerContactName(string $phone, string $companyName): string
{
$phone = trim($phone);
$companyName = trim($companyName);
try {
if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
$row = Db::table('customer')
->where(function ($q) use ($phone) {
$q->where('phone', $phone)->whereOr('account', $phone);
})
->order('id', 'asc')
->find();
if (is_array($row)) {
$nm = trim((string)($row['username'] ?? ''));
if ($nm !== '') {
return $nm;
}
}
}
if ($companyName !== '') {
$row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
if (is_array($row)) {
return trim((string)($row['username'] ?? ''));
}
}
} catch (\Throwable $e) {
}
return '';
}
/**
* 模版纯文本转邮件 HTML:换行转 <br>,保留已替换进的 <a> 等标签
*/
protected function plainTextToHtmlEmailBody(string $text): string
{
$text = str_replace(["\r\n", "\r"], "\n", (string)$text);
$parts = explode("\n", $text);
$out = [];
foreach ($parts as $line) {
if (preg_match('/]*href=/i', $line)) {
$out[] = $line;
} else {
$out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
}
}
return implode("
\n", $out);
}
/**
* 短信场景:去掉链接类变量,避免误填 URL
*
* @param array $vars
* @return array
*/
protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
{
if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
return $vars;
}
foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
$vars[$k] = '';
}
return $vars;
}
/**
* 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
*
* @param array $vars
*/
protected function renderNotifyTemplate(string $scene, array $vars): string
{
$vars = $this->normalizeSmsTemplateVars($vars);
$vars = $this->stripLinkVarsForSmsScene($scene, $vars);
$row = $this->loadNotifyTemplateRow($scene);
if ($row === null) {
throw new \Exception($this->notifyTemplateMissingMessage($scene));
}
$tpl = trim((string)($row['content'] ?? ''));
if ($tpl === '') {
throw new \Exception($this->notifyTemplateMissingMessage($scene));
}
foreach ($vars as $k => $v) {
$tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
}
// 未传入的占位符置空,避免短信出现 {process_lines} 等原文
$tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
return $tpl;
}
protected function resolveProcuremenEmailSubject(string $scene): string
{
// 询价通知业务员 / 供应商询价:模版名称即邮件主题
if ($scene === 'rfq_salesman_email' || $scene === 'rfq_supplier_email') {
$row = $this->loadNotifyTemplateRow($scene);
$title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
if ($title !== '') {
return $title;
}
return $scene === 'rfq_supplier_email' ? '供应商询价通知' : '协助采购询价通知';
}
$map = [
'review_email' => '您有新的协助加工订单',
];
$subject = trim((string)($map[$scene] ?? ''));
if ($subject === '') {
$this->error('未配置邮件主题:' . $scene);
}
return $subject;
}
protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
{
$map = [
'review_email' => '协助下发-邮箱',
'review_sms' => '协助下发-短信',
'confirm_ok' => '采购确认-通过',
'confirm_fail' => '采购确认-未通过',
'bid_open' => '开标双重验证',
'rfq_salesman_email' => '询价通知业务员-邮箱',
'rfq_supplier_email' => '供应商询价通知',
];
$label = $map[$scene] ?? $scene;
if ($titleRequired) {
return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
}
return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
}
/**
* 是否开启协助通知演练(不发真实短信/邮件)
*/
protected function isProcuremenNotifyDryRun(): bool
{
return (bool)Config::get('procuremen_notify_dry_run');
}
/**
* @param array $payload
*/
protected function recordNotifyDryRunPreview(array $payload): void
{
$this->notifyDryRunPreview[] = $payload;
Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
}
/**
* 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
* @throws \Exception
*/
protected function smsbao($phone, $content)
{
if ($this->isProcuremenNotifyDryRun()) {
$this->recordNotifyDryRunPreview([
'scene' => 'sms_only',
'phone' => $phone,
'sms_content' => $content,
]);
return;
}
$statusStr = [
'0' => '短信发送成功',
'-1' => '参数不全',
'-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
'30' => '密码错误',
'40' => '账号不存在',
'41' => '余额不足',
'42' => '帐户已过期',
'43' => 'IP地址限制',
'50' => '内容含有敏感词',
];
$smsapi = 'http://api.smsbao.com/';
$user = 'zhuwei123';
$pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
$sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
$result = @file_get_contents($sendurl);
if ($result === false) {
\think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
}
$result = trim((string)$result);
if ($result !== '0') {
$msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
\think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
}
}
}