25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

743 lines
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 = ItemType.MATERIAL,
  136. id = existingItem?.id,
  137. description = pro.desc,
  138. remarks = null,
  139. shelfLife = null,
  140. countryOfOrigin = null,
  141. maxQty = null,
  142. m18Id = id,
  143. m18LastModifyDate = commonUtils.timestampToLocalDateTime(pro.lastModifyDate)
  144. )
  145. val savedItem = itemsService.saveItem(saveItemRequest)
  146. logger.info("Processing item uom...")
  147. // Find the item uom that ready to delete (not in m18)
  148. val existingItemUoms = savedItem.id?.let { itemUomService.findAllByItemsId(it) }
  149. val m18ItemUomIds = price?.map { it.id } ?: listOf()
  150. // Delete the item uom
  151. logger.info("Deleting item uom...")
  152. // logger.info("Item Uom: ${existingItemUoms?.map { it.m18Id }}")
  153. // logger.info("M18: ${m18ItemUomIds}")
  154. existingItemUoms?.filter { it.m18Id !in m18ItemUomIds }?.mapNotNull { it.id }
  155. ?.let { itemUomService.deleteItemUoms(it) }
  156. // Update the item uom
  157. logger.info("Updating item uom...")
  158. price?.forEach {
  159. val itemUomRequest = ItemUomRequest(
  160. m18UomId = it.unitId,
  161. itemId = savedItem.id,
  162. baseUnit = it.basicUnit,
  163. stockUnit = it.stkUnit,
  164. pickingUnit = it.pickUnit,
  165. salesUnit = it.saleUnit,
  166. purchaseUnit = it.purUnit,
  167. price = null,
  168. currencyId = null,
  169. m18Id = it.id,
  170. m18LastModifyDate = commonUtils.timestampToLocalDateTime(pro.lastModifyDate),
  171. ratioD = it.ratioD,
  172. ratioN = it.ratioN,
  173. deleted = it.expired
  174. )
  175. // logger.info("saved item id: ${savedItem.id}")
  176. itemUomService.saveItemUom(itemUomRequest)
  177. }
  178. logger.info("Success (M18 Item): ${id} | ${pro.code} | ${pro.desc}")
  179. return savedItem
  180. } else {
  181. logger.error("Fail Message: ${itemDetail?.messages?.get(0)?.msgDetail}")
  182. logger.error("Fail: Item ID - ${id} Not Found")
  183. return null
  184. }
  185. } catch (e: Exception) {
  186. logger.error("Exception")
  187. logger.error("Fail Message: ${e.message}")
  188. logger.error("Fail: Item ID - ${id}")
  189. return null
  190. }
  191. }
  192. open fun saveProducts(request: M18CommonRequest) {
  193. logger.info("--------------------------------------------Start - Saving M18 Products / Materials--------------------------------------------")
  194. val items = getProducts(request)
  195. val exampleProducts = listOf<Long>(10946L, 3825L)
  196. val successList = mutableListOf<Long>()
  197. val failList = mutableListOf<Long>()
  198. val values = items?.values?.sortedBy { it.id }
  199. if (values != null) {
  200. values.forEach { item ->
  201. // if (item.id in exampleProducts) {
  202. try {
  203. val itemDetail = getProduct(item.id)
  204. val pro = itemDetail?.data?.pro?.get(0)
  205. val price = itemDetail?.data?.price
  206. if (itemDetail != null && pro != null) {
  207. val existingItem = itemsService.findByM18Id(item.id)
  208. val saveItemRequest = NewItemRequest(
  209. code = pro.code,
  210. name = pro.desc,
  211. // type = if (pro.seriesId == m18Config.SERIESID_PF) ProductType.MATERIAL
  212. // else ItemType.PRODUCT,
  213. type = ItemType.MATERIAL,
  214. id = existingItem?.id,
  215. description = pro.desc,
  216. remarks = null,
  217. shelfLife = null,
  218. countryOfOrigin = null,
  219. maxQty = null,
  220. m18Id = item.id,
  221. m18LastModifyDate = commonUtils.timestampToLocalDateTime(pro.lastModifyDate)
  222. )
  223. val savedItem = itemsService.saveItem(saveItemRequest)
  224. logger.info("Processing item uom...")
  225. // Find the item uom that ready to delete (not in m18)
  226. val existingItemUoms = savedItem.id?.let { itemUomService.findAllByItemsId(it) }
  227. val m18ItemUomIds = price?.map { it.id } ?: listOf()
  228. // Delete the item uom
  229. logger.info("Deleting item uom...")
  230. // logger.info("Item Uom: ${existingItemUoms?.map { it.m18Id }}")
  231. // logger.info("M18: ${m18ItemUomIds}")
  232. existingItemUoms?.filter { it.m18Id !in m18ItemUomIds }?.mapNotNull { it.id }
  233. ?.let { itemUomService.deleteItemUoms(it) }
  234. // Update the item uom
  235. logger.info("Updating item uom...")
  236. price?.forEach {
  237. val itemUomRequest = ItemUomRequest(
  238. m18UomId = it.unitId,
  239. itemId = savedItem.id,
  240. baseUnit = it.basicUnit,
  241. stockUnit = it.stkUnit,
  242. pickingUnit = it.pickUnit,
  243. salesUnit = it.saleUnit,
  244. purchaseUnit = it.purUnit,
  245. price = null,
  246. currencyId = null,
  247. m18Id = it.id,
  248. m18LastModifyDate = commonUtils.timestampToLocalDateTime(pro.lastModifyDate),
  249. ratioD = it.ratioD,
  250. ratioN = it.ratioN,
  251. deleted = it.expired
  252. )
  253. // logger.info("saved item id: ${savedItem.id}")
  254. itemUomService.saveItemUom(itemUomRequest)
  255. }
  256. successList.add(item.id)
  257. logger.info("Success Count ${successList.size}: ${item.id} | ${pro.code} | ${pro.desc}")
  258. } else {
  259. failList.add(item.id)
  260. logger.error("Fail Message: ${itemDetail?.messages?.get(0)?.msgDetail}")
  261. logger.error("Fail Count ${failList.size}: Item ID - ${item.id} Not Found")
  262. }
  263. } catch (e: Exception) {
  264. failList.add(item.id)
  265. logger.error("Exception")
  266. logger.error("Fail Message: ${e.message}")
  267. logger.error("Fail Count ${failList.size}: Item ID - ${item.id}")
  268. }
  269. }
  270. } else {
  271. logger.error("Items List is null. May occur errors.")
  272. }
  273. logger.info("Total Success (${successList.size})")
  274. if (failList.size > 0) {
  275. logger.error("Total Fail (${failList.size}): $failList")
  276. }
  277. logger.info("--------------------------------------------End - Saving M18 Products / Materials--------------------------------------------")
  278. }
  279. // --------------------------------------------- Vendor --------------------------------------------- ///
  280. open fun getVendors(request: M18CommonRequest): M18VendorListResponse? {
  281. return getList<M18VendorListResponse>(
  282. stSearch = StSearchType.VENDOR.value,
  283. params = null,
  284. conds = beIdConds,
  285. request = request
  286. )
  287. }
  288. open fun getVendor(id: Long): M18VendorResponse? {
  289. logger.info("M18 Vendor ID: $id")
  290. return getLine<M18VendorResponse>(
  291. id = id,
  292. params = null,
  293. api = M18_LOAD_VENDOR_API
  294. )
  295. }
  296. open fun saveVendors(request: M18CommonRequest) {
  297. logger.info("--------------------------------------------Start - Saving M18 Vendors--------------------------------------------")
  298. val vendors = getVendors(request)
  299. val exampleVendors = listOf<Long>(191L)
  300. val successList = mutableListOf<Long>()
  301. val failList = mutableListOf<Long>()
  302. val values = vendors?.values?.sortedBy { it.id }
  303. if (values != null) {
  304. values.forEach { vendor ->
  305. // if (vendor.id in exampleVendors) {
  306. try {
  307. val vendorDetail = getVendor(vendor.id)
  308. if (vendorDetail != null && vendorDetail.data?.ven != null) {
  309. val ven = vendorDetail.data.ven[0]
  310. val saveShopRequest = SaveShopRequest(
  311. id = null,
  312. code = ven.code,
  313. name = ven.desc.ifEmpty { ven.`desc_zh-TW` },
  314. brNo = null,
  315. contactNo = ven.tel,
  316. contactEmail = ven.email,
  317. contactName = null,
  318. addr1 = ven.ad1,
  319. addr2 = ven.ad2,
  320. addr3 = ven.ad3,
  321. addr4 = ven.ad4,
  322. district = null,
  323. type = ShopType.SUPPLIER.value,
  324. m18Id = vendor.id,
  325. m18LastModifyDate = commonUtils.timestampToLocalDateTime(ven.lastModifyDate)
  326. )
  327. shopService.saveShop(saveShopRequest)
  328. successList.add(vendor.id)
  329. logger.info("Success Count ${successList.size}: ${vendor.id} | ${ven.code} | ${ven.desc}")
  330. } else {
  331. failList.add(vendor.id)
  332. logger.error("Fail Message: ${vendorDetail?.messages?.get(0)?.msgDetail}")
  333. logger.error("Fail Count ${failList.size}: Vendor ID - ${vendor.id} Not Found")
  334. }
  335. } catch (e: Exception) {
  336. failList.add(vendor.id)
  337. logger.error("Exception")
  338. logger.error("Fail Message: ${e.message}")
  339. logger.error("Fail Count ${failList.size}: Vendor ID - ${vendor.id}")
  340. }
  341. // }
  342. }
  343. } else {
  344. logger.error("Vendor List is null. May occur errors.")
  345. }
  346. logger.info("Total Success (${successList.size})")
  347. if (failList.size > 0) {
  348. logger.error("Total Fail (${failList.size}): $failList")
  349. }
  350. logger.info("--------------------------------------------End - Saving M18 Vendors--------------------------------------------")
  351. }
  352. // --------------------------------------------- Unit (UoM) --------------------------------------------- ///
  353. open fun getUnits(request: M18CommonRequest): M18UnitListResponse? {
  354. // seems no beId
  355. return getList<M18UnitListResponse>(
  356. stSearch = StSearchType.UNIT.value,
  357. params = null,
  358. conds = null,
  359. request = request
  360. )
  361. }
  362. open fun getUnit(id: Long): M18UnitResponse? {
  363. logger.info("M18 Unit ID: $id")
  364. return getLine<M18UnitResponse>(
  365. id = id,
  366. params = null,
  367. api = M18_LOAD_UNIT_API
  368. )
  369. }
  370. open fun saveUnits(request: M18CommonRequest) {
  371. logger.info("--------------------------------------------Start - Saving M18 Units--------------------------------------------")
  372. val units = getUnits(request)
  373. val successTransformList = mutableListOf<Long>()
  374. val successSaveList = mutableListOf<Long>()
  375. val failTransformList = mutableListOf<Long>()
  376. val failSaveList = mutableListOf<Long>()
  377. val values = units?.values?.sortedBy { it.id }
  378. if (values != null) {
  379. val finalUnitList = arrayListOf<UomConversion>()
  380. // transform unit
  381. values.forEach { unit ->
  382. try {
  383. val tempObject = UomConversionService.BomObject().apply {
  384. code = unit.code
  385. udfudesc = unit.udfudesc
  386. lastModifyDate = unit.lastModifyDate
  387. id = unit.id
  388. }
  389. finalUnitList += uomConversionService.transformItem(tempObject)
  390. successTransformList += unit.id
  391. logger.info("Transform Success (M18): ${unit.id}")
  392. } catch (e: Exception) {
  393. failTransformList.add(unit.id)
  394. logger.error("Transform Exception")
  395. logger.error("Transform Fail Message: ${e.message}")
  396. logger.error("Transform Fail Count ${failTransformList.size}: Unit ID - ${unit.id}")
  397. }
  398. }
  399. uomConversionService.calculateSizeInGram(finalUnitList)
  400. finalUnitList.forEach {
  401. try {
  402. uomConversionService.saveUomConversion(it)
  403. successSaveList += it.m18Id
  404. logger.info("Save Success (M18): ${it.m18Id}")
  405. } catch (e: Exception) {
  406. failSaveList.add(it.m18Id)
  407. logger.error("Save Exception")
  408. logger.error("Save Fail Message: ${e.message}")
  409. logger.error("Save Fail Count ${failTransformList.size}: Unit ID - ${it.m18Id}")
  410. }
  411. }
  412. } else {
  413. logger.error("Unit List is null. May occur errors.")
  414. }
  415. logger.info("Total Transform Success (${successTransformList.size})")
  416. logger.info("Total Save Success (${successSaveList.size})")
  417. if (failTransformList.size > 0) {
  418. logger.error("Total Transform Fail (${failTransformList.size}): $failTransformList")
  419. }
  420. if (failSaveList.size > 0) {
  421. logger.error("Total Save Fail (${failSaveList.size}): $failSaveList")
  422. }
  423. logger.info("--------------------------------------------End - Saving M18 Units--------------------------------------------")
  424. }
  425. // --------------------------------------------- Currency --------------------------------------------- ///
  426. open fun getCurrencies(request: M18CommonRequest): M18CurrencyListResponse? {
  427. return getList<M18CurrencyListResponse>(
  428. stSearch = StSearchType.CURRENCY.value,
  429. params = null,
  430. conds = null,
  431. request = request
  432. )
  433. }
  434. open fun getCurrency(id: Long): M18CurrencyResponse? {
  435. logger.info("M18 Currency ID: $id")
  436. return getLine<M18CurrencyResponse>(
  437. id = id,
  438. params = null,
  439. api = M18_LOAD_CURRENCY_API
  440. )
  441. }
  442. open fun saveCurrencies(request: M18CommonRequest) {
  443. logger.info("--------------------------------------------Start - Saving M18 Currencies--------------------------------------------")
  444. val currencies = getCurrencies(request)
  445. val successList = mutableListOf<Long>()
  446. val failList = mutableListOf<Long>()
  447. val values = currencies?.values?.sortedBy { it.id }
  448. if (values != null) {
  449. // save currency
  450. values.forEach { currency ->
  451. try {
  452. val currencyRequest = SaveCurrencyRequest(
  453. id = null,
  454. code = currency.code,
  455. name = currency.sym,
  456. description = currency.curDesc,
  457. m18Id = currency.id,
  458. m18LastModifyDate = LocalDateTime.parse(currency.lastModifyDate, formatter)
  459. )
  460. currencyService.saveCurrency(currencyRequest)
  461. successList += currency.id
  462. logger.info("Save Success (M18): ${currency.id}")
  463. } catch (e: Exception) {
  464. failList += currency.id
  465. logger.error("Exception")
  466. logger.error("Fail Message: ${e.message}")
  467. logger.error("Fail Count ${failList.size}: Unit ID - ${currency.id}")
  468. }
  469. }
  470. } else {
  471. logger.error("Currency List is null. May occur errors.")
  472. }
  473. logger.info("Total Save Success (${successList.size})")
  474. if (failList.size > 0) {
  475. logger.error("Total Fail (${failList.size}): $failList")
  476. }
  477. logger.info("--------------------------------------------End - Saving Currencies--------------------------------------------")
  478. }
  479. // --------------------------------------------- Bom --------------------------------------------- ///
  480. open fun getBoms(request: M18CommonRequest): M18BomListResponse? {
  481. return getList<M18BomListResponse>(
  482. stSearch = StSearchType.BOM.value,
  483. params = null,
  484. conds = beIdConds,
  485. request = request
  486. )
  487. }
  488. open fun getBom(id: Long): M18BomResponse? {
  489. logger.info("M18 Bom ID: $id")
  490. return getLine<M18BomResponse>(
  491. id = id,
  492. params = null,
  493. api = M18_LOAD_BOM_API
  494. )
  495. }
  496. open fun saveBoms(request: M18CommonRequest) {
  497. logger.info("--------------------------------------------Start - Saving M18 Boms--------------------------------------------")
  498. val boms = getBoms(request)
  499. val successList = mutableListOf<Long>()
  500. val successDetailList = mutableListOf<Long>()
  501. val failList = mutableListOf<Long>()
  502. val failDetailList = mutableListOf<Pair<Long, MutableList<Long>>>()
  503. var failDetailCount = 0
  504. val values = boms?.values?.sortedBy { it.id }
  505. if (values != null) {
  506. values.forEach { bom ->
  507. try {
  508. val bomDetail = getBom(bom.id)
  509. val bomUdfBomForShop = bomDetail?.data?.udfbomforshop?.get(0)
  510. val bomUdfProduct = bomDetail?.data?.udfproduct
  511. logger.info(bomUdfBomForShop.toString())
  512. logger.info(bomUdfProduct.toString())
  513. if (bomUdfBomForShop != null && bomUdfProduct != null) {
  514. // Save Bom
  515. val saveBomRequest = SaveBomRequest(
  516. // itemId = itemsService.findByNameAndM18UomId(bomUdfBomForShop.desc, bomUdfBomForShop.udfUnit)?.id,
  517. code = bomUdfBomForShop.code,
  518. name = bomUdfBomForShop.desc,
  519. description = bomUdfBomForShop.desc,
  520. outputQty = if (bomUdfBomForShop.udfHarvest.trim().toBigDecimalOrNull() != null) bomUdfBomForShop.udfHarvest.trim().toBigDecimal() else BigDecimal(0),
  521. outputQtyUom = bomUdfBomForShop.udfHarvestUnit,
  522. yield = bomUdfBomForShop.udfYieldratePP,
  523. m18UomId = bomUdfBomForShop.udfUnit,
  524. m18Id = bomUdfBomForShop.id,
  525. m18LastModifyDate = commonUtils.timestampToLocalDateTime(bomUdfBomForShop.lastModifyDate)
  526. )
  527. val bomId = bomService.saveBom(saveBomRequest).id
  528. successList += bom.id
  529. // Save Bom Material
  530. logger.info("Start saving bom material...")
  531. val tempFailList = mutableListOf<Long>()
  532. bomUdfProduct.forEach { bomMaterial ->
  533. try {
  534. val saveBomMaterialRequest = SaveBomMaterialRequest(
  535. m18ItemId = bomMaterial.udfProduct,
  536. itemName = bomMaterial.udfIngredients,
  537. qty = bomMaterial.udfqty,
  538. m18UomId = bomMaterial.udfpurchaseUnit,
  539. uomName = bomMaterial.udfBaseUnit,
  540. bomId = bomId,
  541. m18Id = bomMaterial.id,
  542. m18LastModifyDate = commonUtils.timestampToLocalDateTime(bomUdfBomForShop.lastModifyDate)
  543. )
  544. bomMaterialService.saveBomMaterial(saveBomMaterialRequest)
  545. successDetailList += bomMaterial.id
  546. } catch (e: Exception) {
  547. tempFailList += bomMaterial.id
  548. logger.error("(Bom Material) Exception")
  549. logger.error("(Bom Material) Fail Message: ${e.message}")
  550. logger.error("(Bom Material) Fail Count ${++failDetailCount}: Bom Material ID - ${bomMaterial.id} | Bom ID - ${bom.id}")
  551. }
  552. }
  553. failDetailList += Pair(bom.id, tempFailList)
  554. logger.info("Save Success (M18): ${bom.id}")
  555. } else {
  556. failList.add(bom.id)
  557. logger.error("(Bom) Fail Message: ${bomDetail?.messages?.get(0)?.msgDetail}")
  558. logger.error("(Bom) Fail Count ${failList.size}: Bom ID - ${bom.id} Not Found")
  559. }
  560. } catch (e: Exception) {
  561. failList += bom.id
  562. logger.error("(Bom) Exception")
  563. logger.error("(Bom) Fail Message: ${e.message}")
  564. logger.error("(Bom) Fail Count ${failList.size}: Bom ID - ${bom.id}")
  565. }
  566. }
  567. } else {
  568. logger.error("Currency List is null. May occur errors.")
  569. }
  570. logger.info("Total Bom Save Success (${successList.size})")
  571. logger.info("Total Bom Save Detail Success (${successDetailList.size})")
  572. if (failList.size > 0) {
  573. logger.error("Total Bom Fail (${failList.size}): $failList")
  574. }
  575. if (failDetailCount > 0) {
  576. logger.error("Total Bom Detail Fail (${failDetailCount}): $failDetailList")
  577. }
  578. logger.info("--------------------------------------------End - Saving Boms--------------------------------------------")
  579. }
  580. // --------------------------------------------- Business Unit (Shop) --------------------------------------------- ///
  581. open fun getBusinessUnits(request: M18CommonRequest): M18BusinessUnitListResponse? {
  582. // seems no beId
  583. return getList<M18BusinessUnitListResponse>(
  584. stSearch = StSearchType.BUSINESS_UNIT.value,
  585. params = null,
  586. // conds = beIdConds
  587. request = request
  588. )
  589. }
  590. open fun getBusinessUnit(id: Long): M18BusinessUnitResponse? {
  591. logger.info("M18 Business Unit ID: $id")
  592. return getLine<M18BusinessUnitResponse>(
  593. id = id,
  594. params = null,
  595. api = M18_LOAD_BUSINESS_UNIT_API
  596. )
  597. }
  598. open fun saveBusinessUnits(request: M18CommonRequest) {
  599. logger.info("--------------------------------------------Start - Saving M18 Business Units (Shops)--------------------------------------------")
  600. val businessUnits = getBusinessUnits(request)
  601. val successList = mutableListOf<Long>()
  602. val failList = mutableListOf<Long>()
  603. val values = businessUnits?.values?.sortedBy { it.id }
  604. val busMessages = if(businessUnits?.messages?.isNotEmpty() == true) businessUnits.messages[0] else null
  605. if (values != null) {
  606. values.forEach { businessUnit ->
  607. // if (vendor.id in exampleVendors) {
  608. try {
  609. val businessUnitDetail = getBusinessUnit(businessUnit.id)
  610. val virdept = businessUnitDetail?.data?.virdept?.get(0)
  611. val buMessages = if(businessUnitDetail?.messages?.isNotEmpty() == true) businessUnitDetail?.messages[0] else null
  612. if (virdept != null) {
  613. val saveShopRequest = SaveShopRequest(
  614. id = null,
  615. code = virdept.code,
  616. name = virdept.desc.ifEmpty { virdept.`desc_zh-TW` },
  617. brNo = null,
  618. contactNo = virdept.tel,
  619. contactEmail = virdept.email,
  620. contactName = null,
  621. addr1 = virdept.addr.ifEmpty { virdept.addr_en },
  622. addr2 = virdept.addr2.ifEmpty { virdept.addr2_en },
  623. addr3 = virdept.addr3.ifEmpty { virdept.addr3_en },
  624. addr4 = null,
  625. district = null,
  626. type = ShopType.SHOP.value,
  627. m18Id = businessUnit.id,
  628. m18LastModifyDate = commonUtils.timestampToLocalDateTime(virdept.lastModifyDate)
  629. )
  630. shopService.saveShop(saveShopRequest)
  631. successList.add(businessUnit.id)
  632. logger.info("Success Count ${successList.size}: ${businessUnit.id} | ${virdept.code} | ${virdept.desc}")
  633. } else {
  634. failList.add(businessUnit.id)
  635. logger.error("(Business Unit) Fail Message: ${buMessages?.msgDetail}")
  636. logger.error("(Business Unit) Fail Count ${failList.size}: Business Unit ID - ${businessUnit.id} Not Found")
  637. }
  638. } catch (e: Exception) {
  639. failList.add(businessUnit.id)
  640. logger.error("(Business Unit) Exception")
  641. logger.error("(Business Unit) Fail Message: ${e.message}")
  642. logger.error("(Business Unit) Fail Count ${failList.size}: Business Unit ID - ${businessUnit.id}")
  643. }
  644. // }
  645. }
  646. } else {
  647. logger.error("(Business Unit) Business Unit List is null. May occur errors.")
  648. logger.error("(Business Unit)) Fail Message: ${busMessages?.msgDetail}")
  649. logger.error("(Business Unit) Business Unit List is null. May occur errors.")
  650. }
  651. logger.info("Total Success (${successList.size})")
  652. if (failList.size > 0) {
  653. logger.error("Total Fail (${failList.size}): $failList")
  654. }
  655. logger.info("--------------------------------------------End - Saving M18 Business Units--------------------------------------------")
  656. }
  657. }