您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 

757 行
33 KiB

  1. package com.ffii.fpsms.m18.service
  2. import com.ffii.core.utils.JwtTokenUtil
  3. import com.ffii.fpsms.api.service.ApiCallerService
  4. import com.ffii.fpsms.m18.M18Config
  5. import com.ffii.fpsms.m18.model.*
  6. import com.ffii.fpsms.m18.utils.CommonUtils
  7. import com.ffii.fpsms.m18.web.models.M18CommonRequest
  8. import com.ffii.fpsms.modules.master.entity.UomConversion
  9. import com.ffii.fpsms.modules.master.enums.ShopType
  10. import com.ffii.fpsms.modules.master.service.*
  11. import com.ffii.fpsms.modules.master.web.models.*
  12. import org.slf4j.Logger
  13. import org.slf4j.LoggerFactory
  14. import org.springframework.stereotype.Service
  15. import java.math.BigDecimal
  16. import java.time.LocalDateTime
  17. import java.time.format.DateTimeFormatter
  18. @Service
  19. open class M18MasterDataService(
  20. val m18Config: M18Config,
  21. val apiCallerService: ApiCallerService,
  22. val itemsService: ItemsService,
  23. val shopService: ShopService,
  24. val uomConversionService: UomConversionService,
  25. val currencyService: CurrencyService,
  26. val itemUomService: ItemUomService,
  27. val bomService: BomService,
  28. val bomMaterialService: BomMaterialService,
  29. ) {
  30. val logger: Logger = LoggerFactory.getLogger(JwtTokenUtil::class.java)
  31. val commonUtils = CommonUtils()
  32. val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
  33. // M18 Conditions
  34. // val lastModifyDate = LocalDate.now().minusDays(1)
  35. // val lastModifyDateConds = "lastModifyDate=largerThan=$lastModifyDate"
  36. val seriesIdList =
  37. listOf(m18Config.SERIESID_SC, m18Config.SERIESID_SE, m18Config.SERIESID_SF, m18Config.SERIESID_SR)
  38. val seriesIdConds =
  39. "(" + commonUtils.listToString(seriesIdList.filterNotNull(), "seriesId=unequal=", "=or=") + ")"
  40. val beIdList = listOf(m18Config.BEID_PF, m18Config.BEID_PP, m18Config.BEID_TOA)
  41. val beIdConds = "(" + commonUtils.listToString(beIdList.filterNotNull(), "beId=equal=", "=or=") + ")"
  42. // val beIdConds = commonUtils.BEID_CONDS
  43. // M18 API
  44. val M18_COMMON_FETCH_LIST_API = "/search/search"
  45. val M18_COMMON_LOAD_LINE_API = "/root/api/read"
  46. val M18_LOAD_PRODUCT_API = "${M18_COMMON_LOAD_LINE_API}/${StSearchType.PRODUCT.value}"
  47. val M18_LOAD_VENDOR_API = "${M18_COMMON_LOAD_LINE_API}/${StSearchType.VENDOR.value}"
  48. val M18_LOAD_UNIT_API = "${M18_COMMON_LOAD_LINE_API}/${StSearchType.UNIT.value}"
  49. val M18_LOAD_CURRENCY_API = "${M18_COMMON_LOAD_LINE_API}/${StSearchType.CURRENCY.value}"
  50. val M18_LOAD_BOM_API = "${M18_COMMON_LOAD_LINE_API}/${StSearchType.BOM.value}"
  51. val M18_LOAD_BUSINESS_UNIT_API = "${M18_COMMON_LOAD_LINE_API}/${StSearchType.BUSINESS_UNIT.value}" // for shop po?
  52. // --------------------------------------------- Common Function --------------------------------------------- ///
  53. private inline fun <reified T : Any> getList(
  54. stSearch: String?,
  55. params: String? = null,
  56. conds: String? = null,
  57. request: M18CommonRequest,
  58. ): T? {
  59. val lastModifyDateFromConds = request.modifiedDateFrom?.let { "lastModifyDate=largerOrEqual=${it}" }
  60. val lastModifyDateToConds = request.modifiedDateTo?.let{ "lastModifyDate=lessOrEqual=${it}" }
  61. val haveFromAndTo = lastModifyDateFromConds != null && lastModifyDateToConds != null
  62. val finalConds = if (lastModifyDateFromConds == null && lastModifyDateToConds == null) {
  63. conds
  64. } else {
  65. conds + "=and=(${lastModifyDateFromConds ?: ""}${if(haveFromAndTo) "=and=" else ""}${lastModifyDateToConds ?: ""})"
  66. }
  67. val request = M18CommonListRequest(
  68. stSearch = stSearch,
  69. params = params,
  70. conds = finalConds
  71. )
  72. val response = apiCallerService.get<T, M18CommonListRequest>(
  73. M18_COMMON_FETCH_LIST_API,
  74. request
  75. ).block()
  76. return response
  77. }
  78. private inline fun <reified T : Any> getLine(
  79. id: Long,
  80. params: String?,
  81. api: String,
  82. ): T? {
  83. val request = M18CommonLineRequest(
  84. id = id,
  85. params = params,
  86. )
  87. val response = apiCallerService.get<T, M18CommonLineRequest>(
  88. api,
  89. request
  90. ).block()
  91. return response
  92. }
  93. // --------------------------------------------- Product --------------------------------------------- ///
  94. open fun getProducts(request: M18CommonRequest): M18ProductListResponse? {
  95. // seems no beId
  96. return getList<M18ProductListResponse>(
  97. stSearch = StSearchType.PRODUCT.value,
  98. params = null,
  99. conds = seriesIdConds,
  100. request = request
  101. )
  102. // val itemsParams = M18CommonListRequest(
  103. // stSearch = StSearchType.PRODUCT.value,
  104. // params = null,
  105. // conds = seriesIdConds
  106. // )
  107. //
  108. // val items = apiCallerService.get<M18ProductListResponse, M18CommonListRequest>(
  109. // M18_COMMON_FETCH_LIST_API,
  110. // itemsParams
  111. // ).block()
  112. //
  113. // return items
  114. }
  115. open fun getProduct(id: Long): M18ProductResponse? {
  116. logger.info("M18 Product ID: $id")
  117. return getLine<M18ProductResponse>(
  118. id = id,
  119. params = null,
  120. api = M18_LOAD_PRODUCT_API
  121. )
  122. }
  123. open fun saveProduct(id: Long): MessageResponse? {
  124. try {
  125. val itemDetail = getProduct(id)
  126. val pro = itemDetail?.data?.pro?.get(0)
  127. val price = itemDetail?.data?.price
  128. if (itemDetail != null && pro != null) {
  129. val existingItem = itemsService.findByM18Id(id)
  130. val saveItemRequest = NewItemRequest(
  131. code = pro.code,
  132. name = pro.desc,
  133. // type = if (pro.seriesId == m18Config.SERIESID_PF) ProductType.MATERIAL
  134. // else ItemType.PRODUCT,
  135. type = when (pro.udfProducttype) {
  136. M18ItemType.CONSUMABLES.type -> ItemType.CONSUMABLES
  137. M18ItemType.NONCONSUMABLES.type -> ItemType.NONCONSUMABLES
  138. M18ItemType.FG.type -> ItemType.FG
  139. M18ItemType.SFG.type -> ItemType.SFG
  140. M18ItemType.ITEM.type -> ItemType.ITEM
  141. else -> ItemType.MATERIAL
  142. },
  143. id = existingItem?.id,
  144. description = pro.desc,
  145. remarks = null,
  146. shelfLife = null,
  147. countryOfOrigin = null,
  148. maxQty = null,
  149. m18Id = id,
  150. m18LastModifyDate = commonUtils.timestampToLocalDateTime(pro.lastModifyDate)
  151. )
  152. val savedItem = itemsService.saveItem(saveItemRequest)
  153. logger.info("Processing item uom...")
  154. // Find the item uom that ready to delete (not in m18)
  155. val existingItemUoms = savedItem.id?.let { itemUomService.findAllByItemsId(it) }
  156. val m18ItemUomIds = price?.map { it.id } ?: listOf()
  157. // Delete the item uom
  158. logger.info("Deleting item uom...")
  159. // logger.info("Item Uom: ${existingItemUoms?.map { it.m18Id }}")
  160. // logger.info("M18: ${m18ItemUomIds}")
  161. existingItemUoms?.filter { it.m18Id !in m18ItemUomIds }?.mapNotNull { it.id }
  162. ?.let { itemUomService.deleteItemUoms(it) }
  163. // Update the item uom
  164. logger.info("Updating item uom...")
  165. price?.forEach {
  166. val itemUomRequest = ItemUomRequest(
  167. m18UomId = it.unitId,
  168. itemId = savedItem.id,
  169. baseUnit = it.basicUnit,
  170. stockUnit = it.stkUnit,
  171. pickingUnit = it.pickUnit,
  172. salesUnit = it.saleUnit,
  173. purchaseUnit = it.purUnit,
  174. price = null,
  175. currencyId = null,
  176. m18Id = it.id,
  177. m18LastModifyDate = commonUtils.timestampToLocalDateTime(pro.lastModifyDate),
  178. ratioD = it.ratioD,
  179. ratioN = it.ratioN,
  180. deleted = it.expired
  181. )
  182. // logger.info("saved item id: ${savedItem.id}")
  183. itemUomService.saveItemUom(itemUomRequest)
  184. }
  185. logger.info("Success (M18 Item): ${id} | ${pro.code} | ${pro.desc}")
  186. return savedItem
  187. } else {
  188. logger.error("Fail Message: ${itemDetail?.messages?.get(0)?.msgDetail}")
  189. logger.error("Fail: Item ID - ${id} Not Found")
  190. return null
  191. }
  192. } catch (e: Exception) {
  193. logger.error("Exception")
  194. logger.error("Fail Message: ${e.message}")
  195. logger.error("Fail: Item ID - ${id}")
  196. return null
  197. }
  198. }
  199. open fun saveProducts(request: M18CommonRequest) {
  200. logger.info("--------------------------------------------Start - Saving M18 Products / Materials--------------------------------------------")
  201. val items = getProducts(request)
  202. val exampleProducts = listOf<Long>(10946L, 3825L)
  203. val successList = mutableListOf<Long>()
  204. val failList = mutableListOf<Long>()
  205. val values = items?.values?.sortedBy { it.id }
  206. if (values != null) {
  207. values.forEach { item ->
  208. // if (item.id in exampleProducts) {
  209. try {
  210. val itemDetail = getProduct(item.id)
  211. val pro = itemDetail?.data?.pro?.get(0)
  212. val price = itemDetail?.data?.price
  213. if (itemDetail != null && pro != null) {
  214. val existingItem = itemsService.findByM18Id(item.id)
  215. val saveItemRequest = NewItemRequest(
  216. code = pro.code,
  217. name = pro.desc,
  218. // type = if (pro.seriesId == m18Config.SERIESID_PF) ProductType.MATERIAL
  219. // else ItemType.PRODUCT,
  220. type = when (pro.udfProducttype) {
  221. M18ItemType.CONSUMABLES.type -> ItemType.CONSUMABLES
  222. M18ItemType.NONCONSUMABLES.type -> ItemType.NONCONSUMABLES
  223. M18ItemType.FG.type -> ItemType.FG
  224. M18ItemType.SFG.type -> ItemType.SFG
  225. M18ItemType.ITEM.type -> ItemType.ITEM
  226. else -> ItemType.MATERIAL
  227. },
  228. id = existingItem?.id,
  229. description = pro.desc,
  230. remarks = null,
  231. shelfLife = null,
  232. countryOfOrigin = null,
  233. maxQty = null,
  234. m18Id = item.id,
  235. m18LastModifyDate = commonUtils.timestampToLocalDateTime(pro.lastModifyDate)
  236. )
  237. val savedItem = itemsService.saveItem(saveItemRequest)
  238. logger.info("Processing item uom...")
  239. // Find the item uom that ready to delete (not in m18)
  240. val existingItemUoms = savedItem.id?.let { itemUomService.findAllByItemsId(it) }
  241. val m18ItemUomIds = price?.map { it.id } ?: listOf()
  242. // Delete the item uom
  243. logger.info("Deleting item uom...")
  244. // logger.info("Item Uom: ${existingItemUoms?.map { it.m18Id }}")
  245. // logger.info("M18: ${m18ItemUomIds}")
  246. existingItemUoms?.filter { it.m18Id !in m18ItemUomIds }?.mapNotNull { it.id }
  247. ?.let { itemUomService.deleteItemUoms(it) }
  248. // Update the item uom
  249. logger.info("Updating item uom...")
  250. price?.forEach {
  251. val itemUomRequest = ItemUomRequest(
  252. m18UomId = it.unitId,
  253. itemId = savedItem.id,
  254. baseUnit = it.basicUnit,
  255. stockUnit = it.stkUnit,
  256. pickingUnit = it.pickUnit,
  257. salesUnit = it.saleUnit,
  258. purchaseUnit = it.purUnit,
  259. price = null,
  260. currencyId = null,
  261. m18Id = it.id,
  262. m18LastModifyDate = commonUtils.timestampToLocalDateTime(pro.lastModifyDate),
  263. ratioD = it.ratioD,
  264. ratioN = it.ratioN,
  265. deleted = it.expired
  266. )
  267. // logger.info("saved item id: ${savedItem.id}")
  268. itemUomService.saveItemUom(itemUomRequest)
  269. }
  270. successList.add(item.id)
  271. logger.info("Success Count ${successList.size}: ${item.id} | ${pro.code} | ${pro.desc}")
  272. } else {
  273. failList.add(item.id)
  274. logger.error("Fail Message: ${itemDetail?.messages?.get(0)?.msgDetail}")
  275. logger.error("Fail Count ${failList.size}: Item ID - ${item.id} Not Found")
  276. }
  277. } catch (e: Exception) {
  278. failList.add(item.id)
  279. logger.error("Exception")
  280. logger.error("Fail Message: ${e.message}")
  281. logger.error("Fail Count ${failList.size}: Item ID - ${item.id}")
  282. }
  283. }
  284. } else {
  285. logger.error("Items List is null. May occur errors.")
  286. }
  287. logger.info("Total Success (${successList.size})")
  288. if (failList.size > 0) {
  289. logger.error("Total Fail (${failList.size}): $failList")
  290. }
  291. logger.info("--------------------------------------------End - Saving M18 Products / Materials--------------------------------------------")
  292. }
  293. // --------------------------------------------- Vendor --------------------------------------------- ///
  294. open fun getVendors(request: M18CommonRequest): M18VendorListResponse? {
  295. return getList<M18VendorListResponse>(
  296. stSearch = StSearchType.VENDOR.value,
  297. params = null,
  298. conds = beIdConds,
  299. request = request
  300. )
  301. }
  302. open fun getVendor(id: Long): M18VendorResponse? {
  303. logger.info("M18 Vendor ID: $id")
  304. return getLine<M18VendorResponse>(
  305. id = id,
  306. params = null,
  307. api = M18_LOAD_VENDOR_API
  308. )
  309. }
  310. open fun saveVendors(request: M18CommonRequest) {
  311. logger.info("--------------------------------------------Start - Saving M18 Vendors--------------------------------------------")
  312. val vendors = getVendors(request)
  313. val exampleVendors = listOf<Long>(191L)
  314. val successList = mutableListOf<Long>()
  315. val failList = mutableListOf<Long>()
  316. val values = vendors?.values?.sortedBy { it.id }
  317. if (values != null) {
  318. values.forEach { vendor ->
  319. // if (vendor.id in exampleVendors) {
  320. try {
  321. val vendorDetail = getVendor(vendor.id)
  322. if (vendorDetail != null && vendorDetail.data?.ven != null) {
  323. val ven = vendorDetail.data.ven[0]
  324. val saveShopRequest = SaveShopRequest(
  325. id = null,
  326. code = ven.code,
  327. name = ven.desc.ifEmpty { ven.`desc_zh-TW` },
  328. brNo = null,
  329. contactNo = ven.tel,
  330. contactEmail = ven.email,
  331. contactName = null,
  332. addr1 = ven.ad1,
  333. addr2 = ven.ad2,
  334. addr3 = ven.ad3,
  335. addr4 = ven.ad4,
  336. district = null,
  337. type = ShopType.SUPPLIER.value,
  338. m18Id = vendor.id,
  339. m18LastModifyDate = commonUtils.timestampToLocalDateTime(ven.lastModifyDate)
  340. )
  341. shopService.saveShop(saveShopRequest)
  342. successList.add(vendor.id)
  343. logger.info("Success Count ${successList.size}: ${vendor.id} | ${ven.code} | ${ven.desc}")
  344. } else {
  345. failList.add(vendor.id)
  346. logger.error("Fail Message: ${vendorDetail?.messages?.get(0)?.msgDetail}")
  347. logger.error("Fail Count ${failList.size}: Vendor ID - ${vendor.id} Not Found")
  348. }
  349. } catch (e: Exception) {
  350. failList.add(vendor.id)
  351. logger.error("Exception")
  352. logger.error("Fail Message: ${e.message}")
  353. logger.error("Fail Count ${failList.size}: Vendor ID - ${vendor.id}")
  354. }
  355. // }
  356. }
  357. } else {
  358. logger.error("Vendor List is null. May occur errors.")
  359. }
  360. logger.info("Total Success (${successList.size})")
  361. if (failList.size > 0) {
  362. logger.error("Total Fail (${failList.size}): $failList")
  363. }
  364. logger.info("--------------------------------------------End - Saving M18 Vendors--------------------------------------------")
  365. }
  366. // --------------------------------------------- Unit (UoM) --------------------------------------------- ///
  367. open fun getUnits(request: M18CommonRequest): M18UnitListResponse? {
  368. // seems no beId
  369. return getList<M18UnitListResponse>(
  370. stSearch = StSearchType.UNIT.value,
  371. params = null,
  372. conds = null,
  373. request = request
  374. )
  375. }
  376. open fun getUnit(id: Long): M18UnitResponse? {
  377. logger.info("M18 Unit ID: $id")
  378. return getLine<M18UnitResponse>(
  379. id = id,
  380. params = null,
  381. api = M18_LOAD_UNIT_API
  382. )
  383. }
  384. open fun saveUnits(request: M18CommonRequest) {
  385. logger.info("--------------------------------------------Start - Saving M18 Units--------------------------------------------")
  386. val units = getUnits(request)
  387. val successTransformList = mutableListOf<Long>()
  388. val successSaveList = mutableListOf<Long>()
  389. val failTransformList = mutableListOf<Long>()
  390. val failSaveList = mutableListOf<Long>()
  391. val values = units?.values?.sortedBy { it.id }
  392. if (values != null) {
  393. val finalUnitList = arrayListOf<UomConversion>()
  394. // transform unit
  395. values.forEach { unit ->
  396. try {
  397. val tempObject = UomConversionService.BomObject().apply {
  398. code = unit.code
  399. udfudesc = unit.udfudesc
  400. lastModifyDate = unit.lastModifyDate
  401. id = unit.id
  402. }
  403. finalUnitList += uomConversionService.transformItem(tempObject)
  404. successTransformList += unit.id
  405. logger.info("Transform Success (M18): ${unit.id}")
  406. } catch (e: Exception) {
  407. failTransformList.add(unit.id)
  408. logger.error("Transform Exception")
  409. logger.error("Transform Fail Message: ${e.message}")
  410. logger.error("Transform Fail Count ${failTransformList.size}: Unit ID - ${unit.id}")
  411. }
  412. }
  413. uomConversionService.calculateSizeInGram(finalUnitList)
  414. finalUnitList.forEach {
  415. try {
  416. uomConversionService.saveUomConversion(it)
  417. successSaveList += it.m18Id
  418. logger.info("Save Success (M18): ${it.m18Id}")
  419. } catch (e: Exception) {
  420. failSaveList.add(it.m18Id)
  421. logger.error("Save Exception")
  422. logger.error("Save Fail Message: ${e.message}")
  423. logger.error("Save Fail Count ${failTransformList.size}: Unit ID - ${it.m18Id}")
  424. }
  425. }
  426. } else {
  427. logger.error("Unit List is null. May occur errors.")
  428. }
  429. logger.info("Total Transform Success (${successTransformList.size})")
  430. logger.info("Total Save Success (${successSaveList.size})")
  431. if (failTransformList.size > 0) {
  432. logger.error("Total Transform Fail (${failTransformList.size}): $failTransformList")
  433. }
  434. if (failSaveList.size > 0) {
  435. logger.error("Total Save Fail (${failSaveList.size}): $failSaveList")
  436. }
  437. logger.info("--------------------------------------------End - Saving M18 Units--------------------------------------------")
  438. }
  439. // --------------------------------------------- Currency --------------------------------------------- ///
  440. open fun getCurrencies(request: M18CommonRequest): M18CurrencyListResponse? {
  441. return getList<M18CurrencyListResponse>(
  442. stSearch = StSearchType.CURRENCY.value,
  443. params = null,
  444. conds = null,
  445. request = request
  446. )
  447. }
  448. open fun getCurrency(id: Long): M18CurrencyResponse? {
  449. logger.info("M18 Currency ID: $id")
  450. return getLine<M18CurrencyResponse>(
  451. id = id,
  452. params = null,
  453. api = M18_LOAD_CURRENCY_API
  454. )
  455. }
  456. open fun saveCurrencies(request: M18CommonRequest) {
  457. logger.info("--------------------------------------------Start - Saving M18 Currencies--------------------------------------------")
  458. val currencies = getCurrencies(request)
  459. val successList = mutableListOf<Long>()
  460. val failList = mutableListOf<Long>()
  461. val values = currencies?.values?.sortedBy { it.id }
  462. if (values != null) {
  463. // save currency
  464. values.forEach { currency ->
  465. try {
  466. val currencyRequest = SaveCurrencyRequest(
  467. id = null,
  468. code = currency.code,
  469. name = currency.sym,
  470. description = currency.curDesc,
  471. m18Id = currency.id,
  472. m18LastModifyDate = LocalDateTime.parse(currency.lastModifyDate, formatter)
  473. )
  474. currencyService.saveCurrency(currencyRequest)
  475. successList += currency.id
  476. logger.info("Save Success (M18): ${currency.id}")
  477. } catch (e: Exception) {
  478. failList += currency.id
  479. logger.error("Exception")
  480. logger.error("Fail Message: ${e.message}")
  481. logger.error("Fail Count ${failList.size}: Unit ID - ${currency.id}")
  482. }
  483. }
  484. } else {
  485. logger.error("Currency List is null. May occur errors.")
  486. }
  487. logger.info("Total Save Success (${successList.size})")
  488. if (failList.size > 0) {
  489. logger.error("Total Fail (${failList.size}): $failList")
  490. }
  491. logger.info("--------------------------------------------End - Saving Currencies--------------------------------------------")
  492. }
  493. // --------------------------------------------- Bom --------------------------------------------- ///
  494. open fun getBoms(request: M18CommonRequest): M18BomListResponse? {
  495. return getList<M18BomListResponse>(
  496. stSearch = StSearchType.BOM.value,
  497. params = null,
  498. conds = beIdConds,
  499. request = request
  500. )
  501. }
  502. open fun getBom(id: Long): M18BomResponse? {
  503. logger.info("M18 Bom ID: $id")
  504. return getLine<M18BomResponse>(
  505. id = id,
  506. params = null,
  507. api = M18_LOAD_BOM_API
  508. )
  509. }
  510. open fun saveBoms(request: M18CommonRequest) {
  511. logger.info("--------------------------------------------Start - Saving M18 Boms--------------------------------------------")
  512. val boms = getBoms(request)
  513. val successList = mutableListOf<Long>()
  514. val successDetailList = mutableListOf<Long>()
  515. val failList = mutableListOf<Long>()
  516. val failDetailList = mutableListOf<Pair<Long, MutableList<Long>>>()
  517. var failDetailCount = 0
  518. val values = boms?.values?.sortedBy { it.id }
  519. if (values != null) {
  520. values.forEach { bom ->
  521. try {
  522. val bomDetail = getBom(bom.id)
  523. val bomUdfBomForShop = bomDetail?.data?.udfbomforshop?.get(0)
  524. val bomUdfProduct = bomDetail?.data?.udfproduct
  525. logger.info(bomUdfBomForShop.toString())
  526. logger.info(bomUdfProduct.toString())
  527. if (bomUdfBomForShop != null && bomUdfProduct != null) {
  528. // Save Bom
  529. val saveBomRequest = SaveBomRequest(
  530. // itemId = itemsService.findByNameAndM18UomId(bomUdfBomForShop.desc, bomUdfBomForShop.udfUnit)?.id,
  531. code = bomUdfBomForShop.code,
  532. name = bomUdfBomForShop.desc,
  533. description = bomUdfBomForShop.desc,
  534. outputQty = if (bomUdfBomForShop.udfHarvest.trim().toBigDecimalOrNull() != null) bomUdfBomForShop.udfHarvest.trim().toBigDecimal() else BigDecimal(0),
  535. outputQtyUom = bomUdfBomForShop.udfHarvestUnit,
  536. yield = bomUdfBomForShop.udfYieldratePP,
  537. m18UomId = bomUdfBomForShop.udfUnit,
  538. m18Id = bomUdfBomForShop.id,
  539. m18LastModifyDate = commonUtils.timestampToLocalDateTime(bomUdfBomForShop.lastModifyDate)
  540. )
  541. val bomId = bomService.saveBom(saveBomRequest).id
  542. successList += bom.id
  543. // Save Bom Material
  544. logger.info("Start saving bom material...")
  545. val tempFailList = mutableListOf<Long>()
  546. bomUdfProduct.forEach { bomMaterial ->
  547. try {
  548. val saveBomMaterialRequest = SaveBomMaterialRequest(
  549. m18ItemId = bomMaterial.udfProduct,
  550. itemName = bomMaterial.udfIngredients,
  551. qty = bomMaterial.udfqty,
  552. m18UomId = bomMaterial.udfpurchaseUnit,
  553. uomName = bomMaterial.udfBaseUnit,
  554. bomId = bomId,
  555. m18Id = bomMaterial.id,
  556. m18LastModifyDate = commonUtils.timestampToLocalDateTime(bomUdfBomForShop.lastModifyDate)
  557. )
  558. bomMaterialService.saveBomMaterial(saveBomMaterialRequest)
  559. successDetailList += bomMaterial.id
  560. } catch (e: Exception) {
  561. tempFailList += bomMaterial.id
  562. logger.error("(Bom Material) Exception")
  563. logger.error("(Bom Material) Fail Message: ${e.message}")
  564. logger.error("(Bom Material) Fail Count ${++failDetailCount}: Bom Material ID - ${bomMaterial.id} | Bom ID - ${bom.id}")
  565. }
  566. }
  567. failDetailList += Pair(bom.id, tempFailList)
  568. logger.info("Save Success (M18): ${bom.id}")
  569. } else {
  570. failList.add(bom.id)
  571. logger.error("(Bom) Fail Message: ${bomDetail?.messages?.get(0)?.msgDetail}")
  572. logger.error("(Bom) Fail Count ${failList.size}: Bom ID - ${bom.id} Not Found")
  573. }
  574. } catch (e: Exception) {
  575. failList += bom.id
  576. logger.error("(Bom) Exception")
  577. logger.error("(Bom) Fail Message: ${e.message}")
  578. logger.error("(Bom) Fail Count ${failList.size}: Bom ID - ${bom.id}")
  579. }
  580. }
  581. } else {
  582. logger.error("Currency List is null. May occur errors.")
  583. }
  584. logger.info("Total Bom Save Success (${successList.size})")
  585. logger.info("Total Bom Save Detail Success (${successDetailList.size})")
  586. if (failList.size > 0) {
  587. logger.error("Total Bom Fail (${failList.size}): $failList")
  588. }
  589. if (failDetailCount > 0) {
  590. logger.error("Total Bom Detail Fail (${failDetailCount}): $failDetailList")
  591. }
  592. logger.info("--------------------------------------------End - Saving Boms--------------------------------------------")
  593. }
  594. // --------------------------------------------- Business Unit (Shop) --------------------------------------------- ///
  595. open fun getBusinessUnits(request: M18CommonRequest): M18BusinessUnitListResponse? {
  596. // seems no beId
  597. return getList<M18BusinessUnitListResponse>(
  598. stSearch = StSearchType.BUSINESS_UNIT.value,
  599. params = null,
  600. // conds = beIdConds
  601. request = request
  602. )
  603. }
  604. open fun getBusinessUnit(id: Long): M18BusinessUnitResponse? {
  605. logger.info("M18 Business Unit ID: $id")
  606. return getLine<M18BusinessUnitResponse>(
  607. id = id,
  608. params = null,
  609. api = M18_LOAD_BUSINESS_UNIT_API
  610. )
  611. }
  612. open fun saveBusinessUnits(request: M18CommonRequest) {
  613. logger.info("--------------------------------------------Start - Saving M18 Business Units (Shops)--------------------------------------------")
  614. val businessUnits = getBusinessUnits(request)
  615. val successList = mutableListOf<Long>()
  616. val failList = mutableListOf<Long>()
  617. val values = businessUnits?.values?.sortedBy { it.id }
  618. val busMessages = if(businessUnits?.messages?.isNotEmpty() == true) businessUnits.messages[0] else null
  619. if (values != null) {
  620. values.forEach { businessUnit ->
  621. // if (vendor.id in exampleVendors) {
  622. try {
  623. val businessUnitDetail = getBusinessUnit(businessUnit.id)
  624. val virdept = businessUnitDetail?.data?.virdept?.get(0)
  625. val buMessages = if(businessUnitDetail?.messages?.isNotEmpty() == true) businessUnitDetail?.messages[0] else null
  626. if (virdept != null) {
  627. val saveShopRequest = SaveShopRequest(
  628. id = null,
  629. code = virdept.code,
  630. name = virdept.desc.ifEmpty { virdept.`desc_zh-TW` },
  631. brNo = null,
  632. contactNo = virdept.tel,
  633. contactEmail = virdept.email,
  634. contactName = null,
  635. addr1 = virdept.addr.ifEmpty { virdept.addr_en },
  636. addr2 = virdept.addr2.ifEmpty { virdept.addr2_en },
  637. addr3 = virdept.addr3.ifEmpty { virdept.addr3_en },
  638. addr4 = null,
  639. district = null,
  640. type = ShopType.SHOP.value,
  641. m18Id = businessUnit.id,
  642. m18LastModifyDate = commonUtils.timestampToLocalDateTime(virdept.lastModifyDate)
  643. )
  644. shopService.saveShop(saveShopRequest)
  645. successList.add(businessUnit.id)
  646. logger.info("Success Count ${successList.size}: ${businessUnit.id} | ${virdept.code} | ${virdept.desc}")
  647. } else {
  648. failList.add(businessUnit.id)
  649. logger.error("(Business Unit) Fail Message: ${buMessages?.msgDetail}")
  650. logger.error("(Business Unit) Fail Count ${failList.size}: Business Unit ID - ${businessUnit.id} Not Found")
  651. }
  652. } catch (e: Exception) {
  653. failList.add(businessUnit.id)
  654. logger.error("(Business Unit) Exception")
  655. logger.error("(Business Unit) Fail Message: ${e.message}")
  656. logger.error("(Business Unit) Fail Count ${failList.size}: Business Unit ID - ${businessUnit.id}")
  657. }
  658. // }
  659. }
  660. } else {
  661. logger.error("(Business Unit) Business Unit List is null. May occur errors.")
  662. logger.error("(Business Unit)) Fail Message: ${busMessages?.msgDetail}")
  663. logger.error("(Business Unit) Business Unit List is null. May occur errors.")
  664. }
  665. logger.info("Total Success (${successList.size})")
  666. if (failList.size > 0) {
  667. logger.error("Total Fail (${failList.size}): $failList")
  668. }
  669. logger.info("--------------------------------------------End - Saving M18 Business Units--------------------------------------------")
  670. }
  671. }