Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 

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