ItemUrlScrapService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. <?php
  2. namespace App\Services\Scrap;
  3. use App\Helpers\File;
  4. use App\Services\CallApiService;
  5. use App\Services\MediaLibraryService;
  6. use App\Services\Msg\MailTemplateService;
  7. use Carbon\Carbon;
  8. use Exception;
  9. use Illuminate\Support\Str;
  10. use Intervention\Image\Facades\Image;
  11. use Unirest\Request;
  12. class ItemUrlScrapService
  13. {
  14. const BASE_URL = 'http://222.239.248.232:19080';
  15. private $callApiService;
  16. private $mediaLibraryService;
  17. private $gateToken;
  18. public function __construct(
  19. CallApiService $callApiService,
  20. MediaLibraryService $mediaLibraryService,
  21. MailTemplateService $mailTemplateService
  22. )
  23. {
  24. $this->callApiService = $callApiService;
  25. $this->mediaLibraryService = $mediaLibraryService;
  26. $this->mailTemplateService = $mailTemplateService;
  27. }
  28. public function execute($gateToken, $request)
  29. {
  30. $this->gateToken['main'] = $gateToken;
  31. $this->mediaLibraryService->setGateToken($gateToken);
  32. $response = $this->callApi($request['ItemUrl']);
  33. if ($this->callApiService->verifyApiError($response)) {
  34. return $response;
  35. }
  36. // 만약 파싱이 에러뜨면 킹콩 상태값0으로 기록 후 개발자와 대표님한테 이메일보낸다
  37. if ($response['SalesPrice'] === 0) {
  38. $this->insertKkcouponData(0, $response, $request, '0');
  39. $this->sendErrorEmail('wngur6076@naver.com', 'kimhi65@gmail.com', $request);
  40. return [ 'apiStatus' => 604, 'body' => 'This is a solution site that does not support' ];
  41. } else {
  42. $updatedMd5 = md5(json_encode($response));
  43. if (! $itemId = $this->existsUpdatedMd5($updatedMd5)) {
  44. if (empty($response['Images'])) {
  45. $mediaIds = [1, 1];
  46. } else {
  47. $mediaIds = $this->insertMediaData($this->imageUpload($response['Images'], $response['ItemName']));
  48. }
  49. $itemId = $this->insertItemData($mediaIds, $response, $request, $updatedMd5);
  50. }
  51. $this->insertKkcouponData($itemId, $response, $request);
  52. $this->sendEmail($request['BuyerEmail'], $request['BuyerEmail']);
  53. }
  54. }
  55. private function existsUpdatedMd5($updatedMd5)
  56. {
  57. $itemPick = $this->callApiService->callApi([
  58. 'url' => 'item-pick',
  59. 'data' => [
  60. 'Page' => [
  61. [
  62. 'UpdatedMd5' => $updatedMd5,
  63. ]
  64. ],
  65. ],
  66. 'headers' => [
  67. 'GateToken' => $this->gateToken['main']
  68. ]
  69. ]);
  70. if ($this->callApiService->verifyApiError($itemPick)) {
  71. if ($itemPick['apiStatus'] === 604) {
  72. return false;
  73. }
  74. throw new Exception('Dabory Api Error', $itemPick['apiStatus']);
  75. }
  76. return $itemPick['Page'][0]['Id'];
  77. }
  78. private function sendErrorEmail($developerEmail, $ceoEmail, $request)
  79. {
  80. $this->mailTemplateService->send('msg.dabory.pro.ko_KR.email.kkcoupon.kkcoupon-failure-1',
  81. [ 'C11' => $request['BuyerEmail'], 'C12' => $request['ItemUrl'], 'C13' => $request['InitDcrate'], 'C14' => $request['Sort'], 'C15' => $request['SortDesc'] ],
  82. $developerEmail, sprintf('[%s] 킹콩스크랩 실패 메일', config('app.name')), $this->gateToken['main']);
  83. $this->mailTemplateService->send('msg.dabory.pro.ko_KR.email.kkcoupon.kkcoupon-failure-1',
  84. [ 'C11' => $request['BuyerEmail'], 'C12' => $request['ItemUrl'], 'C13' => $request['InitDcrate'], 'C14' => $request['Sort'], 'C15' => $request['SortDesc'] ],
  85. $ceoEmail, sprintf('[%s] 킹콩스크랩 실패 메일', config('app.name')), $this->gateToken['main']);
  86. }
  87. private function sendEmail($buyerEmail, $sellerEmail)
  88. {
  89. $this->mailTemplateService->send('msg.dabory.pro.ko_KR.email.kkcoupon.kkcoupon-buyer-1',
  90. [],
  91. $buyerEmail, sprintf('[%s] 킹콩쿠폰 구매자 메일', config('app.name')), $this->gateToken['main']);
  92. $this->mailTemplateService->send('msg.dabory.pro.ko_KR.email.kkcoupon.kkcoupon-seller-1',
  93. [],
  94. $sellerEmail, sprintf('[%s] 킹콩쿠폰 판매자 메일', config('app.name')), $this->gateToken['main']);
  95. }
  96. private function insertKkcouponData($itemId, $scrap, $request, $status = '1')
  97. {
  98. $kkcouponAct = $this->callApiService->callApi([
  99. 'url' => 'kkcoupon-act',
  100. 'data' => [
  101. 'Page' => [
  102. [
  103. 'Id' => 0,
  104. 'TargetUri' => $request['ItemUrl'],
  105. 'ItemId' => $itemId,
  106. 'InitDcrate' => $request['InitDcrate'],
  107. 'BuyerEmail' => $request['BuyerEmail'],
  108. 'SellerEmail' => $scrap['Emails'][0] ?? '',
  109. 'Sort' => $request['Sort'],
  110. 'Status' => $status,
  111. 'IsClosed' => '0',
  112. 'IsFirstRequest' => '1',
  113. ]
  114. ],
  115. ],
  116. 'headers' => [
  117. 'GateToken' => $this->gateToken['main']
  118. ]
  119. ]);
  120. if ($this->callApiService->verifyApiError($kkcouponAct)) {
  121. throw new Exception('Dabory Api Error', $kkcouponAct['apiStatus']);
  122. }
  123. return true;
  124. }
  125. private function insertItemData($mediaIds, $scrap, $request, $updatedMd5)
  126. {
  127. $mediaId = 0;
  128. if (count($mediaIds) > 0) {
  129. $mediaId = array_shift($mediaIds);
  130. }
  131. // $domainName = explode('.', $scrap['DomainName'])[0];
  132. $linkproMd5 = md5($request['ItemUrl']);
  133. $itemCategory = empty($scrap['ItemCategory']) ? '' : $scrap['ItemCategory'];
  134. $itemAct = $this->callApiService->callApi([
  135. 'url' => 'item-act',
  136. 'data' => [
  137. 'Page' => [
  138. [
  139. 'Id' => 0,
  140. 'IgroupId' => 526,
  141. 'ItemCode' => Str::limit($linkproMd5, 21, ''),
  142. 'ItemSlug' => $linkproMd5,
  143. 'ItemName' => $scrap['ItemName'],
  144. // 'SubName' => $scrap['BrandName'],
  145. 'SalesPrc' => (string)$scrap['SalesPrice'],
  146. 'CountUnit' => $scrap['Currency'],
  147. 'ShortDesc' => $scrap['ShortDesc'],
  148. 'ItemDesc' => $scrap['OriginDesc'],
  149. 'CurrStkQty' => '999999',
  150. 'IsStyle' => '0',
  151. 'IsSelfOption' => '0',
  152. 'IsntPro' => '2',
  153. 'OfferCredit' => '0',
  154. 'RewardRate' => '0',
  155. 'RewardAmt' => '0',
  156. 'MediaId' => $mediaId,
  157. 'LinkproCategory' => $itemCategory,
  158. 'LinkproBrand' => $scrap['BrandName'],
  159. 'LinkproDomain' => $scrap['DomainName'],
  160. 'LinkproUrl' => $request['ItemUrl'],
  161. 'LinkproMd5' => $linkproMd5,
  162. 'UpdatedMd5' => $updatedMd5,
  163. ]
  164. ],
  165. ],
  166. 'headers' => [
  167. 'GateToken' => $this->gateToken['main']
  168. ]
  169. ]);
  170. if ($this->callApiService->verifyApiError($itemAct)) {
  171. throw new Exception('Dabory Api Error', $itemAct['apiStatus']);
  172. }
  173. $itemId = $itemAct['Page'][0]['Id'];
  174. $itemThmRq = [ 'Id' => $itemId ];
  175. foreach ($mediaIds as $i => $mediaId) {
  176. $index = $i + 1;
  177. $itemThmRq["MediaId$index"] = $mediaId;
  178. }
  179. $itemThmAct = $this->callApiService->callApi([
  180. 'url' => 'item-thm-act',
  181. 'data' => [
  182. 'Page' => [
  183. $itemThmRq
  184. ],
  185. ],
  186. 'headers' => [
  187. 'GateToken' => $this->gateToken['main']
  188. ]
  189. ]);
  190. if ($this->callApiService->verifyApiError($itemThmAct)) {
  191. throw new Exception('Dabory Api Error', $itemThmAct['apiStatus']);
  192. }
  193. return $itemId;
  194. }
  195. private function insertMediaData($mediaList): array
  196. {
  197. $mediaAct = [];
  198. foreach ($mediaList as $media) {
  199. $mediaBact = $this->callApiService->callApi([
  200. 'url' => 'media-bact',
  201. 'data' => [
  202. 'HdPage' => [
  203. $media['hd_page']
  204. ],
  205. 'BdPage' => $media['bd_page']
  206. ],
  207. 'headers' => [
  208. 'GateToken' => $this->gateToken['main']
  209. ]
  210. ]);
  211. if ($this->callApiService->verifyApiError($mediaBact)) {
  212. throw new Exception('Dabory Api Error', $mediaBact['apiStatus']);
  213. }
  214. $mediaAct[] = $mediaBact;
  215. }
  216. return collect($mediaAct)->pluck('HdPage')
  217. ->collapse()->pluck('Id')->toArray();
  218. }
  219. private function imageUpload($images, $itemName): array
  220. {
  221. $setup = $this->mediaLibraryService->getSetup('item');
  222. $path = $this->mediaLibraryService->getCurrSetupFilePath($setup);
  223. $mediaList = [];
  224. foreach ($images as $i => $imageUrl) {
  225. // 이미지 최대 수 11개
  226. if ($i === 11) { break; }
  227. $file = File::createFromUrl($imageUrl);
  228. $image = Image::make($file);
  229. $fileExtension = $file->extension();
  230. $media = [
  231. 'name' => date('mdYHis') . uniqid() . $file->getClientOriginalName() . '.' . $fileExtension,
  232. 'path' => $path,
  233. 'setup' => $setup,
  234. 'type' => 'image'
  235. ];
  236. $mediaList[$i]['hd_page'] = [
  237. 'Id' => 0,
  238. 'MediaNo' => $this->lastSlipNoGet(),
  239. 'MediaDate' => Carbon::now()->format('Ymd'),
  240. 'MediaBrand' => $setup['BrandCode'],
  241. 'MediaName' => "$itemName-$i",
  242. 'MineType' => $file->getMimeType(),
  243. 'FileUrl' => '/' . substr($media['path'], '1') . $media['name'],
  244. 'FileSize' => (int)round($image->filesize() / 1024),
  245. 'MediaWidth' => $image->width(),
  246. 'MediaHeight' => $image->height(),
  247. 'IsClosed' => '0'
  248. ];
  249. $file->storeAs($media['path'], $media['name'], ['disk' => getDisk()]);
  250. if ($fileExtension === 'gif' || $fileExtension === 'webp' || $fileExtension === 'svg') {
  251. $mediaList[$i]['bd_page'] = $this->mediaLibraryService->makeGifBd($file, $media);
  252. } else {
  253. $mediaList[$i]['bd_page'] = $this->mediaLibraryService->makeImageBd($file, $media);
  254. }
  255. }
  256. return $mediaList;
  257. }
  258. private function callApi($itemUrl)
  259. {
  260. $response = Request::post(self::BASE_URL . '/product-page-get',
  261. [ 'Accept' => 'application/json', 'Content-Type' => 'application/json', ],
  262. json_encode([
  263. 'Products' => [
  264. [ 'Uri' => $itemUrl ]
  265. ],
  266. ], JSON_UNESCAPED_UNICODE)
  267. );
  268. if ($response->code === 200) {
  269. $data = json_encode($response->body ?? []);
  270. $data = json_decode($data, true);
  271. return $data['ProductPage'][0];
  272. } else {
  273. return [ 'apiStatus' => $response->code, 'body' => $response->body->msg ?? _e('Action failed') ];
  274. }
  275. }
  276. private function getCurrSetupFilePath($setup): string
  277. {
  278. $monthYearFolder = '';
  279. $subDir = '';
  280. if ($setup['SubDir']) {
  281. $subDir = $setup['BrandCode'] . '/';
  282. }
  283. if ($setup['DateFolderType'] === '0') {
  284. $monthYearFolder = date('/Y/m/');
  285. } else if ($setup['DateFolderType'] === '1') {
  286. $monthYearFolder = date('/Y/m/d/');
  287. }
  288. return '/uploads' . $monthYearFolder . $subDir;
  289. }
  290. private function getSetup()
  291. {
  292. $response = $this->callApiService->callApi([
  293. 'url' => 'setup-get',
  294. 'data' => [
  295. 'SetupCode' => 'media-body',
  296. 'BrandCode' => 'item'
  297. ],
  298. 'headers' => [
  299. 'GateToken' => $this->gateToken['main']
  300. ]
  301. ]);
  302. if ($this->callApiService->verifyApiError($response)) {
  303. throw new Exception('Dabory Api Error', $response['apiStatus']);
  304. }
  305. $response['BrandCode'] = 'item';
  306. return $response;
  307. }
  308. private function lastSlipNoGet(): string
  309. {
  310. $response = $this->callApiService->callApi([
  311. 'url' => 'last-slip-no-get',
  312. 'data' => [
  313. 'TableName' => 'common/media',
  314. 'YYMMDD' => Carbon::now()->format('ymd'),
  315. ],
  316. 'headers' => [
  317. 'GateToken' => $this->gateToken['main']
  318. ]
  319. ]);
  320. if ($this->callApiService->verifyApiError($response)) {
  321. throw new Exception('Dabory Api Error', $response['apiStatus']);
  322. }
  323. return Carbon::now()->format('ymd') . '-' . $response['LastSlipNo'];
  324. }
  325. }