Merge pull request 'feature/evaluating' (#2) from feature/evaluating into main
Reviewed-on: #2
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -27,3 +27,4 @@ hint.py
|
|||||||
|
|
||||||
#Примеры документов
|
#Примеры документов
|
||||||
document_examples/
|
document_examples/
|
||||||
|
excel_files/
|
||||||
|
|||||||
48
env_example
48
env_example
@@ -1 +1,47 @@
|
|||||||
DIR="/dir/dir/dir"
|
DIR="/dir/dir/dir"
|
||||||
|
PATTERN=[A-ZА-Я]{0,1}\d{4}[A-ZА-Я]{1,2}\d{0,1}
|
||||||
|
TIMEFORMAT="%Y-%m-%dT%H:%M:%S"
|
||||||
|
|
||||||
|
USERNAME = "..."
|
||||||
|
PASSWORD = "..."
|
||||||
|
URL_REPORT = "..."
|
||||||
|
URL_REALISATION = "..."
|
||||||
|
URL_CONTRAGENTS = "..."
|
||||||
|
URL_NOMENCLATURE="..."
|
||||||
|
URL_COMPANIES="..."
|
||||||
|
URL_STORAGES ="..."
|
||||||
|
|
||||||
|
BUYER = "..." #Физические лица-розница
|
||||||
|
COMPANY="..." #Организация_Key
|
||||||
|
STORE = "..." #Склад_Key
|
||||||
|
|
||||||
|
CONTRAGENT_RWB = "..." #WB
|
||||||
|
CONTRACT_RWB1="..." #Purchases
|
||||||
|
CONTRAGENT_OZON = "..." #Озон
|
||||||
|
CONTRAGENT_YANDEX="..." #Яндекс
|
||||||
|
|
||||||
|
CONTRACT_RWB0 = "..." #Основной для ВБ
|
||||||
|
CONTRACT_RWB1 = "..." #основной для яндекса
|
||||||
|
CONTRACT_RWB2 = "..." #основной для озона
|
||||||
|
|
||||||
|
MEASURE="..." #"ЕдиницаИзмерения_Key" шт
|
||||||
|
|
||||||
|
#Accountant sector
|
||||||
|
|
||||||
|
A60_01="..." # 60.01 СчетУчетаРасчетовЗаПосредническиеУслуги_Key
|
||||||
|
A62_02= "..." # 62.02 СчетУчетаРасчетовПоАвансамПолученным_Key
|
||||||
|
A60_02= "..." # 60.02 СчетУчетаРасчетовПоАвансамВыданным_Key
|
||||||
|
A62_01= "..." # 62.01 СчетУчетаРасчетовСКонтрагентом_Key
|
||||||
|
A45_02="..." # 45.02 СчетУчета_Key Счет_передачи_key
|
||||||
|
A43="..." # 43 СчетУчета_Key
|
||||||
|
A90_01_1="..." # 90.01.1 СчетДоходов_Key
|
||||||
|
A90_02_1="..." # 90.02.1 СчетРасходов_Key
|
||||||
|
A90_03="..." # 90.03 СчетУчетаНДСПоРеализации_Key
|
||||||
|
A76_09="..." # 76.09 СчетУчетаРасчетовПоАвансамПолученным_Key and СчетУчетаРасчетовСКонтрагентом_Key
|
||||||
|
A44_01="..." # 44.01 СчетУчетаЗатрат_Key
|
||||||
|
A19_04="..." # 19.04 СчетУчетаНДС_Key
|
||||||
|
|
||||||
|
TYPE1="..." #types of documents
|
||||||
|
TYPE2="..."
|
||||||
|
TYPE3="..."
|
||||||
|
TYPE4="..."
|
||||||
12
makefile
12
makefile
@@ -1,4 +1,12 @@
|
|||||||
VENV=source ./.venv/bin/activate;
|
VENV=source ./.venv/bin/activate;
|
||||||
.PHONY: run
|
.PHONY: run run_full run_stocks run_orgs run_contractors
|
||||||
run:
|
run:
|
||||||
$(VENV) python run.py
|
$(VENV) python run.py
|
||||||
|
run_full:
|
||||||
|
$(VENV) python run.py --mode full
|
||||||
|
run_stocks:
|
||||||
|
$(VENV) python run.py --mode stocks
|
||||||
|
run_orgs:
|
||||||
|
$(VENV) python run.py --mode orgs
|
||||||
|
run_contractors:
|
||||||
|
$(VENV) python run.py --mode contractors
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
pandas==2.3.3
|
pandas==2.3.3
|
||||||
openpyxl==3.1.5
|
openpyxl==3.1.5
|
||||||
pydantic==2.12.3
|
pydantic==2.12.3
|
||||||
|
pydantic_settings == 2.12.0
|
||||||
|
requests==2.32.5
|
||||||
dotenv==0.9.9
|
dotenv==0.9.9
|
||||||
36
run.py
36
run.py
@@ -1,3 +1,35 @@
|
|||||||
import server.backend.excel as excel
|
from server.backend.services.validating_files import validating
|
||||||
from server.backend.validating_files import validating
|
from server.backend.api import companies,contractors,storages, nomenclature
|
||||||
|
#_______________
|
||||||
|
from pathlib import Path
|
||||||
|
path = Path("./excel_files")
|
||||||
|
path.mkdir(exist_ok=True)
|
||||||
|
#_______________
|
||||||
|
import argparse
|
||||||
|
parser = argparse.ArgumentParser(description="Экспорт в Excel")
|
||||||
|
parser.add_argument(
|
||||||
|
"--mode",
|
||||||
|
choices=["stocks", "orgs", "contractors", "full", "standart"],
|
||||||
|
default="standart",
|
||||||
|
help="Режим экспорта (по умолчанию: standart)"
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
match args.mode:
|
||||||
|
case "full":
|
||||||
|
print("Режим:", args.mode)
|
||||||
|
companies.companies()
|
||||||
|
contractors.contractor()
|
||||||
|
storages.storages()
|
||||||
|
nomenclature.nomenclature(flag=True)
|
||||||
|
case "orgs":
|
||||||
|
print("Режим:", args.mode)
|
||||||
|
companies.companies()
|
||||||
|
case "contractors":
|
||||||
|
print("Режим:", args.mode)
|
||||||
|
contractors.contractor()
|
||||||
|
case "stocks":
|
||||||
|
print("Режим:", args.mode)
|
||||||
|
storages.storages()
|
||||||
|
case "standart":
|
||||||
|
print("Режим:", args.mode)
|
||||||
print(validating())
|
print(validating())
|
||||||
0
server/backend/api/__init__.py
Normal file
0
server/backend/api/__init__.py
Normal file
42
server/backend/api/companies.py
Normal file
42
server/backend/api/companies.py
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import requests
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
from base64 import b64encode
|
||||||
|
from server.backend.schemas.pydantic import settings
|
||||||
|
import pandas as pd
|
||||||
|
from server.backend.api.session import get_session
|
||||||
|
|
||||||
|
session = get_session({
|
||||||
|
"Accept": "application/xml",
|
||||||
|
})
|
||||||
|
|
||||||
|
def fetch_contragents():
|
||||||
|
response = session.get(settings.URL_COMPANIES, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.text
|
||||||
|
|
||||||
|
def parse_contragents(xml: str):
|
||||||
|
try:
|
||||||
|
NS = {
|
||||||
|
"atom": "http://www.w3.org/2005/Atom",
|
||||||
|
"m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
|
||||||
|
"d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
|
||||||
|
}
|
||||||
|
rows = []
|
||||||
|
# Парсинг XML-ответа
|
||||||
|
root = ET.fromstring(xml)
|
||||||
|
# Извлечение конкретных данных
|
||||||
|
for entry in root.findall('atom:entry', NS):
|
||||||
|
properties = entry.find('atom:content',NS).find(
|
||||||
|
'm:properties', NS)
|
||||||
|
rows.append({
|
||||||
|
'Ref_Key': properties.findtext('d:Ref_Key', default=None, namespaces=NS),
|
||||||
|
'Description': properties.findtext('d:Description', default=None, namespaces=NS),
|
||||||
|
})
|
||||||
|
df = pd.DataFrame(rows)
|
||||||
|
return df
|
||||||
|
except ET.ParseError:
|
||||||
|
raise
|
||||||
|
def companies():
|
||||||
|
xml_data = fetch_contragents()
|
||||||
|
root = parse_contragents(xml_data)
|
||||||
|
root.to_excel("./excel_files/companies.xlsx")
|
||||||
47
server/backend/api/contractors.py
Normal file
47
server/backend/api/contractors.py
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import requests
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
from base64 import b64encode
|
||||||
|
from server.backend.schemas.pydantic import settings
|
||||||
|
import pandas as pd
|
||||||
|
from server.backend.api.session import get_session
|
||||||
|
|
||||||
|
session = get_session({
|
||||||
|
"Accept": "application/xml",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_companies():
|
||||||
|
response = session.get(settings.URL_CONTRACTORS, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.text
|
||||||
|
|
||||||
|
def parse_companies(xml: str):
|
||||||
|
try:
|
||||||
|
NS = {
|
||||||
|
"atom": "http://www.w3.org/2005/Atom",
|
||||||
|
"m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
|
||||||
|
"d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
|
||||||
|
}
|
||||||
|
rows = []
|
||||||
|
# Парсинг XML-ответа
|
||||||
|
root = ET.fromstring(xml)
|
||||||
|
# Извлечение конкретных данных
|
||||||
|
for entry in root.findall('atom:entry', NS):
|
||||||
|
properties = entry.find('atom:content',NS).find(
|
||||||
|
'm:properties', NS)
|
||||||
|
rows.append({
|
||||||
|
'Ref_Key': properties.findtext('d:Ref_Key', default=None, namespaces=NS),
|
||||||
|
'Description': properties.findtext('d:Description', default=None, namespaces=NS),
|
||||||
|
'FullName': properties.findtext('d:НаименованиеПолное', default=None, namespaces=NS),
|
||||||
|
'INN': properties.findtext('d:ИНН', default=None, namespaces=NS),
|
||||||
|
'KPP': properties.findtext('d:КПП', default=None, namespaces=NS),
|
||||||
|
'DoC': properties.findtext('d:ДатаСоздания', default=None, namespaces=NS),
|
||||||
|
})
|
||||||
|
df = pd.DataFrame(rows)
|
||||||
|
return df
|
||||||
|
except ET.ParseError:
|
||||||
|
raise
|
||||||
|
def contractor():
|
||||||
|
xml_data = fetch_companies()
|
||||||
|
root = parse_companies(xml_data)
|
||||||
|
root.to_excel("./excel_files/contractors.xlsx")
|
||||||
61
server/backend/api/nomenclature.py
Normal file
61
server/backend/api/nomenclature.py
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import requests
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
from base64 import b64encode
|
||||||
|
from server.backend.schemas.pydantic import settings
|
||||||
|
from functools import lru_cache
|
||||||
|
import pandas as pd
|
||||||
|
from server.backend.api.session import get_session
|
||||||
|
|
||||||
|
session = get_session({
|
||||||
|
"Accept": "application/xml",
|
||||||
|
})
|
||||||
|
|
||||||
|
def fetch_nomenclature():
|
||||||
|
response = session.get(settings.URL_NOMENCLATURE, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.text
|
||||||
|
|
||||||
|
def parse_nomenclature(xml: str):
|
||||||
|
try:
|
||||||
|
NS = {
|
||||||
|
"atom": "http://www.w3.org/2005/Atom",
|
||||||
|
"m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
|
||||||
|
"d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
|
||||||
|
}
|
||||||
|
rows = []
|
||||||
|
# Парсинг XML-ответа
|
||||||
|
root = ET.fromstring(xml)
|
||||||
|
# Извлечение конкретных данных
|
||||||
|
for entry in root.findall('atom:entry', NS):
|
||||||
|
properties = entry.find('atom:content',NS).find(
|
||||||
|
'm:properties', NS)
|
||||||
|
rows.append({
|
||||||
|
'ref_key': properties.findtext('d:Ref_Key', default=None, namespaces=NS),
|
||||||
|
'description': properties.findtext('d:Description', default=None, namespaces=NS),
|
||||||
|
'parent_key': properties.findtext('d:Parent_Key', default=None, namespaces=NS)
|
||||||
|
})
|
||||||
|
df = pd.DataFrame(rows)
|
||||||
|
df = df[df['parent_key'] == 'e0eb911c-03a0-11ef-95bd-fa163e7429d8']
|
||||||
|
df['description'] = df['description'].str.extract(r'^([^\s(]+)')
|
||||||
|
return df
|
||||||
|
except ET.ParseError:
|
||||||
|
raise
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def nomenclature(flag=False):
|
||||||
|
xml_data = fetch_nomenclature()
|
||||||
|
root = parse_nomenclature(xml_data)
|
||||||
|
if flag:
|
||||||
|
root.to_excel("./excel_files/nomenclature.xlsx")
|
||||||
|
return root
|
||||||
|
def processing(df):
|
||||||
|
df2=nomenclature()
|
||||||
|
result = df.merge(
|
||||||
|
df2[['description', 'ref_key']], #берутся столбцы из df2
|
||||||
|
left_on='arti', #столбец для сравнения в df
|
||||||
|
right_on='description', #столбец для сравнения в df2
|
||||||
|
how='left' #left join для df
|
||||||
|
).drop(columns='description') #удаление временного стобца
|
||||||
|
not_matched = result.loc[result['ref_key'].isna(), 'arti'].unique()
|
||||||
|
if len(not_matched) > 0:
|
||||||
|
raise ValueError(f'Не найдены значения: {not_matched}')
|
||||||
|
return result
|
||||||
170
server/backend/api/report.py
Normal file
170
server/backend/api/report.py
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
import requests
|
||||||
|
import json
|
||||||
|
import pandas as pd
|
||||||
|
from server.backend.schemas.pydantic import settings
|
||||||
|
from server.backend.api.session import get_session
|
||||||
|
|
||||||
|
class DocumentCreation:
|
||||||
|
def __init__(self, URL):
|
||||||
|
self.session = get_session({
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Accept": "application/json",
|
||||||
|
})
|
||||||
|
self.url = URL
|
||||||
|
|
||||||
|
def save_key_txt(self, document_key: str, filename: str = "./excel_files/documents.txt"):
|
||||||
|
with open(filename, "a", encoding="utf-8") as f:
|
||||||
|
f.write(document_key + "\n")
|
||||||
|
|
||||||
|
def build_dict(self, **kwargs) -> dict:
|
||||||
|
return dict(kwargs)
|
||||||
|
|
||||||
|
def create_document(self, **kwargs) -> str:
|
||||||
|
data = self.build_dict(**kwargs)
|
||||||
|
|
||||||
|
self.contragent = kwargs.get("Контрагент_Key")
|
||||||
|
response = self.session.post(self.url, json=data)
|
||||||
|
response.raise_for_status()
|
||||||
|
result = response.json()
|
||||||
|
document_key = result.get("Ref_Key") or result.get("Ссылка_Key")
|
||||||
|
|
||||||
|
if not document_key:
|
||||||
|
raise RuntimeError(f"Не удалось получить ключ документа: {result}")
|
||||||
|
|
||||||
|
self.save_key_txt(document_key)
|
||||||
|
return document_key
|
||||||
|
|
||||||
|
def fill_document_items_purchase(self, document_key: str, validated_rows: list):
|
||||||
|
line_url = f"{self.url}({document_key})"
|
||||||
|
|
||||||
|
response = self.session.get(line_url)
|
||||||
|
response.raise_for_status()
|
||||||
|
document_data = response.json()
|
||||||
|
|
||||||
|
items = document_data.get("Товары", [])
|
||||||
|
start_line = len(items)
|
||||||
|
|
||||||
|
for idx, row in enumerate(validated_rows, start=1):
|
||||||
|
new_item = {
|
||||||
|
"LineNumber": str(start_line + idx),
|
||||||
|
"Номенклатура_Key": row.ref_key,
|
||||||
|
"Количество": row.counts,
|
||||||
|
"ЕдиницаИзмерения_Key": settings.MEASURE,
|
||||||
|
"Цена": row.price / row.counts if row.counts else 0,
|
||||||
|
"Сумма": row.price,
|
||||||
|
"СчетУчета_Key": settings.A45_02,
|
||||||
|
"СчетДоходов_Key": settings.A90_01_1,
|
||||||
|
"СчетРасходов_Key": settings.A90_02_1,
|
||||||
|
"СтавкаНДС": "НДС5",
|
||||||
|
"СуммаНДС": row.price * 5 / 105,
|
||||||
|
"СчетУчетаНДСПоРеализации_Key": settings.A90_03,
|
||||||
|
}
|
||||||
|
items.append(new_item)
|
||||||
|
|
||||||
|
document_data["Товары"] = items
|
||||||
|
patch_response = self.session.patch(line_url, json=document_data)
|
||||||
|
patch_response.raise_for_status()
|
||||||
|
def fill_document_items_to_real(self, document_key: str, validated_rows: list):
|
||||||
|
line_url = f"{self.url}({document_key})"
|
||||||
|
|
||||||
|
response = self.session.get(line_url)
|
||||||
|
response.raise_for_status()
|
||||||
|
document_data = response.json()
|
||||||
|
|
||||||
|
items = document_data.get("Товары", [])
|
||||||
|
start_line = len(items)
|
||||||
|
|
||||||
|
for idx, row in enumerate(validated_rows, start=1):
|
||||||
|
new_item = {
|
||||||
|
"LineNumber": str(start_line + idx),
|
||||||
|
"Номенклатура_Key": row.ref_key,
|
||||||
|
"Количество": row.counts,
|
||||||
|
"ЕдиницаИзмерения_Key": settings.MEASURE,
|
||||||
|
"Цена": row.price / row.counts if row.counts else 0,
|
||||||
|
"Сумма": row.price,
|
||||||
|
"СчетУчета_Key": settings.A43,
|
||||||
|
"ПереданныеСчетУчета_Key": settings.A45_02,
|
||||||
|
"СтавкаНДС": "НДС5",
|
||||||
|
"СуммаНДС": row.price * 5 / 105,
|
||||||
|
}
|
||||||
|
items.append(new_item)
|
||||||
|
|
||||||
|
document_data["Товары"] = items
|
||||||
|
patch_response = self.session.patch(line_url, json=document_data)
|
||||||
|
patch_response.raise_for_status()
|
||||||
|
def fill_document_items_report(self, document_key:str, validated_rows_real:list, validated_rows_refund:list):
|
||||||
|
line_url = f"{self.url}({document_key})"
|
||||||
|
|
||||||
|
response = self.session.get(line_url)
|
||||||
|
response.raise_for_status()
|
||||||
|
document_data = response.json()
|
||||||
|
items = document_data.get("Покупатели",[])
|
||||||
|
new_item={
|
||||||
|
"LineNumber": str(len(items) + 1),
|
||||||
|
"Покупатель_Key": self.contragent
|
||||||
|
}
|
||||||
|
items.append(new_item)
|
||||||
|
document_data["Покупатели"] = items
|
||||||
|
patch_response = self.session.patch(line_url, json=document_data)
|
||||||
|
patch_response.raise_for_status()
|
||||||
|
|
||||||
|
items = document_data.get("Товары", [])
|
||||||
|
start_line = len(items)
|
||||||
|
|
||||||
|
for idx, row in enumerate(validated_rows_real, start=1):
|
||||||
|
new_item = {
|
||||||
|
"LineNumber": str(start_line + idx),
|
||||||
|
"Номенклатура_Key": row.ref_key,
|
||||||
|
"Количество": row.counts,
|
||||||
|
"ЕдиницаИзмерения_Key": settings.MEASURE,
|
||||||
|
"Цена": row.price / row.counts if row.counts else 0,
|
||||||
|
"Сумма": row.price,
|
||||||
|
"СчетУчета_Key": settings.A45_02,
|
||||||
|
"СчетДоходов_Key": settings.A90_01_1,
|
||||||
|
"СчетРасходов_Key": settings.A90_02_1,
|
||||||
|
"СтавкаНДС": "НДС5",
|
||||||
|
"СуммаНДС": row.price * 5 / 105,
|
||||||
|
"СчетУчетаНДСПоРеализации_Key": settings.A90_03,
|
||||||
|
}
|
||||||
|
items.append(new_item)
|
||||||
|
|
||||||
|
document_data["Товары"] = items
|
||||||
|
patch_response = self.session.patch(line_url, json=document_data)
|
||||||
|
patch_response.raise_for_status()
|
||||||
|
|
||||||
|
items = document_data.get("Возвраты", [])
|
||||||
|
new_item = {
|
||||||
|
"LineNumber": str(len(items) + 1),
|
||||||
|
"Покупатель_Key": settings.BUYER
|
||||||
|
}
|
||||||
|
items.append(new_item)
|
||||||
|
document_data["Возвраты"] = items
|
||||||
|
patch_response = self.session.patch(line_url, json=document_data)
|
||||||
|
patch_response.raise_for_status()
|
||||||
|
|
||||||
|
|
||||||
|
items = document_data.get("ТоварыВозвращенные", [])
|
||||||
|
start_line = len(items)
|
||||||
|
|
||||||
|
for idx, row in enumerate(validated_rows_refund, start=1):
|
||||||
|
new_item = {
|
||||||
|
"LineNumber": str(start_line + idx),
|
||||||
|
"Номенклатура_Key": row.ref_key,
|
||||||
|
"Количество": row.counts,
|
||||||
|
"ЕдиницаИзмерения_Key": settings.MEASURE,
|
||||||
|
"Цена": row.price / row.counts if row.counts else 0,
|
||||||
|
"Сумма": row.price,
|
||||||
|
"СчетУчета_Key": settings.A45_02,
|
||||||
|
"СчетДоходов_Key": settings.A90_01_1,
|
||||||
|
"СчетРасходов_Key": settings.A90_02_1,
|
||||||
|
"СтавкаНДС": "НДС5",
|
||||||
|
"СуммаНДС": row.price * 5 / 105,
|
||||||
|
"СчетУчетаНДСПоРеализации_Key": settings.A90_03,
|
||||||
|
"Себестоимость": 100,
|
||||||
|
"ОтражениеВУСН": "Принимаются",
|
||||||
|
}
|
||||||
|
items.append(new_item)
|
||||||
|
|
||||||
|
document_data["ТоварыВозвращенные"] = items
|
||||||
|
patch_response = self.session.patch(line_url, json=document_data)
|
||||||
|
patch_response.raise_for_status()
|
||||||
20
server/backend/api/session.py
Normal file
20
server/backend/api/session.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import requests
|
||||||
|
from base64 import b64encode
|
||||||
|
from server.backend.schemas.pydantic import settings
|
||||||
|
def get_session(extra_headers=None):
|
||||||
|
"""
|
||||||
|
Создаёт и возвращает requests.Session с базовой авторизацией.
|
||||||
|
Можно менять username, password и добавлять дополнительные заголовки.
|
||||||
|
"""
|
||||||
|
session = requests.Session()
|
||||||
|
auth_str = f"{settings.USERNAME}:{settings.PASSWORD}"
|
||||||
|
b64_auth_str = b64encode(auth_str.encode("utf-8")).decode("utf-8")
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"Basic {b64_auth_str}",
|
||||||
|
"Accept": "application/json"
|
||||||
|
}
|
||||||
|
if extra_headers:
|
||||||
|
headers.update(extra_headers)
|
||||||
|
session.headers.update(headers)
|
||||||
|
return session
|
||||||
43
server/backend/api/storages.py
Normal file
43
server/backend/api/storages.py
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import requests
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
from base64 import b64encode
|
||||||
|
from server.backend.schemas.pydantic import settings
|
||||||
|
import pandas as pd
|
||||||
|
from server.backend.api.session import get_session
|
||||||
|
|
||||||
|
session = get_session({
|
||||||
|
"Accept": "application/xml",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_stores():
|
||||||
|
response = session.get(settings.URL_STORAGES, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.text
|
||||||
|
|
||||||
|
def parse_stores(xml: str):
|
||||||
|
try:
|
||||||
|
NS = {
|
||||||
|
"atom": "http://www.w3.org/2005/Atom",
|
||||||
|
"m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
|
||||||
|
"d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
|
||||||
|
}
|
||||||
|
rows = []
|
||||||
|
# Парсинг XML-ответа
|
||||||
|
root = ET.fromstring(xml)
|
||||||
|
# Извлечение конкретных данных
|
||||||
|
for entry in root.findall('atom:entry', NS):
|
||||||
|
properties = entry.find('atom:content',NS).find(
|
||||||
|
'm:properties', NS)
|
||||||
|
rows.append({
|
||||||
|
'Ref_Key': properties.findtext('d:Ref_Key', default=None, namespaces=NS),
|
||||||
|
'Description': properties.findtext('d:Description', default=None, namespaces=NS),
|
||||||
|
})
|
||||||
|
df = pd.DataFrame(rows)
|
||||||
|
return df
|
||||||
|
except ET.ParseError:
|
||||||
|
raise
|
||||||
|
def storages():
|
||||||
|
xml_data = fetch_stores()
|
||||||
|
root = parse_stores(xml_data)
|
||||||
|
root.to_excel("./excel_files/storages.xlsx")
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
import pandas as pd
|
|
||||||
# def read_excel(base_dir):
|
|
||||||
# try:
|
|
||||||
# dfs = pd.read_excel(base_dir, sheet_name=None)
|
|
||||||
# return dfs
|
|
||||||
# except Exception as e:
|
|
||||||
# raise f"⚠️ Ошибка при чтении {file.name}: {e}"
|
|
||||||
|
|
||||||
class BaseHandler:
|
|
||||||
def __init__(self, file_path):
|
|
||||||
self.file_path = file_path
|
|
||||||
self.dfs = self.read()
|
|
||||||
|
|
||||||
def read(self):
|
|
||||||
try:
|
|
||||||
return pd.read_excel(self.file_path, sheet_name=None)
|
|
||||||
except Exception as e:
|
|
||||||
raise Exception(f"⚠️ Ошибка при чтении {self.file_path}: {e}")
|
|
||||||
|
|
||||||
def process(self):
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
class YandexHandler(BaseHandler):
|
|
||||||
def process(self):
|
|
||||||
# читаем Excel внутри объекта
|
|
||||||
dfs = pd.read_excel(self.file_path, sheet_name=None)
|
|
||||||
# проверяем наличие нужных листов
|
|
||||||
if "Получено от потребителей" not in dfs or "Возвращено потребителям" not in dfs:
|
|
||||||
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
|
||||||
# сама обработка
|
|
||||||
print("Реализация Яндекс")
|
|
||||||
|
|
||||||
class WBHandler(BaseHandler):
|
|
||||||
def process(self):
|
|
||||||
dfs = pd.read_excel(self.file_path, sheet_name=None)
|
|
||||||
if "Sheet1" not in dfs :
|
|
||||||
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
|
||||||
print("Реализация WB")
|
|
||||||
|
|
||||||
class OZONHandler(BaseHandler):
|
|
||||||
def process(self):
|
|
||||||
dfs = pd.read_excel(self.file_path, sheet_name=None)
|
|
||||||
if "Отчет о реализации" not in dfs :
|
|
||||||
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
|
||||||
print("Реализация OZON")
|
|
||||||
|
|
||||||
class OZONPurchasesHandler(BaseHandler):
|
|
||||||
def process(self):
|
|
||||||
dfs = pd.read_excel(self.file_path, sheet_name=None)
|
|
||||||
if "Отчет о выкупленных товарах" not in dfs:
|
|
||||||
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
|
||||||
print("Выкупы озон")
|
|
||||||
|
|
||||||
class WBPurchasesHandler(BaseHandler):
|
|
||||||
def process(self):
|
|
||||||
dfs = pd.read_excel(self.file_path, sheet_name=None)
|
|
||||||
if "Sheet1" not in dfs:
|
|
||||||
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
|
||||||
print("Выкупы wb")
|
|
||||||
class OZONComHandler(BaseHandler):
|
|
||||||
def process(self):
|
|
||||||
dfs = pd.read_excel(self.file_path, sheet_name=None)
|
|
||||||
if "Лист_1" not in dfs:
|
|
||||||
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
|
||||||
df = dfs["Лист_1"]
|
|
||||||
cont = df.iloc[1, 0]
|
|
||||||
if cont != "«Интернет решения» ООО":
|
|
||||||
raise Exception(f"В файле {self.file_path.name} неверный контрагент")
|
|
||||||
print("Товары, переданные на комиссию озон")
|
|
||||||
|
|
||||||
class WBComHandler(BaseHandler):
|
|
||||||
def process(self):
|
|
||||||
dfs = pd.read_excel(self.file_path, sheet_name=None)
|
|
||||||
if "Лист_1" not in dfs:
|
|
||||||
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
|
||||||
df = dfs["Лист_1"]
|
|
||||||
cont = df.iloc[1, 0]
|
|
||||||
if cont != '"Вайлдберриз" ООО':
|
|
||||||
raise Exception(f"В файле {self.file_path.name} неверный контрагент")
|
|
||||||
print("Товары, переданные на комиссию wb")
|
|
||||||
|
|
||||||
class YandexComHandler(BaseHandler):
|
|
||||||
def process(self):
|
|
||||||
dfs = pd.read_excel(self.file_path, sheet_name=None)
|
|
||||||
if "Лист_1" not in dfs:
|
|
||||||
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
|
||||||
df = dfs["Лист_1"]
|
|
||||||
cont = df.iloc[1, 0]
|
|
||||||
if cont != "Яндекс Маркет ООО":
|
|
||||||
raise Exception(f"В файле {self.file_path.name} неверный контрагент")
|
|
||||||
print("Товары, переданные на комиссию yandex")
|
|
||||||
|
|
||||||
0
server/backend/handlers/__init__.py
Normal file
0
server/backend/handlers/__init__.py
Normal file
44
server/backend/handlers/ozon_handler.py
Normal file
44
server/backend/handlers/ozon_handler.py
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
from pydantic import ValidationError
|
||||||
|
from server.backend.schemas.pydantic import ExcelInfo,settings,Translit
|
||||||
|
from server.backend.api.nomenclature import processing
|
||||||
|
import datetime
|
||||||
|
import re
|
||||||
|
def last_day_of_month(format: str):
|
||||||
|
today = datetime.datetime.now()
|
||||||
|
first_day_current_month = today.replace(day=1)
|
||||||
|
last_day_prev_month = first_day_current_month - datetime.timedelta(days=1)
|
||||||
|
return last_day_prev_month.strftime(format)
|
||||||
|
def process_sheet(df,real_arti: int,real_quantity: int,real_sum_1: int,real_sum_2: int):
|
||||||
|
# выбираем нужные колонки по индексам
|
||||||
|
df = df.iloc[:, [real_arti, real_quantity, real_sum_1, real_sum_2]].copy()
|
||||||
|
df.dropna(inplace=True)
|
||||||
|
df = df[(df != 0).all(axis=1)]
|
||||||
|
|
||||||
|
# складываем суммы
|
||||||
|
df.iloc[:, 2] += df.iloc[:, 3]
|
||||||
|
df = df.iloc[:, [0, 1, 2]]
|
||||||
|
df.columns = ['arti', 'counts', 'price']
|
||||||
|
|
||||||
|
# нормализация
|
||||||
|
df['arti'] = df['arti'].replace(Translit.TRANSLIT, regex=True)
|
||||||
|
df['arti'] = df['arti'].astype(str).str.upper().str.extract(f'({settings.PATTERN})')
|
||||||
|
df['price'] = df['price'].astype(float)
|
||||||
|
df['counts'] = df['counts'].astype(int)
|
||||||
|
|
||||||
|
# группировка
|
||||||
|
df = df.groupby('arti', as_index=False).agg({'counts': 'sum', 'price': 'sum'})
|
||||||
|
df = processing(df)
|
||||||
|
validated_rows, errors = [], []
|
||||||
|
for i, row in df.iterrows():
|
||||||
|
try:
|
||||||
|
validated_rows.append(ExcelInfo(**row.to_dict()))
|
||||||
|
except ValidationError as e:
|
||||||
|
errors.append((i, e.errors()))
|
||||||
|
if errors:
|
||||||
|
raise Exception("There are some errors with validation in Отчет о реализации", errors)
|
||||||
|
return validated_rows
|
||||||
|
def evaluating(dfs):
|
||||||
|
validated_rows_1 = process_sheet(dfs["Отчет о реализации"], real_arti=2,real_quantity=8, real_sum_1=5,real_sum_2=6) # номера столбцов от озона
|
||||||
|
validated_rows_2 = process_sheet(dfs["Отчет о реализации"], real_arti=2,real_quantity=16, real_sum_1=13,real_sum_2=14)#
|
||||||
|
date=last_day_of_month(format=settings.TIMEFORMAT)
|
||||||
|
return validated_rows_1, validated_rows_2, date
|
||||||
48
server/backend/handlers/ozon_purchases_handler.py
Normal file
48
server/backend/handlers/ozon_purchases_handler.py
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
from pydantic import ValidationError
|
||||||
|
from server.backend.schemas.pydantic import ExcelInfo, settings,Translit
|
||||||
|
from server.backend.api.nomenclature import processing
|
||||||
|
import re
|
||||||
|
import datetime
|
||||||
|
import re
|
||||||
|
import datetime
|
||||||
|
def report_date(df, date_format: str):
|
||||||
|
row_text = " ".join(df.iloc[0].astype(str))
|
||||||
|
match = re.search(r"по\s+(\d{2}\.\d{2}\.\d{4})", row_text)
|
||||||
|
if not match:
|
||||||
|
raise ValueError("There is no date in ozon_purchase_handler")
|
||||||
|
dt = datetime.datetime.strptime(match.group(1), "%d.%m.%Y")
|
||||||
|
return dt.strftime(date_format)
|
||||||
|
def process_sheet(df, real_arti:int, real_quantity:int, real_sum_1:int):
|
||||||
|
df = df.iloc[2:].reset_index(drop=True)
|
||||||
|
# выбор нужных столбцов ПО ПОЗИЦИИ
|
||||||
|
df = df.iloc[:, [real_arti, real_quantity, real_sum_1]].copy().dropna()
|
||||||
|
df = df[(df != 0).all(axis=1)]
|
||||||
|
|
||||||
|
# сразу задаём нужные имена
|
||||||
|
df.columns = ['arti', 'counts', 'price']
|
||||||
|
|
||||||
|
# нормализация
|
||||||
|
df['arti'] = df['arti'].replace(Translit.TRANSLIT, regex=True)
|
||||||
|
df['arti'] = df['arti'].astype(str).str.upper().str.extract(f'({settings.PATTERN})')
|
||||||
|
df['price'] = df['price'].astype(float)
|
||||||
|
df['counts'] = df['counts'].astype(int)
|
||||||
|
|
||||||
|
#Группировка
|
||||||
|
df = df.groupby('arti', as_index=False).agg({'counts': 'sum', 'price': 'sum'}) #groupping
|
||||||
|
df = processing(df) #vlookup for ref_keys
|
||||||
|
validated_rows, errors = [], []
|
||||||
|
for i, row in df.iterrows():
|
||||||
|
try:
|
||||||
|
validated_rows.append(ExcelInfo(**row.to_dict()))
|
||||||
|
except ValidationError as e:
|
||||||
|
errors.append((i, e.errors()))
|
||||||
|
if errors:
|
||||||
|
raise Exception(
|
||||||
|
"There are some errors with validation in Отчет о выкупленных товарах",
|
||||||
|
errors
|
||||||
|
)
|
||||||
|
return validated_rows
|
||||||
|
def evaluating(dfs):
|
||||||
|
validated_rows_1 = process_sheet(dfs["Отчёт о выкупленных товарах"], real_arti=3,real_quantity=10, real_sum_1=11) # номера столбцов от озона
|
||||||
|
date=report_date(dfs["Отчёт о выкупленных товарах"], date_format=settings.TIMEFORMAT)
|
||||||
|
return validated_rows_1, date
|
||||||
38
server/backend/handlers/ozon_wb_yandex_com_handler.py
Normal file
38
server/backend/handlers/ozon_wb_yandex_com_handler.py
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
from pydantic import ValidationError
|
||||||
|
from server.backend.schemas.pydantic import ExcelInfo,settings,Translit
|
||||||
|
from server.backend.api.nomenclature import processing
|
||||||
|
import re
|
||||||
|
import datetime
|
||||||
|
def first_day_of_prev_month(format: str):
|
||||||
|
today = datetime.datetime.now()
|
||||||
|
first_day_current_month = today.replace(day=1)
|
||||||
|
last_day_prev_month = (first_day_current_month - datetime.timedelta(days=1)).replace(day=1)
|
||||||
|
return last_day_prev_month.strftime(format)
|
||||||
|
def process_sheet(df, real_arti:str, real_quantity:str, real_sum_1:str):
|
||||||
|
df= df.iloc[2:].reset_index(drop=True)
|
||||||
|
#Выборка
|
||||||
|
df = df.iloc[:, [real_arti, real_quantity, real_sum_1]].copy().dropna()
|
||||||
|
df = df[(df != 0).all(axis=1)] #drop all 0 values
|
||||||
|
df.columns = ['arti', 'counts', 'price']
|
||||||
|
#Нормализация
|
||||||
|
df['arti'] = df['arti'].replace(Translit.TRANSLIT, regex=True)
|
||||||
|
df['arti'] = df['arti'].astype(str).str.upper().str.extract(f'({settings.PATTERN})') #arti под regex
|
||||||
|
df['price'] = df['price'].astype(float) #переделка к норм виду и преобразование в float
|
||||||
|
df['counts'] = df['counts'].astype(int) #Float to Int, if exists
|
||||||
|
|
||||||
|
#Группировка
|
||||||
|
df = df.groupby('arti', as_index=False).agg({'counts': 'sum', 'price': 'sum'}) #groupping
|
||||||
|
df = processing(df) #vlookup for ref_keys
|
||||||
|
validated_rows, errors = [], []
|
||||||
|
for i, row in df.iterrows(): #проходит построчно по df, где i - индекс строки, row - данные строки
|
||||||
|
try:
|
||||||
|
validated_rows.append(ExcelInfo(**row.to_dict())) #добавляем в список проверенные данные полученные от pydantic, которые туда передаются в виде dict
|
||||||
|
except ValidationError as e:
|
||||||
|
errors.append((i, e.errors())) #выводит ошибку и пишет номер строки
|
||||||
|
if errors:
|
||||||
|
raise Exception(f"There are some errors with validation in Лист_1, check it ", errors)
|
||||||
|
return validated_rows
|
||||||
|
def evaluating(dfs):
|
||||||
|
validated_rows_1 = process_sheet(dfs["Лист_1"], real_arti=0,real_quantity=4, real_sum_1=8)
|
||||||
|
date = first_day_of_prev_month(settings.TIMEFORMAT)
|
||||||
|
return validated_rows_1, date
|
||||||
49
server/backend/handlers/wb_handler.py
Normal file
49
server/backend/handlers/wb_handler.py
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
from pydantic import ValidationError
|
||||||
|
from server.backend.schemas.pydantic import ExcelInfo, settings,Translit
|
||||||
|
from server.backend.api.nomenclature import processing
|
||||||
|
import pandas as pd
|
||||||
|
import datetime
|
||||||
|
def report_date(df, date_format: str):
|
||||||
|
dates = pd.to_datetime(df["Дата продажи"], format="%Y-%m-%d", errors="coerce")
|
||||||
|
if dates.isna().all():
|
||||||
|
raise ValueError("В колонке нет валидных дат")
|
||||||
|
max_date = dates.max()
|
||||||
|
return max_date.strftime(date_format)
|
||||||
|
def process_sheet(df, document_type:str):
|
||||||
|
#Выборка
|
||||||
|
df = df[['Артикул поставщика', 'Тип документа', 'Кол-во', 'Вайлдберриз реализовал Товар (Пр)']].copy().dropna() #copy and drop all NA values
|
||||||
|
df = df[(df != 0).all(axis=1)] #drop all 0 values
|
||||||
|
df = df[df['Тип документа'] == document_type] #фильтруем по типу документа
|
||||||
|
df = df[['Артикул поставщика', 'Кол-во', 'Вайлдберриз реализовал Товар (Пр)']]
|
||||||
|
df.rename(columns={'Артикул поставщика': 'arti', 'Кол-во': 'counts', 'Вайлдберриз реализовал Товар (Пр)': 'price'}, inplace=True) #переименовываем для pydantic
|
||||||
|
|
||||||
|
#Нормализация
|
||||||
|
df['arti'] = df['arti'].replace(Translit.TRANSLIT, regex=True)
|
||||||
|
df['arti'] = df['arti'].astype(str).str.upper().str.extract(f'({settings.PATTERN})') #arti под regex
|
||||||
|
df['price'] = df['price'].astype(float) #Float to Int, if exists
|
||||||
|
df['counts'] = df['counts'].astype(int) #Float to Int, if exists
|
||||||
|
|
||||||
|
#Группировка
|
||||||
|
df = df.groupby('arti', as_index=False).agg({'counts': 'sum', 'price': 'sum'})
|
||||||
|
df = processing(df) #vlookup for ref_keys
|
||||||
|
validated_rows, errors = [], []
|
||||||
|
for i, row in df.iterrows(): #проходит построчно по df, где i - индекс строки, row - данные строки
|
||||||
|
try:
|
||||||
|
validated_rows.append(ExcelInfo(**row.to_dict())) #добавляем в список проверенные данные полученные от pydantic, которые туда передаются в виде dict
|
||||||
|
except ValidationError as e:
|
||||||
|
errors.append((i, e.errors())) #выводит ошибку и пишет номер строки
|
||||||
|
if errors:
|
||||||
|
raise Exception(f"There are some errors with validation in Sheet1, check it ", errors)
|
||||||
|
return validated_rows
|
||||||
|
|
||||||
|
def evaluating(dfs):
|
||||||
|
validated_rows_1 = process_sheet(dfs["Sheet1"], document_type='Продажа')
|
||||||
|
validated_rows_2 = process_sheet(dfs["Sheet1"], document_type='Возврат')
|
||||||
|
date = report_date(dfs["Sheet1"], settings.TIMEFORMAT)
|
||||||
|
# sum_1 = sum(row.price for row in validated_rows_1)
|
||||||
|
# sum_2 = sum(row.price for row in validated_rows_2)
|
||||||
|
|
||||||
|
# print("Sum for 'Продажа':", sum_1)
|
||||||
|
# print("Sum for 'Возврат':", sum_2)
|
||||||
|
return validated_rows_1, validated_rows_2, date
|
||||||
|
|
||||||
40
server/backend/handlers/wb_purchases_handler.py
Normal file
40
server/backend/handlers/wb_purchases_handler.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
from pydantic import ValidationError
|
||||||
|
from server.backend.schemas.pydantic import ExcelInfo, settings,Translit
|
||||||
|
from server.backend.api.nomenclature import processing
|
||||||
|
import re
|
||||||
|
import datetime
|
||||||
|
def report_date(df, date_format: str):
|
||||||
|
row_text = " ".join(df.iloc[0].astype(str))
|
||||||
|
match = re.search(r"\d{4}-\d{2}-\d{2}", row_text)
|
||||||
|
if not match:
|
||||||
|
raise ValueError("There is no date in ozon_purchase_handler")
|
||||||
|
dt = datetime.datetime.strptime(match.group(0), "%Y-%m-%d")
|
||||||
|
return dt.strftime(date_format)
|
||||||
|
def process_sheet(df, real_arti:str, real_quantity:str, real_sum_1:str):
|
||||||
|
df = df.iloc[2:].reset_index(drop=True)
|
||||||
|
#Выборка
|
||||||
|
df = df.iloc[:, [real_arti, real_quantity, real_sum_1]].copy().dropna()
|
||||||
|
df = df[(df != 0).all(axis=1)] #drop all 0 values
|
||||||
|
df.rename(columns={"Unnamed: 1": 'arti', "Unnamed: 3": 'counts', "Unnamed: 4": 'price'}, inplace=True) #переименовываем для pydantic
|
||||||
|
#Нормализация
|
||||||
|
df['arti'] = df['arti'].astype(str).str.upper().str.extract(f'({settings.PATTERN})') #arti под regex
|
||||||
|
df['arti'] = df['arti'].replace(Translit.TRANSLIT, regex=True)
|
||||||
|
df['price'] = df['price'].str.replace(' ', '', regex=False).str.replace(',', '.', regex=False).astype(float) #переделка к норм виду и преобразование в float
|
||||||
|
df['counts'] = df['counts'].astype(int) #Float to Int, if exists
|
||||||
|
|
||||||
|
#Группировка
|
||||||
|
df = df.groupby('arti', as_index=False).agg({'counts': 'sum', 'price': 'sum'}) #groupping
|
||||||
|
df = processing(df) #vlookup for ref_keys
|
||||||
|
validated_rows, errors = [], []
|
||||||
|
for i, row in df.iterrows(): #проходит построчно по df, где i - индекс строки, row - данные строки
|
||||||
|
try:
|
||||||
|
validated_rows.append(ExcelInfo(**row.to_dict())) #добавляем в список проверенные данные полученные от pydantic, которые туда передаются в виде dict
|
||||||
|
except ValidationError as e:
|
||||||
|
errors.append((i, e.errors())) #выводит ошибку и пишет номер строки
|
||||||
|
if errors:
|
||||||
|
raise Exception(f"There are some errors with validation in Sheet1, check it ", errors)
|
||||||
|
return validated_rows
|
||||||
|
def evaluating(dfs):
|
||||||
|
validated_rows_1 = process_sheet(dfs["Sheet1"], real_arti=1,real_quantity=3, real_sum_1=4) # номера столбцов от озона
|
||||||
|
date=report_date(dfs["Sheet1"], date_format=settings.TIMEFORMAT)
|
||||||
|
return validated_rows_1, date
|
||||||
40
server/backend/handlers/yandex_handler.py
Normal file
40
server/backend/handlers/yandex_handler.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
from pydantic import ValidationError
|
||||||
|
from server.backend.schemas.pydantic import ExcelInfo, settings,Translit
|
||||||
|
from server.backend.api.nomenclature import processing
|
||||||
|
import datetime
|
||||||
|
import re
|
||||||
|
def last_day_of_month(format: str):
|
||||||
|
today = datetime.datetime.now()
|
||||||
|
first_day_current_month = today.replace(day=1)
|
||||||
|
last_day_prev_month = first_day_current_month - datetime.timedelta(days=1)
|
||||||
|
return last_day_prev_month.strftime(format)
|
||||||
|
def process_sheet(df, multiply_price=1, sheet_name=''):
|
||||||
|
#Выборка
|
||||||
|
df = df[['Ваш SKU', 'Количество, шт.', 'Сумма транзакции, ₽']].copy().dropna() #выбираем нужные колонки, делаем копию, чтобы можно было удалить None inline модом
|
||||||
|
df = df[(df != 0).all(axis=1)] #drop all 0 values
|
||||||
|
df['Сумма транзакции, ₽'] *= multiply_price #умножаем на -1 для возвратов
|
||||||
|
df.rename(columns={'Ваш SKU': 'arti', 'Количество, шт.': 'counts', 'Сумма транзакции, ₽': 'price'}, inplace=True) #переименовываем для pydantic
|
||||||
|
|
||||||
|
#Нормализация
|
||||||
|
df['arti'] = df['arti'].replace(Translit.TRANSLIT, regex=True)
|
||||||
|
df['arti'] = df['arti'].astype(str).str.upper().str.extract(f'({settings.PATTERN})') #arti под regex
|
||||||
|
df['price'] = df['price'].astype(float) #To float, if exists
|
||||||
|
df['counts'] = df['counts'].astype(int) #To float, if exists
|
||||||
|
|
||||||
|
#Группировка
|
||||||
|
df = df.groupby('arti', as_index=False).agg({'counts': 'sum', 'price': 'sum'}) #groupping
|
||||||
|
df = processing(df) #vlookup for ref_keys
|
||||||
|
validated_rows, errors = [], []
|
||||||
|
for i, row in df.iterrows(): #проходит построчно по df, где i - индекс строки, row - данные строки
|
||||||
|
try:
|
||||||
|
validated_rows.append(ExcelInfo(**row.to_dict())) #добавляем в список проверенные данные полученные от pydantic, которые туда передаются в виде dict
|
||||||
|
except ValidationError as e:
|
||||||
|
errors.append((i, e.errors())) #выводит ошибку и пишет номер строки
|
||||||
|
if errors:
|
||||||
|
raise Exception(f"There are some errors with validation in {sheet_name}, check it ", errors)
|
||||||
|
return validated_rows
|
||||||
|
def evaluating(dfs):
|
||||||
|
validated_rows_1 = process_sheet(dfs["Получено от потребителей"], sheet_name="Получено от потребителей")
|
||||||
|
validated_rows_2 = process_sheet(dfs["Возвращено потребителям"], multiply_price=-1, sheet_name="Возвращено потребителям")
|
||||||
|
date = last_day_of_month(settings.TIMEFORMAT)
|
||||||
|
return validated_rows_1, validated_rows_2, date
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
from pydantic import BaseModel, Field, field_validator
|
|
||||||
class ExcelInfo(BaseModel):
|
|
||||||
arti:str = Field(..., min_length=6, max_length=12, description="arti of the clothes")
|
|
||||||
counts:int = Field(..., ge=0, description="the quantity of the clothes")
|
|
||||||
price:int = Field(..., ge=0, description="the price of the clothes")
|
|
||||||
class ExcelRealization(BaseModel):
|
|
||||||
pass
|
|
||||||
class ExcelReturning(BaseModel):
|
|
||||||
pass
|
|
||||||
class ExcelOut(BaseModel):
|
|
||||||
pass
|
|
||||||
0
server/backend/schemas/__init__.py
Normal file
0
server/backend/schemas/__init__.py
Normal file
71
server/backend/schemas/pydantic.py
Normal file
71
server/backend/schemas/pydantic.py
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
from pydantic import BaseModel, Field, field_validator
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
class ExcelInfo(BaseModel):
|
||||||
|
arti:str = Field(..., min_length=5, max_length=12, description="arti of the clothes")
|
||||||
|
counts:int = Field(..., gt=0, description="the quantity of the clothes")
|
||||||
|
price:float = Field(..., gt=0, description="the price of the clothes")
|
||||||
|
ref_key:str = Field(..., description="reffering key from db")
|
||||||
|
class ExcelRealization(BaseModel):
|
||||||
|
pass
|
||||||
|
class ExcelReturning(BaseModel):
|
||||||
|
pass
|
||||||
|
class ExcelOut(BaseModel):
|
||||||
|
pass
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
DIR:str
|
||||||
|
PATTERN: str
|
||||||
|
TIMEFORMAT:str
|
||||||
|
USERNAME: str
|
||||||
|
PASSWORD: str
|
||||||
|
URL_REPORT:str
|
||||||
|
URL_REALISATION:str
|
||||||
|
URL_CONTRACTORS:str
|
||||||
|
URL_NOMENCLATURE:str
|
||||||
|
URL_COMPANIES:str
|
||||||
|
URL_STORAGES:str
|
||||||
|
BUYER: str
|
||||||
|
COMPANY: str
|
||||||
|
STORE: str
|
||||||
|
CONTRAGENT_RWB:str
|
||||||
|
CONTRAGENT_OZON:str
|
||||||
|
CONTRAGENT_YANDEX:str
|
||||||
|
CONTRACT_RWB:str
|
||||||
|
CONTRACT_RWB1:str
|
||||||
|
CONTRACT_YAN:str
|
||||||
|
CONTRACT_OZON:str
|
||||||
|
MEASURE:str
|
||||||
|
A60_01:str
|
||||||
|
A62_02:str
|
||||||
|
A60_02:str
|
||||||
|
A62_01:str
|
||||||
|
A45_02:str
|
||||||
|
A43:str
|
||||||
|
A90_01_1:str
|
||||||
|
A90_02_1:str
|
||||||
|
A90_03:str
|
||||||
|
A76_09:str
|
||||||
|
A44_01:str
|
||||||
|
A19_04:str
|
||||||
|
TYPE1:str
|
||||||
|
TYPE2:str
|
||||||
|
TYPE3:str
|
||||||
|
TYPE4:str
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_file=".env",
|
||||||
|
env_file_encoding="utf-8"
|
||||||
|
)
|
||||||
|
class Translit():
|
||||||
|
TRANSLIT = {
|
||||||
|
'А': 'A',
|
||||||
|
'В': 'B',
|
||||||
|
'Е': 'E',
|
||||||
|
'К': 'K',
|
||||||
|
'М': 'M',
|
||||||
|
'Н': 'H',
|
||||||
|
'О': 'O',
|
||||||
|
'Р': 'P',
|
||||||
|
'С': 'C',
|
||||||
|
'Т': 'T',
|
||||||
|
'Х': 'X',
|
||||||
|
}
|
||||||
|
settings = Settings()
|
||||||
0
server/backend/services/__init__.py
Normal file
0
server/backend/services/__init__.py
Normal file
227
server/backend/services/excel.py
Normal file
227
server/backend/services/excel.py
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import server.backend.handlers.yandex_handler as yandex_handler
|
||||||
|
import server.backend.handlers.wb_handler as wb_handler
|
||||||
|
import server.backend.handlers.ozon_handler as ozon_handler
|
||||||
|
import server.backend.handlers.ozon_purchases_handler as ozon_purchases_handler
|
||||||
|
import server.backend.handlers.wb_purchases_handler as wb_purchases_handler
|
||||||
|
import server.backend.handlers.ozon_wb_yandex_com_handler as ozon_wb_yandex_com_handler
|
||||||
|
from server.backend.schemas.pydantic import settings
|
||||||
|
from server.backend.api.report import DocumentCreation
|
||||||
|
class BaseHandler:
|
||||||
|
def __init__(self, file_path):
|
||||||
|
self.file_path = file_path
|
||||||
|
self.dfs = self.read()
|
||||||
|
|
||||||
|
def read(self, skiprows=None, skipfooter=0):
|
||||||
|
try:
|
||||||
|
return pd.read_excel(self.file_path, sheet_name=None, skiprows=skiprows,skipfooter=skipfooter)
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"⚠️ Ошибка при чтении {self.file_path}: {e}")
|
||||||
|
|
||||||
|
def process(self):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
class YandexHandler(BaseHandler):
|
||||||
|
def process(self):
|
||||||
|
dfs = self.read(skiprows=[0,1,3])
|
||||||
|
# проверяем наличие нужных листов
|
||||||
|
if "Получено от потребителей" not in dfs or "Возвращено потребителям" not in dfs:
|
||||||
|
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
||||||
|
# вызываем функцию evaluating
|
||||||
|
validated_data = yandex_handler.evaluating(dfs)
|
||||||
|
print("Реализация Яндекс завершена, валидированных строк:", len(validated_data[0]), "Реализация", len(validated_data[1]), "Возвраты", validated_data[2], "Дата")
|
||||||
|
doc_creator = DocumentCreation(URL=settings.URL_REPORT)
|
||||||
|
doc_key = doc_creator.create_document(
|
||||||
|
Date=validated_data[2],
|
||||||
|
ВидОперации=settings.TYPE3,
|
||||||
|
Контрагент_Key=settings.CONTRAGENT_YANDEX,
|
||||||
|
ДоговорКонтрагента_Key=settings.CONTRACT_YAN,
|
||||||
|
Организация_Key=settings.COMPANY,
|
||||||
|
Склад_Key=settings.STORE,
|
||||||
|
ДокументБезНДС="false",
|
||||||
|
СуммаВключаетНДС="true",
|
||||||
|
УдержатьВознаграждение="true",
|
||||||
|
СчетУчетаРасчетовПоАвансамПолученным_Key=settings.A76_09,
|
||||||
|
СчетУчетаРасчетовСКонтрагентом_Key=settings.A76_09,
|
||||||
|
СчетУчетаРасчетовПоАвансамВыданным_Key=settings.A60_02,
|
||||||
|
СчетУчетаРасчетовЗаПосредническиеУслуги_Key=settings.A60_01,
|
||||||
|
СтавкаНДСВознаграждения="БезНДС",
|
||||||
|
СчетУчетаЗатрат_Key=settings.A44_01,
|
||||||
|
СчетУчетаНДС_Key=settings.A19_04
|
||||||
|
)
|
||||||
|
doc_creator.fill_document_items_report(doc_key, validated_data[0], validated_data[1])
|
||||||
|
class WBHandler(BaseHandler):
|
||||||
|
def process(self):
|
||||||
|
dfs = self.read()
|
||||||
|
if "Sheet1" not in dfs :
|
||||||
|
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
||||||
|
validated_data = wb_handler.evaluating(dfs)
|
||||||
|
print("Реализация WB завершена, валидированных строк:", len(validated_data[0]), "Реализация", len(validated_data[1]), "Возвраты", validated_data[2], "Дата")
|
||||||
|
doc_creator = DocumentCreation(URL=settings.URL_REPORT)
|
||||||
|
doc_key = doc_creator.create_document(
|
||||||
|
Date=validated_data[2],
|
||||||
|
ВидОперации=settings.TYPE3,
|
||||||
|
Контрагент_Key=settings.CONTRAGENT_RWB,
|
||||||
|
ДоговорКонтрагента_Key=settings.CONTRACT_RWB,
|
||||||
|
Организация_Key=settings.COMPANY,
|
||||||
|
Склад_Key=settings.STORE,
|
||||||
|
ДокументБезНДС="false",
|
||||||
|
СуммаВключаетНДС="true",
|
||||||
|
УдержатьВознаграждение="true",
|
||||||
|
СчетУчетаРасчетовПоАвансамПолученным_Key=settings.A62_02,
|
||||||
|
СчетУчетаРасчетовСКонтрагентом_Key=settings.A62_01,
|
||||||
|
СчетУчетаРасчетовПоАвансамВыданным_Key=settings.A60_02,
|
||||||
|
СчетУчетаРасчетовЗаПосредническиеУслуги_Key=settings.A60_01,
|
||||||
|
СтавкаНДСВознаграждения="НДС20",
|
||||||
|
СчетУчетаЗатрат_Key=settings.A44_01,
|
||||||
|
СчетУчетаНДС_Key=settings.A19_04
|
||||||
|
)
|
||||||
|
doc_creator.fill_document_items_report(doc_key, validated_data[0], validated_data[1])
|
||||||
|
class OZONHandler(BaseHandler):
|
||||||
|
def process(self):
|
||||||
|
dfs = self.read(skiprows=14, skipfooter=17)
|
||||||
|
if "Отчет о реализации" not in dfs:
|
||||||
|
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
||||||
|
validated_data = ozon_handler.evaluating(dfs)
|
||||||
|
print("Реализация OZON завершена, валидированных строк:", len(validated_data[0]), "Реализация", len(validated_data[1]), "Возвраты", validated_data[2], "Дата")
|
||||||
|
doc_creator = DocumentCreation(URL=settings.URL_REPORT)
|
||||||
|
doc_key = doc_creator.create_document(
|
||||||
|
Date=validated_data[2],
|
||||||
|
ВидОперации=settings.TYPE3,
|
||||||
|
Контрагент_Key=settings.CONTRAGENT_OZON,
|
||||||
|
ДоговорКонтрагента_Key=settings.CONTRACT_OZON,
|
||||||
|
Организация_Key=settings.COMPANY,
|
||||||
|
Склад_Key=settings.STORE,
|
||||||
|
ДокументБезНДС="false",
|
||||||
|
СуммаВключаетНДС="true",
|
||||||
|
УдержатьВознаграждение="true",
|
||||||
|
СчетУчетаРасчетовПоАвансамПолученным_Key=settings.A62_02,
|
||||||
|
СчетУчетаРасчетовСКонтрагентом_Key=settings.A62_01,
|
||||||
|
СчетУчетаРасчетовПоАвансамВыданным_Key=settings.A60_02,
|
||||||
|
СчетУчетаРасчетовЗаПосредническиеУслуги_Key=settings.A60_01,
|
||||||
|
СтавкаНДСВознаграждения="НДС20",
|
||||||
|
СчетУчетаЗатрат_Key=settings.A44_01,
|
||||||
|
СчетУчетаНДС_Key=settings.A19_04
|
||||||
|
)
|
||||||
|
doc_creator.fill_document_items_report(doc_key, validated_data[0], validated_data[1])
|
||||||
|
|
||||||
|
class OZONPurchasesHandler(BaseHandler):
|
||||||
|
def process(self):
|
||||||
|
dfs = self.read(skiprows=[0,3,4,5,6,7,8,9,10,11], skipfooter=1)
|
||||||
|
if "Отчёт о выкупленных товарах" not in dfs:
|
||||||
|
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
||||||
|
validated_data, date = ozon_purchases_handler.evaluating(dfs)
|
||||||
|
print("Выкупы OZON завершены, валидированных строк:", len(validated_data), "Реализация", date, "Дата")
|
||||||
|
doc_creator = DocumentCreation(URL=settings.URL_REALISATION)
|
||||||
|
doc_key = doc_creator.create_document(
|
||||||
|
Date=date,
|
||||||
|
ВидОперации=settings.TYPE1,
|
||||||
|
Контрагент_Key=settings.CONTRAGENT_OZON,
|
||||||
|
ДоговорКонтрагента_Key=settings.CONTRACT_OZON,
|
||||||
|
Организация_Key=settings.COMPANY,
|
||||||
|
ДокументБезНДС="false",
|
||||||
|
СуммаВключаетНДС="true",
|
||||||
|
СчетУчетаРасчетовПоАвансам_Key=settings.A62_02,
|
||||||
|
СчетУчетаРасчетовСКонтрагентом_Key=settings.A62_01,
|
||||||
|
)
|
||||||
|
doc_creator.fill_document_items_purchase(doc_key, validated_data)
|
||||||
|
class WBPurchasesHandler(BaseHandler):
|
||||||
|
def process(self):
|
||||||
|
dfs = self.read(skiprows=[0,3,4,5,6,7,8], skipfooter=7)
|
||||||
|
if "Sheet1" not in dfs:
|
||||||
|
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
||||||
|
validated_data, date = wb_purchases_handler.evaluating(dfs)
|
||||||
|
print("Выкупы WB завершены, валидированных строк:", len(validated_data), "Реализация", date, "Дата" )
|
||||||
|
doc_creator = DocumentCreation(URL=settings.URL_REALISATION)
|
||||||
|
doc_key = doc_creator.create_document(
|
||||||
|
Date=date,
|
||||||
|
ВидОперации=settings.TYPE1,
|
||||||
|
Контрагент_Key=settings.CONTRAGENT_RWB,
|
||||||
|
ДоговорКонтрагента_Key=settings.CONTRACT_RWB1,
|
||||||
|
Организация_Key=settings.COMPANY,
|
||||||
|
ДокументБезНДС="false",
|
||||||
|
СуммаВключаетНДС="true",
|
||||||
|
СчетУчетаРасчетовПоАвансам_Key=settings.A62_02,
|
||||||
|
СчетУчетаРасчетовСКонтрагентом_Key=settings.A62_01
|
||||||
|
)
|
||||||
|
doc_creator.fill_document_items_purchase(doc_key, validated_data)
|
||||||
|
class OZONComHandler(BaseHandler):
|
||||||
|
def process(self):
|
||||||
|
dfs = self.read(skipfooter=1)
|
||||||
|
if "Лист_1" not in dfs:
|
||||||
|
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
||||||
|
df = dfs["Лист_1"]
|
||||||
|
# контрагент
|
||||||
|
cont = df.iloc[1, 0]
|
||||||
|
if cont != "«Интернет решения» ООО":
|
||||||
|
raise Exception(f"В файле {self.file_path.name} неверный контрагент")
|
||||||
|
validated_data, date = ozon_wb_yandex_com_handler.evaluating(dfs)
|
||||||
|
print("Передача на коммисию OZON завершена, валидированных строк:", len(validated_data), "Реализация", date, "Дата")
|
||||||
|
doc_creator = DocumentCreation(URL=settings.URL_REALISATION)
|
||||||
|
doc_key = doc_creator.create_document(
|
||||||
|
Date=date,
|
||||||
|
ВидОперации=settings.TYPE2,
|
||||||
|
Контрагент_Key=settings.CONTRAGENT_OZON,
|
||||||
|
ДоговорКонтрагента_Key=settings.CONTRACT_OZON,
|
||||||
|
Организация_Key=settings.COMPANY,
|
||||||
|
Склад_Key=settings.STORE,
|
||||||
|
ДокументБезНДС="false",
|
||||||
|
СуммаВключаетНДС="true",
|
||||||
|
СчетУчетаРасчетовПоАвансам_Key=settings.A62_02,
|
||||||
|
СчетУчетаРасчетовСКонтрагентом_Key=settings.A62_01
|
||||||
|
)
|
||||||
|
doc_creator.fill_document_items_to_real(doc_key, validated_data)
|
||||||
|
class WBComHandler(BaseHandler):
|
||||||
|
def process(self):
|
||||||
|
dfs = self.read(skipfooter=1)
|
||||||
|
if "Лист_1" not in dfs:
|
||||||
|
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
||||||
|
df = dfs["Лист_1"]
|
||||||
|
# контрагент
|
||||||
|
cont = df.iloc[1, 0]
|
||||||
|
if cont != '"Вайлдберриз" ООО':
|
||||||
|
raise Exception(f"В файле {self.file_path.name} неверный контрагент")
|
||||||
|
validated_data, date = ozon_wb_yandex_com_handler.evaluating(dfs)
|
||||||
|
print("Передача на коммисию WB завершена, валидированных строк:", len(validated_data), "Реализация", date, "Дата")
|
||||||
|
doc_creator = DocumentCreation(URL=settings.URL_REALISATION)
|
||||||
|
doc_key = doc_creator.create_document(
|
||||||
|
Date=date,
|
||||||
|
ВидОперации=settings.TYPE2,
|
||||||
|
Контрагент_Key=settings.CONTRAGENT_RWB,
|
||||||
|
ДоговорКонтрагента_Key=settings.CONTRACT_RWB,
|
||||||
|
Организация_Key=settings.COMPANY,
|
||||||
|
Склад_Key=settings.STORE,
|
||||||
|
ДокументБезНДС="false",
|
||||||
|
СуммаВключаетНДС="true",
|
||||||
|
СчетУчетаРасчетовПоАвансам_Key=settings.A62_02,
|
||||||
|
СчетУчетаРасчетовСКонтрагентом_Key=settings.A76_09
|
||||||
|
)
|
||||||
|
doc_creator.fill_document_items_to_real(doc_key, validated_data)
|
||||||
|
|
||||||
|
class YandexComHandler(BaseHandler):
|
||||||
|
def process(self):
|
||||||
|
dfs = self.read(skipfooter=1)
|
||||||
|
if "Лист_1" not in dfs:
|
||||||
|
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
||||||
|
df = dfs["Лист_1"]
|
||||||
|
# контрагент
|
||||||
|
cont = df.iloc[1, 0]
|
||||||
|
if cont != "Яндекс Маркет ООО":
|
||||||
|
raise Exception(f"В файле {self.file_path.name} неверный контрагент")
|
||||||
|
validated_data, date = ozon_wb_yandex_com_handler.evaluating(dfs)
|
||||||
|
print("Передача на коммисию YANDEX завершена, валидированных строк:", len(validated_data), "Реализация", date, "Дата")
|
||||||
|
doc_creator = DocumentCreation(URL=settings.URL_REALISATION)
|
||||||
|
doc_key = doc_creator.create_document(
|
||||||
|
Date=date,
|
||||||
|
ВидОперации=settings.TYPE2,
|
||||||
|
Контрагент_Key=settings.CONTRAGENT_YANDEX,
|
||||||
|
ДоговорКонтрагента_Key=settings.CONTRACT_YAN,
|
||||||
|
Организация_Key=settings.COMPANY,
|
||||||
|
Склад_Key=settings.STORE,
|
||||||
|
ДокументБезНДС="false",
|
||||||
|
СуммаВключаетНДС="true",
|
||||||
|
СчетУчетаРасчетовПоАвансам_Key=settings.A62_02,
|
||||||
|
СчетУчетаРасчетовСКонтрагентом_Key=settings.A76_09
|
||||||
|
)
|
||||||
|
doc_creator.fill_document_items_to_real(doc_key, validated_data)
|
||||||
|
|
||||||
@@ -1,10 +1,7 @@
|
|||||||
import server.backend.excel as excel
|
import server.backend.services.excel as excel
|
||||||
|
from server.backend.schemas.pydantic import settings
|
||||||
from dotenv import load_dotenv #Работа с env
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
load_dotenv()
|
DIR = Path(settings.DIR)
|
||||||
base_dir = Path(os.getenv("DIR"))
|
|
||||||
|
|
||||||
handlers = { #метки какие файлы есть и должны быть занесены с вызовами функций из файла
|
handlers = { #метки какие файлы есть и должны быть занесены с вызовами функций из файла
|
||||||
"period_closure_income": excel.YandexHandler,
|
"period_closure_income": excel.YandexHandler,
|
||||||
@@ -19,9 +16,9 @@ handlers = { #метки какие файлы есть и должны быть
|
|||||||
|
|
||||||
#Проход по всем файлам в директории
|
#Проход по всем файлам в директории
|
||||||
def validating():
|
def validating():
|
||||||
if not base_dir.exists():
|
if not DIR.exists():
|
||||||
raise (f"Директория {base_dir} не существует") #Проверка существует ли директория
|
raise (f"Директория {DIR} не существует") #Проверка существует ли директория
|
||||||
for file in base_dir.rglob("*.xlsx"):
|
for file in DIR.rglob("*.xlsx"):
|
||||||
|
|
||||||
if file.name.startswith("~$"): #Проверка не редактируемый ли файл
|
if file.name.startswith("~$"): #Проверка не редактируемый ли файл
|
||||||
continue
|
continue
|
||||||
@@ -32,7 +29,7 @@ def validating():
|
|||||||
match file:
|
match file:
|
||||||
case _ if "period_closure_income" in name:
|
case _ if "period_closure_income" in name:
|
||||||
label = "period_closure_income"
|
label = "period_closure_income"
|
||||||
case _ if name == "0":
|
case _ if name == "0" or "weekly_report" in name:
|
||||||
label = "0"
|
label = "0"
|
||||||
case _ if "отчет о реализации товара" in name:
|
case _ if "отчет о реализации товара" in name:
|
||||||
label = "отчет о реализации товара"
|
label = "отчет о реализации товара"
|
||||||
Reference in New Issue
Block a user