huangyifan 6 mēneši atpakaļ
vecāks
revīzija
379fb90d38

+ 24 - 2
sync_amz_data/public/amz_ad_client.py

@@ -21,8 +21,30 @@ cache = TTLCache(maxsize=10, ttl=3200)
 logger = logging.getLogger(__name__)
 
 def shop_infos(profile_id):
-    resp_rel = requests.get("http://192.168.1.225/api/ad_manage/profiles/",headers={"X-Token": "da4ab6bc5cbf1dfa"})
-    data = resp_rel.json().get("data")
+    try:
+        resp_rel = requests.get("http://192.168.1.225/api/ad_manage/profiles/",headers={"X-Token": "da4ab6bc5cbf1dfa"})
+        data = resp_rel.json().get("data")
+    except Exception as e:
+        data = [{'id': 2,
+          'modifier_name': None,
+          'creator_name': None,
+          'create_datetime': '2023-10-23 10:14:28',
+          'update_datetime': '2023-10-23 10:14:26',
+          'refresh_token': 'Atzr|IwEBIL4ur8kbcwRyxVu_srprAAoTYzujnBvA6jU-0SMxkRgOhGjYJSUNGKvw24EQwJa1jG5RM76mQD2P22AKSq8qSD94LddoXGdKDO74eQVYl0RhuqOMFqdrEZpp1p4bIR6_N8VeSJDHr7UCuo8FiabkSHrkq7tsNvRP-yI-bnpQv4EayPBh7YwHVX3hYdRbhxaBvgJENgCuiEPb35Q2-Z6w6ujjiKUAK2VSbCFpENlEfcHNsjDeY7RCvFlwlCoHj1IeiNIaFTE9yXFu3aEWlExe3LzHv6PZyunEi88QJSXKSh56Um0e0eEg05rMv-VBM83cAqc5POmZnTP1vUdZO8fQv3NFLZ-xU6e1WQVxVPi5Cyqk4jYhGf1Y9t98N654y0tVvw74qNIsTrB-8bGS0Uhfe24oBEWmzObvBY3zhtT1d42myGUJv4pMTU6yPoS83zhPKm3LbUDEpBA1hvvc_09jHk7vUEAuFB-UAZzlht2C1yklzQ',
+          'currency_symbol': '$',
+          'description': None,
+          'modifier': None,
+          'type': 'seller',
+          'account_name': 'ZosiDirect',
+          'advertiser_id': 'A252W7I0ACJHS1',
+          'profile_id': '3006125408623189',
+          'country_code': 'US',
+          'currency_code': 'USD',
+          'marketplace_str_id': 'ATVPDKIKX0DER',
+          'time_zone': 'America/Los_Angeles',
+          'creator': None,
+          'ad_auth': 1}]
+
     profile_info = {}
     for info in data:
         if info.get("profile_id") in [int(profile_id),str(profile_id)]:

+ 131 - 6
sync_amz_data/public/sp_api_client.py

@@ -5,7 +5,7 @@ warnings.filterwarnings('ignore')
 import numpy as np
 from pymysql import Timestamp
 from sp_api.util import throttle_retry, load_all_pages
-from sp_api.api import Orders,ListingsItems,Inventories,Reports,CatalogItems
+from sp_api.api import Orders,ListingsItems,Inventories,Reports,CatalogItems,Products
 from sp_api.base import Marketplaces,ReportType,ProcessingStatus
 import pandas as pd
 import gzip
@@ -143,7 +143,11 @@ class SpApiRequest:
                 rp_table = report.get_report_document(reportDocumentId=reportDocumentId,download=False)
                 print(rp_table)
                 if rp_table.payload.get('compressionAlgorithm') is not None and self.marketplace.marketplace_id not in ['A1VC38T7YXB528']:#
