Procuremen.php 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use PHPMailer\PHPMailer\PHPMailer;
  6. use think\Config;
  7. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  8. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  9. use PhpOffice\PhpSpreadsheet\Style\Border;
  10. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  11. use think\Db;
  12. use think\Log;
  13. class Procuremen extends Backend
  14. {
  15. /**
  16. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  17. */
  18. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,a.CDXMC,a.cGzzxMc';
  19. /**
  20. * Procuremen模型对象
  21. * @var \app\admin\model\Procuremen
  22. */
  23. protected $model = null;
  24. /**
  25. * @var array
  26. */
  27. protected $noNeedRight = ['review', 'reviewCompanies', 'outward_detail', 'export_month_outward', 'snapshotToProcure'];
  28. public function _initialize()
  29. {
  30. parent::_initialize();
  31. $this->model = new \app\admin\model\Procuremen;
  32. }
  33. /**
  34. * 手机端外发明细首页直达链接(登录后打开对应明细,免搜索)
  35. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  36. *
  37. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  38. */
  39. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  40. {
  41. static $mprocCfgLoaded = false;
  42. if (!$mprocCfgLoaded) {
  43. $mprocCfgLoaded = true;
  44. if (is_file(APP_PATH . 'extra/mproc.php')) {
  45. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  46. }
  47. }
  48. $eid = (int)$purchaseOrderDetailId;
  49. $base = $this->resolveMprocMobilePublicBaseUrl();
  50. if ($base === '') {
  51. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  52. }
  53. $path = trim((string)Config::get('mproc.mobile_index_path'));
  54. if ($path === '') {
  55. $path = '/index.php/index/index/index';
  56. } else {
  57. $path = '/' . ltrim($path, '/');
  58. }
  59. $query = ['main_tab' => 'orders'];
  60. if ($eid > 0) {
  61. $query['focus_eid'] = $eid;
  62. }
  63. return $base . $path . '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986);
  64. }
  65. /**
  66. * 邮件/短信外链:须为带点的公网域名
  67. */
  68. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  69. {
  70. $u = trim((string)$baseUrl);
  71. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  72. return false;
  73. }
  74. $host = parse_url($u, PHP_URL_HOST);
  75. if (!is_string($host) || $host === '') {
  76. return false;
  77. }
  78. if (strcasecmp($host, 'localhost') === 0) {
  79. return false;
  80. }
  81. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  82. return false;
  83. }
  84. if (strpos($host, '.') === false) {
  85. return false;
  86. }
  87. return true;
  88. }
  89. /**
  90. * 解析用于外发邮件/短信的手机端站点根
  91. */
  92. protected function resolveMprocMobilePublicBaseUrl()
  93. {
  94. $candidates = [];
  95. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  96. $candidates[] = trim((string)Config::get('site.indexurl'));
  97. $cdn = trim((string)Config::get('site.cdnurl'));
  98. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  99. $candidates[] = rtrim($cdn, '/');
  100. }
  101. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  102. $candidates[] = $reqBase;
  103. foreach ($candidates as $c) {
  104. if ($c === '') {
  105. continue;
  106. }
  107. $c = rtrim($c, '/');
  108. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  109. return $c;
  110. }
  111. }
  112. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  113. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  114. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  115. return $reqBase;
  116. }
  117. Log::write('外发邮件手机链接:配置地址失效', 'warning');
  118. return '';
  119. }
  120. /**
  121. * 排除 mcyd.dputrecord 空串、零日期等非法值,避免 MySQL 1525(DATE_FORMAT/BETWEEN 遇 '' 报错)
  122. */
  123. protected function whereMcydDputrecordValid($query, $alias = 'a')
  124. {
  125. $c = $alias . '.dStamp';
  126. // 先转成 CHAR 再判断,避免 DATETIME 列里存 '' / 0000-00-00 时参与日期函数报错
  127. return $query->whereRaw(
  128. $c . ' IS NOT NULL'
  129. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) <> \'\''
  130. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) NOT LIKE \'0000-00-00%\''
  131. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) REGEXP \'^[12][0-9]{3}-[01][0-9]-[0-3][0-9]\''
  132. );
  133. }
  134. /**
  135. * 获取 Redis 中 procuremen_redis
  136. */
  137. protected function ProcuremenRedis(): array
  138. {
  139. try {
  140. $redis = redis();
  141. $raw = $redis->get('procuremen_redis');
  142. if ($raw === false || $raw === '') {
  143. return [];
  144. }
  145. $decoded = json_decode($raw, true);
  146. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  147. return [];
  148. }
  149. return $decoded['data'];
  150. } catch (\Throwable $e) {
  151. return [];
  152. }
  153. }
  154. /**
  155. * 左侧菜单
  156. */
  157. protected function GetIndexYearMonths()
  158. {
  159. $ymSet = [];
  160. //获取此方法调用缓存数据
  161. foreach ($this->ProcuremenRedis() as $r) {
  162. if (!is_array($r)) {
  163. continue;
  164. }
  165. $ds = trim((string)($r['dputrecord'] ?? ''));
  166. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  167. continue;
  168. }
  169. if (!preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  170. continue;
  171. }
  172. $mo = (int)$m[2];
  173. if ($mo < 1 || $mo > 12) {
  174. continue;
  175. }
  176. $ymSet[$m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT)] = true;
  177. }
  178. $ymList = array_keys($ymSet);
  179. rsort($ymList, SORT_STRING);
  180. $byYear = [];
  181. foreach ($ymList as $ym) {
  182. $y = substr($ym, 0, 4);
  183. $mo = (int)substr($ym, 5, 2);
  184. if (!isset($byYear[$y])) {
  185. $byYear[$y] = [];
  186. }
  187. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  188. }
  189. krsort($byYear, SORT_NUMERIC);
  190. foreach ($byYear as $y => $items) {
  191. usort($byYear[$y], function ($a, $b) {
  192. return strcmp($b['ym'], $a['ym']);
  193. });
  194. }
  195. $sidebar = [];
  196. foreach ($byYear as $y => $months) {
  197. $sidebar[] = ['year' => $y, 'months' => $months];
  198. }
  199. return $sidebar;
  200. }
  201. /**
  202. * 列表页
  203. */
  204. public function index(){
  205. $this->request->filter(['strip_tags', 'trim']);
  206. if (!$this->request->isAjax()) {
  207. $rootTrue = rtrim((string)$this->request->root(true), '/');
  208. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  209. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  210. $indexPhpRoot = $rootTrue . '/index.php';
  211. }
  212. $procuremenRedisApi = $indexPhpRoot . '/api/procuremen/getprocuremen';
  213. $this->view->assign('procuremenRedisApi', $procuremenRedisApi);
  214. $this->view->assign('defaultYm', date('Y-m'));
  215. $this->view->assign('sidebarYearMonths', $this->GetIndexYearMonths());
  216. return $this->view->fetch();
  217. }
  218. if ($this->request->request('keyField')) {
  219. return $this->selectpage();
  220. }
  221. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  222. $limit = max(10, min(500, (int)$limit));
  223. $ym = $this->request->request('ym', date('Y-m'));
  224. $ym = is_string($ym) ? trim($ym) : '';
  225. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  226. $ym = date('Y-m');
  227. }
  228. $monthStart = $ym . '-01 00:00:00';
  229. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  230. $search = trim((string)$this->request->get('search', ''));
  231. $hasActiveSearch = ($search !== '');
  232. if (!$hasActiveSearch) {
  233. $filterStr = $this->request->get('filter', '');
  234. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  235. $arr = json_decode($filterStr, true);
  236. if (is_array($arr) && count($arr) > 0) {
  237. foreach ($arr as $v) {
  238. if (is_array($v)) {
  239. if (array_filter($v, function ($x) {
  240. return $x !== '' && $x !== null;
  241. })) {
  242. $hasActiveSearch = true;
  243. break;
  244. }
  245. } elseif ($v !== '' && $v !== null) {
  246. $hasActiveSearch = true;
  247. break;
  248. }
  249. }
  250. }
  251. }
  252. }
  253. $applyMonthRange = !$hasActiveSearch;
  254. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  255. $opArr = (array)json_decode($this->request->get('op', ''), true);
  256. /* wff_tab:all=未发;pending=已下发;picked=已选中(主表 status=1 且存在明细 status=1);done=已完结 */
  257. $wffTab = trim((string)$this->request->request('wff_tab', 'all'));
  258. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done'], true)) {
  259. $wffTab = 'all';
  260. }
  261. try {
  262. $issuedSet = $this->loadIssuedScydgySet();
  263. if (in_array($wffTab, ['pending', 'done', 'picked'], true)) {
  264. $wantStatus = $wffTab === 'pending' ? 0 : 1;
  265. $dbRows = [];
  266. try {
  267. if ($wantStatus === 0) {
  268. $dbRows = Db::table('purchase_order')
  269. ->where('status', $wantStatus)
  270. ->select();
  271. } else {
  272. $dbRows = Db::table('purchase_order')
  273. ->where('status', $wantStatus)
  274. ->select();
  275. }
  276. } catch (\Throwable $e) {
  277. $dbRows = [];
  278. }
  279. if (!is_array($dbRows)) {
  280. $dbRows = [];
  281. }
  282. if ($wffTab === 'picked') {
  283. $pickedSidSet = $this->loadScydgyIdsWithPickedSupplierDetail();
  284. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($pickedSidSet) {
  285. if (!is_array($dbRow)) {
  286. return false;
  287. }
  288. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  289. if ($sid <= 0 && isset($dbRow['SCYDGY_ID'])) {
  290. $sid = (int)$dbRow['SCYDGY_ID'];
  291. }
  292. return $sid > 0 && isset($pickedSidSet[$sid]);
  293. }));
  294. }
  295. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  296. } else {
  297. $pool = $this->ProcuremenRedis();
  298. if ($pool === []) {
  299. return json([
  300. 'total' => 0,
  301. 'rows' => [],
  302. 'msg' => '暂无缓存数据',
  303. ]);
  304. }
  305. // 未发:主表已有且 status 为 0/1 才从列表隐藏;status 为空(NULL)仍可在未发展示
  306. try {
  307. $poIds = Db::table('purchase_order')
  308. ->whereRaw('(`status` = 0 OR `status` = 1)')
  309. ->column('scydgy_id');
  310. } catch (\Throwable $e) {
  311. $poIds = [];
  312. }
  313. if ($pool !== [] && is_array($poIds) && $poIds !== []) {
  314. $poSet = [];
  315. foreach ($poIds as $pid) {
  316. $k = (int)$pid;
  317. if ($k > 0) {
  318. $poSet[$k] = true;
  319. }
  320. }
  321. if ($poSet !== []) {
  322. $pool = array_values(array_filter($pool, function ($r) use ($poSet) {
  323. if (!is_array($r)) {
  324. return false;
  325. }
  326. $id = (int)($r['ID'] ?? 0);
  327. if ($id <= 0) {
  328. return true;
  329. }
  330. return !isset($poSet[$id]);
  331. }));
  332. }
  333. }
  334. }
  335. $filtered = $this->filterProcuremenIndexPool(
  336. $pool,
  337. $monthStart,
  338. $monthEnd,
  339. $applyMonthRange,
  340. $search,
  341. $filterArr,
  342. $opArr
  343. );
  344. $sortField = 'ID';
  345. if (is_string($sort) && $sort !== '') {
  346. $parts = explode(',', $sort);
  347. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  348. if ($sortField === '') {
  349. $sortField = 'ID';
  350. }
  351. }
  352. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  353. $nFiltered = count($filtered);
  354. if ($nFiltered > 1) {
  355. // 默认按主键 ID 排序时,用 array_multisort 比 usort+闭包略省开销
  356. if ($sortField === 'ID') {
  357. $sortKeys = [];
  358. foreach ($filtered as $i => $row) {
  359. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  360. }
  361. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  362. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  363. } else {
  364. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  365. $va = $a[$sortField] ?? null;
  366. $vb = $b[$sortField] ?? null;
  367. $sa = (string)$va;
  368. $sb = (string)$vb;
  369. if ($sa === $sb) {
  370. return 0;
  371. }
  372. return strcmp($sa, $sb) * $ord;
  373. });
  374. }
  375. }
  376. $offset = max(0, (int)$offset);
  377. $limit = max(1, (int)$limit);
  378. $rows = array_slice($filtered, $offset, $limit);
  379. foreach ($rows as &$rw) {
  380. if (!is_array($rw)) {
  381. continue;
  382. }
  383. $rid = (int)($rw['ID'] ?? 0);
  384. if ($wffTab === 'pending' || $wffTab === 'done' || $wffTab === 'picked') {
  385. $rw['_iss_out'] = true;
  386. } else {
  387. $rw['_iss_out'] = $rid > 0 && isset($issuedSet[$rid]);
  388. }
  389. }
  390. unset($rw);
  391. if ($wffTab === 'pending' && count($rows) > 0) {
  392. $idList = [];
  393. foreach ($rows as $rw) {
  394. if (!is_array($rw)) {
  395. continue;
  396. }
  397. $id = (int)($rw['ID'] ?? 0);
  398. if ($id > 0) {
  399. $idList[$id] = true;
  400. }
  401. }
  402. $sumMap = $this->OrderDetailSummary(array_keys($idList));
  403. foreach ($rows as &$rw) {
  404. if (!is_array($rw)) {
  405. continue;
  406. }
  407. $rid = (int)($rw['ID'] ?? 0);
  408. $s = isset($sumMap[$rid]) ? $sumMap[$rid] : ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  409. $rw['po_detail_count'] = $s['cnt'];
  410. $rw['po_amount_fill_cnt'] = $s['amt'];
  411. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  412. }
  413. unset($rw);
  414. }
  415. if ($wffTab === 'picked' && count($rows) > 0) {
  416. $idList = [];
  417. foreach ($rows as $rw) {
  418. if (!is_array($rw)) {
  419. continue;
  420. }
  421. $id = (int)($rw['ID'] ?? 0);
  422. if ($id > 0) {
  423. $idList[$id] = true;
  424. }
  425. }
  426. $nameMap = $this->loadPickedSupplierCompanyByScydgyIds(array_keys($idList));
  427. foreach ($rows as &$rw) {
  428. if (!is_array($rw)) {
  429. continue;
  430. }
  431. $rid = (int)($rw['ID'] ?? 0);
  432. $rw['picked_supplier_name'] = $nameMap[$rid] ?? '';
  433. }
  434. unset($rw);
  435. }
  436. if ($wffTab === 'all' && count($rows) > 0) {
  437. $this->mergePurchaseOrder($rows);
  438. }
  439. return json([
  440. 'total' => count($filtered),
  441. 'rows' => $rows,
  442. ]);
  443. } catch (\Throwable $e) {
  444. return json([
  445. 'total' => 0,
  446. 'rows' => [],
  447. 'msg' => $e->getMessage(),
  448. ]);
  449. }
  450. }
  451. /**
  452. * 已外发判定:主表 purchase_order.scydgy_id ∪ 明细 purchase_order_detail.scydgy_id(与工序列表行 ID 对应)
  453. *
  454. * @return array<int, true> 列表行 ID => true
  455. */
  456. protected function loadIssuedScydgySet()
  457. {
  458. $issuedSet = [];
  459. foreach (['purchase_order', 'purchase_order_detail'] as $tbl) {
  460. try {
  461. $issuedList = Db::table($tbl)->group('scydgy_id')->column('scydgy_id');
  462. if (!is_array($issuedList)) {
  463. continue;
  464. }
  465. foreach ($issuedList as $ids) {
  466. $n = (int)$ids;
  467. if ($n > 0) {
  468. $issuedSet[$n] = true;
  469. }
  470. }
  471. } catch (\Throwable $e) {
  472. }
  473. }
  474. return $issuedSet;
  475. }
  476. /**
  477. * 采购确认已选定供应商:明细 purchase_order_detail.status = 1 的工序行 scydgy_id 集合
  478. *
  479. * @return array<int, true>
  480. */
  481. protected function loadScydgyIdsWithPickedSupplierDetail(): array
  482. {
  483. $set = [];
  484. try {
  485. $rows = Db::table('purchase_order_detail')->where('status', 1)->field('scydgy_id')->select();
  486. } catch (\Throwable $e) {
  487. $rows = [];
  488. }
  489. if (!is_array($rows)) {
  490. return $set;
  491. }
  492. foreach ($rows as $r) {
  493. if (!is_array($r)) {
  494. continue;
  495. }
  496. $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
  497. if ($sid > 0) {
  498. $set[$sid] = true;
  499. }
  500. }
  501. return $set;
  502. }
  503. /**
  504. * 每个工序行对应已选中供应商名称(取 status=1 的首条明细 company_name)
  505. *
  506. * @param int[] $scydgyIds
  507. * @return array<int, string> scydgy_id => company_name
  508. */
  509. protected function loadPickedSupplierCompanyByScydgyIds(array $scydgyIds): array
  510. {
  511. $out = [];
  512. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  513. if ($scydgyIds === []) {
  514. return $out;
  515. }
  516. try {
  517. $rows = Db::table('purchase_order_detail')
  518. ->where('scydgy_id', 'in', $scydgyIds)
  519. ->where('status', 1)
  520. ->field('scydgy_id,company_name')
  521. ->order('id', 'asc')
  522. ->select();
  523. } catch (\Throwable $e) {
  524. try {
  525. $rows = Db::table('purchase_order_detail')
  526. ->where('scydgy_id', 'in', $scydgyIds)
  527. ->where('status', 1)
  528. ->field('scydgy_id,company_name')
  529. ->order('ID', 'asc')
  530. ->select();
  531. } catch (\Throwable $e2) {
  532. $rows = [];
  533. }
  534. }
  535. if (!is_array($rows)) {
  536. return $out;
  537. }
  538. foreach ($rows as $r) {
  539. if (!is_array($r)) {
  540. continue;
  541. }
  542. $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
  543. if ($sid <= 0 || isset($out[$sid])) {
  544. continue;
  545. }
  546. $name = trim((string)($r['company_name'] ?? ''));
  547. $out[$sid] = $name;
  548. }
  549. return $out;
  550. }
  551. /**
  552. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行(含 row_json、dStamp 补全)
  553. *
  554. * @return array<int, array<string, mixed>>
  555. */
  556. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  557. {
  558. $pool = [];
  559. if (!is_array($dbRows) || $dbRows === []) {
  560. return $pool;
  561. }
  562. $dStampMap = [];
  563. $sidList = [];
  564. foreach ($dbRows as $tmpRow) {
  565. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  566. $sid = (int)$tmpRow['scydgy_id'];
  567. if ($sid > 0) {
  568. $sidList[$sid] = true;
  569. }
  570. }
  571. }
  572. if ($sidList !== []) {
  573. try {
  574. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  575. } catch (\Throwable $e) {
  576. $dStampMap = [];
  577. }
  578. }
  579. foreach ($dbRows as $dbRow) {
  580. if (!is_array($dbRow)) {
  581. continue;
  582. }
  583. $rj = null;
  584. if (!empty($dbRow['row_json'])) {
  585. $decoded = json_decode($dbRow['row_json'], true);
  586. if (is_array($decoded)) {
  587. $rj = $decoded;
  588. }
  589. }
  590. if ($rj !== null && isset($rj['ID'])) {
  591. $rid = (int)$rj['ID'];
  592. $dsFix = isset($rj['dStamp']) ? trim((string)$rj['dStamp']) : '';
  593. if (($dsFix === '' || stripos($dsFix, '0000-00-00') === 0)
  594. && isset($dStampMap[$rid]) && trim((string)$dStampMap[$rid]) !== '') {
  595. $rj['dStamp'] = $dStampMap[$rid];
  596. }
  597. if (array_key_exists('id', $dbRow)) {
  598. $rj['purchase_order_id'] = (int)$dbRow['id'];
  599. }
  600. $pool[] = $rj;
  601. continue;
  602. }
  603. $r = [];
  604. foreach ($dbRow as $k => $v) {
  605. $lk = strtolower((string)$k);
  606. if ($lk === 'id' || $lk === 'row_json') {
  607. continue;
  608. }
  609. $r[$k] = $v;
  610. }
  611. if (isset($dbRow['scydgy_id'])) {
  612. $r['ID'] = (int)$dbRow['scydgy_id'];
  613. $sid = $r['ID'];
  614. $dsOut = '';
  615. if (isset($dStampMap[$sid])) {
  616. $t = trim((string)$dStampMap[$sid]);
  617. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  618. $dsOut = $dStampMap[$sid];
  619. }
  620. }
  621. if ($dsOut === '' && !empty($dbRow['createtime'])) {
  622. $ct = $dbRow['createtime'];
  623. if (is_numeric($ct) && (int)$ct > 946684800) {
  624. $dsOut = date('Y-m-d H:i:s', (int)$ct);
  625. } elseif (is_string($ct) && trim($ct) !== '') {
  626. $tc = trim($ct);
  627. if ($tc !== '' && stripos($tc, '0000-00-00') !== 0) {
  628. $dsOut = $tc;
  629. }
  630. }
  631. }
  632. if ($dsOut !== '') {
  633. $r['dStamp'] = $dsOut;
  634. }
  635. }
  636. if (array_key_exists('id', $dbRow)) {
  637. $r['purchase_order_id'] = (int)$dbRow['id'];
  638. }
  639. $pool[] = $r;
  640. }
  641. return $pool;
  642. }
  643. /**
  644. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  645. *
  646. * @param int[] $scydgyIds
  647. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  648. */
  649. protected function OrderDetailSummary(array $scydgyIds)
  650. {
  651. $out = [];
  652. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  653. if ($scydgyIds === []) {
  654. return $out;
  655. }
  656. $list = [];
  657. try {
  658. $list = Db::table('purchase_order_detail')
  659. ->where('scydgy_id', 'in', $scydgyIds)
  660. ->field('id,scydgy_id,amount,delivery')
  661. ->select();
  662. } catch (\Throwable $e) {
  663. $list = [];
  664. }
  665. if (!is_array($list)) {
  666. return $out;
  667. }
  668. foreach ($list as $r) {
  669. if (!is_array($r)) {
  670. continue;
  671. }
  672. $ids = (int)($r['scydgy_id'] ?? 0);
  673. if ($ids <= 0) {
  674. continue;
  675. }
  676. if (!isset($out[$ids])) {
  677. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  678. }
  679. $out[$ids]['cnt']++;
  680. $am = $r['amount'] ?? null;
  681. if ($am !== null && $am !== '') {
  682. if (!(is_string($am) && trim($am) === '')) {
  683. $out[$ids]['amt']++;
  684. }
  685. }
  686. $dv = $r['delivery'] ?? null;
  687. if ($dv !== null && trim((string)$dv) !== '') {
  688. $out[$ids]['deliv']++;
  689. }
  690. }
  691. return $out;
  692. }
  693. /**
  694. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  695. *
  696. * @return array
  697. */
  698. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr)
  699. {
  700. $strContains = function ($haystack, $needle) {
  701. if ($needle === '') {
  702. return false;
  703. }
  704. $haystack = (string)$haystack;
  705. if (function_exists('mb_stripos')) {
  706. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  707. }
  708. return stripos($haystack, $needle) !== false;
  709. };
  710. $stripAlias = function ($f) {
  711. return preg_replace('/^[ab]\./i', '', (string)$f);
  712. };
  713. $searchColNames = [];
  714. foreach (explode(',', $this->searchFields) as $colRaw) {
  715. $c = $stripAlias(trim($colRaw));
  716. if ($c !== '') {
  717. $searchColNames[] = $c;
  718. }
  719. }
  720. $filtered = [];
  721. foreach ($pool as $r) {
  722. if (!is_array($r)) {
  723. continue;
  724. }
  725. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  726. if ($ds === '' || stripos($ds, '0000-00-00') === 0
  727. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  728. continue;
  729. }
  730. if ($applyMonthRange) {
  731. $mo = (int)$m[2];
  732. if ($mo < 1 || $mo > 12) {
  733. continue;
  734. }
  735. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  736. $rowMonthStart = $ymRow . '-01 00:00:00';
  737. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  738. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  739. continue;
  740. }
  741. }
  742. if ($search !== '') {
  743. $hitSearch = false;
  744. foreach ($searchColNames as $c) {
  745. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  746. if ($cell !== '' && $strContains($cell, $search)) {
  747. $hitSearch = true;
  748. break;
  749. }
  750. }
  751. if (!$hitSearch) {
  752. continue;
  753. }
  754. }
  755. foreach ($filterArr as $fk => $fv) {
  756. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  757. continue;
  758. }
  759. if (is_array($fv)) {
  760. continue;
  761. }
  762. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  763. continue;
  764. }
  765. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  766. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  767. $field = $stripAlias($fk);
  768. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  769. $cellStr = trim((string)$cell);
  770. switch ($sym) {
  771. case '=':
  772. if ((string)$cell !== (string)$fv) {
  773. continue 3;
  774. }
  775. break;
  776. case '<>':
  777. if ((string)$cell === (string)$fv) {
  778. continue 3;
  779. }
  780. break;
  781. case 'LIKE':
  782. case 'NOT LIKE':
  783. $needle = trim((string)$fv);
  784. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  785. if ($sym === 'LIKE' && !$hit) {
  786. continue 3;
  787. }
  788. if ($sym === 'NOT LIKE' && $hit) {
  789. continue 3;
  790. }
  791. break;
  792. case '>':
  793. case '>=':
  794. case '<':
  795. case '<=':
  796. if (!is_numeric($cell) && $cellStr === '') {
  797. continue 3;
  798. }
  799. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  800. $vv = (float)$fv;
  801. if ($sym === '>' && !($cv > $vv)) {
  802. continue 3;
  803. }
  804. if ($sym === '>=' && !($cv >= $vv)) {
  805. continue 3;
  806. }
  807. if ($sym === '<' && !($cv < $vv)) {
  808. continue 3;
  809. }
  810. if ($sym === '<=' && !($cv <= $vv)) {
  811. continue 3;
  812. }
  813. break;
  814. case 'BETWEEN':
  815. case 'NOT BETWEEN':
  816. case 'BETWEEN TIME':
  817. case 'NOT BETWEEN TIME':
  818. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  819. $rawR = str_replace(' - ', ',', $rawR);
  820. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  821. if (count($arr) < 2 || $arr[0] === '' || $arr[1] === '') {
  822. break;
  823. }
  824. $lo = $arr[0];
  825. $hi = $arr[1];
  826. $in = ($cellStr >= $lo && $cellStr <= $hi);
  827. $isNot = (strpos($sym, 'NOT') !== false);
  828. if ($isNot ? $in : !$in) {
  829. continue 3;
  830. }
  831. break;
  832. case 'NULL':
  833. case 'IS NULL':
  834. if ($cell !== null && $cell !== '') {
  835. continue 3;
  836. }
  837. break;
  838. case 'NOT NULL':
  839. case 'IS NOT NULL':
  840. if ($cell === null || $cell === '') {
  841. continue 3;
  842. }
  843. break;
  844. default:
  845. break;
  846. }
  847. }
  848. $filtered[] = $r;
  849. }
  850. return $filtered;
  851. }
  852. /**
  853. * 审核弹窗提交
  854. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  855. */
  856. public function snapshotToProcure()
  857. {
  858. if (!$this->request->isPost() || !$this->request->isAjax()) {
  859. $this->error(__('Invalid parameters'));
  860. }
  861. $row = json_decode($this->request->post('row_json', ''), true);
  862. if (!is_array($row)) {
  863. $this->error(__('Invalid parameters'));
  864. }
  865. try {
  866. $ids = (int)($row['ID'] ?? $row['id'] ?? 0);
  867. if ($ids <= 0) {
  868. throw new \Exception('无效的行主键 ID');
  869. }
  870. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  871. $data = [
  872. 'scydgy_id' => $ids,
  873. 'CCYDH' => $row['CCYDH'] ?? null,
  874. 'CYJMC' => $row['CYJMC'] ?? null,
  875. 'CDXMC' => $row['CDXMC'] ?? null,
  876. 'CGYBH' => $row['CGYBH'] ?? null,
  877. 'CGYMC' => $row['CGYMC'] ?? null,
  878. 'CDW' => $row['CDW'] ?? null,
  879. 'NGZL' => $row['NGZL'] ?? null,
  880. 'CDF' => $row['CDF'] ?? null,
  881. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  882. 'MBZ' => $row['MBZ'] ?? null,
  883. 'bwjg' => $row['bwjg'] ?? null,
  884. 'iStatus' => $row['iStatus'] ?? null,
  885. 'dStamp' => $row['dStamp'] ?? null,
  886. 'dputrecord' => $row['dputrecord'] ?? null,
  887. 'cywyxm' => $row['cywyxm'] ?? null,
  888. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  889. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  890. ];
  891. if ($exists) {
  892. $upd = $data;
  893. unset($upd['scydgy_id'], $upd['status']);
  894. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  895. } else {
  896. // 新增:不写 status(空/走库默认);仅写创建时间
  897. $data['createtime'] = date('Y-m-d H:i:s');
  898. Db::table('purchase_order')->insert($data);
  899. }
  900. } catch (\Throwable $e) {
  901. $this->error($e->getMessage());
  902. }
  903. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  904. $this->success('操作成功');
  905. }
  906. /**
  907. * 未发列表
  908. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  909. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  910. */
  911. public function completeDirectly()
  912. {
  913. if (!$this->request->isPost() || !$this->request->isAjax()) {
  914. $this->error(__('参数错误'));
  915. }
  916. $row = json_decode($this->request->post('row_json', ''), true);
  917. if (!is_array($row)) {
  918. $this->error(__('Invalid parameters'));
  919. }
  920. $finishRaw = $this->request->post('finish', '1');
  921. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  922. try {
  923. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  924. $ids = (int)($row['ID'] ?? $row['id'] ?? 0);
  925. if ($ids <= 0) {
  926. throw new \Exception('无效的行主键 ID');
  927. }
  928. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  929. $data = [
  930. 'scydgy_id' => $ids,
  931. 'CCYDH' => $row['CCYDH'] ?? null,
  932. 'CYJMC' => $row['CYJMC'] ?? null,
  933. 'CDXMC' => $row['CDXMC'] ?? null,
  934. 'CGYBH' => $row['CGYBH'] ?? null,
  935. 'CGYMC' => $row['CGYMC'] ?? null,
  936. 'CDW' => $row['CDW'] ?? null,
  937. 'NGZL' => $row['NGZL'] ?? null,
  938. 'CDF' => $row['CDF'] ?? null,
  939. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  940. 'MBZ' => $row['MBZ'] ?? null,
  941. 'bwjg' => $row['bwjg'] ?? null,
  942. 'iStatus' => $row['iStatus'] ?? null,
  943. 'dStamp' => $row['dStamp'] ?? null,
  944. 'dputrecord' => $row['dputrecord'] ?? null,
  945. 'cywyxm' => $row['cywyxm'] ?? null,
  946. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  947. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  948. ];
  949. if ($asComplete) {
  950. $data['status'] = 1;
  951. }
  952. if ($exists) {
  953. $upd = $data;
  954. unset($upd['scydgy_id']);
  955. if (!$asComplete) {
  956. unset($upd['status']);
  957. }
  958. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  959. } else {
  960. // 新增:不写 status;完结时 $data 已含 status=1
  961. $data['createtime'] = date('Y-m-d H:i:s');
  962. Db::table('purchase_order')->insert($data);
  963. }
  964. } catch (\Throwable $e) {
  965. $this->error($e->getMessage());
  966. }
  967. $poIdLog = null;
  968. try {
  969. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  970. if (is_array($rpo)) {
  971. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  972. $poIdLog = $tid > 0 ? $tid : null;
  973. }
  974. } catch (\Throwable $e) {
  975. $poIdLog = null;
  976. }
  977. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  978. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  979. if ($asComplete) {
  980. $this->addOrderLog(
  981. $ids,
  982. 'mark_complete',
  983. '点击「完结」,已标记为已完结;本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  984. $poIdLog
  985. );
  986. } else {
  987. $this->addOrderLog(
  988. $ids,
  989. 'save_qty_price',
  990. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  991. $poIdLog
  992. );
  993. }
  994. $this->success("操作成功");
  995. }
  996. /**
  997. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  998. *
  999. * @param array<int, array> $rows 引用传递当前页行
  1000. */
  1001. protected function mergePurchaseOrder(array &$rows)
  1002. {
  1003. if ($rows === []) {
  1004. return;
  1005. }
  1006. $ids = [];
  1007. foreach ($rows as $rw) {
  1008. if (!is_array($rw)) {
  1009. continue;
  1010. }
  1011. $id = (int)($rw['ID'] ?? 0);
  1012. if ($id > 0) {
  1013. $ids[$id] = true;
  1014. }
  1015. }
  1016. $idList = array_keys($ids);
  1017. if ($idList === []) {
  1018. return;
  1019. }
  1020. try {
  1021. $list = Db::table('purchase_order')
  1022. ->where('scydgy_id', 'in', $idList)
  1023. ->field('scydgy_id,This_quantity,ceilingPrice')
  1024. ->select();
  1025. } catch (\Throwable $e) {
  1026. return;
  1027. }
  1028. if (!is_array($list)) {
  1029. return;
  1030. }
  1031. $byId = [];
  1032. foreach ($list as $dbRow) {
  1033. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  1034. continue;
  1035. }
  1036. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  1037. }
  1038. foreach ($rows as &$rw) {
  1039. if (!is_array($rw)) {
  1040. continue;
  1041. }
  1042. $sid = (int)($rw['ID'] ?? 0);
  1043. if ($sid <= 0 || !isset($byId[$sid])) {
  1044. continue;
  1045. }
  1046. $db = $byId[$sid];
  1047. if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
  1048. $rw['This_quantity'] = $db['This_quantity'];
  1049. }
  1050. if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
  1051. $rw['ceilingPrice'] = $db['ceilingPrice'];
  1052. } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
  1053. $rw['ceilingPrice'] = $db['ceiling_price'];
  1054. }
  1055. }
  1056. unset($rw);
  1057. }
  1058. /**
  1059. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  1060. */
  1061. public function purchaseConfirmPick()
  1062. {
  1063. if (!$this->request->isPost() || !$this->request->isAjax()) {
  1064. $this->error(__('Invalid parameters'));
  1065. }
  1066. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  1067. $sid = (int)$scydgyId;
  1068. if ($sid <= 0) {
  1069. $this->error('参数无效');
  1070. }
  1071. $parseIdList = function ($raw) {
  1072. if (is_array($raw)) {
  1073. $arr = $raw;
  1074. } else {
  1075. $decoded = json_decode((string)$raw, true);
  1076. $arr = is_array($decoded) ? $decoded : [];
  1077. }
  1078. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  1079. };
  1080. $selectedRaw = $this->request->post('selected_ids', null);
  1081. if ($selectedRaw === null || $selectedRaw === '') {
  1082. $legacy = (int)$this->request->post('selected_id', 0);
  1083. $selectedIds = $legacy > 0 ? [$legacy] : [];
  1084. } else {
  1085. $selectedIds = $parseIdList($selectedRaw);
  1086. }
  1087. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  1088. if ($selectedIds === []) {
  1089. $this->error('请至少勾选一条明细');
  1090. }
  1091. $inter = array_intersect($selectedIds, $unselectedIds);
  1092. if ($inter !== []) {
  1093. $this->error('选中与未选中 ID 不能重复');
  1094. }
  1095. $allIds = $this->purchaseOrderDetail($sid);
  1096. if ($allIds === []) {
  1097. $this->error('未找到该工序行的下发明细');
  1098. }
  1099. foreach ($selectedIds as $id) {
  1100. if (!in_array($id, $allIds, true)) {
  1101. $this->error('选中 ID 不属于当前工序行');
  1102. }
  1103. }
  1104. foreach ($unselectedIds as $id) {
  1105. if (!in_array($id, $allIds, true)) {
  1106. $this->error('未选中 ID 不属于当前工序行');
  1107. }
  1108. }
  1109. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  1110. sort($union, SORT_NUMERIC);
  1111. $expect = $allIds;
  1112. sort($expect, SORT_NUMERIC);
  1113. if ($union !== $expect) {
  1114. $this->error('请提交当前工序下全部明细 ID(选中 + 未选中)');
  1115. }
  1116. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  1117. Db::startTrans();
  1118. try {
  1119. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => 0]);
  1120. $aff = 0;
  1121. try {
  1122. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => 1]);
  1123. } catch (\Throwable $e) {
  1124. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => 1]);
  1125. }
  1126. if ($aff < 1) {
  1127. throw new \Exception('更新选中状态失败');
  1128. }
  1129. if ($purchaseOrderId > 0) {
  1130. $poAff = (int)Db::table('purchase_order')
  1131. ->where('id', $purchaseOrderId)
  1132. ->where('scydgy_id', $sid)
  1133. ->update(['status' => 1]);
  1134. if ($poAff < 1) {
  1135. throw new \Exception('主表订单不存在或与工序行不匹配');
  1136. }
  1137. } else {
  1138. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update(['status' => 1]);
  1139. if ($poAff < 1) {
  1140. throw new \Exception('未找到');
  1141. }
  1142. }
  1143. Db::commit();
  1144. } catch (\Throwable $e) {
  1145. Db::rollback();
  1146. $this->error($e->getMessage());
  1147. }
  1148. $poIdFinal = $purchaseOrderId;
  1149. if ($poIdFinal <= 0) {
  1150. try {
  1151. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1152. if (is_array($rpo)) {
  1153. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  1154. }
  1155. } catch (\Throwable $e) {
  1156. $poIdFinal = 0;
  1157. }
  1158. }
  1159. $pickNames = [];
  1160. foreach ($selectedIds as $pid) {
  1161. $dr = $this->purchaseOrderDetai($sid, $pid);
  1162. $nm = trim((string)($dr['company_name'] ?? ''));
  1163. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  1164. }
  1165. $this->addOrderLog(
  1166. $sid,
  1167. 'purchase_confirm',
  1168. '采购确认:已选中供应商「' . implode('、', $pickNames) . '」;',
  1169. $poIdFinal > 0 ? $poIdFinal : null
  1170. );
  1171. $ccydh = '';
  1172. $cyjmc = '';
  1173. try {
  1174. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1175. if (is_array($po)) {
  1176. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  1177. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  1178. }
  1179. } catch (\Throwable $e) {
  1180. }
  1181. if ($ccydh === '' || $cyjmc === '') {
  1182. $any = $this->purchaseOrderDetai($sid, $selectedIds[0] ?? 0);
  1183. if (is_array($any)) {
  1184. if ($ccydh === '') {
  1185. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  1186. }
  1187. if ($cyjmc === '') {
  1188. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  1189. }
  1190. }
  1191. }
  1192. $sendSmsSafe = function ($phone, $content) {
  1193. $phone = trim((string)$phone);
  1194. if ($phone === '') {
  1195. return;
  1196. }
  1197. try {
  1198. $this->smsbao($phone, $content);
  1199. } catch (\Throwable $e) {
  1200. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  1201. }
  1202. };
  1203. //批量发送手机短信:采购确认通过
  1204. foreach ($selectedIds as $pid) {
  1205. $dr = $this->purchaseOrderDetai($sid, $pid);
  1206. if (!is_array($dr)) {
  1207. continue;
  1208. }
  1209. $cname = trim((string)($dr['company_name'] ?? ''));
  1210. $sms = "您好,{$cname}:\n\n"
  1211. . "您参与的外发加工订单采购确认结果:已通过。\n"
  1212. . "订单号:{$ccydh}\n"
  1213. . "印件名称:{$cyjmc}\n\n";
  1214. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  1215. }
  1216. //批量发送手机短信:采购确认未通过
  1217. foreach ($unselectedIds as $pid) {
  1218. $dr = $this->purchaseOrderDetai($sid, $pid);
  1219. if (!is_array($dr)) {
  1220. continue;
  1221. }
  1222. $cname = trim((string)($dr['company_name'] ?? ''));
  1223. $sms = "您好,{$cname}:\n\n"
  1224. . "您参与的外发加工订单采购确认结果:未通过。\n"
  1225. . "订单号:{$ccydh}\n"
  1226. . "印件名称:{$cyjmc}\n\n";
  1227. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  1228. }
  1229. $line = sprintf(
  1230. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  1231. $scydgyId,
  1232. $purchaseOrderId,
  1233. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  1234. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  1235. );
  1236. Log::write($line, 'notice');
  1237. $pdfPublicPath = '';
  1238. try {
  1239. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  1240. } catch (\Throwable $e) {
  1241. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  1242. }
  1243. $this->success('操作成功', '', [
  1244. 'scydgy_id' => $scydgyId,
  1245. 'purchase_order_id' => $purchaseOrderId,
  1246. 'selected_ids' => $selectedIds,
  1247. 'unselected_ids' => $unselectedIds,
  1248. 'purchase_confirm_pdf' => $pdfPublicPath,
  1249. ]);
  1250. }
  1251. /**
  1252. * @return int[]
  1253. */
  1254. protected function purchaseOrderDetail(int $scydgyId): array
  1255. {
  1256. if ($scydgyId <= 0) {
  1257. return [];
  1258. }
  1259. try {
  1260. $list = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->select();
  1261. } catch (\Throwable $e) {
  1262. return [];
  1263. }
  1264. if (!is_array($list)) {
  1265. return [];
  1266. }
  1267. $ids = [];
  1268. foreach ($list as $r) {
  1269. if (!is_array($r)) {
  1270. continue;
  1271. }
  1272. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  1273. if ($pk > 0) {
  1274. $ids[] = $pk;
  1275. }
  1276. }
  1277. return array_values(array_unique($ids));
  1278. }
  1279. /**
  1280. * 获取当前登录用户信息 [id, 展示名]
  1281. */
  1282. protected function GetUseName(): array
  1283. {
  1284. $id = 0;
  1285. $name = '';
  1286. try {
  1287. if ($this->auth && $this->auth->isLogin()) {
  1288. $u = $this->auth->getUserInfo();
  1289. if (is_array($u)) {
  1290. $id = (int)($u['id'] ?? 0);
  1291. $name = trim((string)($u['nickname'] ?? ''));
  1292. if ($name === '') {
  1293. $name = trim((string)($u['username'] ?? ''));
  1294. }
  1295. }
  1296. }
  1297. } catch (\Throwable $e) {
  1298. }
  1299. if ($name === '') {
  1300. $name = '未知用户';
  1301. }
  1302. return [$id, $name];
  1303. }
  1304. /**
  1305. * 外发采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  1306. */
  1307. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  1308. {
  1309. if ($scydgyId <= 0 || $content === '') {
  1310. return;
  1311. }
  1312. list($adminId, $adminName) = $this->GetUseName();
  1313. $cut = function ($s, $max) {
  1314. if (function_exists('mb_substr')) {
  1315. return mb_substr($s, 0, $max, 'UTF-8');
  1316. }
  1317. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  1318. };
  1319. try {
  1320. Db::table('purchase_order_oper_log')->insert([
  1321. 'scydgy_id' => $scydgyId,
  1322. 'purchase_order_id' => $purchaseOrderId,
  1323. 'admin_id' => $adminId,
  1324. 'admin_name' => $cut($adminName, 64),
  1325. 'action' => $cut((string)$action, 64),
  1326. 'content' => $cut($content, 1000),
  1327. // 表结构 createtime 为 int Unix 时间戳;日期字符串会导致插入失败或时间为 0,详情「操作记录」为空
  1328. 'createtime' => time(),
  1329. ]);
  1330. } catch (\Throwable $e) {
  1331. Log::write('procuremen addOrderLog: ' . $e->getMessage(), 'error');
  1332. }
  1333. }
  1334. /**
  1335. * 按主键取一条
  1336. */
  1337. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  1338. {
  1339. if ($scydgyId <= 0 || $pk <= 0) {
  1340. return [];
  1341. }
  1342. try {
  1343. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  1344. if (is_array($one)) {
  1345. return $one;
  1346. }
  1347. } catch (\Throwable $e) {
  1348. }
  1349. try {
  1350. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  1351. if (is_array($one)) {
  1352. return $one;
  1353. }
  1354. } catch (\Throwable $e) {
  1355. }
  1356. return [];
  1357. }
  1358. /**
  1359. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  1360. */
  1361. protected function formatProcuremenDetailTime($v): string
  1362. {
  1363. if ($v === null || $v === '') {
  1364. return '';
  1365. }
  1366. if (is_numeric($v) && (int)$v > 946684800) {
  1367. return date('Y-m-d H:i:s', (int)$v);
  1368. }
  1369. $s = trim((string)$v);
  1370. if ($s !== '' && stripos($s, '0000-00-00') !== 0) {
  1371. return $s;
  1372. }
  1373. return '';
  1374. }
  1375. /**
  1376. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  1377. */
  1378. protected function formatDeliveryYmd($v): string
  1379. {
  1380. if ($v === null || $v === '') {
  1381. return '';
  1382. }
  1383. $s = trim((string)$v);
  1384. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1385. return '';
  1386. }
  1387. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  1388. return $m[1];
  1389. }
  1390. $ts = strtotime($s);
  1391. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  1392. }
  1393. /**
  1394. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  1395. */
  1396. protected function detailRowSupplierAccepted(array $r): bool
  1397. {
  1398. $am = $r['amount'] ?? null;
  1399. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  1400. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  1401. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  1402. return $okAmt && $okDel;
  1403. }
  1404. /**
  1405. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  1406. *
  1407. * @param array $main purchase_order 一行
  1408. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  1409. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  1410. */
  1411. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  1412. {
  1413. $issueCnt = count($details);
  1414. $acceptCnt = 0;
  1415. $pickedName = '';
  1416. $pickedTime = '';
  1417. foreach ($details as $dr) {
  1418. if (!is_array($dr)) {
  1419. continue;
  1420. }
  1421. if ($this->detailRowSupplierAccepted($dr)) {
  1422. $acceptCnt++;
  1423. }
  1424. if ((int)($dr['status'] ?? 0) === 1) {
  1425. if ($pickedName === '') {
  1426. $pickedName = trim((string)($dr['company_name'] ?? ''));
  1427. }
  1428. if ($pickedTime === '') {
  1429. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  1430. if ($pickedTime === '') {
  1431. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  1432. }
  1433. }
  1434. }
  1435. }
  1436. $hasMain = $main !== [];
  1437. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  1438. $mainStatus = isset($main['status']) ? (int)$main['status'] : 0;
  1439. $supplierTime = '';
  1440. if ($acceptCnt > 0) {
  1441. foreach ($details as $dr) {
  1442. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  1443. continue;
  1444. }
  1445. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  1446. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  1447. $supplierTime = $t;
  1448. }
  1449. }
  1450. }
  1451. $doneTime = '';
  1452. if ($mainStatus === 1) {
  1453. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  1454. if ($doneTime === '') {
  1455. foreach ($details as $dr) {
  1456. if (!is_array($dr)) {
  1457. continue;
  1458. }
  1459. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  1460. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  1461. $doneTime = $t;
  1462. }
  1463. }
  1464. }
  1465. if ($doneTime === '') {
  1466. $doneTime = $poTime;
  1467. }
  1468. }
  1469. $step1Done = $hasMain;
  1470. $step2Done = $hasMain;
  1471. $step3Done = $acceptCnt > 0;
  1472. $step4Done = false;
  1473. foreach ($details as $dr) {
  1474. if (is_array($dr) && (int)($dr['status'] ?? 0) === 1) {
  1475. $step4Done = true;
  1476. break;
  1477. }
  1478. }
  1479. $step5Done = $mainStatus === 1;
  1480. // 主表已完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  1481. if ($mainStatus === 1) {
  1482. $step3Done = true;
  1483. $step4Done = true;
  1484. if ($supplierTime === '') {
  1485. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  1486. if ($fillT !== '') {
  1487. $supplierTime = $fillT;
  1488. }
  1489. }
  1490. if ($pickedTime === '') {
  1491. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  1492. if ($fillT !== '') {
  1493. $pickedTime = $fillT;
  1494. }
  1495. }
  1496. }
  1497. $steps = [
  1498. [
  1499. 'title' => '未发',
  1500. 'subtitle' => '',
  1501. 'time' => $step1Done ? '—' : '',
  1502. 'done' => $step1Done,
  1503. ],
  1504. [
  1505. 'title' => '已发未结束',
  1506. 'subtitle' => '',
  1507. 'time' => $step2Done ? $poTime : '',
  1508. 'done' => $step2Done,
  1509. ],
  1510. [
  1511. 'title' => '供应商接单',
  1512. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  1513. 'time' => $step3Done ? $supplierTime : '',
  1514. 'done' => $step3Done,
  1515. ],
  1516. [
  1517. 'title' => '采购确认',
  1518. 'subtitle' => $pickedName !== '' ? ('选中供应商:' . $pickedName) : '',
  1519. 'time' => $step4Done ? ($pickedTime !== '' ? $pickedTime : '') : '',
  1520. 'done' => $step4Done,
  1521. ],
  1522. [
  1523. 'title' => '已完结',
  1524. 'subtitle' => '',
  1525. 'time' => $step5Done ? $doneTime : '',
  1526. 'done' => $step5Done,
  1527. ],
  1528. ];
  1529. $currentIdx = count($steps) - 1;
  1530. foreach ($steps as $i => $s) {
  1531. if (!$s['done']) {
  1532. $currentIdx = $i;
  1533. break;
  1534. }
  1535. }
  1536. $nSteps = count($steps);
  1537. foreach ($steps as $idx => &$s) {
  1538. $s['current'] = ($idx === $currentIdx);
  1539. if ($idx === 0) {
  1540. $s['pdf_left_bg'] = '';
  1541. } else {
  1542. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  1543. }
  1544. if ($idx >= $nSteps - 1) {
  1545. $s['pdf_right_bg'] = '';
  1546. } else {
  1547. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  1548. }
  1549. }
  1550. unset($s);
  1551. $labelMap = [
  1552. 'CCYDH' => '订单号',
  1553. 'CYJMC' => '印件名称',
  1554. 'CDXMC' => '订单名称',
  1555. 'CGYMC' => '工序名称',
  1556. 'CGYBH' => '工序编号',
  1557. 'CDW' => '单位',
  1558. 'NGZL' => '工作量',
  1559. 'CDF' => '单价',
  1560. 'cGzzxMc' => '工作中心',
  1561. 'MBZ' => '备注',
  1562. 'This_quantity' => '本次数量',
  1563. 'ceilingPrice' => '最高限价',
  1564. ];
  1565. $orderSummary = [];
  1566. foreach ($labelMap as $key => $lab) {
  1567. if (!array_key_exists($key, $main)) {
  1568. continue;
  1569. }
  1570. $val = $main[$key];
  1571. if ($val === null) {
  1572. $val = '';
  1573. } elseif (!is_scalar($val)) {
  1574. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  1575. } else {
  1576. $val = (string)$val;
  1577. }
  1578. $orderSummary[] = ['label' => $lab, 'value' => $val];
  1579. }
  1580. $orderSummaryGrid = [];
  1581. $n = count($orderSummary);
  1582. for ($i = 0; $i < $n; $i += 2) {
  1583. $left = $orderSummary[$i];
  1584. $hasRight = ($i + 1) < $n;
  1585. $orderSummaryGrid[] = [
  1586. 'l1' => $left['label'],
  1587. 'v1' => $left['value'],
  1588. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  1589. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  1590. ];
  1591. }
  1592. return [
  1593. 'steps' => $steps,
  1594. 'orderSummary' => $orderSummary,
  1595. 'orderSummaryGrid' => $orderSummaryGrid,
  1596. 'detailRows' => $details,
  1597. ];
  1598. }
  1599. /**
  1600. * 加载并 assign 外发采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  1601. *
  1602. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  1603. */
  1604. protected function prepareProcuremenDetailsView(string $ids): array
  1605. {
  1606. $main = [];
  1607. try {
  1608. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  1609. $main = is_array($one) ? $one : [];
  1610. } catch (\Throwable $e) {
  1611. $main = [];
  1612. }
  1613. $details = [];
  1614. try {
  1615. $details = Db::table('purchase_order_detail')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  1616. } catch (\Throwable $e) {
  1617. $details = [];
  1618. }
  1619. if (!is_array($details)) {
  1620. $details = [];
  1621. }
  1622. foreach ($details as &$r) {
  1623. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  1624. $r['id'] = $r['ID'];
  1625. }
  1626. if (isset($r['createtime'])) {
  1627. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  1628. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  1629. } else {
  1630. $r['createtime_text'] = (string)$r['createtime'];
  1631. }
  1632. } else {
  1633. $r['createtime_text'] = '';
  1634. }
  1635. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  1636. }
  1637. unset($r);
  1638. $operLogs = [];
  1639. try {
  1640. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  1641. } catch (\Throwable $e) {
  1642. $operLogs = [];
  1643. }
  1644. if (!is_array($operLogs)) {
  1645. $operLogs = [];
  1646. }
  1647. foreach ($operLogs as &$lg) {
  1648. if (!is_array($lg)) {
  1649. continue;
  1650. }
  1651. $ct = isset($lg['createtime']) ? (int)$lg['createtime'] : 0;
  1652. $lg['createtime_text'] = $ct > 946684800 ? date('Y-m-d H:i:s', $ct) : '';
  1653. }
  1654. unset($lg);
  1655. $bundle = $this->buildProcuremenDetailsViewData($main, $details);
  1656. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  1657. if ($ccydh === '') {
  1658. foreach ($details as $r) {
  1659. if (!is_array($r)) {
  1660. continue;
  1661. }
  1662. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  1663. if ($ccydh !== '') {
  1664. break;
  1665. }
  1666. }
  1667. }
  1668. $this->view->assign('ccydh', $ccydh);
  1669. $this->view->assign('steps', $bundle['steps']);
  1670. $this->view->assign('orderSummary', $bundle['orderSummary']);
  1671. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  1672. $this->view->assign('detailRows', $bundle['detailRows']);
  1673. $this->view->assign('operLogs', $operLogs);
  1674. return [
  1675. 'ok' => $main !== [] || $details !== [],
  1676. 'ccydh' => $ccydh,
  1677. ];
  1678. }
  1679. /**
  1680. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  1681. */
  1682. public function details()
  1683. {
  1684. $ids = $this->request->param('ids', $this->request->param('id', ''));
  1685. if (is_array($ids)) {
  1686. $ids = isset($ids[0]) ? $ids[0] : '';
  1687. }
  1688. $ids = trim((string)$ids);
  1689. if ($ids === '') {
  1690. $this->error(__('Invalid parameters'));
  1691. }
  1692. $this->prepareProcuremenDetailsView($ids);
  1693. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  1694. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  1695. $this->view->engine->layout(false);
  1696. try {
  1697. return $this->view->fetch('procuremen/details_dialog_shell');
  1698. } finally {
  1699. if ($restoreLayout) {
  1700. $this->view->engine->layout($restoreLayout);
  1701. }
  1702. }
  1703. }
  1704. /**
  1705. * 审核弹窗提交:GET 打开弹窗;POST 保存下发(主表 + 明细 + 操作日志)
  1706. */
  1707. public function review()
  1708. {
  1709. if ($this->request->isPost()) {
  1710. $rowJson = $this->request->post('row_json', '');
  1711. $companiesJson = $this->request->post('companies_json', '[]');
  1712. $row = json_decode($rowJson, true);
  1713. if (!is_array($row)) {
  1714. $this->error(__('Invalid parameters'));
  1715. }
  1716. $companies = json_decode($companiesJson, true);
  1717. if (!is_array($companies) || count($companies) === 0) {
  1718. $this->error('请至少选择一个下发单位');
  1719. }
  1720. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  1721. if ($sysRq === '') {
  1722. $this->error('请选择截止时间');
  1723. }
  1724. $sysRqTs = strtotime($sysRq);
  1725. if ($sysRqTs === false || $sysRqTs <= 0) {
  1726. $this->error('截止时间格式无效');
  1727. }
  1728. //示例:2026-05-18 14:31:09
  1729. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  1730. //示例:2026-05-18 14:31
  1731. $sysRqNotify = date('Y-m-d H:i', $sysRqTs);
  1732. $toDb = function ($value) {
  1733. if ($value === null) {
  1734. return null;
  1735. }
  1736. if (is_scalar($value)) {
  1737. return $value;
  1738. }
  1739. return json_encode($value, JSON_UNESCAPED_UNICODE);
  1740. };
  1741. Db::startTrans();
  1742. try {
  1743. $ids = (int)($row['ID'] ?? $row['id'] ?? 0);
  1744. if ($ids <= 0) {
  1745. throw new \Exception('无效的行主键 ID');
  1746. }
  1747. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  1748. $data = [
  1749. 'scydgy_id' => $ids,
  1750. 'CCYDH' => $row['CCYDH'] ?? null,
  1751. 'CYJMC' => $row['CYJMC'] ?? null,
  1752. 'CDXMC' => $row['CDXMC'] ?? null,
  1753. 'CGYBH' => $row['CGYBH'] ?? null,
  1754. 'CGYMC' => $row['CGYMC'] ?? null,
  1755. 'CDW' => $row['CDW'] ?? null,
  1756. 'NGZL' => $row['NGZL'] ?? null,
  1757. 'CDF' => $row['CDF'] ?? null,
  1758. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1759. 'MBZ' => $row['MBZ'] ?? null,
  1760. 'bwjg' => $row['bwjg'] ?? null,
  1761. 'iStatus' => $row['iStatus'] ?? null,
  1762. 'dStamp' => $row['dStamp'] ?? null,
  1763. 'dputrecord' => $row['dputrecord'] ?? null,
  1764. 'cywyxm' => $row['cywyxm'] ?? null,
  1765. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1766. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1767. 'status' => 0,
  1768. 'sys_rq' => $sysRqDb,
  1769. ];
  1770. if ($exists) {
  1771. $upd = $data;
  1772. unset($upd['scydgy_id']);
  1773. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  1774. } else {
  1775. $data['createtime'] = date('Y-m-d H:i:s');
  1776. Db::table('purchase_order')->insert($data);
  1777. }
  1778. $row['scydgy_id'] = (int)($row['ID'] ?? $row['id'] ?? 0);
  1779. unset($row['ID'], $row['id'], $row['_iss_out'], $row['ids'], $row['purchase_order_id']);
  1780. foreach ($companies as $c) {
  1781. if (!is_array($c)) {
  1782. continue;
  1783. }
  1784. $one = [
  1785. 'scydgy_id' => $toDb($row['scydgy_id']),
  1786. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  1787. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  1788. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  1789. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  1790. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  1791. 'createtime' => date('Y-m-d H:i:s'),
  1792. 'status' => 0,
  1793. 'status_name' => "未提交",
  1794. ];
  1795. // 先校验邮箱与手机号,再写入明细(写入后根据主键生成手机端直达链接 focus_eid)
  1796. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  1797. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  1798. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  1799. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件,未写入数据');
  1800. }
  1801. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  1802. if ($phone === '') {
  1803. $cname = isset($c['name']) ? trim((string)$c['name']) : '';
  1804. throw new \Exception(($cname !== '' ? $cname : '外协单位') . ' 未填写手机号,无法发送短信,未写入数据');
  1805. }
  1806. Db::table('purchase_order_detail')->insert($one);
  1807. $detailId = (int)Db::getLastInsID();
  1808. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  1809. $mprocUrlEsc = htmlspecialchars($mprocUrl, ENT_QUOTES, 'UTF-8');
  1810. // 发送邮箱
  1811. $mailConfig = Config::get('Mailer');
  1812. if (!is_array($mailConfig) || empty($mailConfig['host']) || empty($mailConfig['addr'])) {
  1813. throw new \Exception('邮件未配置');
  1814. }
  1815. $mail = new PHPMailer(true);
  1816. $mail->isSMTP();
  1817. $mail->Host = $mailConfig['host'];
  1818. $mail->SMTPAuth = true;
  1819. $mail->Username = $mailConfig['addr'];
  1820. $mail->Password = $mailConfig['pass'];
  1821. $mail->SMTPSecure = $mailConfig['security'];
  1822. $mail->Port = $mailConfig['port'];
  1823. $mail->CharSet = $mailConfig['charset'];
  1824. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  1825. $mail->addAddress($toEmail, $companyName);
  1826. $mail->isHTML(true);
  1827. $mail->Subject = '【外发加工订单通知】';
  1828. $mail->Body = "
  1829. 您好,{$companyName}:<br><br>
  1830. 您有新的外发加工订单待处理:<br>
  1831. 订单号:{$row['CCYDH']}<br>
  1832. 印件名称:{$row['CYJMC']}<br>
  1833. 请在 <strong>{$sysRqNotify}</strong> 前登陆我司平台处理<br><br>
  1834. 您可点击链接进行查看等操作:<br>
  1835. <a href=\"{$mprocUrlEsc}\">{$mprocUrlEsc}</a><br><br>
  1836. 请及时查收并处理,谢谢!
  1837. ";
  1838. $mail->send();
  1839. //发送短信
  1840. $ccydh = isset($row['CCYDH']) ? (string)$row['CCYDH'] : '';
  1841. $cyjmc = isset($row['CYJMC']) ? (string)$row['CYJMC'] : '';
  1842. $smsContent = "您好,{$companyName}:\n\n"
  1843. . "您有新的外发加工订单待处理:\n"
  1844. . "订单号:{$ccydh}\n"
  1845. . "印件名称:{$cyjmc}\n"
  1846. . "请在 {$sysRqNotify} 前登陆我司平台处理\n\n"
  1847. // . "您可点击链接进行查看等操作::\n"
  1848. // . $mprocUrl . "\n\n"
  1849. . '请及时查收并处理,谢谢!';
  1850. $this->smsbao($phone, $smsContent);
  1851. }
  1852. Db::commit();
  1853. } catch (\Throwable $e) {
  1854. Db::rollback();
  1855. $this->error($e->getMessage());
  1856. }
  1857. $poIdLog = null;
  1858. try {
  1859. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  1860. if (is_array($rpo)) {
  1861. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  1862. $poIdLog = $tid > 0 ? $tid : null;
  1863. }
  1864. } catch (\Throwable $e) {
  1865. $poIdLog = null;
  1866. }
  1867. $names = [];
  1868. foreach ($companies as $c) {
  1869. if (!is_array($c)) {
  1870. continue;
  1871. }
  1872. $nm = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  1873. if ($nm !== '') {
  1874. $names[] = $nm;
  1875. }
  1876. }
  1877. $n = count($names);
  1878. $nameStr = $n ? implode('、', $names) : '(未查询到单位名称)';
  1879. $this->addOrderLog(
  1880. $ids,
  1881. 'review_issue',
  1882. '审核共选择 ' . $n . ' 家单位:' . $nameStr,
  1883. $poIdLog
  1884. );
  1885. $this->success('操作成功');
  1886. }
  1887. return $this->view->fetch();
  1888. }
  1889. /**
  1890. * 审核弹窗获取公司列表
  1891. */
  1892. public function reviewCompanies()
  1893. {
  1894. if (!$this->request->isAjax()) {
  1895. $this->error(__('Invalid parameters'));
  1896. }
  1897. $list = [];
  1898. try {
  1899. $rows = Db::table('customer')->order('id', 'desc')->select();
  1900. } catch (\Throwable $e) {
  1901. $this->success('', '', []);
  1902. return;
  1903. }
  1904. if (!is_array($rows)) {
  1905. $this->success('', '', []);
  1906. return;
  1907. }
  1908. $detailColCandidates = [
  1909. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  1910. 'company_detail', 'company_desc', 'address',
  1911. ];
  1912. foreach ($rows as $row) {
  1913. if (!is_array($row)) {
  1914. continue;
  1915. }
  1916. $norm = [];
  1917. foreach ($row as $k => $v) {
  1918. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  1919. }
  1920. $row = $norm;
  1921. $id = isset($row['id']) ? (string)$row['id'] : '';
  1922. $companyName = '';
  1923. foreach (['company_name', 'name'] as $nk) {
  1924. if (!empty($row[$nk])) {
  1925. $companyName = trim((string)$row[$nk]);
  1926. break;
  1927. }
  1928. }
  1929. $username = '';
  1930. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  1931. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  1932. $username = trim((string)$row[$uk]);
  1933. break;
  1934. }
  1935. }
  1936. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  1937. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  1938. $category = '';
  1939. foreach (['company_type', 'category', 'type_name'] as $ck) {
  1940. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  1941. $category = trim((string)$row[$ck]);
  1942. break;
  1943. }
  1944. }
  1945. $detail = '';
  1946. foreach ($detailColCandidates as $dk) {
  1947. if (!isset($row[$dk])) {
  1948. continue;
  1949. }
  1950. $dv = trim((string)$row[$dk]);
  1951. if ($dv !== '') {
  1952. $detail = $dv;
  1953. break;
  1954. }
  1955. }
  1956. $list[] = [
  1957. 'id' => $id,
  1958. 'name' => $companyName,
  1959. 'company_name' => $companyName,
  1960. 'username' => $username,
  1961. 'email' => $email,
  1962. 'phone' => $phone,
  1963. 'category' => $category,
  1964. 'company_type' => $category,
  1965. 'detail' => $detail,
  1966. ];
  1967. }
  1968. $this->success('', '', $list);
  1969. }
  1970. /**
  1971. * 采购确认-下发明细弹窗:
  1972. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  1973. */
  1974. public function outward_detail()
  1975. {
  1976. $ids = $this->request->param('ids', $this->request->param('id', ''));
  1977. if (is_array($ids)) {
  1978. $ids = isset($ids[0]) ? $ids[0] : '';
  1979. }
  1980. $ids = trim((string)$ids);
  1981. if ($ids === '') {
  1982. $this->error(__('Invalid parameters'));
  1983. }
  1984. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  1985. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done'], true)) {
  1986. $wffTab = 'all';
  1987. }
  1988. $headTitle = $wffTab === 'pending' ? '采购确认(明细)' : '下发明细';
  1989. $rows = [];
  1990. try {
  1991. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $ids)->order('id', 'desc')->select();
  1992. } catch (\Throwable $e) {
  1993. $rows = [];
  1994. }
  1995. foreach ($rows as &$r) {
  1996. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  1997. $r['id'] = $r['ID'];
  1998. }
  1999. if (isset($r['createtime'])) {
  2000. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  2001. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  2002. } else {
  2003. $r['createtime_text'] = (string)$r['createtime'];
  2004. }
  2005. } else {
  2006. $r['createtime_text'] = '';
  2007. }
  2008. }
  2009. unset($r);
  2010. $purchaseOrderId = 0;
  2011. try {
  2012. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2013. if (is_array($po)) {
  2014. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  2015. }
  2016. } catch (\Throwable $e) {
  2017. $purchaseOrderId = 0;
  2018. }
  2019. $this->view->assign('rows', $rows ?: []);
  2020. $this->view->assign('rowCount', count($rows ?: []));
  2021. $this->view->assign('scydgyId', $ids);
  2022. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  2023. $this->view->assign('headTitle', $headTitle);
  2024. $this->view->assign('showPurchaseConfirm', $wffTab === 'pending' ? 1 : 0);
  2025. $this->view->assign('detailColspan', $wffTab === 'pending' ? 10 : 9);
  2026. /* 采购确认(pending)需在 iframe 内加载 require-backend,以便勾选与提交;其它 tab 仅只读表格,用轻量壳避免整站 JS/CSS 二次初始化导致弹窗极慢 */
  2027. if ($wffTab === 'pending') {
  2028. return $this->view->fetch();
  2029. }
  2030. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2031. $this->view->engine->layout(false);
  2032. try {
  2033. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  2034. $this->view->assign('dialogBody', $bodyHtml);
  2035. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  2036. } finally {
  2037. if ($restoreLayout) {
  2038. $this->view->engine->layout($restoreLayout);
  2039. }
  2040. }
  2041. }
  2042. /**
  2043. * 按月份导出:已完结且采购确认已选定供应商(明细 status=1),与列表「已完结」∩「已选中」一致。
  2044. * 表头固定 8 列(与历史「外发明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  2045. */
  2046. public function export_month_outward()
  2047. {
  2048. $this->request->filter(['strip_tags', 'trim']);
  2049. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  2050. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  2051. $ym = date('Y-m');
  2052. }
  2053. $monthStart = $ym . '-01 00:00:00';
  2054. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  2055. $dbRows = [];
  2056. try {
  2057. $dbRows = Db::table('purchase_order')->where('status', 1)->select();
  2058. } catch (\Throwable $e) {
  2059. $dbRows = [];
  2060. }
  2061. if (!is_array($dbRows)) {
  2062. $dbRows = [];
  2063. }
  2064. $pickedSidSet = $this->loadScydgyIdsWithPickedSupplierDetail();
  2065. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($pickedSidSet) {
  2066. if (!is_array($dbRow)) {
  2067. return false;
  2068. }
  2069. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2070. if ($sid <= 0 && isset($dbRow['SCYDGY_ID'])) {
  2071. $sid = (int)$dbRow['SCYDGY_ID'];
  2072. }
  2073. return $sid > 0 && isset($pickedSidSet[$sid]);
  2074. }));
  2075. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  2076. $filtered = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], []);
  2077. $mainBySid = [];
  2078. foreach ($filtered as $rw) {
  2079. if (!is_array($rw)) {
  2080. continue;
  2081. }
  2082. $rid = (int)($rw['ID'] ?? 0);
  2083. if ($rid > 0) {
  2084. $mainBySid[$rid] = $rw;
  2085. }
  2086. }
  2087. if ($mainBySid === []) {
  2088. $detailRows = [];
  2089. } else {
  2090. try {
  2091. $detailRows = Db::table('purchase_order_detail')
  2092. ->where('scydgy_id', 'in', array_keys($mainBySid))
  2093. ->where('status', 1)
  2094. ->order('CCYDH', 'asc')
  2095. ->order('company_name', 'asc')
  2096. ->order('id', 'asc')
  2097. ->select();
  2098. } catch (\Throwable $e) {
  2099. try {
  2100. $detailRows = Db::table('purchase_order_detail')
  2101. ->where('scydgy_id', 'in', array_keys($mainBySid))
  2102. ->where('status', 1)
  2103. ->order('CCYDH', 'asc')
  2104. ->order('company_name', 'asc')
  2105. ->order('ID', 'asc')
  2106. ->select();
  2107. } catch (\Throwable $e2) {
  2108. $detailRows = [];
  2109. }
  2110. }
  2111. }
  2112. if (!is_array($detailRows)) {
  2113. $detailRows = [];
  2114. }
  2115. $exportLines = [];
  2116. foreach ($detailRows as $dr) {
  2117. if (!is_array($dr)) {
  2118. continue;
  2119. }
  2120. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  2121. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  2122. continue;
  2123. }
  2124. $m = $mainBySid[$sid];
  2125. $exportLines[] = [
  2126. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  2127. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  2128. 'company_name' => (string)($dr['company_name'] ?? ''),
  2129. 'CDF' => (string)($m['CDF'] ?? ''),
  2130. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  2131. 'gx' => $this->procuremenExportGxText($m),
  2132. 'detail' => $dr,
  2133. ];
  2134. }
  2135. $groups = [];
  2136. foreach ($exportLines as $line) {
  2137. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  2138. if (!isset($groups[$k])) {
  2139. $groups[$k] = [];
  2140. }
  2141. $groups[$k][] = $line;
  2142. }
  2143. ksort($groups, SORT_STRING);
  2144. $spreadsheet = new Spreadsheet();
  2145. $sheet = $spreadsheet->getActiveSheet();
  2146. $sheet->setTitle('外发明细');
  2147. $mon = (int)substr($ym, 5, 2);
  2148. $sheet->mergeCells('A1:H1');
  2149. $sheet->setCellValue('A1', $mon . '月外发明细');
  2150. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  2151. $sheet->getStyle('A1')->getAlignment()
  2152. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  2153. ->setVertical(Alignment::VERTICAL_CENTER);
  2154. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  2155. $col = 'A';
  2156. foreach ($headers as $h) {
  2157. $sheet->setCellValue($col . '2', $h);
  2158. $col++;
  2159. }
  2160. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  2161. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  2162. $rowNum = 3;
  2163. $sumSubtotalCounts = 0;
  2164. $grandAmount = 0.0;
  2165. if ($groups === []) {
  2166. $sheet->mergeCells('A3:H3');
  2167. $sheet->setCellValue('A3', '(当月暂无符合条件的外发明细)');
  2168. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  2169. $rowNum = 4;
  2170. } else {
  2171. foreach ($groups as $items) {
  2172. if ($items === []) {
  2173. continue;
  2174. }
  2175. $groupLineCount = count($items);
  2176. $subAmount = 0.0;
  2177. $i = 0;
  2178. foreach ($items as $line) {
  2179. $i++;
  2180. $dr = $line['detail'];
  2181. $amt = $this->procuremenExportAmount($dr);
  2182. $subAmount += $amt;
  2183. $sheet->setCellValue('A' . $rowNum, $i);
  2184. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  2185. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  2186. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  2187. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  2188. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  2189. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  2190. $sheet->setCellValue('H' . $rowNum, $amt);
  2191. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  2192. $rowNum++;
  2193. }
  2194. $sumSubtotalCounts += $groupLineCount;
  2195. $grandAmount += $subAmount;
  2196. $sheet->setCellValue('A' . $rowNum, $groupLineCount);
  2197. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  2198. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  2199. $sheet->getStyle('G' . $rowNum)->getAlignment()
  2200. ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
  2201. ->setVertical(Alignment::VERTICAL_CENTER);
  2202. $rowNum++;
  2203. }
  2204. }
  2205. $sheet->setCellValue('A' . $rowNum, '总计');
  2206. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  2207. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  2208. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  2209. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  2210. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  2211. $lastRow = $rowNum;
  2212. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  2213. 'borders' => [
  2214. 'allBorders' => [
  2215. 'borderStyle' => Border::BORDER_THIN,
  2216. 'color' => ['rgb' => '000000'],
  2217. ],
  2218. ],
  2219. ]);
  2220. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  2221. if ($lastRow >= 3) {
  2222. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  2223. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  2224. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  2225. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  2226. }
  2227. $sheet->getColumnDimension('A')->setWidth(7);
  2228. $sheet->getColumnDimension('B')->setWidth(16);
  2229. $sheet->getColumnDimension('C')->setWidth(52);
  2230. $sheet->getColumnDimension('D')->setWidth(32);
  2231. $sheet->getColumnDimension('E')->setWidth(12);
  2232. $sheet->getColumnDimension('F')->setWidth(44);
  2233. $sheet->getColumnDimension('G')->setWidth(26);
  2234. $sheet->getColumnDimension('H')->setWidth(13);
  2235. $sheet->getRowDimension(1)->setRowHeight(28);
  2236. $fileBase = '外发明细_' . str_replace('-', '', $ym);
  2237. $filename = $fileBase . '.xlsx';
  2238. if (ob_get_length()) {
  2239. ob_end_clean();
  2240. }
  2241. $asciiName = 'outward_' . str_replace('-', '', $ym) . '.xlsx';
  2242. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  2243. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  2244. header('Cache-Control: max-age=0');
  2245. $writer = new Xlsx($spreadsheet);
  2246. $writer->save('php://output');
  2247. $spreadsheet->disconnectWorksheets();
  2248. unset($spreadsheet);
  2249. exit;
  2250. }
  2251. /**
  2252. * 导出用:工序列文案
  2253. */
  2254. protected function procuremenExportGxText(array $r)
  2255. {
  2256. $a = trim((string)($r['CDXMC'] ?? ''));
  2257. $b = trim((string)($r['CGYMC'] ?? ''));
  2258. if ($a !== '' && $b !== '') {
  2259. return $a . ':' . $b;
  2260. }
  2261. return $a !== '' ? $a : $b;
  2262. }
  2263. /**
  2264. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  2265. */
  2266. protected function procuremenExportAmount(array $r)
  2267. {
  2268. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  2269. if (!array_key_exists($k, $r)) {
  2270. continue;
  2271. }
  2272. $v = $r[$k];
  2273. if ($v === null || $v === '') {
  2274. continue;
  2275. }
  2276. if (is_numeric($v)) {
  2277. return (float)$v;
  2278. }
  2279. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  2280. if ($v !== '' && is_numeric($v)) {
  2281. return (float)$v;
  2282. }
  2283. }
  2284. return 0.0;
  2285. }
  2286. /**
  2287. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  2288. */
  2289. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  2290. {
  2291. $s = trim($ccydh);
  2292. if ($s === '') {
  2293. return 'ORDER';
  2294. }
  2295. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  2296. $s = trim($s, '._-');
  2297. if ($s === '') {
  2298. return 'ORDER';
  2299. }
  2300. if (function_exists('mb_substr')) {
  2301. return mb_substr($s, 0, 80, 'UTF-8');
  2302. }
  2303. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  2304. }
  2305. /**
  2306. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  2307. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  2308. *
  2309. * @return array{objectKey: string, webPath: string}
  2310. */
  2311. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  2312. {
  2313. $sid = (int)$scydgyId;
  2314. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  2315. $y = date('Y');
  2316. $m = date('m');
  2317. $d = date('d');
  2318. $basename = $safeOrder . '_' . $sid . '.pdf';
  2319. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  2320. return [
  2321. 'objectKey' => $objectKey,
  2322. 'webPath' => '/' . $objectKey,
  2323. ];
  2324. }
  2325. /**
  2326. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  2327. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  2328. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  2329. *
  2330. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  2331. */
  2332. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  2333. {
  2334. if ($scydgyId <= 0) {
  2335. return '';
  2336. }
  2337. $ids = trim((string)$scydgyId);
  2338. $prep = $this->prepareProcuremenDetailsView($ids);
  2339. if (!$prep['ok']) {
  2340. return '';
  2341. }
  2342. $ccydh = $prep['ccydh'];
  2343. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  2344. $objectKey = $paths['objectKey'];
  2345. $webPath = $paths['webPath'];
  2346. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  2347. $this->view->assign([
  2348. 'pdf_export' => 1,
  2349. 'pdfMetaLine' => $meta,
  2350. ]);
  2351. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  2352. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2353. $this->view->engine->layout(false);
  2354. try {
  2355. $html = $this->view->fetch('procuremen/details_pdf_shell');
  2356. } catch (\Throwable $e) {
  2357. if ($restoreLayout) {
  2358. $this->view->engine->layout($restoreLayout);
  2359. }
  2360. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  2361. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  2362. return '';
  2363. }
  2364. if ($restoreLayout) {
  2365. $this->view->engine->layout($restoreLayout);
  2366. }
  2367. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  2368. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  2369. if (!is_dir($tempDir)) {
  2370. @mkdir($tempDir, 0755, true);
  2371. }
  2372. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  2373. try {
  2374. $mpdf = new \Mpdf\Mpdf([
  2375. 'mode' => 'utf-8',
  2376. 'format' => 'A4',
  2377. 'margin_left' => 12,
  2378. 'margin_right' => 12,
  2379. 'margin_top' => 14,
  2380. 'margin_bottom' => 14,
  2381. 'tempDir' => $tempDir,
  2382. 'autoScriptToLang' => true,
  2383. 'autoLangToFont' => true,
  2384. ]);
  2385. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  2386. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  2387. $mpdf->SetBasePath('http://127.0.0.1/');
  2388. $mpdf->WriteHTML($html);
  2389. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  2390. } catch (\Throwable $e) {
  2391. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  2392. if (is_file($tempPdf)) {
  2393. @unlink($tempPdf);
  2394. }
  2395. return '';
  2396. }
  2397. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  2398. if ($ossUrl !== '') {
  2399. @unlink($tempPdf);
  2400. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  2401. return $ossUrl;
  2402. }
  2403. $pi = pathinfo($objectKey);
  2404. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  2405. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  2406. if ($baseFile === '') {
  2407. @unlink($tempPdf);
  2408. return '';
  2409. }
  2410. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  2411. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  2412. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  2413. @unlink($tempPdf);
  2414. return '';
  2415. }
  2416. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  2417. if (!@copy($tempPdf, $fullPath)) {
  2418. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  2419. @unlink($tempPdf);
  2420. return '';
  2421. }
  2422. @unlink($tempPdf);
  2423. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  2424. return $webPath;
  2425. }
  2426. /**
  2427. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  2428. */
  2429. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  2430. {
  2431. if ($scydgyId <= 0 || $webPath === '') {
  2432. return;
  2433. }
  2434. try {
  2435. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  2436. } catch (\Throwable $e) {
  2437. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  2438. }
  2439. }
  2440. /**
  2441. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  2442. * @throws \Exception
  2443. */
  2444. protected function smsbao($phone, $content)
  2445. {
  2446. $statusStr = [
  2447. '0' => '短信发送成功',
  2448. '-1' => '参数不全',
  2449. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  2450. '30' => '密码错误',
  2451. '40' => '账号不存在',
  2452. '41' => '余额不足',
  2453. '42' => '帐户已过期',
  2454. '43' => 'IP地址限制',
  2455. '50' => '内容含有敏感词',
  2456. ];
  2457. $smsapi = 'http://api.smsbao.com/';
  2458. $user = 'zhuwei123';
  2459. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  2460. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  2461. $result = @file_get_contents($sendurl);
  2462. if ($result === false) {
  2463. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  2464. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  2465. }
  2466. $result = trim((string)$result);
  2467. if ($result !== '0') {
  2468. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  2469. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  2470. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  2471. }
  2472. }
  2473. }