Skip to content

Instantly share code, notes, and snippets.

@BlaayLock
Created May 30, 2021 07:41
Show Gist options
  • Save BlaayLock/5b86fa8b643fc2d1b82c1755fbf8fa27 to your computer and use it in GitHub Desktop.
Save BlaayLock/5b86fa8b643fc2d1b82c1755fbf8fa27 to your computer and use it in GitHub Desktop.
'''
Решение, когда ИД - это баркод+код1с. Почему? Один баркод это один ценник. Много штрихкодов на один товар, поэтому баркод+код1с.
Синхронизация по группам и получение данных из 1с, а ровно как обработка ошибок не помещается в этом gist. Понадобится - свяжитесь со мной. Если через e-mail, шлите месседж с уведомлением, что прочитано. Ну очень много спама, а я не такой прыткий, везде не успеваю. В июне 2021 у меня был телеграм @skylinkfetch
Для здешних сваггеров берите прогу Insomnia, а API коды тут - неактуальные.
if id1c not foun in idS
add to insert
else
add to compare
if compare
if id1c.price not equal idS.price
add idS to delete
add id1c to insert
run delete
ren insert
'''
class exh():
def __init__(self):
self.filesource1c = "nomenclature_.txt"
self.filesavelog = "listLog.json"
self.lsLog = []
self.dict1c = []
self.dictS = []
self.fcompare = []
self.finsert = []
self.fdelete = []
self.getfromS()
def getfromS(self):
pass
rh = ngAux()
ret = rh.run()
self.dictS = rh.dictS
def run(self):
pass
fileObj = codecs.open(self.filesource1c, "r", "utf_8_sig")
textf = fileObj.read() # или читайте по строке
fileObj.close()
lst = textf.split('\n')
textls = [it.split(' ') for it in lst if len(it.split(' ')) > 6]
iterlen = len(textls)
print('ttl', iterlen)
for x in range(0, iterlen):
pass
objtextls = textls[x]
self.dict1c.append({
'id': objtextls[0] + '_' + objtextls[2],
'group_id': "656699d0-650f-4bcb-b00a-af093ed31b62", # обработано
'name': objtextls[1],
'price': objtextls[6].replace('\r', ''), # random.randint(100,200) ,#objtextls[6].replace('\r', ''),
'sku': objtextls[7].replace('\r', ''),
'barcode': objtextls[0]
})
# print(objtextls)
lsID1c = [val['id'] for val in self.dict1c]
lsIDS = [val['id'] for val in self.dictS]
for xv in lsID1c:
if xv not in lsIDS:
self.finsert.append(xv)
else:
self.fcompare.append(xv)
if any(self.fcompare):
self.funccompare(self.fcompare)
if any(self.fdelete): self.funcdelete(self.fdelete)
if any(self.finsert): self.funcinsert(self.finsert)
def funcdelete(self, lsinc):
for xv in lsinc:
objinc = [x for x in self.dictS if x['id'] == xv]
if len(objinc) > 1:
raise RuntimeError('..this barcode have two and better offer:' + xv)
if len(objinc) == 1:
objinc = objinc[0]
url = "https://api.aqsi.ru/pub/v2/Goods/" + objinc['id']
payload = ""
headers = {
"x-client-key": "Application 2kd3uAe1LeSTaBpDsgry5RskIjdnm61NzgNHmw2hJsntzljMUN5Sjb9skshhGdkj"}
response = requests.request("DELETE", url, data=payload, headers=headers)
inflog = response.ok # response.status_code
self.lsLog.append({'delete': objinc['id'], 'status': str(inflog)})
# return inflog
def funcinsert(self, lsinc):
for xv in lsinc:
objinc = [x for x in self.dict1c if x['id'] == xv]
if len(objinc) > 1:
raise RuntimeError('..this barcode have two and better offer:' + xv)
if len(objinc) == 1:
objinc = objinc[0]
payload = {
"id": objinc['id'],
"group_id": objinc['group_id'],
"nomenclatureCode": None,
"type": "simple",
"productionCost": None,
"marginPercent": None,
"isWeight": 0,
"tax": "6",
"unit": "шт",
"subject": "1",
"isOrderable": False,
"name": objinc['name'],
"slotInfo": None,
"sku": objinc['sku'] if 'sku' in objinc else '',
"1cSku": objinc['id'],
"price": objinc['price'],
"barcodes": [objinc['barcode']],
"img": None,
"lastPurchasePrice": None,
"accountingMethod": None,
"cookingTimeMinutes": None,
"cookingTimeSeconds": None,
"cookingReceipt": None,
"nonTradable": False,
"markingType": None,
"modifiers": [],
"paymentMethodType": 4,
"receiptProperties": {
"supplierInfo": None,
"supplierINN": None,
"agentType": None,
"agentInfo": None,
"additionalAttribute": None,
"manufacturerCountryCode": None,
"customsDeclarationNumber": None,
"excise": None
},
"maxDiscountPercent": None
}
headers = {
"x-client-key": "Application 2kd3uAe1LeSTaBpDsgry5RskIjdnm61NzgNHmw2hJsntzljMUN5Sjb9skshhGdkj",
"Content-Type": "application/json"
}
url = "https://api.aqsi.ru/pub/v2/Goods"
response = requests.request("POST", url, json=payload, headers=headers)
inflog = response.ok # response.status_code
self.lsLog.append({'insert': objinc['id'], 'status': str(inflog)})
def funccompare(self, lsinc):
'''
who is compare?
if price in idS not equal id1C
idS to delete
id!C to insert
:param lsinc:
:return:
'''
for xv in lsinc:
obj1c = self.getObjbyID(self.dict1c, xv)
objS = self.getObjbyID(self.dictS, xv)
if float(obj1c['price']) != float(objS['price']):
self.fdelete.append(objS['id'])
self.finsert.append(obj1c['id'])
var = 1
def getObjbyID(self, where, what):
objinc = [x for x in where if x['id'] == what]
if len(objinc) > 1:
raise RuntimeError('..this barcode have two and better offer:' + what)
if len(objinc) == 1:
objinc = objinc[0]
return objinc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment