sync_get_order_data.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. import clickhouse_connect
  2. import time
  3. import warnings
  4. warnings.filterwarnings('ignore')
  5. import numpy as np
  6. from pymysql import Timestamp
  7. from sp_api.util import throttle_retry, load_all_pages
  8. from sp_api.api import Orders,ListingsItems,Inventories,Reports,CatalogItems
  9. from sp_api.base import Marketplaces,ReportType,ProcessingStatus
  10. import pandas as pd
  11. import gzip
  12. from io import BytesIO,StringIO
  13. from datetime import datetime, timedelta,timezone
  14. import pytz
  15. import time
  16. from dateutil.parser import parse
  17. import pymysql
  18. from typing import List, Literal
  19. from apscheduler.schedulers.blocking import BlockingScheduler
  20. class SpApiRequest:
  21. def __init__(self, credentials,marketplace):
  22. self.credentials = credentials
  23. self.marketplace = marketplace
  24. # self.shopInfo = shop_infos('3006125408623189')
  25. # self.timezone = self.shopInfo['time_zone']
  26. # self.profileid = '3006125408623189'
  27. @classmethod
  28. def mysql_connect_auth(cls):
  29. conn = pymysql.connect(user="admin",
  30. password="NSYbBSPbkGQUbOSNOeyy",
  31. host="retail-data.cnrgrbcygoap.us-east-1.rds.amazonaws.com",
  32. database="ansjer_dvadmin",
  33. port=3306)
  34. return conn
  35. @classmethod
  36. def mysql_connect_auth_lst(cls):
  37. conn = pymysql.connect(user="root",
  38. password="sandbox",
  39. host="192.168.1.225",
  40. database="asj_ads",
  41. port=3306)
  42. # conn = pymysql.connect(user="huangyifan",
  43. # password="123456",
  44. # host="127.0.0.1",
  45. # database="amz_sp_api",
  46. # port=3306)
  47. return conn
  48. @classmethod
  49. def mysql_connect(cls):
  50. conn = pymysql.connect(user="huangyifan",
  51. password="123456",
  52. host="127.0.0.1",
  53. database="amz_sp_api",
  54. port=3306)
  55. return conn
  56. @classmethod
  57. def mysql_adTest_connect(cls):
  58. conn = pymysql.connect(user="root",
  59. password="sandbox",
  60. host="192.168.1.225",
  61. database="asj_ads",
  62. port=3306)
  63. return conn
  64. @classmethod
  65. def get_catelog(cls,account_name,country=Marketplaces.US,asin=None):
  66. if country in [Marketplaces.US, Marketplaces.BR, Marketplaces.CA,Marketplaces.MX]:
  67. region = 'NA'
  68. elif country in [Marketplaces.DE,Marketplaces.AE, Marketplaces.BE, Marketplaces.PL,
  69. Marketplaces.EG,Marketplaces.ES, Marketplaces.GB, Marketplaces.IN, Marketplaces.IT,
  70. Marketplaces.NL, Marketplaces.SA, Marketplaces.SE, Marketplaces.TR,Marketplaces.UK,Marketplaces.FR,
  71. ]:
  72. region = 'EU'
  73. else:
  74. region = str(country)[-2:]
  75. df = cls.auth_info()
  76. try:
  77. refresh_token = df.query("account_name==@account_name and region==@region")['refresh_token'].values[0]
  78. except:
  79. print("请输入正确的account name与Marketplace")
  80. return '获取失败'
  81. cred = {
  82. 'refresh_token': refresh_token,
  83. 'lwa_app_id': 'amzn1.application-oa2-client.1f9d3d4747e14b22b4b598e54e6b922e', # 卖家中心里面开发者资料LWA凭证
  84. 'lwa_client_secret': 'amzn1.oa2-cs.v1.3af0f5649f5b8e151cd5bd25c10f2bf3113172485cd6ffc52ccc6a5e8512b490',
  85. 'aws_access_key': 'AKIARBAGHTGOZC7544GN',
  86. 'aws_secret_key': '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',
  87. 'role_arn': 'arn:aws:iam::070880041373:role/Amazon_SP_API_ROLE'
  88. }
  89. cate_item = CatalogItems(credentials=cred, marketplace=country)
  90. images_info = cate_item.get_catalog_item(asin=asin,**{"includedData":['images']})
  91. images = images_info.images[0].get('images')[0]['link']
  92. title_info = cate_item.get_catalog_item(asin=asin)
  93. title = title_info.payload['summaries'][0]['itemName']
  94. return {'images':images,'title':title}
  95. def create_report(self,**kwargs): # 创建报告
  96. reportType = kwargs['reportType']
  97. reportOptions =kwargs.get("reportOptions")
  98. # give a time period
  99. dataStartTime = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") if kwargs.get("dataStartTime") is None else kwargs.get("dataStartTime")+"T00:00:00"
  100. dataEndTime = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") if kwargs.get("dataEndTime") is None else kwargs.get("dataEndTime")+"T23:59:59"
  101. report = Reports(credentials=self.credentials, marketplace=self.marketplace)
  102. rel = report.create_report(
  103. reportType=reportType,marketplaceIds=[kwargs['marketpalceids'] if kwargs.get('marketpalceids') is not None else self.marketplace.marketplace_id],
  104. reportOptions=reportOptions,dataStartTime=dataStartTime,dataEndTime=dataEndTime
  105. )
  106. reportId = rel.payload.get("reportId")
  107. # print(reportId)
  108. return reportId
  109. def decompression(self,reportId): #解压生成的报告
  110. report = Reports(credentials=self.credentials, marketplace=self.marketplace)
  111. while True:
  112. reportId_info = report.get_report(reportId=reportId)
  113. # print(reportId_info.payload)
  114. print("please wait...")
  115. if reportId_info.payload.get("processingStatus")==ProcessingStatus.DONE:
  116. reportDocumentId = reportId_info.payload.get("reportDocumentId")
  117. rp_table = report.get_report_document(reportDocumentId=reportDocumentId,download=False)
  118. print(rp_table)
  119. if rp_table.payload.get('compressionAlgorithm') is not None and self.marketplace.marketplace_id not in ['A1VC38T7YXB528']:#
  120. df = pd.read_table(filepath_or_buffer=rp_table.payload['url'],compression={"method":'gzip'},encoding='iso-8859-1')
  121. return df
  122. elif rp_table.payload.get('compressionAlgorithm') is not None and self.marketplace.marketplace_id in ['A1VC38T7YXB528']:
  123. df = pd.read_table(filepath_or_buffer=rp_table.payload['url'], compression={"method": 'gzip'},
  124. encoding='Shift-JIS')
  125. # df.columns =
  126. return df
  127. elif rp_table.payload.get('compressionAlgorithm') is None and self.marketplace.marketplace_id not in ['A1VC38T7YXB528']:
  128. df = pd.read_table(rp_table.payload.get("url"),encoding='iso-8859-1')
  129. return df
  130. elif rp_table.payload.get('compressionAlgorithm') is None and self.marketplace.marketplace_id in ['A1VC38T7YXB528']:
  131. df = pd.read_table(rp_table.payload.get("url"),encoding='Shift-JIS')
  132. return df
  133. elif reportId_info.payload.get("processingStatus") in [ProcessingStatus.CANCELLED,ProcessingStatus.FATAL]:
  134. print(reportId_info)
  135. print("取消或失败")
  136. break
  137. time.sleep(15)
  138. print("please wait...")
  139. def data_deal(self,decom_df,seller_id): # 数据处理-for listing SUB
  140. decom_df['mainImageUrl'] = decom_df['seller-sku'].map(lambda x: self.get_mainImage_url(x))
  141. url_columns = [i for i in decom_df.columns if "url" in i.lower()]
  142. if len(url_columns) > 0:
  143. decom_df[url_columns] = decom_df[url_columns].astype("string")
  144. asin_columns = [i for i in decom_df.columns if 'asin' in i.lower()]
  145. if len(asin_columns) > 0:
  146. decom_df[asin_columns] = decom_df[asin_columns].astype("string")
  147. if 'pending-quantity' in decom_df.columns:
  148. decom_df['pending-quantity'] = decom_df['pending-quantity'].map(
  149. lambda x: 0 if pd.isna(x) or np.isinf(x) else x).astype("int32")
  150. deletecolumns = [i for i in decom_df.columns if 'zshop' in i.lower()]
  151. decom_df.drop(columns=deletecolumns, inplace=True)
  152. if 'quantity' in decom_df.columns:
  153. decom_df['quantity'] = decom_df['quantity'].map(lambda x: 0 if pd.isna(x) or np.isinf(x) else x).astype(
  154. "int32")
  155. decom_df['opendate_date'] = decom_df['open-date'].map(lambda x: self.datetime_deal(x))
  156. if 'add-delete' in decom_df.columns:
  157. decom_df['add-delete'] = decom_df['add-delete'].astype('string', errors='ignore')
  158. if 'will-ship-internationally' in decom_df.columns:
  159. decom_df['will-ship-internationally'] = decom_df['will-ship-internationally'].astype('string',errors='ignore')
  160. if 'expedited-shipping' in decom_df.columns:
  161. decom_df['expedited-shipping'] = decom_df['expedited-shipping'].astype('string',errors='ignore')
  162. decom_df['updateTime'] = datetime.now()
  163. decom_df['timezone'] = "UTC"
  164. decom_df['seller_id'] = seller_id
  165. #
  166. decom_df['item-description'] = decom_df['item-description'].str.slice(0,500)
  167. decom_df[decom_df.select_dtypes(float).columns] = decom_df[decom_df.select_dtypes(float).columns].fillna(0.0)
  168. decom_df[decom_df.select_dtypes(int).columns] = decom_df[decom_df.select_dtypes(int).columns].fillna(0)
  169. decom_df[decom_df.select_dtypes(datetime).columns] = decom_df[decom_df.select_dtypes(datetime).columns].astype(
  170. 'string')
  171. decom_df.fillna('', inplace=True)
  172. # print(decom_df.info())
  173. return decom_df
  174. def GET_MERCHANT_LISTINGS_ALL_DATA(self,limit=None): # 获取listing信息 SUB
  175. start = time.time()
  176. para = {"reportType":ReportType.GET_MERCHANT_LISTINGS_ALL_DATA}
  177. reportid = self.create_report(**para)
  178. decom_df = self.decompression(reportid)
  179. print("连接数据库")
  180. conn = self.mysql_connect()
  181. print("连接成功")
  182. cursor = conn.cursor()
  183. timezone = "UTC" #pytz.timezone(self.timezone)
  184. bondary_date = (datetime.now()).strftime("%Y-%m-%d") #+ timedelta(days=-28)
  185. cursor.execute(f"""select * from amz_sp_api.productInfo where (mainImageUrl is not null and mainImageUrl not in ('', ' ')) and
  186. (`seller-sku` not in ('',' ') and `seller-sku` is not null) and
  187. `updateTime`>='{bondary_date}'""") #`seller-sku`,`updateTime`,`mainImageUrl`
  188. col = [i[0] for i in cursor.description]
  189. query_rel = cursor.fetchall()
  190. if len(query_rel)!=0:
  191. print(query_rel[0])
  192. df = pd.DataFrame(query_rel,columns=col)
  193. listingid = df['listing-id'].to_numpy().tolist()
  194. decom_df = decom_df.query("`listing-id` not in @listingid")
  195. print("数据条数: ",len(decom_df))
  196. # print(f"delete * from amz_sp_api.productInfo where `listing-id` not in {tuple(listingid)}")
  197. # conn.commit()
  198. if len(decom_df)==0:
  199. return "Done"
  200. if limit != None:
  201. decom_df = decom_df.iloc[:limit,:]
  202. print("getting mainImageInfo...")
  203. rowcount = 0
  204. while rowcount < len(decom_df):
  205. df_insert = decom_df.copy()
  206. df_insert = df_insert.iloc[rowcount:rowcount + 200, :]
  207. df_insert = self.data_deal(df_insert)
  208. list_df = df_insert.to_numpy().tolist()
  209. # print(list(conn.query("select * from amz_sp_api.orderReport")))
  210. sql = f"""
  211. insert into amz_sp_api.productInfo
  212. values (%s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s,%s)
  213. """ #ok
  214. # print(sql)
  215. conn = self.mysql_connect()
  216. cursor = conn.cursor()
  217. try:
  218. conn.begin()
  219. cursor.executemany(sql, list_df)
  220. conn.commit()
  221. print("插入中...")
  222. insert_listingid = df_insert['listing-id'].to_numpy().tolist()
  223. cursor.execute(f"delete from amz_sp_api.productInfo where `listing-id` not in {tuple(insert_listingid)} and `updateTime`<'{bondary_date}'")
  224. conn.commit()
  225. rowcount += 200
  226. except Exception as e:
  227. conn.rollback()
  228. print(e)
  229. try:
  230. conn = self.mysql_connect()
  231. cursor = conn.cursor()
  232. conn.begin()
  233. cursor.executemany(sql, list_df)
  234. conn.commit()
  235. insert_listingid = df_insert['listing-id'].to_numpy().tolist()
  236. cursor.execute(f"delete from amz_sp_api.productInfo where `listing-id` not in {tuple(insert_listingid)} and `updateTime`<'{bondary_date}'")
  237. conn.commit()
  238. except Exception as e:
  239. conn.rollback()
  240. print(e)
  241. break
  242. # break
  243. conn.close()
  244. print("全部完成")
  245. end =time.time()
  246. print("duration:",end-start)
  247. return decom_df
  248. def GET_FLAT_FILE_OPEN_LISTINGS_DATA(self,conn=None,seller_id=None): # MAIN
  249. para = {"reportType": ReportType.GET_MERCHANT_LISTINGS_ALL_DATA}
  250. reportid = self.create_report(**para)
  251. df = self.decompression(reportid)
  252. if len(df)>0:
  253. if self.marketplace.marketplace_id =='A1VC38T7YXB528':
  254. df.columns = ['item-name','listing-id','seller-sku','price','quantity','open-date','product-id-type','item-description',
  255. 'item-condition','overseas shipping','fast shipping','asin1','stock_number','fulfillment-channel','merchant-shipping-group','status']
  256. df['seller_id'] = seller_id
  257. df['marketplace_id'] = self.marketplace.marketplace_id
  258. df['country_code'] = str(self.marketplace)[-2:]
  259. if 'fulfilment-channel' in df.columns:
  260. print("changed fulfilment-channel:")
  261. print(seller_id,self.marketplace)
  262. df['fulfillment-channel'] = df['fulfilment-channel'].copy()
  263. df['fulfillment_channel'] = df['fulfillment-channel'].map(lambda x:"FBA" if not pd.isna(x) and len(x)>0 and str(x)[1:4] in "AMAZON" else x)
  264. df['fulfillment_channel'] = df['fulfillment_channel'].map(lambda x: "FBM" if not pd.isna(x) and len(x)>0 and str(x)[1:4] in "DEFAULT" else x)
  265. if 'asin1' not in df.columns:
  266. df['asin1'] = ''
  267. if 'product-id' not in df.columns:
  268. df['product-id'] = ''
  269. # 空值处理
  270. df['quantity'] = df['quantity'].fillna(0).astype('int64',errors='ignore')
  271. df[['listing-id','seller_id','asin1','seller-sku','country_code','marketplace_id','fulfillment_channel','status','product-id']] = df[['listing-id','seller_id','asin1','seller-sku','country_code','marketplace_id','fulfillment_channel','status','product-id']].fillna('').astype('string',errors='ignore')
  272. df['price'] = df['price'].fillna(0.0).astype('float64',errors='ignore')
  273. df.fillna('',inplace=True)
  274. # 时间处理
  275. df['opendate'] = df['open-date'].map(lambda x: self.datetime_deal(x))
  276. df['update_datetime'] = datetime.now(pytz.UTC).date()
  277. origin_columns = ['listing-id','seller_id',
  278. 'asin1','seller-sku','title','image_link','country_code',
  279. 'marketplace_id','quantity','fulfillment_channel',
  280. 'price','opendate','status','update_datetime','product-id','product-id-type'
  281. ]
  282. # DONE 连数据库
  283. conn = SpApiRequest.mysql_connect_auth_lst()
  284. cursor = conn.cursor()
  285. # DONE 修改查询条件
  286. cursor.execute("""select product_id,asin from (select * from asj_ads.seller_listings_dailyUP where asin is not null
  287. and asin<>'' and product_id is not null and product_id <>'') t1 group by product_id,asin""")
  288. query_ = cursor.fetchall()
  289. col_name = [i[0] for i in cursor.description]
  290. df_datatable = pd.DataFrame(query_, columns=col_name)
  291. merged_df = df.merge(df_datatable[['product_id','asin']],how='left',left_on='product-id',right_on='product_id')
  292. print(merged_df.head())
  293. def func_(asin,asin1,product_id,cred,market_p,seller_id,sku): # 创建功能函数
  294. if 'B0' in str(product_id)[:3]:
  295. return str(product_id)
  296. if (pd.isna(asin1) or asin1=='') and (pd.isna(asin)==False and asin !=''):
  297. if 'B0' in asin[:3]:
  298. return asin
  299. elif (pd.isna(asin1)==False and asin1!=''):
  300. if 'B0' in asin1[:3]:
  301. return asin1
  302. listingClient = ListingsItems(credentials=cred, marketplace=market_p) # 获取listing 信息
  303. try:
  304. r1 = listingClient.get_listings_item(sellerId=seller_id, sku=sku)
  305. print(r1.payload)
  306. asin = r1.payload.get("summaries")[0].get("asin")
  307. return asin
  308. except Exception as e:
  309. print("获取图片url过程错误重试, 错误message: ", e)
  310. time.sleep(3)
  311. r1 = listingClient.get_listings_item(sellerId=seller_id, sku=sku)
  312. print(r1.payload)
  313. asin = r1.payload.get("summaries")[0].get("asin")
  314. return asin
  315. # 应用自定函数
  316. merged_df['asin1'] = merged_df.apply(lambda x:func_(x['asin'],x['asin1'],x['product-id'],self.credentials,self.marketplace,seller_id,x['seller-sku']),axis=1) #x['asin'] if pd.isna(x['asin1']) or x['asin1']=='' else x['asin1']
  317. print("获取listing Info...")
  318. merged_df['temp_columns'] = merged_df.apply(lambda x: self.get_listing_info(x['seller-sku'],seller_id),axis=1)
  319. merged_df[['image_link','title']] = merged_df['temp_columns'].str.split("-----",expand=True)
  320. # merged_df['image_link'] = ''
  321. # merged_df['title'] = ''
  322. merged_df.fillna('',inplace=True)
  323. df1 = merged_df.copy()
  324. print(df1[origin_columns].head(1))
  325. # DONE 更新数据
  326. update_df = self.update_data(df1,seller_id,str(self.marketplace)[-2:],conn)
  327. if len(update_df)==0:
  328. return '无更新数据插入'
  329. # update_df['country_code'] = update_df['country_code'].map({"GB":"UK"})
  330. # DONE 连接数据库
  331. conn = SpApiRequest.mysql_connect_auth_lst()
  332. cursor = conn.cursor()
  333. try:
  334. insertsql = """insert into
  335. asj_ads.seller_listings_dailyUP(listing_id,seller_id,asin,sku,title,image_link,country_code,marketplace_id,quantity,
  336. fulfillment_channel,price,launch_datetime,status,update_datetime,product_id,product_id_type)
  337. values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
  338. conn.begin()
  339. cursor.executemany(insertsql,tuple(update_df[origin_columns].to_numpy().tolist()))
  340. conn.commit()
  341. print("插入完成")
  342. return '插入完成'
  343. except Exception as e:
  344. print("插入错误:",e)
  345. conn.rollback()
  346. return '出错回滚'
  347. def get_listing_info(self, sku,seller_id): # MAIN—GET LISTING
  348. listingClient = ListingsItems(credentials=self.credentials, marketplace=self.marketplace)
  349. try:
  350. r1 = listingClient.get_listings_item(sellerId=seller_id, sku=sku)
  351. # print(r1.payload)
  352. json_content = r1.payload.get("summaries")[0]
  353. item_name = json_content.get("itemName")
  354. item_name ='###' if item_name==None else item_name
  355. img = json_content.get("mainImage")
  356. img_url = '###' if img is None else img.get("link")
  357. # print(str(img_url)+"-----"+ str(item_name))
  358. return str(img_url)+"-----"+ str(item_name)
  359. except Exception as e:
  360. try:
  361. print("获取图片url过程错误重试, 错误message: ",e)
  362. time.sleep(3)
  363. r1 = listingClient.get_listings_item(sellerId=seller_id, sku=sku)
  364. print(r1.payload)
  365. json_content = r1.payload.get("summaries")[0]
  366. item_name = json_content.get("itemName")
  367. item_name = '###' if item_name == None else item_name
  368. img = json_content.get("mainImage")
  369. img_url = '###' if img is None else img.get("link")
  370. return str(img_url)+"-----"+ str(item_name)
  371. except Exception as e:
  372. print(e)
  373. return "###-----###"
  374. def datetime_deal(self,timestring): #时间处理-Main
  375. timezone_ = {"AEST":"Australia/Sydney",
  376. "AEDT":"Australia/Sydney",
  377. "PST":"America/Los_Angeles",
  378. "PDT":"America/Los_Angeles",
  379. "CST":"America/Chicago",
  380. "CDT":"America/Chicago",
  381. "MET":"MET",
  382. "MEST":"MET",
  383. "BST":"Europe/London",
  384. "GMT":"GMT",
  385. "CET":"CET",
  386. "CEST":"CET",
  387. "JST":"Asia/Tokyo",
  388. "BRT":"America/Sao_Paulo"}
  389. date_list = str.split(timestring,sep = ' ')
  390. if len(date_list)<3:
  391. try:
  392. return datetime.strptime(date_list[0],"%Y-%m-%d")
  393. except:
  394. try:
  395. return datetime.strptime(date_list[0], "%Y/%m/%d")
  396. except:
  397. try:
  398. return datetime.strptime(date_list[0], "%d/%m/%Y")
  399. except Exception as e:
  400. print(e)
  401. return datetime(1999, 12, 31, 0, 0, 0)
  402. try:
  403. time_date = datetime.strptime(date_list[0]+date_list[1],"%Y-%m-%d%H:%M:%S")
  404. timezone = pytz.timezone(timezone_[date_list[2]])
  405. time_ = timezone.localize(time_date)
  406. return time_.astimezone(pytz.UTC)
  407. except:
  408. try:
  409. time_date = datetime.strptime(date_list[0] + date_list[1], "%d/%m/%Y%H:%M:%S")
  410. timezone = pytz.timezone(timezone_[date_list[2]])
  411. time_ = timezone.localize(time_date)
  412. return time_.astimezone(pytz.UTC)
  413. except :
  414. try:
  415. time_date = datetime.strptime(date_list[0] + date_list[1], "%Y/%m/%d%H:%M:%S")
  416. timezone = pytz.timezone(timezone_[date_list[2]])
  417. time_ = timezone.localize(time_date)
  418. return time_.astimezone(pytz.UTC)
  419. except Exception as e1:
  420. print(e1)
  421. return datetime(1999,12,31,0,0,0)
  422. def update_data(self,df,seller_id,country_code,conn): # 更新-Main
  423. conn = SpApiRequest.mysql_connect_auth_lst()
  424. cursor = conn.cursor()
  425. columns = ['listing-id', 'seller_id',
  426. 'asin1', 'seller-sku', 'title', 'image_link', 'country_code',
  427. 'marketplace_id', 'quantity', 'fulfillment_channel',
  428. 'price', 'opendate', 'status', 'update_datetime', 'product-id', 'product-id-type'
  429. ]
  430. if country_code=='GB':
  431. country_code="UK"
  432. df['country_code'] = "UK"
  433. df_data = pd.DataFrame(columns=columns)
  434. delete_list = []
  435. marketplace_id = self.marketplace.marketplace_id
  436. try:
  437. # DONE 更改查询语句
  438. cursor.execute(f"""select * from
  439. asj_ads.seller_listings_dailyUP where seller_id='{seller_id}' and marketplace_id='{marketplace_id}'""")
  440. col = [i[0] for i in cursor.description]
  441. query_rel = cursor.fetchall()
  442. df_rel = pd.DataFrame(query_rel, columns=col)
  443. df_rel['quantity'] = df_rel['quantity'].fillna(0).astype('int64')
  444. df_rel['price'] = df_rel['price'].fillna(0.0).astype('float64')
  445. df_rel['product_id_type'] = df_rel['product_id_type'].astype('int64')
  446. df['update_datetime'] =df['update_datetime'].astype('datetime64[ns]')
  447. df['quantity'] = df['quantity'].fillna(0).astype('int64')
  448. df['price']= df['price'].fillna(0.0).astype('float64')
  449. # print(df_rel.dtypes)
  450. # print(df[columns].dtypes)
  451. row = 0
  452. while row < len(df):
  453. temp_df = df.iloc[row, :]
  454. listing_id = temp_df['listing-id']
  455. asin = temp_df['asin1']
  456. sku = temp_df['seller-sku']
  457. quantity = temp_df['quantity']
  458. fulfillment_channel = temp_df['fulfillment_channel']
  459. price = temp_df['price']
  460. product_id = temp_df['product-id']
  461. title = temp_df['title']
  462. imageurl = temp_df['image_link']
  463. temp = df_rel.query("""listing_id==@listing_id and asin==@asin and sku==@sku and quantity==@quantity and fulfillment_channel==@fulfillment_channel and price==@price and product_id==@product_id and country_code==@country_code and seller_id==@seller_id and title==@title and image_link==@imageurl""")
  464. print("需要关注数据(是否异常):",len(temp),temp.to_numpy().tolist()) if len(temp)>1 else 1
  465. if len(temp)>1:
  466. # temp = temp.head(1).to_numpy().tolist()
  467. df_data = df_data.append(temp_df, ignore_index=True)
  468. delete_list.append((seller_id, marketplace_id, sku, listing_id, product_id))
  469. # print(len(temp))
  470. elif len(temp)==0:
  471. df_data = df_data.append(temp_df,ignore_index=True)
  472. delete_list.append((seller_id,marketplace_id,sku,listing_id,product_id))
  473. row += 1
  474. print("判断不同数据条数",len(delete_list))
  475. print("预计更新数据条数",len(df_data))
  476. try:
  477. # print(tuple(delete_list))
  478. if len(delete_list)>0:
  479. query = f"""delete from asj_ads.seller_listings_dailyUP
  480. where (seller_id,marketplace_id,sku,listing_id,product_id) in %s""" #where (seller_id,country_code) in %s"""
  481. cursor.execute(query,(delete_list,))
  482. conn.commit()
  483. print(delete_list)
  484. print("进行中...")
  485. except Exception as e:
  486. print(e)
  487. conn.rollback()
  488. return df_data
  489. except Exception as e:
  490. print("错误:", e)
  491. return df
  492. @staticmethod
  493. def auth_info():
  494. auth_conn = SpApiRequest.mysql_connect_auth()
  495. cursor = auth_conn.cursor()
  496. cursor.execute("select * from amazon_sp_report.amazon_sp_auth_info;")
  497. columns_name = [i[0] for i in cursor.description]
  498. rel = cursor.fetchall()
  499. df = pd.DataFrame(rel, columns=columns_name)
  500. return df
  501. @classmethod
  502. def get_orders_allShops(cls):
  503. pass
  504. @staticmethod
  505. def data_judge_secondTry(sp_api,data_type,seller_id,auth_conn):
  506. try:
  507. SpApiRequest.data_judge(sp_api, data_type, seller_id, auth_conn)
  508. except:
  509. time.sleep(3)
  510. SpApiRequest.data_judge(sp_api, data_type, seller_id, auth_conn)
  511. @staticmethod
  512. def data_judge(sp_api,data_type,seller_id,auth_conn):
  513. if data_type == "GET_FLAT_FILE_OPEN_LISTINGS_DATA":
  514. return sp_api.GET_FLAT_FILE_OPEN_LISTINGS_DATA(auth_conn,seller_id)
  515. elif data_type =="GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL":
  516. return sp_api.GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL(seller_id)
  517. elif data_type =="GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE":
  518. return sp_api.GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE(seller_id)
  519. else:
  520. return ""
  521. @classmethod
  522. def get_refreshtoken(cls):
  523. df = cls.auth_info()
  524. refreshtoken_list = (df['refresh_token'].to_numpy().tolist())
  525. return refreshtoken_list
  526. @classmethod
  527. def get_allShops(cls,data_type=Literal["GET_FLAT_FILE_OPEN_LISTINGS_DATA","GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL"]):
  528. df = cls.auth_info()
  529. refreshtoken_list = (df['refresh_token'].to_numpy().tolist())
  530. refreshtoken_list.reverse()
  531. for refresh_token in refreshtoken_list:
  532. aws_credentials = {
  533. 'refresh_token': refresh_token,
  534. 'lwa_app_id': 'amzn1.application-oa2-client.1f9d3d4747e14b22b4b598e54e6b922e', # 卖家中心里面开发者资料LWA凭证
  535. 'lwa_client_secret': 'amzn1.oa2-cs.v1.3af0f5649f5b8e151cd5bd25c10f2bf3113172485cd6ffc52ccc6a5e8512b490',
  536. 'aws_access_key': 'AKIARBAGHTGOZC7544GN',
  537. 'aws_secret_key': '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',
  538. 'role_arn': 'arn:aws:iam::070880041373:role/Amazon_SP_API_ROLE'
  539. }
  540. single_info = df.query("refresh_token==@refresh_token")
  541. region_circle = single_info['region'].values[0]
  542. seller_id = single_info['selling_partner_id'].values[0]
  543. account_name = single_info['account_name'].values[0]
  544. if region_circle == 'NA':
  545. pass
  546. for marketplace in [Marketplaces.US, Marketplaces.BR, Marketplaces.CA,Marketplaces.MX]:
  547. sp_api = SpApiRequest(aws_credentials, marketplace)
  548. try:
  549. auth_conn = SpApiRequest.mysql_connect_auth()
  550. cls.data_judge_secondTry(sp_api, data_type, seller_id, auth_conn)
  551. ## sp_api.GET_FLAT_FILE_OPEN_LISTINGS_DATA(auth_conn, seller_id)
  552. except Exception as e:
  553. print(e)
  554. elif region_circle == 'EU':
  555. pass
  556. for marketplace in [Marketplaces.DE,Marketplaces.AE, Marketplaces.BE, Marketplaces.PL,
  557. Marketplaces.EG,Marketplaces.ES, Marketplaces.GB, Marketplaces.IN, Marketplaces.IT,
  558. Marketplaces.NL, Marketplaces.SA, Marketplaces.SE, Marketplaces.TR,Marketplaces.UK,Marketplaces.FR,
  559. ]:
  560. sp_api = SpApiRequest(aws_credentials, marketplace)
  561. try:
  562. auth_conn = SpApiRequest.mysql_connect_auth()
  563. cls.data_judge_secondTry(sp_api, data_type, seller_id, auth_conn)
  564. ## sp_api.GET_FLAT_FILE_OPEN_LISTINGS_DATA(auth_conn, seller_id)
  565. except Exception as e:
  566. print(e)
  567. else:
  568. # if region_circle not in ['NA','EU']:
  569. auth_conn = SpApiRequest.mysql_connect_auth()
  570. print(region_circle)
  571. marketplace = eval(f'Marketplaces.{region_circle}')
  572. sp_api = SpApiRequest(aws_credentials, marketplace)
  573. cls.data_judge_secondTry(sp_api, data_type, seller_id, auth_conn)
  574. ## sp_api.GET_FLAT_FILE_OPEN_LISTINGS_DATA(auth_conn, seller_id)
  575. def timeDeal(self, orgTime):
  576. orgTime = parse(orgTime)
  577. timezone = pytz.timezone("UTC")
  578. shopTime = orgTime.astimezone(timezone)
  579. shopTime_datetime = datetime(shopTime.year, shopTime.month, shopTime.day, shopTime.hour, shopTime.minute,
  580. shopTime.second)
  581. return shopTime_datetime
  582. def GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE(self,seller_id):
  583. shopReportday = (datetime.now() + timedelta(days=-2)).strftime("%Y-%m-%d")
  584. # print(shopReportday)
  585. para = {"reportType": ReportType.GET_SELLER_FEEDBACK_DATA,
  586. "dataStartTime": shopReportday, "dataEndTime": shopReportday,
  587. }
  588. reportid = self.create_report(**para) # {"ShowSalesChannel":"true"}
  589. decom_df = self.decompression(reportid)
  590. print(decom_df)
  591. # print(decom_df.columns)
  592. def GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL(self,seller_id):
  593. # timezone_ = pytz.timezone(self.timezone)
  594. shopReportday = (datetime.now() + timedelta(days=-1)).strftime("%Y-%m-%d")
  595. # print(shopReportday)
  596. para = {"reportType":ReportType.GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL,"dataStartTime":shopReportday,"dataEndTime":shopReportday,"reportOptions":{"ShowSalesChannel":"true"}}
  597. reportid = self.create_report(**para) #{"ShowSalesChannel":"true"}
  598. decom_df = self.decompression(reportid)
  599. decom_df[decom_df.select_dtypes(float).columns] = decom_df[decom_df.select_dtypes(float).columns].fillna(0.0)
  600. decom_df[decom_df.select_dtypes(int).columns] = decom_df[decom_df.select_dtypes(int).columns].fillna(0)
  601. decom_df[decom_df.select_dtypes(datetime).columns] = decom_df[decom_df.select_dtypes(datetime).columns].astype('string')
  602. if "purchase-order-number" in decom_df.columns:
  603. decom_df['purchase-order-number'] = decom_df['purchase-order-number'].astype("string")
  604. decom_df.fillna('',inplace=True)
  605. # decom_df.to_csv('order.csv')
  606. decom_df["ReportDate"] = parse(shopReportday)
  607. # decom_df['timezone'] = decom_df["purchase-date"].map(lambda x: parse(x).tzname()).fillna(method='bfill')
  608. decom_df['timezone'] = "UTC"
  609. print("==========================================================")
  610. decom_df[["purchase-date", "last-updated-date"]] = decom_df[["purchase-date", "last-updated-date"]].applymap(
  611. lambda x: self.timeDeal(x) if pd.isna(x) == False or x != None else x)
  612. if 'is-business-order' not in decom_df.columns:
  613. decom_df['is-business-order'] = None
  614. if 'purchase-order-number' not in decom_df.columns:
  615. decom_df['purchase-order-number'] = '-'
  616. if 'price-designation' not in decom_df.columns:
  617. decom_df['price-designation'] = '-'
  618. decom_df['seller_id'] = seller_id
  619. country_code = str(self.marketplace)[-2:]
  620. if country_code=='GB':
  621. country_code="UK"
  622. # decom_df['country_code'] = "UK"
  623. decom_df['country_code'] = country_code
  624. # print(decom_df[])
  625. reserve_columns = ["amazon-order-id","merchant-order-id","purchase-date","last-updated-date","order-status",
  626. "fulfillment-channel","sales-channel","order-channel","ship-service-level","product-name",
  627. "sku","asin","item-status","quantity","currency","item-price","item-tax","shipping-price",
  628. "shipping-tax","gift-wrap-price","gift-wrap-tax","item-promotion-discount",
  629. "ship-promotion-discount","ship-city","ship-state","ship-postal-code","ship-country",
  630. "promotion-ids","is-business-order","purchase-order-number","price-designation","ReportDate",
  631. "timezone","seller_id","country_code"
  632. ]
  633. list_df = decom_df[reserve_columns].to_numpy().tolist()
  634. # print(list_df)
  635. # print(list_df[0])
  636. # tuple_data = [tuple(i) for i in list_df]
  637. try:
  638. conn = self.mysql_connect_auth_lst()
  639. cursor = conn.cursor()
  640. except:
  641. time.sleep(5)
  642. conn = self.mysql_connect_auth_lst()
  643. cursor = conn.cursor()
  644. # print(list(conn.query("select * from amz_sp_api.orderReport")))
  645. sql = f"""
  646. insert into asj_ads.orderReport
  647. values (%s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s)
  648. """ #ok
  649. # print(sql)
  650. try:
  651. conn.begin()
  652. cursor.executemany(sql,list_df)
  653. conn.commit()
  654. print("插入完成")
  655. conn.close()
  656. time.sleep(1)
  657. except Exception as e:
  658. conn.rollback()
  659. print(e)
  660. def func_run():
  661. SpApiRequest.get_allShops("GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL")
  662. if __name__ == '__main__':
  663. # func_run()
  664. sched = BlockingScheduler()
  665. sched.add_job(func_run, 'cron', hour=0, minute=0,
  666. second=30)
  667. sched.start()
  668. """
  669. create database amz_sp_api;
  670. """
  671. """
  672. create table amz_sp_api.productInfo
  673. (
  674. `item-name` VARCHAR(300),
  675. `item-description` VARCHAR(1000),
  676. `listing-id` VARCHAR(50),
  677. `seller-sku` VARCHAR(50),
  678. `price` FLOAT,
  679. `quantity` INT,
  680. `open-date` VARCHAR(70),
  681. `image-url` VARCHAR(300),
  682. `item-is-marketplace` VARCHAR(50),
  683. `product-id-type` INT,
  684. `item-note` VARCHAR(300),
  685. `item-condition` INT,
  686. `asin1` VARCHAR(50),
  687. `asin2` VARCHAR(50),
  688. `asin3` VARCHAR(50),
  689. `will-ship-internationally` VARCHAR(50),
  690. `expedited-shipping` VARCHAR(50),
  691. `product-id` VARCHAR(50),
  692. `bid-for-featured-placement` FLOAT,
  693. `add-delete` VARCHAR(50),
  694. `pending-quantity` INT,
  695. `fulfillment-channel` VARCHAR(50),
  696. `merchant-shipping-group` VARCHAR(50),
  697. `status` VARCHAR(50),
  698. `mainImageUrl` VARCHAR(300),
  699. `opendate_date` Date,
  700. `updateTime` Date,
  701. `timezone` VARCHAR(30)
  702. )
  703. """
  704. """
  705. create table amz_sp_api.orderReport
  706. (`amazon-order-id` VARCHAR(40),
  707. `merchant-order-id` VARCHAR(40),
  708. `purchase-date` DATETIME,
  709. `last-updated-date` DATETIME,
  710. `order-status` VARCHAR(40),
  711. `fulfillment-channel` VARCHAR(40),
  712. `sales-channel` VARCHAR(40),
  713. `order-channel` VARCHAR(40),
  714. `ship-service-level` VARCHAR(40),
  715. `product-name` VARCHAR(250),
  716. `sku` VARCHAR(50),
  717. `asin` VARCHAR(40),
  718. `item-status` VARCHAR(40),
  719. `quantity` INT,
  720. `currency` VARCHAR(40),
  721. `item-price` FLOAT,
  722. `item-tax` FLOAT,
  723. `shipping-price` FLOAT,
  724. `shipping-tax` FLOAT,
  725. `gift-wrap-price` FLOAT,
  726. `gift-wrap-tax` FLOAT,
  727. `item-promotion-discount` FLOAT,
  728. `ship-promotion-discount` FLOAT,
  729. `ship-city` VARCHAR(40),
  730. `ship-state` VARCHAR(40),
  731. `ship-postal-code` VARCHAR(40),
  732. `ship-country` VARCHAR(40),
  733. `promotion-ids` VARCHAR(50),
  734. `cpf` VARCHAR(40),
  735. `is-business-order` BOOL,
  736. `purchase-order-number` VARCHAR(50),
  737. `price-designation` VARCHAR(40),
  738. `signature-confirmation-recommended` BOOL,
  739. `ReportDate` DATE not null,
  740. `timezone` VARCHAR(20) not null
  741. );
  742. """