-                    df = pd.read_table(filepath_or_buffer=rp_table.payload['url'],compression={"method":'gzip'},encoding='iso-8859-1')
+                    try:
+                        df = pd.read_table(filepath_or_buffer=rp_table.payload['url'],compression={"method":'gzip'},encoding='iso-8859-1')
+                    except:
+                        df = pd.read_csv(filepath_or_buffer=rp_table.payload['url'], compression={"method": 'gzip'},
+                                           encoding='iso-8859-1')
                     return df
                 elif rp_table.payload.get('compressionAlgorithm') is not None and self.marketplace.marketplace_id in ['A1VC38T7YXB528']:
                     df = pd.read_table(filepath_or_buffer=rp_table.payload['url'], compression={"method": 'gzip'},
@@ -1215,9 +1219,67 @@ class SpApiRequest:
         para = {"reportType": ReportType.GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT,"reportOptions":{"reportPeriod": "WEEK"},"dataStartTime": shopReportday, "dataEndTime": shopReportday_E,}
         reportid = self.create_report(**para)
 
+    @staticmethod
+    def GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT_DAY(self,**kwargs):
+        shopReportday = "2024-09-04"
+        shopReportday_E = "2024-09-04"
+        print(shopReportday)
+        para = {"reportType": ReportType.GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT,"reportOptions":{"reportPeriod": "DAY"},"dataStartTime": shopReportday, "dataEndTime": shopReportday_E,}
+        reportid = self.create_report(**para)
+
     def BRAND_ANALYTICS_TEXT_deal(self,text):
         pass
 
+    def GET_SELLER_FEEDBACK_DATA(self,**kwargs):
+        shopReportday = "2024-11-04"
+        shopReportday_E = "2024-11-04"
+        print(shopReportday)
+        para = {"reportType": ReportType.GET_SELLER_FEEDBACK_DATA,# GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE |GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA
+                 "dataStartTime": shopReportday,
+                "dataEndTime": shopReportday_E, "reportOptions":{"reportPeriod": "DAY"}}
+        reportid = self.create_report(**para)
+        print(reportid)
+        return reportid
+
+    def GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENTS_DATA(self,**kwargs):
+        shopReportday = "2024-11-04"
+        shopReportday_E = "2024-11-04"
+        print(shopReportday)
+        para = {"reportType": ReportType.GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA,
+                # GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE |GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA
+                "dataStartTime": shopReportday,
+                "dataEndTime": shopReportday_E, "reportOptions": {"reportPeriod": "DAY"}}
+        reportid = self.create_report(**para)
+        print(reportid)
+        return reportid
+
+    def GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE(self, refresh_token,seller_id,days=-1,**kwargs):
+        countryCode = None if kwargs.get("countryCode") == None else kwargs.get("countryCode")
+        shopReportday = (datetime.now() + timedelta(days=days)).strftime("%Y-%m-%d")
+        print(shopReportday)
+        para = {"reportType": ReportType.GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL,
+                "dataStartTime": shopReportday, "dataEndTime": shopReportday,
+                "reportOptions": {"ShowSalesChannel": "true"}}
+        reportid = self.create_report(**para)  # {"ShowSalesChannel":"true"}
+        decom_df = self.decompression(reportid)
+        decom_df['seller_id'] = seller_id
+        country_code = str(self.marketplace)[-2:]
+        if country_code == 'GB':
+            country_code = "UK"
+            # decom_df['country_code'] = "UK"
+        decom_df['country_code'] = country_code
+        decom_df['insert_time'] = datetime.now()
+        # shopReportday = "2024-11-04"
+        # shopReportday_E = "2024-11-04"
+        # print(shopReportday)
+        # para = {"reportType": ReportType.GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE,
+        #         # GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE |GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA
+        #         "dataStartTime": shopReportday,
+        #         "dataEndTime": shopReportday_E, "reportOptions": {"reportPeriod": "DAY"}}
+        # reportid = self.create_report(**para)
+        # print(reportid)
+        return reportid
+
     @staticmethod
     def data_judge_secondTry(refresh_token,sp_api,data_type,seller_id,auth_conn,days=-1,**kwargs): # Main-retry, 重试函数,重试次数2次
         a_kw = kwargs
@@ -1253,6 +1315,12 @@ class SpApiRequest:
             return sp_api.GET_FBA_MYI_UNSUPPRESSED_INVENTORY_DATA(refresh_token,auth_conn,seller_id,days,**a_kw)
         elif data_type=="GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT":
             return sp_api.GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT(refresh_token,seller_id,days,**a_kw)
+        elif data_type=="GET_SELLER_FEEDBACK_DATA":
+            return sp_api.GET_SELLER_FEEDBACK_DATA(refresh_token,seller_id,days,**a_kw)
+        elif data_type=="GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENTS_DATA":
+            return sp_api.GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENTS_DATA(refresh_token,seller_id,days,**a_kw)
+        elif data_type=="GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE":
+            return sp_api.GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE(refresh_token,seller_id,days,**a_kw)
         else:
             return ""
 
@@ -1321,6 +1389,9 @@ class SpApiRequest:
                 a_kw['countryCode'] = str(marketplace)[-2:]
                 cls.data_judge_secondTry(refresh_token,sp_api, data_type, seller_id, auth_conn,days,**a_kw)
             ## sp_api.GET_FLAT_FILE_OPEN_LISTINGS_DATA(auth_conn, seller_id)
+    def price_tracker(self,asin):
+        base_product = Products(credentials=self.credentials,marketplace=Marketplaces.US)
+        return base_product.get_product_pricing_for_asins(asin)
 
 if __name__ == '__main__':
     # for days in range(35,45):
@@ -1328,7 +1399,61 @@ if __name__ == '__main__':
     # SpApiRequest.listing_infoTable()
     # rel = SpApiRequest.get_catelog(account_name='AM-ZOSI-US',country=Marketplaces.US,asin='B0B8CPHSL4')
     # print(rel)
-    # SpApiRequest.get_allShops("GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT")
-    # pass
-    SpApiRequest.listing_infoTable()
-    # SpApiRequest.Goods_drop_duplicates()
+    # SpApiRequest
+    df = SpApiRequest.auth_info()
+    print(df)
+    zosi = df.query("account_name=='AM-ZOSI-US'")['refresh_token'].to_numpy().tolist()
+    # print(zosi)
+    refreshtoken_list = df.query("account_name!='AM-ZOSI-US'")['refresh_token'].to_numpy().tolist()
+    zosi.extend(refreshtoken_list)
+    refreshtoken_list = zosi.copy()
+    aws_credentials = {
+        'refresh_token': refreshtoken_list[0],
+        'lwa_app_id': 'amzn1.application-oa2-client.1f9d3d4747e14b22b4b598e54e6b922e',  # 卖家中心里面开发者资料LWA凭证
+        'lwa_client_secret': 'amzn1.oa2-cs.v1.13ebfa8ea7723b478215a2b61f4dbf5ca6f6927fa097c2dd0941a66d510aca7f',
+        'aws_access_key': 'AKIARBAGHTGOZC7544GN',
+        'aws_secret_key': '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',
+        'role_arn': 'arn:aws:iam::070880041373:role/Amazon_SP_API_ROLE'
+    }
+    sp_api = SpApiRequest(aws_credentials, Marketplaces.US)
+    id = sp_api.GET_SELLER_FEEDBACK_DATA()
+    df= sp_api.decompression(str(id))
+    print(df)
+    df.to_csv('GET_S.csv')
+    # print(sp_api.price_tracker(['B00L3W2QJ2']))
+    # shopReportday = "2024-08-25"
+    # shopReportday_E = "2024-08-31"
+    # print(shopReportday)
+    # # para = {"reportType": ReportType.GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT, "reportOptions": {"reportPeriod": "WEEK"},
+    # #         "dataStartTime": shopReportday, "dataEndTime": shopReportday_E, }
+    # # report = Reports(credentials=aws, marketplace=self.marketplace)
+    # report = Reports(credentials=aws_credentials, marketplace=Marketplaces.US)
+    # rel = report.create_report(
+    #     reportType=ReportType.GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT, marketplaceIds=['ATVPDKIKX0DER'],
+    #     reportOptions={"reportPeriod": "WEEK"}, dataStartTime=shopReportday, dataEndTime=shopReportday_E
+    # )
+    # reportId = rel.payload.get("reportId")
+    #
+    # while True:
+    #     reportId_info = report.get_report(reportId=reportId)
+    #     # print(reportId_info.payload)
+    #     print("please wait...",reportId_info.payload.get("processingStatus"))
+    #     # print(reportId_info)
+    #     if reportId_info.payload.get("processingStatus") == ProcessingStatus.DONE:
+    #         print(reportId_info.payload)
+    #         reportDocumentId = reportId_info.payload.get("reportDocumentId")
+    #         rp_table = report.get_report_document(reportDocumentId=reportDocumentId, download=False)
+    #         print(rp_table)
+    #     elif reportId_info.payload.get("processingStatus") == ProcessingStatus.FATAL:
+    #         reportDocumentId = reportId_info.payload.get("reportDocumentId")
+    #         rp_table = report.get_report_document(reportDocumentId=reportDocumentId, download=False)
+    #         import requests
+    #         # requests.get(rp_table['payload']['url'])
+    #
+    #         df = pd.read_table(filepath_or_buffer=rp_table.payload['url'], compression={"method": 'gzip'},
+    #                       encoding='iso-8859-1')
+    #         # df = pandas.read_csv(rp_table['payload']['url'],)
+    #         print(df.to_dict(orient='records'))
+    #         break
+
+