destination_delivery.class.php 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659
  1. <?php
  2. if (!defined('IN_ONLINE')) {
  3. exit('Access Denied');
  4. }
  5. /**
  6. * Description of operation_log
  7. *
  8. * @author Administrator
  9. */
  10. class destination_delivery {
  11. private static $_destination_delivery;
  12. public static function getInstance() {
  13. if (!self::$_destination_delivery) {
  14. $c = __CLASS__;
  15. self::$_destination_delivery = new $c;
  16. }
  17. return self::$_destination_delivery;
  18. }
  19. /**
  20. * 关于destination_delivery 页面的所有的静态加载数据查询
  21. */
  22. public function destination_delivery_load(){
  23. $operate = utils::_get('operate');
  24. $operate = strtolower($operate);
  25. /**
  26. * select country
  27. */
  28. if ($operate == "country") {
  29. $term = $_POST['term'];
  30. $term = trim($term);
  31. $sql = "select DISTINCT category AS country_code from public.kerry_system_code
  32. where description='COUNTRY-STATION'
  33. and category ilike '" . common::check_input($term) . "%'";
  34. $sql .= " order by category";
  35. $rs = common::excuteListSql($sql);
  36. //前端要加上id 从1开始
  37. $retData = array();
  38. foreach($rs as $key => $val){
  39. if(!empty($val['country_code'])){
  40. $retData[] = array("value" =>$val['country_code'] ,"label"=>$val['country_code']);
  41. }
  42. }
  43. common::echo_json_encode(200,$retData);
  44. exit();
  45. }
  46. /**
  47. * select station 选择国家后再展示 station list数据
  48. */
  49. if ($operate == "station") {
  50. $country = common::check_input($_REQUEST['country']);
  51. $sql = "select code from public.kerry_system_code
  52. where description='COUNTRY-STATION'
  53. and category = '".$country."'
  54. and code NOT LIKE 'Online_%'";
  55. $rs = common::excuteListSql($sql);
  56. foreach($rs as $key => $val){
  57. if(!empty($val['code'])){
  58. $retData[] = array("value" =>$val['code'] ,"label"=>$val['code']);
  59. }
  60. }
  61. common::echo_json_encode(200,$retData);
  62. exit();
  63. }
  64. /**
  65. * select KLN PIC 下拉可供选择的employee帐号,且帐号权限站点包括选中的station ?
  66. */
  67. if ($operate == "employee_account") {
  68. $term = $_POST['term'];
  69. $term = trim($term);
  70. $station = $_REQUEST['station'];
  71. $sqlwhere = '';
  72. if(!empty($station)){
  73. $more_param = common::getInNotInSqlForSearch(utils::implode(';',$station));
  74. $sqlwhere = " and lower(e.contact_id) in ($more_param) ";
  75. }
  76. $sql = "select e.email from public.ra_online_user r, employee e
  77. where r.employee_id=e.employee_id
  78. and r.online_active = true
  79. and r.user_type = 'Employee'
  80. and e.active = true
  81. ".$sqlwhere."
  82. and coalesce(e.email,'') <>''
  83. and e.email ilike '" . common::check_input($term) . "%' limit 20";
  84. // $sql = "select email from public.ra_online_user where user_type = 'Employee' and lower(contact_id) in ($more_param)
  85. // and email ilike '" . common::check_input($term) . "%' limit 20";
  86. //error_log($sql);
  87. $rs = common::excuteListSql($sql);
  88. $retData = array();
  89. foreach($rs as $key => $val){
  90. if(!empty($val['email'])){
  91. $retData[] = array("value" =>$val['email'] ,"label"=>$val['email']);
  92. }
  93. }
  94. common::echo_json_encode(200,$retData);
  95. exit();
  96. }
  97. /**
  98. * 下拉可供选择的ports
  99. */
  100. if ($operate == "ports") {
  101. $mode = $_POST['mode'];
  102. $term = $_POST['term'];
  103. $term = trim($term);
  104. if ($mode == 'sea'){
  105. $sql = "select DISTINCT uncode from public.ports
  106. where coalesce(uncode,'')<> '' and uncode ilike '" . common::check_input($term) . "%'";
  107. } else {
  108. $sql = "select DISTINCT coalesce(airport.country_abb,'')||airport.airport_code as uncode from sfs.airport
  109. where coalesce(country_abb,'')<>''
  110. and coalesce(airport.country_abb,'')||airport.airport_code ilike '" . common::check_input($term) . "%'";
  111. }
  112. $sql .= " order by uncode limit 20";
  113. $rs = common::excuteListSql($sql);
  114. //前端要加上id 从1开始
  115. $retData = array();
  116. foreach($rs as $key => $val){
  117. if(!empty($val['uncode'])){
  118. $retData[] = array("value" =>$val['uncode'] ,"label"=>$val['uncode'],"checked"=>false);
  119. }
  120. }
  121. common::echo_json_encode(200,$retData);
  122. exit();
  123. }
  124. /**
  125. * 下拉可供选择的carrier
  126. */
  127. if ($operate == "carrier") {
  128. $term = $_POST['term'];
  129. $term = trim($term);
  130. $sql = "select DISTINCT scac from public.vessel_company
  131. where coalesce(scac,'')<> '' and scac ilike '" . common::check_input($term) . "%'";
  132. $sql .= " order by scac limit 20";
  133. $rs = common::excuteListSql($sql);
  134. //前端要加上id 从1开始
  135. $retData = array();
  136. foreach($rs as $key => $val){
  137. if(!empty($val['scac'])){
  138. $retData[] = array("value" =>$val['scac'] ,"label"=>$val['scac'],"checked"=>false);
  139. }
  140. }
  141. common::echo_json_encode(200,$retData);
  142. exit();
  143. }
  144. /**
  145. * Manage Address load
  146. */
  147. if ($operate == "manage_address"){
  148. $consignee = $_REQUEST['consignee_id'];
  149. //$consignee =array('COMGEN38002','FGB050132','ATOZTI35005','WILSON80001');
  150. $more_param = common::getInNotInSqlForSearch(utils::implode(';',$consignee));
  151. $country = $_REQUEST['country'];
  152. //$country =array('GB','DE','US');
  153. $more_param_country = common::getInNotInSqlForSearch(utils::implode(';',$country));
  154. $delivery_serial_no = common::deCode($_REQUEST['delivery_serial_no'], 'D');
  155. //$delivery_serial_no = 'c4d2951f438a4c9fccde37f26614740a';
  156. if(!empty($delivery_serial_no)){
  157. $sql = "SELECT addr1,addr2,addr3,addr4,
  158. ctry_code,city_code,postal_code,
  159. contact_person,contact_number,
  160. create_user,contact_id,sync_key,
  161. from_station,
  162. 'from Ksmart' as op_action
  163. FROM public.contacts_address ca
  164. WHERE addr_type = 'D'
  165. and lower(ca.contact_id) in (".$more_param.")
  166. and ca.from_station in (select code from public.kerry_system_code where lower(category) in (".$more_param_country."))
  167. and ca.sync_key not in (select sync_key from public.contacts_address_online where delivery_serial_no = '".$delivery_serial_no."')
  168. union all
  169. SELECT addr1,addr2,addr3,addr4,
  170. ctry_code,city_code,postal_code,
  171. contact_person,contact_number,
  172. create_user,contact_id,sync_key,
  173. from_station,
  174. action as op_action
  175. FROM public.contacts_address_online
  176. where delivery_serial_no = '$delivery_serial_no'";
  177. }else{
  178. $sql = "SELECT addr1,addr2,addr3,addr4,
  179. ctry_code,city_code,postal_code,
  180. contact_person,contact_number,
  181. create_user,contact_id,sync_key,
  182. from_station,
  183. 'from Ksmart' as op_action
  184. FROM public.contacts_address ca
  185. WHERE addr_type = 'D'
  186. and lower(ca.contact_id) in (".$more_param.")
  187. and ca.from_station in (select code from public.kerry_system_code where lower(category) in (".$more_param_country."))";
  188. }
  189. $data = common::excuteListSql($sql);
  190. error_log($sql);
  191. $manageAddressList = array();
  192. //Online_D_Address
  193. foreach($data as $d){
  194. if ($d['op_action'] == "from Ksmart" && $d['create_user'] <> "Online_D_Address"){
  195. $address_remark = "read-only";
  196. } elseif ($d['op_action'] == "from Ksmart" && $d['create_user'] == "Online_D_Address"){
  197. $address_remark = "reviewed";
  198. } elseif ($d['op_action'] == "Add" && $d['create_user'] == "Online_D_Address"){
  199. $address_remark = "unreviewed";
  200. } elseif ($d['op_action'] == "Modify" && $d['create_user'] == "Online_D_Address"){
  201. $address_remark = "unreviewed";
  202. } else {
  203. $address_remark = "deletion";
  204. }
  205. $manageAddressList[] = array(
  206. "address_1"=>$d['addr1'],
  207. "address_2"=>$d['addr2'],
  208. "address_3"=>$d['addr3'],
  209. "address_4"=>$d['addr4'],
  210. "country"=>$d['ctry_code'],
  211. "city"=>$d['city_code'],
  212. "postal_code"=>$d['postal_code'],
  213. "contact_person"=>$d['contact_person'] === null ? '' : $d['contact_person'],
  214. "contact_number" =>$d['contact_number'] === null ? '' : $d['contact_number'],
  215. "create_user" => $d['create_user'], //create_user = Online_D_Address 时,代表對客戶賬號類型自己創建的D類地址
  216. "contact_id" => $d['contact_id'],
  217. "sync_key" => $d['sync_key'], //唯一key
  218. "from_station" => $d['from_station'], //只有是客户新键的才会特殊处理station Online_GE. 好判断是那个国家的
  219. "contact_type" => "Unedit", //这个前端控制的
  220. "op_action" => $d['op_action'],
  221. "address_remark" => $address_remark
  222. );
  223. }
  224. common::echo_json_encode(200,$manageAddressList);
  225. exit();
  226. }
  227. /**
  228. * country and city load
  229. */
  230. if ($operate == "country_city_load") {
  231. $term_type = $_POST['term_type'];
  232. $limit = $_POST['limit'];
  233. $term = $_POST['term'];
  234. $term = trim($term);
  235. $extend_sql_where = "";
  236. if ($term_type == "country" && !empty($limit)){
  237. $extend_sql_where = " and location_code = '$limit'";
  238. }
  239. if ($term_type == "city" && !empty($limit)){
  240. $extend_sql_where = " and country_code = '$limit'";
  241. }
  242. if ($term_type == "country"){
  243. $sql = "select DISTINCT country_code AS code from public.unlocode
  244. where country_code ilike '" . common::check_input($term) . "%'".$extend_sql_where;
  245. $sql .= " order by country_code limit 20";
  246. }
  247. if ($term_type == "city"){
  248. $sql = "select DISTINCT location_code AS code from public.unlocode
  249. where location_code ilike '" . common::check_input($term) . "%'".$extend_sql_where;
  250. $sql .= " order by location_code limit 20";
  251. }
  252. $rs = common::excuteListSql($sql);
  253. //前端要加上id 从1开始
  254. $retData = array();
  255. foreach($rs as $key => $val){
  256. if(!empty($val['code'])){
  257. $retData[] = array("value" =>$val['code'] ,"label"=>$val['code']);
  258. }
  259. }
  260. common::echo_json_encode(200,$retData);
  261. exit();
  262. }
  263. }
  264. /**
  265. * destination_delivery 配置
  266. */
  267. public function destination_delivery_config(){
  268. $operate = utils::_get('operate');
  269. $operate = strtolower($operate);
  270. /**
  271. * 这个是嵌套在destination_delivery的配置查询,
  272. */
  273. if ($operate == "search"){
  274. $cp = common::check_input($_POST ['cp']); //current_page
  275. $ps = common::check_input($_POST ['ps']); //ps
  276. if (empty($ps))
  277. $ps = 100;
  278. if (empty($cp))
  279. $cp = 1;
  280. $rc = $_POST ['rc'];
  281. if ($rc == - 1) {
  282. $sql = "select count(*) from public.kln_destination_delivery_config";
  283. $rc = common::excuteOneSql($sql);
  284. }
  285. $tp = ceil($rc / $ps);
  286. if ($rc > 0) {
  287. $sql = "select * from public.kln_destination_delivery_config";
  288. $sql .= " order by id desc limit " . $ps . " offset " . ($cp - 1) * $ps;
  289. $rs = common::excuteListSql($sql);
  290. foreach($rs as $key => $val){
  291. $rs[$key]["_serial_no"] = common::deCode($val['serial_no'], 'E');
  292. }
  293. $arrTmp = array('searchData' => $rs,
  294. 'rc' => intval($rc),
  295. 'ps' => intval($ps),
  296. 'cp' => intval($cp),
  297. 'tp' => intval($tp));
  298. common::echo_json_encode(200,$arrTmp);
  299. exit();
  300. }else{
  301. $arrTmp = array('searchData' => array());
  302. common::echo_json_encode(200, $arrTmp);
  303. exit();
  304. }
  305. }
  306. if ($operate == "add"){
  307. $serial_no = common::deCode($_REQUEST['a'], 'D');
  308. $data = array();
  309. $rule = array();
  310. if (!empty($serial_no)){
  311. $sql = "select * from public.kln_destination_delivery_config where serial_no = '$serial_no'";
  312. $data = common::excuteObjectSql($sql);
  313. if ($data['recommended_delivery'] == 'Delivery_ETA_ATA') {
  314. $sql = "select * from public.kln_destination_delivery_rule where recommended_delivery_serial_no = '$serial_no'";
  315. $rule = common::excuteListSql($sql);
  316. }
  317. } else{
  318. //代表新加,页面初始
  319. $data['booking_window'] = "No_Restrictions";
  320. $data['booking_window_date_start'] ="";
  321. $data['booking_window_date_end'] ="";
  322. $data['recommended_delivery'] ="No_Recommended";
  323. }
  324. //处理组装返回格式
  325. //RcommendDeliveryDate
  326. $RecommendCheckedAirList = array();
  327. $RecommendCheckedSeaList = array();
  328. $RecommendCheckedList = array();
  329. foreach($rule as $item){
  330. if ($item['mode_type'] == 'sea'){
  331. $RecommendCheckedSeaList[] = array("priority"=>$item['priority'],"rule_type"=>$item['rule_type'],
  332. "ports"=>explode(",", $item['ports']),
  333. "carrier"=>explode(",", $item['carrier']),
  334. "recommended_delivery_from"=>$item['recommended_delivery_from'],
  335. "recommended_delivery_to"=>$item['recommended_delivery_to'],
  336. "mode_type"=>$item['mode_type']);
  337. }
  338. if ($item['mode_type'] == 'air'){
  339. $RecommendCheckedAirList[] = array("priority"=>$item['priority'],"rule_type"=>$item['rule_type'],
  340. "ports"=>explode(",", $item['ports']),
  341. "carrier"=>explode(",", $item['carrier']),
  342. "recommended_delivery_from"=>$item['recommended_delivery_from'],
  343. "recommended_delivery_to"=>$item['recommended_delivery_to'],
  344. "mode_type"=>$item['mode_type']);
  345. }
  346. if (!utils::in_array(ucfirst($item['mode_type']), $RecommendCheckedList)) {
  347. $RecommendCheckedList[] = ucfirst($item['mode_type']);
  348. }
  349. }
  350. $returnData = $data;
  351. $returnData["SetBookingWindow"] = array("windowradio" =>common::destination_delivery_window_radio($data['booking_window']),
  352. "windowBeforeDays"=>$data['booking_window_date_start'],
  353. "windowAfterDays"=>$data['booking_window_date_end']);
  354. $returnData["RcommendDeliveryDate"] = array("Recommendradio" =>common::destination_delivery_recommended($data['recommended_delivery']),
  355. "RecommendCheckedList"=>$RecommendCheckedList,
  356. "RecommendCheckedAirList"=>$RecommendCheckedAirList,
  357. "RecommendCheckedSeaList"=>$RecommendCheckedSeaList);
  358. $returnData["KLNPLCvalue"] = empty($data['kln_pic']) ? array() : explode(";", $data['kln_pic']);
  359. $CountryCheckedList = array();
  360. $sql = "select crm.overeas from public.contract_region_mapping crm
  361. left join ocean.contacts c on c.contact_id = crm.overeas and crm.ksmart_station_new ilike 'ksmart%'
  362. where SUBSTRING(c.country FROM 1 FOR 2) = '".$data['country']."'";
  363. $rs = common::excuteListSql($sql);
  364. foreach($rs as $key => $val){
  365. if(!empty($val['overeas'])){
  366. $CountryCheckedList[] = array("value" =>$val['overeas'] ,"label"=>$val['overeas']);
  367. }
  368. }
  369. $returnData["CountryCheckedList"] = $CountryCheckedList;
  370. $returnData["station"] = explode(",", $returnData["station"]);
  371. $data = array('returnData' =>$returnData);
  372. common::echo_json_encode(200,$data);
  373. exit();
  374. }
  375. if ($operate == "save"){
  376. $serial_no = common::deCode($_POST['serial_no'], 'D');
  377. $country = common::check_input($_POST['country']);
  378. $station = empty($_POST['station']) ? "" : utils::implode(",",$_POST['station']);
  379. $booking_window = common::check_input($_POST['booking_window']);
  380. $booking_window_date_start = common::check_input($_POST['booking_window_date_start']);
  381. $booking_window_date_end = common::check_input($_POST['booking_window_date_end']);
  382. $recommended_delivery = common::check_input($_POST['recommended_delivery']);
  383. $kln_pic = common::check_input($_POST['kln_pic']);
  384. $booking_window_desc = common::check_input($_POST['booking_window_desc']);
  385. $recommended_delivery_date_desc = common::check_input($_POST['recommended_delivery_date_desc']);
  386. //rule
  387. $_mode_type = $_POST['mode_type'];
  388. $_priority = $_POST['priority'];
  389. $_rule_type = $_POST['rule_type'];
  390. $_ports = $_POST['ports'];
  391. $_carrier = $_POST['carrier'];
  392. $_recommended_delivery_from = $_POST['recommended_delivery_from'];
  393. $_recommended_delivery_to = $_POST['recommended_delivery_to'];
  394. $sql = "";
  395. if (!empty($serial_no)){
  396. $updateSqlSet = " modify_by = '"._getLoginName()."',update_time = now()";
  397. if (!empty($country)) {
  398. $updateSqlSet.= ", country = '$country' ";
  399. }
  400. if (!empty($station)) {
  401. $updateSqlSet.= ", station = '$station' ";
  402. }
  403. if (!empty($booking_window)) {
  404. $updateSqlSet.= ", booking_window = '$booking_window' ";
  405. }
  406. if (!empty($booking_window_date_start)) {
  407. $updateSqlSet.= ", booking_window_date_start = '$booking_window_date_start' ";
  408. }
  409. if (!empty($booking_window_date_end)) {
  410. $updateSqlSet.= ", booking_window_date_end = '$booking_window_date_end' ";
  411. }
  412. if (!empty($recommended_delivery)) {
  413. $updateSqlSet.= ", recommended_delivery = '$recommended_delivery' ";
  414. }
  415. if (!empty($kln_pic)) {
  416. $updateSqlSet.= ", kln_pic = '$kln_pic' ";
  417. }
  418. if (!empty($booking_window_desc)) {
  419. $updateSqlSet.= ", booking_window_desc = '$booking_window_desc' ";
  420. }
  421. if (!empty($recommended_delivery_date_desc)) {
  422. $updateSqlSet.= ", recommended_delivery_date_desc = '$recommended_delivery_date_desc' ";
  423. }
  424. //代表update
  425. $sql .= "update public.kln_destination_delivery_config set ".$updateSqlSet."
  426. where serial_no = '$serial_no';";
  427. } else {
  428. //检查配置的站点是否于以前的配置的,是否重合
  429. $exist = common::excuteListSql("select country,station from public.kln_destination_delivery_config WHERE string_to_array('$station', ',') && string_to_array(station, ',')");
  430. if(!empty($exist)){
  431. $data = array("msg" =>"The station has been reconfigured. Please check ".$exist[0]['country'] ." - " .$exist[0]['station']);
  432. common::echo_json_encode(200,$data);
  433. exit();
  434. }
  435. //代表更新
  436. $serial_no = common::uuid();
  437. $sql .="INSERT INTO public.kln_destination_delivery_config(
  438. serial_no, country, station, booking_window, booking_window_date_start,
  439. booking_window_date_end, recommended_delivery, kln_pic, booking_window_desc,recommended_delivery_date_desc,
  440. create_by, created_time, modify_by, update_time)
  441. VALUES ('$serial_no', '$country', '$station', '$booking_window', '$booking_window_date_start',
  442. '$booking_window_date_end', '$recommended_delivery', '$kln_pic','$booking_window_desc','$recommended_delivery_date_desc',
  443. '"._getLoginName()."', now(), '"._getLoginName()."', now());";
  444. }
  445. $errmsg = "";
  446. //柜子是先删除,后添加
  447. $sql .= "delete from public.kln_destination_delivery_rule where recommended_delivery_serial_no = '$serial_no';";
  448. if ($recommended_delivery == "Delivery_ETA_ATA"){
  449. // 用于统计每种类型是否存在,以及是否满足 rule_type = 'all'
  450. $typeExists = ['air' => false, 'sea' => false];
  451. $typeHasAllRule = ['air' => false, 'sea' => false];
  452. //检查判断规则不能重合
  453. $seaRule = [];
  454. $airRule = [];
  455. foreach($_mode_type as $key => $v){
  456. $mode_type = $v;
  457. $priority = $_priority[$key];
  458. $rule_type = $_rule_type[$key];
  459. $ports = $_ports[$key];
  460. $carrier = $_carrier[$key];
  461. if( $mode_type == 'sea'){
  462. $seaRule[] = explode(",",$_ports[$key]);
  463. ///$sea_carrier_index += 1;
  464. } else {
  465. $airRule[] = explode(",",$_ports[$key]);
  466. }
  467. $recommended_delivery_from = $_recommended_delivery_from[$key];
  468. $recommended_delivery_to = $_recommended_delivery_to[$key];
  469. $sql .= "INSERT INTO public.kln_destination_delivery_rule(
  470. recommended_delivery_serial_no, mode_type, priority,
  471. rule_type, ports, carrier, recommended_delivery_from, recommended_delivery_to,
  472. create_by, created_time, modify_by, update_time)
  473. VALUES ('$serial_no', '$mode_type', '$priority',
  474. '$rule_type', '$ports', '$carrier', '$recommended_delivery_from', '$recommended_delivery_to',
  475. '"._getLoginName()."', now(), '"._getLoginName()."', now());";
  476. $typeExists[$mode_type] = true;
  477. if ($rule_type == '*Default Rule') {
  478. $typeHasAllRule[$mode_type] = true;
  479. }
  480. }
  481. // 检查缺失的 rule_type = 'all'
  482. $missingTypes = [];
  483. foreach (['air', 'sea'] as $type) {
  484. if ($typeExists[$type] && !$typeHasAllRule[$type]) {
  485. $missingTypes[] = $type;
  486. }
  487. }
  488. if (!empty($missingTypes)) {
  489. $errmsg = "The Default Rule must exist.";
  490. }
  491. //检查规则不能重复
  492. $errmsg .= common::checkOverlap($seaRule,"Sea Rule");
  493. $errmsg .= common::checkOverlap($airRule,"Air Rule");
  494. }
  495. if (empty($errmsg) && !empty($sql)){
  496. common::excuteUpdateSql($sql);
  497. $data = array("msg" =>"success");
  498. } else {
  499. $data = array("msg" =>$errmsg);
  500. }
  501. common::echo_json_encode(200,$data);
  502. exit();
  503. }
  504. if ($operate == "delete"){
  505. $serial_no = common::deCode($_POST['a'], 'D');
  506. $sql = "delete from public.kln_destination_delivery_config where serial_no = '$serial_no';";
  507. $sql .= "delete from public.kln_destination_delivery_rule where recommended_delivery_serial_no = '$serial_no';";
  508. error_log($sql);
  509. common::excuteUpdateSql($sql);
  510. $data = array("msg" =>"success");
  511. common::echo_json_encode(200,$data);
  512. exit();
  513. }
  514. }
  515. /**
  516. * booking
  517. */
  518. public function destination_delivery_booking(){
  519. $operate = utils::_get('operate');
  520. $operate = strtolower($operate);
  521. if ($operate == "destination_delivery_search") {
  522. //search
  523. //栏位信息
  524. $column = column::getInstance()->getDisplayColumn('Destination_Delivery_Search');
  525. $BookingTableColumns = column::getInstance()->tableColumns('Destination_Delivery_Search',$column);
  526. $data['TrackingTableColumns'] = $BookingTableColumns;
  527. common::echo_json_encode(200,$data);
  528. exit();
  529. }
  530. if ($operate == "destination_delivery_shipment_search") {
  531. //search
  532. //栏位信息
  533. $column = column::getInstance()->getDisplayColumn('destination_delivery_shipment_search');
  534. $BookingTableColumns = column::getInstance()->tableColumns('destination_delivery_shipment_search',$column);
  535. $data['TrackingTableColumns'] = $BookingTableColumns;
  536. common::echo_json_encode(200,$data);
  537. exit();
  538. }
  539. /**
  540. * select shipment,
  541. * Pending Approval Approve Reject Cancel Modify Submit
  542. */
  543. if ($operate == "search"){
  544. $cp = common::check_input($_POST ['cp']); //current_page
  545. $ps = common::check_input($_POST ['ps']); //ps
  546. if (empty($ps))
  547. $ps = 100;
  548. if (empty($cp))
  549. $cp = 1;
  550. $sqlWhere = ' where ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  551. //兜底规则
  552. $sqlWhere .= " and eta >= now() - INTERVAL '6 months' and eta <= now() + INTERVAL '6 months'";
  553. //代表employee
  554. $sqlDeliveryWhere = " 1=1";
  555. if(_isApexLogin()){
  556. //$sqlWhere .= " and kln_pic ilike '"._getLoginEamil()."'";
  557. $sqlDeliveryWhere .= " and '".strtolower(_getLoginEmployeeEamil())."' in (select regexp_split_to_table(lower(kd.kln_pic), ','))";
  558. }
  559. //条件带入
  560. $text_search = $_REQUEST['text_search'];
  561. if (!empty($text_search)){
  562. $sqlWhere .= " and (booking_no ilike '%".strtolower($text_search)."%'
  563. or h_bol ilike '%".strtolower($text_search)."%'
  564. or m_bol ilike '%".strtolower($text_search)."%'
  565. or ctnr ilike '%".strtolower($text_search)."%'
  566. or consignee ilike '%".strtolower($text_search)."%')";
  567. }
  568. if (isset($_REQUEST['delivery_date_start']) && !empty($_REQUEST['delivery_date_start']))
  569. $sqlDeliveryWhere .= " and kd.delivery_date >= '" . common::usDate2sqlDate($_REQUEST['delivery_date_start']) . " 00:00:00'";
  570. if (isset($_REQUEST['delivery_date_end']) && !empty($_REQUEST['delivery_date_end']))
  571. $sqlDeliveryWhere .= " and kd.delivery_date <= '" . common::usDate2sqlDate($_REQUEST['delivery_date_end']) . " 23:59:59'";
  572. if(!empty($_POST['delivery_mode'])){
  573. $sqlDeliveryWhere .= " and kd.delivery_mode ='". common::check_input($_REQUEST['delivery_mode'])."'";
  574. }
  575. if (isset($_REQUEST['created_time_start']) && !empty($_REQUEST['created_time_start']))
  576. $sqlDeliveryWhere .= " and kd.created_time >= '" . common::usDate2sqlDate($_REQUEST['created_time_start']) . " 00:00:00'";
  577. if (isset($_REQUEST['created_time_end']) && !empty($_REQUEST['created_time_end']))
  578. $sqlDeliveryWhere .= " and kd.created_time <= '" . common::usDate2sqlDate($_REQUEST['created_time_end']) . " 23:59:59'";
  579. //移除filterTag
  580. //$sqlWhere_befrom_filterTag = $sqlWhere;
  581. $filterTag_param = "";
  582. if (!empty($_POST["filterTag"])) {
  583. if (utils::count($_POST['filterTag']) == 1){
  584. $filterTag = $_POST['filterTag'][0];
  585. }else{
  586. $filterTag = utils::implode(",", $_POST['filterTag']);
  587. }
  588. $filterTag_param = "1<>1";
  589. if(strtolower($filterTag) == "all"){
  590. $filterTag_param = "1=1";
  591. }
  592. if (stripos($filterTag, "Pending Approval") !== FALSE) {
  593. $filterTag_param .= " or (kd.status = 'Pending Approval')";
  594. }
  595. if (stripos($filterTag, "Approve") !== FALSE) {
  596. $filterTag_param .= " or (kd.status = 'Approve')";
  597. }
  598. if (stripos($filterTag, "Reject") !== FALSE) {
  599. $filterTag_param .= " or (kd.status = 'Reject')";
  600. }
  601. if (stripos($filterTag, "Cancel") !== FALSE) {
  602. $filterTag_param .= " or (kd.status = 'Cancel')";
  603. }
  604. if(strtolower($filterTag) <> "all" && !empty($filterTag)){
  605. $filterTag_param = " ($filterTag_param)";
  606. }
  607. }
  608. if(empty($filterTag_param)){
  609. $filterTag_param = "1=1";
  610. }
  611. $tag_and_mode_param = $filterTag_param;
  612. $rc = $_POST ['rc'];
  613. if ($rc == - 1 || true) {
  614. $sql = "select count(1) as rc,
  615. sum(case when $tag_and_mode_param then 1 else 0 end) as seach_rc,
  616. sum(case when kd.status ='Pending Approval' then 1 else 0 end) as pending_approval_rc,
  617. sum(case when kd.status ='Approve' then 1 else 0 end) as approved_rc,
  618. sum(case when kd.status ='Reject' then 1 else 0 end) as rejected_rc,
  619. sum(case when kd.status ='Cancel' then 1 else 0 end) as cancelled_rc
  620. from public.kln_destination_delivery kd
  621. where ".$sqlDeliveryWhere."
  622. and exists(select 1 from public.kln_ocean oo ". $sqlWhere." and oo.serial_no = any(kd.h_serial_no))";
  623. error_log("kln_destination_delivery_count:".$sql);
  624. $statusRc = common::excuteObjectSql($sql);
  625. $rc = $statusRc['rc'];
  626. $search_rc = $statusRc['seach_rc'];
  627. $pending_approval_rc = $statusRc['pending_approval_rc'];
  628. $approved_rc = $statusRc['approved_rc'];
  629. $rejected_rc = $statusRc['rejected_rc'];
  630. $cancelled_rc = $statusRc['cancelled_rc'];
  631. }
  632. $tp = ceil($rc / $ps);
  633. if ($rc > 0) {
  634. $sql = "select *,to_char((recommended_delivery_window_date_from)::date, 'YYYY-MM-DD')
  635. || ';' ||
  636. to_char((recommended_delivery_window_date_to)::date, 'YYYY-MM-DD') AS date_range
  637. from public.kln_destination_delivery kd
  638. where ".$tag_and_mode_param."
  639. and ".$sqlDeliveryWhere."
  640. and exists(select 1 from public.kln_ocean oo ". $sqlWhere." and oo.serial_no = any(h_serial_no))";
  641. $sql .= " order by id desc limit " . $ps . " offset " . ($cp - 1) * $ps;
  642. error_log("kln_destination_delivery_search:".$sql);
  643. $rs = common::excuteListSql($sql);
  644. foreach($rs as $key => $val){
  645. $rs[$key]["_serial_no"] = common::deCode($val['serial_no'], 'E');
  646. $rs[$key]["status"] = common::deliveryStatusConvert($val['status']);
  647. $rs[$key]["h_bol"] = json_decode($val['h_bol_multiple_link']);
  648. }
  649. $arrTmp = array('searchData' => $rs,
  650. 'is_employee' => _isApexLogin(),
  651. 'All' =>$rc,
  652. 'pending_approval_rc' =>$pending_approval_rc,
  653. 'approved_rc' =>$approved_rc,
  654. 'rejected_rc' =>$rejected_rc,
  655. 'cancelled_rc' =>$cancelled_rc,
  656. 'rc' => $search_rc,
  657. 'ps' => $ps,
  658. 'cp' => $cp,
  659. 'tp' => $tp);
  660. common::echo_json_encode(200,$arrTmp);
  661. exit();
  662. }else{
  663. $arrTmp = array('searchData' => array(),
  664. 'is_employee' => _isApexLogin(),
  665. 'All' =>$rc,
  666. 'pending_approval_rc' =>$pending_approval_rc,
  667. 'approved_rc' =>$approved_rc,
  668. 'rejected_rc' =>$rejected_rc,
  669. 'cancelled_rc' =>$cancelled_rc,
  670. 'rc' => $search_rc,
  671. 'ps' => $ps,
  672. 'cp' => $cp,
  673. 'tp' => $tp);
  674. common::echo_json_encode(200,$arrTmp);
  675. exit();
  676. }
  677. }
  678. if ($operate == "search_shipment"){
  679. $data = $this->search_shipment();
  680. if(!empty($data['msg'])){
  681. $arrTmp = array("msg" =>$data['msg']);
  682. }else{
  683. $arrTmp = array("msg" =>"success","data"=>$data['data']);
  684. }
  685. common::echo_json_encode(200, $arrTmp);
  686. exit();
  687. }
  688. if ($operate == "add"){
  689. $serial_no = common::deCode($_POST['serial_no'], 'D');
  690. //前端按钮 后台权限拦截
  691. if(!empty($serial_no)){
  692. common::checkedActionLegal($serial_no,$operate);
  693. }else{
  694. if(!_isApexLogin()){
  695. $data = array("msg" =>"Employees cannot create booking");
  696. common::echo_json_encode(200,$data);
  697. exit();
  698. }
  699. }
  700. $booking_data = array();
  701. if(!empty($serial_no)){
  702. //to_char(delivery_date, 'MM/DD/YYYY') AS _delivery_date,
  703. $sql = "select *,
  704. to_char(delivery_date, 'HH24:MI') AS _delivery_time
  705. from public.kln_destination_delivery where serial_no = '$serial_no'";
  706. $booking_data = common::excuteObjectSql($sql);
  707. $booking_data["delivery_time"] = $booking_data["_delivery_time"];
  708. $booking_data["delivery_address_detail"] = json_decode($booking_data["delivery_address_detail"],true);
  709. $shipments = $this->search_shipment_with_booking($booking_data['serial_no'],$booking_data['h_serial_no'],$booking_data['ctnr']);
  710. } else {
  711. $shipments = $this->search_shipment();
  712. }
  713. if(!empty($shipments['msg'])){
  714. $data = array("msg" =>$shipments['msg']);
  715. common::echo_json_encode(200,$data);
  716. exit();
  717. }
  718. $booking_data['tableData'] = $shipments['data'];
  719. $data = array("msg" =>"success","data"=>$booking_data);
  720. common::echo_json_encode(200,$data);
  721. exit();
  722. }
  723. if ($operate == "save"){
  724. $serial_no = common::deCode($_POST['serial_no'], 'D');
  725. $booking_no = $_POST['booking_no'];
  726. $manifest_type = $_POST['manifest_type'];
  727. $h_bol = $_POST['h_bol'];
  728. $h_serial_no = $_POST['serial_no'];
  729. $order_from = $_POST['order_from'];
  730. $m_bol = $_POST['m_bol'];
  731. $ctnr = $_POST['ctnr'];
  732. $kln_pic = $_POST['dc_kln_pic'];
  733. $consignee = $_POST['consignee'];
  734. $consignee_id = $_POST['consignee_id'];
  735. $dc_country = $_POST['dc_country'];
  736. $recommended_delivery_window_date_from = $_POST['recommended_delivery_from_date'];
  737. $recommended_delivery_window_date_to = $_POST['recommended_delivery_to_date'];
  738. $recommended_delivery_from = $_POST['recommended_delivery_from'];
  739. $recommended_delivery_to = $_POST['recommended_delivery_to'];
  740. $modify_reason = common::check_input($_POST['modify_reason']);
  741. $delivery_date = $_POST['delivery_date'];
  742. $delivery_time = $_POST['delivery_time'];
  743. $delivery_mode = common::check_input($_POST['delivery_mode']);
  744. //这status 编辑只有两种情况,新加,和在拒绝后 用户重新编辑 状态都是Pending Approval
  745. $status = "Pending Approval";
  746. $is_new = false;
  747. if(empty($serial_no)){
  748. $is_new = true;
  749. }
  750. $delivery_address = common::check_input($_POST['delivery_address']);
  751. $special_requirements = common::check_input($_POST['special_requirements']);
  752. //检查不能重复添加booking 这里空运没问题,但是会遇到相同hbol 不同的柜子情况,本质上来说就是一条
  753. //$sqlWhere = ' where ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  754. //兜底规则
  755. //$sqlWhere .= " and eta >= now() - INTERVAL '6 months' and eta <= now() + INTERVAL '6 months'";
  756. // $ckeckedSql = "with save_table as (select regexp_split_to_table('".utils::implode(',',$h_serial_no)."', ',') as serial_no)
  757. // select string_agg(h_bol, ';') as h_bol from public.kln_destination_delivery kde
  758. // where exists(select 1 from save_table where save_table.serial_no = any(kde.h_serial_no))
  759. // and exists(select 1 from public.kln_ocean oo ". $sqlWhere." and oo.serial_no = any(kde.h_serial_no))";
  760. // //代表编辑
  761. // if(!empty($serial_no)){
  762. // $ckeckedSql .=" and kde.serial_no <> '$serial_no'";
  763. // }
  764. // $checkeData = common::excuteObjectSql($ckeckedSql);
  765. // if(!empty($checkeData['h_bol'])){
  766. // $data = array("msg" =>"The ".$checkeData['h_bol'] ." already exists");
  767. // common::echo_json_encode(200,$data);
  768. // exit();
  769. // }
  770. $sql = "";
  771. //代表修改
  772. if(!empty($serial_no)){
  773. $updateSqlSet = " modify_by = '"._getLoginName()."',update_time = now()";
  774. if (!empty($status)) {
  775. $updateSqlSet.= ", status = '$status' ";
  776. }
  777. if (!empty($delivery_address)) {
  778. $delivery_address_detail = common::check_input(json_encode(common::returnDAddress(),JSON_UNESCAPED_UNICODE));
  779. $updateSqlSet.= ", delivery_address = '$delivery_address' ";
  780. $updateSqlSet.= ", delivery_address_detail = '$delivery_address_detail' ";
  781. }
  782. if (!empty($special_requirements)) {
  783. $updateSqlSet.= ", special_requirements = '$special_requirements' ";
  784. }
  785. if (!empty($modify_reason)) {
  786. $updateSqlSet.= ", modify_reason = '$modify_reason' ";
  787. }
  788. if (!empty($delivery_date)) {
  789. $delivery_date = empty($_POST['delivery_date']) ? "null": "'".common::usDate2sqlDate($_POST['delivery_date'])." ".$delivery_time."'";
  790. $updateSqlSet.= ", delivery_date = $delivery_date";
  791. }
  792. //修改记录临时表
  793. common::saveDAddressTempTable($serial_no,$consignee_id);
  794. //代表update
  795. $sql .= "update public.kln_destination_delivery set ".$updateSqlSet."
  796. where serial_no = '$serial_no';";
  797. //记录log
  798. $sql .="INSERT INTO public.kln_destination_delivery_operation_log(
  799. serial_no, action,notes, create_by, created_time, created_zone)
  800. VALUES ('$serial_no', 'Submit','".$modify_reason."', '"._getLoginName()."', now(), ''); ";
  801. } else {
  802. $saveData = $this->groupShipments($booking_no,$manifest_type,$h_bol,$h_serial_no,$order_from,$m_bol,$ctnr,$kln_pic,$consignee,$consignee_id,
  803. $recommended_delivery_window_date_from, $recommended_delivery_window_date_to,
  804. $recommended_delivery_from,$recommended_delivery_to,$dc_country);
  805. foreach($saveData as $sData){
  806. $serial_no = common::uuid();
  807. // 使用 PostgreSQL 的 ARRAY 语法
  808. $tags_sql = "ARRAY['" . implode("','", array_map('pg_escape_string', $sData['h_serial_no'])) . "']";
  809. // 使用 PostgreSQL 的 ARRAY 语法
  810. $country_sql = "ARRAY['" . implode("','", array_map('pg_escape_string', $sData['dc_country'])) . "']";
  811. $recommended_delivery_window_date_from = "";
  812. if(empty($sData['recommended_delivery_window_date_from'])){
  813. $recommended_delivery_window_date_from = "null";
  814. } else {
  815. $recommended_delivery_window_date_from = "'".$sData['recommended_delivery_window_date_from']."'";
  816. }
  817. $recommended_delivery_window_date_to = "";
  818. if(empty($sData['recommended_delivery_window_date_to'])){
  819. $recommended_delivery_window_date_to = "null";
  820. } else {
  821. $recommended_delivery_window_date_to = "'".$sData['recommended_delivery_window_date_to']."'";
  822. }
  823. $delivery_date = empty($_POST['delivery_date']) ? "null": "'".common::usDate2sqlDate($_POST['delivery_date'])." ".$delivery_time."'";
  824. //修改记录临时表,有值代表选择的add
  825. $_sync_key_add = common::saveDAddressTempTable($serial_no,$sData['consignee_id']);
  826. $delivery_address_detail = common::check_input(json_encode(common::returnDAddress($_sync_key_add),JSON_UNESCAPED_UNICODE));
  827. $sql .= "INSERT INTO public.kln_destination_delivery(
  828. serial_no, h_serial_no,address_country,
  829. booking_no, h_bol,h_bol_multiple_link,
  830. m_bol, ctnr,
  831. consignee, delivery_date, delivery_mode, status, delivery_address,delivery_address_detail, special_requirements,
  832. recommended_delivery_window_date_from, recommended_delivery_window_date_to, d_address_change_log,
  833. recommended_delivery_from, recommended_delivery_to,kln_pic,
  834. create_by, created_time, modify_by, update_time)
  835. VALUES ('$serial_no', ".$tags_sql.",".$country_sql.",
  836. '".$sData['booking_no']."', '".utils::implode(',',$sData['h_bol'])."','".common::check_input(json_encode($sData['h_bol_multiple_link']))."',
  837. '".utils::implode(',',$sData['m_bol'])."', '".utils::implode(',',$sData['ctnr'])."',
  838. '".$sData['consignee']."', $delivery_date,'$delivery_mode','$status', '$delivery_address','$delivery_address_detail', '$special_requirements',
  839. $recommended_delivery_window_date_from, $recommended_delivery_window_date_to,'',
  840. '".$sData['recommended_delivery_from']."', '".$sData['recommended_delivery_to']."','".$sData['kln_pic']."',
  841. '"._getLoginName()."', now(), '"._getLoginName()."', now());";
  842. //记录log
  843. $sql .="INSERT INTO public.kln_destination_delivery_operation_log(
  844. serial_no, action,notes, create_by, created_time, created_zone)
  845. VALUES ('$serial_no', 'Submit','', '"._getLoginName()."', now(), ''); ";
  846. }
  847. }
  848. if(!empty($sql)){
  849. $rs = common::excuteUpdateSql($sql);
  850. if ($rs === FALSE){
  851. $data = array("msg" =>"error");
  852. common::echo_json_encode(200,$data);
  853. exit();
  854. }
  855. }
  856. if(!$is_new){
  857. //状态变更时,发送邮件提醒
  858. $status = "Modify";
  859. $data = common::excuteObjectSql("select *, TO_CHAR(delivery_date, 'Mon-DD-YYYY') as _delivery_date,
  860. TO_CHAR(created_time, 'Mon-DD-YYYY') as _created_time,
  861. TO_CHAR(update_time, 'Mon-DD-YYYY') as _update_time
  862. from public.kln_destination_delivery where serial_no = '$serial_no'");
  863. $shipmentsData = $this->search_shipment_with_booking($data['serial_no'],$data['h_serial_no'],$data['ctnr']);
  864. $email_sql = common::sendDestinationDeliveryReminder($data,$shipmentsData,$status);
  865. if(!empty($email_sql)){
  866. common::excuteUpdateSql($email_sql);
  867. }
  868. } else {
  869. $status = "Submit";
  870. $data = common::excuteObjectSql("select *, TO_CHAR(delivery_date, 'Mon-DD-YYYY') as _delivery_date,
  871. TO_CHAR(created_time, 'Mon-DD-YYYY') as _created_time,
  872. TO_CHAR(update_time, 'Mon-DD-YYYY') as _update_time
  873. from public.kln_destination_delivery where serial_no = '$serial_no'");
  874. $shipmentsData = $this->search_shipment_with_booking($data['serial_no'],$data['h_serial_no'],$data['ctnr']);
  875. $email_sql = common::sendDestinationDeliveryReminder($data,$shipmentsData,$status);
  876. if(!empty($email_sql)){
  877. common::excuteUpdateSql($email_sql);
  878. }
  879. }
  880. $data = array("msg" =>"success");
  881. common::echo_json_encode(200,$data);
  882. exit();
  883. }
  884. /**
  885. * 审核 Approve or Reject Cancel Pending Approval
  886. */
  887. if ($operate == "review"){
  888. $serial_no = common::deCode($_POST['serial_no'], 'D');
  889. $status = common::check_input($_POST['status']);
  890. $notes = common::check_input($_POST['notes']);
  891. $action_user = _getLoginName();
  892. //前端按钮 后台权限拦截
  893. common::checkedActionLegal($serial_no,$operate);
  894. $sql = "";
  895. //审核通过时,才取下放当时应用修改的地址
  896. if ($status == "Approve") {
  897. $address_country = common::excuteOneSql("select array_to_json(address_country) as address_country from public.kln_destination_delivery where serial_no = '$serial_no'");
  898. $onine_address = common::excuteListSql("select * from public.contacts_address_online where delivery_serial_no = '$serial_no'");
  899. $sql .= "delete from public.contacts_address_online where delivery_serial_no = '$serial_no';";
  900. $sql .=common::returnDAddressRecord($address_country,$onine_address);
  901. }
  902. if ($status == "Reject" || $status == "Cancel") {
  903. //这种情况,清除当前用户对这一票的修改和添加的信息
  904. $sql .= "delete from public.contacts_address_online where delivery_serial_no = '$serial_no';";
  905. }
  906. $sql .= "update public.kln_destination_delivery set status = '$status', modify_by = '"._getLoginName()."',update_time = now() where serial_no = '$serial_no';";
  907. $sql .="INSERT INTO public.kln_destination_delivery_operation_log(
  908. serial_no, action,notes, create_by, created_time, created_zone)
  909. VALUES ('$serial_no', '$status','$notes', '$action_user', now(), ''); ";
  910. $rs = common::excuteUpdateSql($sql);
  911. if ($rs === FALSE){
  912. $data = array("msg" => "Update Error");
  913. common::echo_json_encode(200,$data);
  914. } else{
  915. //状态变更时,发送邮件提醒
  916. $data = common::excuteObjectSql("select *,
  917. TO_CHAR(delivery_date, 'Mon-DD-YYYY') as _delivery_date,
  918. TO_CHAR(created_time, 'Mon-DD-YYYY') as _created_time,
  919. TO_CHAR(update_time, 'Mon-DD-YYYY') as _update_time
  920. from public.kln_destination_delivery where serial_no = '$serial_no'");
  921. $shipmentsData = $this->search_shipment_with_booking($data['serial_no'],$data['h_serial_no'],$data['ctnr']);
  922. $email_sql = common::sendDestinationDeliveryReminder($data,$shipmentsData,$status);
  923. if(!empty($email_sql)){
  924. common::excuteUpdateSql($email_sql);
  925. }
  926. $data = array("msg" =>"success");
  927. common::echo_json_encode(200,$data);
  928. }
  929. }
  930. /**
  931. * 邮件留言初始
  932. */
  933. if ($operate == "email_message_init"){
  934. try {
  935. $email_uuid = common::deCode($_POST['serial_no'], 'D');
  936. $emailRecords = $this->getCommunicationNew($email_uuid);
  937. common::echo_json_encode(200,array("msg" => "Sent Successfully", "emailRecords" => $emailRecords));
  938. exit();
  939. } catch (Exception $e) {
  940. common::echo_json_encode(500,array("msg" => "Sent Error."));
  941. exit();
  942. }
  943. }
  944. /**
  945. * 邮件留言
  946. */
  947. if ($operate == "email_message_board"){
  948. //前端按钮 后台权限拦截
  949. $email_uuid = common::deCode($_POST['serial_no'], 'D');
  950. common::checkedActionLegal($email_uuid,$operate);
  951. try {
  952. $content = $_POST["content"];
  953. $content = common::check_input($content);
  954. $content = urldecode($content);
  955. $text = $_POST["text"];
  956. $web_content = urldecode($text);
  957. $serial_no = common::uuid();
  958. $email_uuid = common::deCode($_POST['serial_no'], 'D');
  959. $add_by = _getLoginName();
  960. $refer_id = 0;
  961. $from_email = "US.KApex.Online@kerryapex.com";
  962. $to_email = $_POST["kln_pic"];
  963. $cc_email = "";
  964. $communication_cc = $_POST["communication_cc"];
  965. $communication_cc = trim($communication_cc);
  966. if (!empty($communication_cc)) {
  967. $communication_cc = common::check_input($communication_cc);
  968. $cc_email = $communication_cc;
  969. }
  970. $user_from = _getLoginName();
  971. $h_bol_str = array();
  972. foreach($_POST["h_bol"] as $obj){
  973. $h_bol_str[] = $obj['key'];
  974. }
  975. //邮件发送
  976. $title = "Destination Delivery from " . _getLoginName() . ", Shipment No: " . utils::implode(',',$h_bol_str);
  977. $emailContent = $content;
  978. common::excuteUpdateSql("insert into public.email_record (type,title,from_email,to_email,cc_email,content,insert_date)values('Delivery_Comm','$title','$from_email','$to_email','$cc_email','$emailContent',now());");
  979. $rs = common::excuteUpdateSql("INSERT INTO public.online_ocean_communication(serial_no, email_uuid, content,web_content,user_from, user_to, user_cc, refer_id, add_by, add_time, cc_email)
  980. VALUES ('$serial_no', '$email_uuid', '$emailContent','$web_content', '$user_from', '$to_email', '$cc_email', $refer_id, '$add_by', now(), '$communication_cc');");
  981. $emailRecords = $this->getCommunicationNew($email_uuid);
  982. common::echo_json_encode(200,array("msg" => "Sent Successfully", "emailRecords" => $emailRecords));
  983. exit();
  984. } catch (Exception $e) {
  985. common::echo_json_encode(500,array("msg" => "Sent Error."));
  986. exit();
  987. }
  988. }
  989. /**
  990. * view detail and log
  991. */
  992. if ($operate == "view_detail"){
  993. $serial_no = common::deCode($_POST['serial_no'], 'D');
  994. //前端按钮 后台权限拦截
  995. common::checkedActionLegal($serial_no,$operate);
  996. $data = common::excuteObjectSql("select * from public.kln_destination_delivery where serial_no = '$serial_no'");
  997. $_shipmentsData = array();
  998. $shipmentsData = $this->search_shipment_with_booking($data['serial_no'],$data['h_serial_no'],$data['ctnr']);
  999. foreach($shipmentsData["data"] as $shipment){
  1000. $_shipmentsData[] = array("HBOL No." => $shipment['h_bol'],"Container No." => $shipment['ctnr'],
  1001. "Service Type" => $shipment['service'],"ETA" => $shipment['eta'],
  1002. "Recommended Delivery Date" => $shipment['date_range']);
  1003. }
  1004. $_operation_log = array();
  1005. $operation_log = common::excuteListSql("select * from public.kln_destination_delivery_operation_log where serial_no = '$serial_no' order by id desc");
  1006. foreach($operation_log as $log){
  1007. $action = $log['action'] == "Pending Approval" ? "Submit" : $log['action'];
  1008. $_operation_log[] = array("time" => $log['created_time'],"timezone" => $log['created_zone'],
  1009. "label" => $action,"createdBy" => $log['create_by'],
  1010. "tips" => $log['notes']);
  1011. }
  1012. $retData = $data;
  1013. $retData["status"] = common::deliveryStatusConvert($retData["status"]);
  1014. $retData['shipmentsData'] = $_shipmentsData;
  1015. $retData['operation_log'] = $_operation_log;
  1016. $data = array("msg" =>"success","data"=>$retData);
  1017. common::echo_json_encode(200,$data);
  1018. exit();
  1019. }
  1020. /**
  1021. * Delivery date
  1022. */
  1023. if ($operate == "delivery_date_load"){
  1024. $sqlWhere = ' where ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1025. //兜底规则
  1026. $sqlWhere .= " and eta >= now() - INTERVAL '6 months' and eta <= now() + INTERVAL '6 months'";
  1027. $sqlDeliveryWhere = " 1=1";
  1028. if(_isApexLogin()){
  1029. //$sqlWhere .= " and kln_pic ilike '"._getLoginEamil()."'";
  1030. $sqlDeliveryWhere .= " and '".strtolower(_getLoginEmployeeEamil())."' in (select regexp_split_to_table(lower(kd.kln_pic), ','))";
  1031. }
  1032. //$sqlWhere_befrom_filterTag = $sqlWhere;
  1033. $sql = "select delivery_date::date as delivery_date,
  1034. sum(case when status ='Pending Approval' then 1 else 0 end) as pending_approval_rc,
  1035. sum(case when status ='Approve' then 1 else 0 end) as approved_rc
  1036. from public.kln_destination_delivery kd
  1037. where ".$sqlDeliveryWhere."
  1038. and exists(select 1 from public.kln_ocean oo ". $sqlWhere." and oo.serial_no = any(h_serial_no))
  1039. group by delivery_date::date order by delivery_date::date desc";
  1040. $rs = common::excuteListSql($sql);
  1041. error_log("delivery_date_load:".$sql);
  1042. $dateArr = new stdClass();
  1043. foreach($rs as $val){
  1044. //$dateArr[] = array($val['delivery_date'] => array("pending"=>$val['pending_approval_rc'],"approved"=>$val['approved_rc']));
  1045. $dateArr->{$val['delivery_date']} = new stdClass();
  1046. $dateArr->{$val['delivery_date']}->pending = $val['pending_approval_rc'];
  1047. $dateArr->{$val['delivery_date']}->approved = $val['approved_rc'];
  1048. }
  1049. $data = array("msg" =>"success","data"=>$dateArr);
  1050. common::echo_json_encode(200,$data);
  1051. }
  1052. }
  1053. private function getCommunicationNew($serial_no) {
  1054. $list = common::excuteListSql("select to_char(add_time, 'MM/dd/yyyy hh24:MI:ss') as add_times, * from public.online_ocean_communication where email_uuid='$serial_no' and refer_id = 0 order by id");
  1055. $emialRecords =array();
  1056. foreach ($list as $k => $v) {
  1057. $msg =array();
  1058. $msg["name"] = $v["add_by"];
  1059. $msg["creatTime"] = $v["add_times"];
  1060. $msg["content"] = urldecode($v["web_content"]);
  1061. $emialRecords[] = $msg;
  1062. }
  1063. return $emialRecords;
  1064. }
  1065. function search_shipment(){
  1066. $sqlWhere_common = ' where ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  1067. //根據用戶的賬號權限所能看到的全部shipment數據的目的地站點,去匹配是否有開通destination delivery的服務,如果未開通,則展示此提示頁面
  1068. //兜底规则
  1069. $sqlWhere = $sqlWhere_common;
  1070. $sqlWhere .= " and eta >= now() - INTERVAL '6 months' and eta <= now() + INTERVAL '6 months'";
  1071. // $checkOpenSql = "with oo as ( select DISTINCT agent from public.kln_ocean oo ". $sqlWhere.")
  1072. // select agent from oo
  1073. // where exists(select 1 from public.kln_destination_delivery_config where oo.agent in (select regexp_split_to_table(station, E',')))
  1074. // limit 1";
  1075. $checkOpenSql = "select station from public.kln_destination_delivery_config dc
  1076. where exists(select 1 from
  1077. public.kln_ocean oo ". $sqlWhere."
  1078. and oo.agent in (select regexp_split_to_table(dc.station, E',')) limit 1
  1079. )";
  1080. $config = common::excuteListSql($checkOpenSql);
  1081. if(empty($config)){
  1082. return array("msg"=>"Destination Delivery Service Not Available","data"=>"");
  1083. }
  1084. //根據用戶的賬號權限所能看到的全部shipment數據的目的地站點,去匹配是否有開通destination delivery的服務,如果有開通,但沒有符合條件的shipment,則展示此提示頁面
  1085. $sqlWhere = $sqlWhere_common;
  1086. $sqlWhere .= " and eta >= now() - INTERVAL '6 months' and eta <= now() + INTERVAL '6 months'";
  1087. $text_search = $_REQUEST['text_search'];
  1088. if (!empty($text_search)){
  1089. $sqlWhere .= " and (oo.h_bol ilike '%".strtolower($text_search)."%'
  1090. or oo.po_no ilike '%".strtolower($text_search)."%'
  1091. or oo.ctnrs ilike '%".strtolower($text_search)."%')";
  1092. }
  1093. //vessel name
  1094. $vessel = $_REQUEST['vessel'];
  1095. if (!empty($vessel)){
  1096. $sqlWhere .= " and vessel ilike '%".strtolower($vessel)."'%";
  1097. }
  1098. $consignee = $_REQUEST['consignee'];
  1099. if (!empty($vessel)){
  1100. $sqlWhere .= " and consignee ilike '%".strtolower($consignee)."'%";
  1101. }
  1102. $shipper = $_REQUEST['shipper'];
  1103. if (!empty($vessel)){
  1104. $sqlWhere .= " and shipper ilike '%".strtolower($shipper)."'%";
  1105. }
  1106. if (isset($_REQUEST['eta_start']) && !empty($_REQUEST['eta_start']))
  1107. $sqlWhere .= " and eta >= '" . common::usDate2sqlDate($_REQUEST['eta_start']) . " 00:00:00'";
  1108. if (isset($_REQUEST['eta_end']) && !empty($_REQUEST['eta_end']))
  1109. $sqlWhere .= " and eta <= '" . common::usDate2sqlDate($_REQUEST['eta_end']) . " 23:59:59'";
  1110. if (isset($_REQUEST['ata_start']) && !empty($_REQUEST['ata_start']))
  1111. $sqlWhere .= " and ata >= '" . common::usDate2sqlDate($_REQUEST['ata_start']) . " 00:00:00'";
  1112. if (isset($_REQUEST['ata_end']) && !empty($_REQUEST['ata_end']))
  1113. $sqlWhere .= " and ata <= '" . common::usDate2sqlDate($_REQUEST['ata_end']) . " 23:59:59'";
  1114. $sql = "with oo as(
  1115. select * from public.kln_ocean oo ". $sqlWhere ."
  1116. ),
  1117. ooc as (
  1118. select oo.*,
  1119. dc.serial_no as dc_serial_no,
  1120. dc.country as dc_country,
  1121. dc.kln_pic as dc_kln_pic
  1122. from public.kln_destination_delivery_config dc
  1123. Inner Join oo
  1124. on oo.agent in (select regexp_split_to_table(dc.station, ','))
  1125. where 1=1 and
  1126. case when dc.booking_window = 'Restrictions_ETD_ATD' and COALESCE(dc.booking_window_date_start,'')<>'' and COALESCE(dc.booking_window_date_end,'')<>''
  1127. then COALESCE(atd, etd) >= (NOW() - (dc.booking_window_date_start ||' days')::INTERVAL)::date and COALESCE(atd, etd) <= (NOW() + (dc.booking_window_date_end ||' days')::INTERVAL)::date
  1128. when dc.booking_window = 'Restrictions_ETA_ATA' and COALESCE(dc.booking_window_date_start,'')<>'' and COALESCE(dc.booking_window_date_end,'')<>''
  1129. then COALESCE(ata, eta) >= (NOW() - (dc.booking_window_date_start ||' days')::INTERVAL)::date and COALESCE(ata, eta) <= (NOW() + (dc.booking_window_date_end ||' days')::INTERVAL)::date
  1130. else 1=1 end
  1131. ),
  1132. matched_data as (
  1133. select
  1134. ooc.serial_no,
  1135. ooc.h_bol,
  1136. ooc.m_bol,
  1137. oc.ctnr,
  1138. ooc.service,
  1139. ooc.po_no,
  1140. (select reference_no from public.ocean o where o.serial_no = ooc.serial_no limit 1) as reference_no,
  1141. ooc.transport_mode,
  1142. oc.qty::text as pakages,
  1143. oc.unit as package_type ,
  1144. oc.grs_kgs::text as kgw,
  1145. oc.cbm as volume,
  1146. ooc.vessel,
  1147. ooc.voyage,
  1148. ooc.carrier,
  1149. ooc.fport_of_loading_un,
  1150. ooc.mport_of_discharge_un,
  1151. ooc.eta,
  1152. ooc.ata,
  1153. ooc.shipper,
  1154. ooc.consignee_id,
  1155. ooc.consignee,
  1156. (select customer_name from public.ocean_extend ex where ex.serial_no = ooc.serial_no limit 1) as controlling_customer,
  1157. ooc.booking_no,
  1158. (select manifest_type from public.ocean o where o.serial_no = ooc.serial_no limit 1) as manifest_type,
  1159. dc_serial_no,
  1160. dc_country,
  1161. dc_kln_pic,
  1162. ooc.agent,
  1163. ooc.order_from
  1164. from ooc
  1165. LEFT JOIN public.oc_container oc ON oc.serial_no::text = ooc.serial_no::text
  1166. where ooc.order_from = 'public' and transport_mode = 'sea'
  1167. union all
  1168. select
  1169. ooc.serial_no,
  1170. ooc.h_bol,
  1171. ooc.m_bol,
  1172. oc.ctnr,
  1173. ooc.service,
  1174. ooc.po_no,
  1175. (select reference_no from sfs.ocean o where o.serial_no = ooc.serial_no limit 1) as reference_no,
  1176. ooc.transport_mode,
  1177. oc.qty::text as pakages,
  1178. oc.unit as package_type ,
  1179. oc.grs_kgs::text as kgw,
  1180. oc.cbm as volume,
  1181. ooc.vessel,
  1182. ooc.voyage,
  1183. ooc.carrier,
  1184. ooc.fport_of_loading_un,
  1185. ooc.mport_of_discharge_un,
  1186. ooc.eta,
  1187. ooc.ata,
  1188. ooc.shipper,
  1189. ooc.consignee_id,
  1190. ooc.consignee,
  1191. (select customer_name from ocean_extend ex where ex.serial_no = ooc.serial_no limit 1) as controlling_customer,
  1192. ooc.booking_no,
  1193. (select manifest_type from sfs.ocean o where o.serial_no = ooc.serial_no limit 1) as manifest_type,
  1194. dc_serial_no,
  1195. dc_country,
  1196. dc_kln_pic,
  1197. ooc.agent,
  1198. ooc.order_from
  1199. from ooc
  1200. LEFT JOIN sfs.oc_container oc ON oc.serial_no::text = ooc.serial_no::text
  1201. where ooc.order_from = 'sfs' and transport_mode = 'sea'
  1202. union all
  1203. select
  1204. ooc.serial_no,
  1205. ooc.h_bol,
  1206. ooc.m_bol,
  1207. '' as ctnr,
  1208. ooc.service,
  1209. ooc.po_no,
  1210. '' as reference_no,
  1211. ooc.transport_mode,
  1212. ooc.qty as pakages,
  1213. ooc.qty_uom as package_type ,
  1214. ooc.piece_count as kgw,
  1215. ooc.cbm as volume,
  1216. ooc.vessel,
  1217. ooc.voyage,
  1218. ooc.carrier,
  1219. ooc.fport_of_loading_un,
  1220. ooc.mport_of_discharge_un,
  1221. ooc.eta,
  1222. ooc.ata,
  1223. ooc.shipper,
  1224. ooc.consignee_id,
  1225. ooc.consignee,
  1226. '' as controlling_customer,
  1227. ooc.booking_no,
  1228. '' as manifest_type,
  1229. dc_serial_no,
  1230. dc_country,
  1231. dc_kln_pic,
  1232. ooc.agent,
  1233. ooc.order_from
  1234. from ooc
  1235. where ooc.transport_mode = 'air'
  1236. )
  1237. select md.*,
  1238. CASE
  1239. WHEN r.recommended_delivery_from IS NOT NULL AND r.recommended_delivery_to IS NOT NULL THEN
  1240. to_char((COALESCE(ata, eta) - (r.recommended_delivery_from ||' days')::INTERVAL)::date, 'YYYY.MM.DD')
  1241. || '-' ||
  1242. to_char((COALESCE(ata, eta) + (r.recommended_delivery_to ||' days')::INTERVAL)::date, 'YYYY.MM.DD')
  1243. WHEN r.recommended_delivery_from IS NULL AND r.recommended_delivery_to IS NOT NULL THEN
  1244. '-' ||
  1245. to_char((COALESCE(ata, eta) + (r.recommended_delivery_to || ' days')::INTERVAL)::date, 'YYYY.MM.DD')
  1246. WHEN r.recommended_delivery_from IS NOT NULL AND r.recommended_delivery_to IS NULL THEN
  1247. to_char((COALESCE(ata, eta) - (r.recommended_delivery_from || ' days')::INTERVAL)::date, 'YYYY.MM.DD')
  1248. || '-'
  1249. ELSE '' END
  1250. AS date_range,
  1251. r.recommended_delivery_from,
  1252. r.recommended_delivery_to,
  1253. CASE
  1254. WHEN r.recommended_delivery_from IS NOT NULL THEN
  1255. (COALESCE(ata, eta) - (r.recommended_delivery_from ||' days')::INTERVAL)::date
  1256. ELSE null END
  1257. AS recommended_delivery_from_date,
  1258. CASE
  1259. WHEN r.recommended_delivery_to IS NOT NULL THEN
  1260. (COALESCE(ata, eta) + (r.recommended_delivery_to ||' days')::INTERVAL)::date
  1261. ELSE null END
  1262. AS recommended_delivery_to_date
  1263. from matched_data md
  1264. LEFT JOIN LATERAL (
  1265. SELECT
  1266. r.*
  1267. FROM public.kln_destination_delivery_rule r
  1268. WHERE md.transport_mode = r.mode_type
  1269. and r.recommended_delivery_serial_no = md.dc_serial_no
  1270. AND ((md.transport_mode = 'sea' AND (
  1271. (r.ports ilike '%'|| md.mport_of_discharge_un ||'%' AND r.carrier ilike '%'|| md.carrier ||'%')
  1272. OR (r.ports ilike '%'|| md.mport_of_discharge_un ||'%' AND r.carrier = 'ALL')
  1273. OR (r.ports = 'ALL' AND r.carrier ilike '%'|| md.carrier ||'%')
  1274. OR (r.ports = 'ALL' AND r.carrier = 'ALL'))
  1275. )
  1276. OR (md.transport_mode = 'air' AND (
  1277. r.ports ilike '%'|| md.mport_of_discharge_un ||'%'
  1278. OR r.ports = 'ALL')
  1279. )
  1280. )
  1281. ORDER BY priority asc
  1282. LIMIT 1
  1283. ) r ON true
  1284. order by md.eta desc";
  1285. $rs = common::excuteListSql($sql);
  1286. error_log($sql);
  1287. if(empty($rs)){
  1288. return array("msg"=>"No Eligible Shipments for Booking","data"=>"");
  1289. }
  1290. return array("msg"=>"","data"=>$rs);
  1291. }
  1292. /**
  1293. * 不依赖配置的规则查询,如果规则已经移除或者修改不在查询范围内,開通期間創建的booking數據正常保留和展示
  1294. */
  1295. function search_shipment_with_booking($serial_no,$h_serial_no,$ctnr){
  1296. $sqlCtnr = "";
  1297. if(!empty($ctnr)){
  1298. $sqlCtnr = "and oc.ctnr in (select regexp_split_to_table('".$ctnr."', ','))";
  1299. }
  1300. $sqlWhere = "where oo.serial_no = ANY('".$h_serial_no."'::TEXT[])";
  1301. $sql = "with ooc as(
  1302. select * from public.kln_ocean oo ". $sqlWhere ."
  1303. ),
  1304. matched_data as (
  1305. select
  1306. ooc.serial_no,
  1307. ooc.h_bol,
  1308. ooc.m_bol,
  1309. oc.ctnr,
  1310. ooc.service,
  1311. ooc.po_no,
  1312. (select reference_no from public.ocean o where o.serial_no = ooc.serial_no limit 1) as reference_no,
  1313. ooc.transport_mode,
  1314. oc.qty::text as pakages,
  1315. oc.unit as package_type ,
  1316. oc.grs_kgs::text as kgw,
  1317. oc.cbm as volume,
  1318. ooc.vessel,
  1319. ooc.voyage,
  1320. ooc.carrier,
  1321. ooc.fport_of_loading_un,
  1322. ooc.mport_of_discharge_un,
  1323. ooc.eta,
  1324. ooc.ata,
  1325. ooc.shipper,
  1326. ooc.consignee_id,
  1327. ooc.consignee,
  1328. (select customer_name from public.ocean_extend ex where ex.serial_no = ooc.serial_no limit 1) as controlling_customer,
  1329. ooc.booking_no,
  1330. (select manifest_type from public.ocean o where o.serial_no = ooc.serial_no limit 1) as manifest_type,
  1331. ooc.agent,
  1332. ooc.order_from
  1333. from ooc
  1334. LEFT JOIN public.oc_container oc ON oc.serial_no::text = ooc.serial_no::text
  1335. where ooc.order_from = 'public' and transport_mode = 'sea' ".$sqlCtnr."
  1336. union all
  1337. select
  1338. ooc.serial_no,
  1339. ooc.h_bol,
  1340. ooc.m_bol,
  1341. oc.ctnr,
  1342. ooc.service,
  1343. ooc.po_no,
  1344. (select reference_no from sfs.ocean o where o.serial_no = ooc.serial_no limit 1) as reference_no,
  1345. ooc.transport_mode,
  1346. oc.qty::text as pakages,
  1347. oc.unit as package_type ,
  1348. oc.grs_kgs::text as kgw,
  1349. oc.cbm as volume,
  1350. ooc.vessel,
  1351. ooc.voyage,
  1352. ooc.carrier,
  1353. ooc.fport_of_loading_un,
  1354. ooc.mport_of_discharge_un,
  1355. ooc.eta,
  1356. ooc.ata,
  1357. ooc.shipper,
  1358. ooc.consignee_id,
  1359. ooc.consignee,
  1360. (select customer_name from ocean_extend ex where ex.serial_no = ooc.serial_no limit 1) as controlling_customer,
  1361. ooc.booking_no,
  1362. (select manifest_type from sfs.ocean o where o.serial_no = ooc.serial_no limit 1) as manifest_type,
  1363. ooc.agent,
  1364. ooc.order_from
  1365. from ooc
  1366. LEFT JOIN sfs.oc_container oc ON oc.serial_no::text = ooc.serial_no::text
  1367. where ooc.order_from = 'sfs' and transport_mode = 'sea' ".$sqlCtnr."
  1368. union all
  1369. select
  1370. ooc.serial_no,
  1371. ooc.h_bol,
  1372. ooc.m_bol,
  1373. '' as ctnr,
  1374. ooc.service,
  1375. ooc.po_no,
  1376. '' as reference_no,
  1377. ooc.transport_mode,
  1378. ooc.qty as pakages,
  1379. ooc.qty_uom as package_type ,
  1380. ooc.piece_count as kgw,
  1381. ooc.cbm as volume,
  1382. ooc.vessel,
  1383. ooc.voyage,
  1384. ooc.carrier,
  1385. ooc.fport_of_loading_un,
  1386. ooc.mport_of_discharge_un,
  1387. ooc.eta,
  1388. ooc.ata,
  1389. ooc.shipper,
  1390. ooc.consignee_id,
  1391. ooc.consignee,
  1392. '' as controlling_customer,
  1393. ooc.booking_no,
  1394. '' as manifest_type,
  1395. ooc.agent,
  1396. ooc.order_from
  1397. from ooc
  1398. where ooc.transport_mode = 'air'
  1399. )
  1400. select md.*,
  1401. CASE
  1402. WHEN kd.recommended_delivery_window_date_from IS NOT NULL AND kd.recommended_delivery_window_date_to IS NOT NULL THEN
  1403. to_char((recommended_delivery_window_date_from)::date, 'YYYY-MM-DD')
  1404. || ';' ||
  1405. to_char((recommended_delivery_window_date_to)::date, 'YYYY-MM-DD')
  1406. WHEN kd.recommended_delivery_window_date_from IS NULL AND kd.recommended_delivery_window_date_to IS NOT NULL THEN
  1407. ';' ||
  1408. to_char((recommended_delivery_window_date_to)::date, 'YYYY-MM-DD')
  1409. WHEN kd.recommended_delivery_window_date_from IS NOT NULL AND kd.recommended_delivery_window_date_to IS NULL THEN
  1410. to_char((recommended_delivery_window_date_from)::date, 'YYYY-MM-DD')
  1411. || ';'
  1412. ELSE ''
  1413. END AS date_range,
  1414. kd.recommended_delivery_from,
  1415. kd.recommended_delivery_to,
  1416. kd.recommended_delivery_window_date_from as recommended_delivery_from_date,
  1417. kd.recommended_delivery_window_date_to as recommended_delivery_to_date,
  1418. (select dc.country from public.kln_destination_delivery_config dc where md.agent in (select regexp_split_to_table(dc.station, ','))) as dc_country
  1419. from matched_data md
  1420. LEFT join public.kln_destination_delivery kd on kd.serial_no = '$serial_no'
  1421. order by md.eta desc";
  1422. //error_log($sql);
  1423. $rs = common::excuteListSql($sql);
  1424. return array("msg"=>"","data"=>$rs);
  1425. }
  1426. function groupShipments($booking_no, $manifest_type, $h_bol,$h_serial_no, $order_from,$m_bol, $ctnr,$kln_pic,$consignee,$consignee_id,
  1427. $recommended_delivery_window_date_from, $recommended_delivery_window_date_to,
  1428. $recommended_delivery_from,$recommended_delivery_to,$dc_country){
  1429. // Combine the data into an array of shipments
  1430. $shipments = [];
  1431. foreach ($h_bol as $index => $_h_bol) {
  1432. $shipments[] = [
  1433. 'booking_no' =>$booking_no[$index],
  1434. 'manifest_type' => $manifest_type[$index],
  1435. 'h_bol' => $h_bol[$index],
  1436. 'h_serial_no' => $h_serial_no[$index],
  1437. 'order_from' => $order_from[$index],
  1438. 'm_bol' => $m_bol[$index],
  1439. 'ctnr' => $ctnr[$index],
  1440. 'kln_pic' => $kln_pic[$index],
  1441. 'consignee' => $consignee[$index],
  1442. 'consignee_id' => $consignee_id[$index],
  1443. 'dc_country' => $dc_country[$index],
  1444. 'recommended_delivery_window_date_from' => $recommended_delivery_window_date_from[$index],
  1445. 'recommended_delivery_window_date_to' => $recommended_delivery_window_date_to[$index],
  1446. 'recommended_delivery_from' => $recommended_delivery_from[$index],
  1447. 'recommended_delivery_to' => $recommended_delivery_to[$index]
  1448. ];
  1449. }
  1450. // 按 MBOL 分组
  1451. $groupedByMbol = [];
  1452. // 按 ShipmentID 分组
  1453. $groupedByShipmentId = [];
  1454. foreach ($shipments as $item) {
  1455. $m_bol = $item['m_bol'];
  1456. $h_serial_no = $item['h_serial_no'];
  1457. $h_bol = $item['h_bol'];
  1458. $order_from = $item['order_from'];
  1459. $ctnr = $item['ctnr'];
  1460. $dc_country = $item['dc_country'];
  1461. $consignee_id = $item['consignee_id'];
  1462. if($item['manifest_type'] == 'BCN'){
  1463. if (!isset($groupedByMbol[$m_bol])) {
  1464. $item['h_bol'] = array();
  1465. $item['h_bol_multiple_link'] = array();
  1466. $item['h_serial_no'] = array();
  1467. $item['ctnr'] = array();
  1468. $item['dc_country'] = array();
  1469. $item['consignee_id'] = array();
  1470. $item['m_bol'] = array($item['m_bol']);
  1471. $groupedByMbol[$m_bol] = $item;
  1472. }
  1473. if (!in_array($h_serial_no, $groupedByMbol[$m_bol]['h_serial_no'])) {
  1474. $groupedByMbol[$m_bol]['h_bol'][] = $h_bol;
  1475. $groupedByMbol[$m_bol]['h_bol_multiple_link'][] = array("key"=>$h_bol,"value" =>$h_serial_no,"order_from"=>$order_from);
  1476. $groupedByMbol[$m_bol]['h_serial_no'][] = $h_serial_no;
  1477. $groupedByMbol[$m_bol]['dc_country'][] = $dc_country;
  1478. $groupedByMbol[$m_bol]['consignee_id'][] = $consignee_id;
  1479. }
  1480. if (!in_array($ctnr, $groupedByMbol[$m_bol]['ctnr'])) {
  1481. $groupedByMbol[$m_bol]['ctnr'][] = $ctnr;
  1482. }
  1483. } else {
  1484. if (!isset($groupedByShipmentId[$h_serial_no])) {
  1485. $item['m_bol'] = array();
  1486. $item['ctnr'] = array();
  1487. $item['dc_country'] = array($item['dc_country']);
  1488. $item['consignee_id'] = array($item['consignee_id']);
  1489. $item['h_serial_no'] = array($item['h_serial_no']);
  1490. $item['h_bol'] = array($item['h_bol']);
  1491. $item['h_bol_multiple_link'] = array(array("key"=>$h_bol,"value" =>$h_serial_no,"order_from"=>$order_from));
  1492. $groupedByShipmentId[$h_serial_no] = $item;
  1493. }
  1494. if (!in_array($m_bol, $groupedByShipmentId[$h_serial_no]['m_bol'])) {
  1495. $groupedByShipmentId[$h_serial_no]['m_bol'][] = $m_bol;
  1496. }
  1497. if (!in_array($ctnr, $groupedByShipmentId[$h_serial_no]['ctnr'])) {
  1498. $groupedByShipmentId[$h_serial_no]['ctnr'][] = $ctnr;
  1499. }
  1500. }
  1501. }
  1502. $result = array();
  1503. foreach($groupedByMbol as $mb){
  1504. $result[] = $mb;
  1505. }
  1506. foreach($groupedByShipmentId as $hb){
  1507. $result[] = $hb;
  1508. }
  1509. return $result;
  1510. }
  1511. }
  1512. ?>