from tkinter import Tk
from tkinter.filedialog import askopenfilename, askdirectory
import sys
import os
import re
import chardet
from packages.syncfile import importAmazonOrder, writeNewCsv
from packages.shipment_finish import finishShipment
from packages.plenty_export import plentyExport
#from packages.excelfile import createExcelSheet
def main():
# Create a root window, with the purpose of withdrawing it
# askdirectory & askopenfilename both create a root by default but there is no variable
# in that case to withdraw
root = Tk()
root.withdraw()
use_current_dir = 'x'
newpath = ''
export_file = {"filepath":"",
"encoding":""}
shipment_file = {"filepath":"",
"encoding":""}
# Check if there is already a Report folder for the Amazon report files, if not create a new one.
reportpath = os.getcwd() + '/Report'
if not os.path.exists(reportpath):
while(not(re.match(r'^(y|j)', use_current_dir[0].lower()) or re.match(r'^n',use_current_dir[0].lower()))):
use_current_dir = input("Do you want to use the current directory, for the folders and config?")
if(use_current_dir[0].lower() == 'y' or use_current_dir[0].lower() == 'j'):
os.makedirs(reportpath)
if(use_current_dir[0].lower() == 'n'):
newpath = askdirectory(title="Choose the directory for the folders")
reportpath = newpath + '/Report'
try:
os.makedirs(reportpath)
except FileExistsError:
print("The Report folder exists!")
# Check if there is already a Upload folder if not create a new one.
if(newpath):
uploadpath = newpath + '/Upload'
else:
uploadpath = os.getcwd() + '/Upload'
if not os.path.exists(uploadpath):
try:
os.makedirs(uploadpath)
except FileExistsError:
print("The Upload folder exists!")
# Get the producer list by following the config.txt to the location
# Get the plentymarkets id by following the config.txt
# If there is no config.txt create a new one
producer = ''
configid = ''
configpath = ''
if(newpath):
configpath = newpath + '/config.txt'
else:
configpath = './config.txt'
if(os.path.isfile(configpath)):
with open(configpath, mode = 'r') as config:
# Take every row into a list rows and strip them of spaces and new lines
rows = (row.strip(' ').strip('\n').split(';') for row in config)
for row in rows:
# combine the list to a string and split it at the '='
option = "".join(row[0]).split('=')
if(not(option[0].strip(' ') == '#')):
if(option[0].strip(' ') == 'producer_list'):
producer = option[1].strip(' ')
#if(not( os.path.isfile(producer) )):
#print('No valid producer list located!\n')
#sys.exit()
if(option[0].strip(' ') == 'plenty_id'):
configid = int(option[1])
# if no producer_list option was set
if(not(producer)):
print("config reading failed or producer_list not set!\n")
print("The producer list needs the header: 'producer', 'adressid', 'customerid', 'firstname', 'lastname'\n")
os.system('pause')
sys.exit()
if(not(configid)):
print("config reading failed or plenty_id not valid!\n")
os.system('pause')
sys.exit()
# If there is no config.txt then create a new one
# and fill it with the base text and options
else:
with open(configpath , mode = 'a') as config:
config.write( "#-Config file for the order import;\n" )
config.write( "#= '#= marks the beginning of a comment', '= splits between name and value';\n" )
config.write( "#=provide the position of the producer list file in the format ./'location';\n" )
config.write( "producer_list = ;\n" )
config.write( "#=Enter your plentymarkets ID here;\n" )
config.write( "plenty_id = ;\n" )
config.write( "CountryCode = ;\n")
if(os.path.isfile('./config.txt')):
print("\nNew config file created, please fill out the options!\n")
os.system('pause')
sys.exit()
# Ask the user if the task is to import received items at amazon or to
# create a new order for production
line = "#" * 70
altline = "-" * 70
print("{0}\n".format(line))
print(" Preparation for the Script / Vorbereitung für den Script\n")
print("{0}\n".format(line))
print(" Get a export of all variations from plentymarkets\n & save it in Report\n")
print(" Lade einen Export von allen Varianten in Plentymarkets\n & speichere diesen in Report\n")
print("{0}\n".format(altline))
print(" Save your Storagereport from Amazon as .csv and name the column\n of the units to be sent as FBA-SHIPMENT\n")
print(" Speichere deine Lagerbestandsdatei as .csv und benenne die Spalte\n mit den zu versendenden Artikeln als FBA-SHIPMENT\n")
print("{0}\n".format(altline))
print(" Get a export of the locations from plentymarkets\n & save it in Report\n")
print(" Lade einen Export der Lagerstandorte von plentymarkets\n & speichere diesen in Report\n")
print("{0}\n".format(line))
task = ''
while(not(task.lower() == 'ama' or\
task.lower() == 'fin' or\
task.lower() == 'exp' or\
task.lower() == 'fba')):
task = input('Do you want to create a new FBA Shipment?(fba)\nDo you want to finish a shipment?(fin)\nDo you want to export the plenty quantity to the storage report?(exp)\nOr do you want to import received items at Amazon (ama)?\n')
if(not(task.lower() == 'ama' or task.lower() == 'fin' or task.lower() == 'exp' or task.lower() == 'fba')):
print("Please enter either 'fba', 'fin', 'exp' or 'ama'.\n")
# Set to 0000 because the current state of the script doesnt need the orderid anymore
order ='0000'
# A filedialog for the export and the report file
root = Tk()
root.withdraw()
if(task.lower() == 'ama' or task.lower() == 'fba'):
print("\n{0}\n".format(line))
print("Open the export file of all items, to get the Variation ID which is needed for the Upload.\n")
export_file['filepath'] = askopenfilename(initialdir=reportpath
, title="Export from Plentymarkets"
, filetypes=[ ("csv files" ,"*.csv" ) ] )
# detect the encoding of the file
with open(export_file['filepath'], mode='rb') as item:
raw_data = item.read()
export_file['encoding'] = chardet.detect(raw_data)['encoding']
# AMAZON RECEIVED PART
if(task.lower() == 'ama'):
print("Open the report file of the recent delivered FBA packages,\nthis will contain the amount of items that amazon received.\n")
print("\n{0}\n".format(line))
shipment_file['filepath'] = askopenfilename(initialdir=reportpath
, title="FBA-Report"
, filetypes=[ ("csv files" ,"*.csv" ) ] )
# detect the encoding of the file
with open(shipment_file['filepath'], mode='rb') as item:
raw_data = item.read()
shipment_file['encoding'] = chardet.detect(raw_data)['encoding']
try:
importAmazonOrder(export=export_file, folder=uploadpath, orderid=order,
plentyid=configid, report=shipment_file
)
except Exception as Err:
print("Something went terribly wrong...")
print(Err)
# FINISH SHIPMENT PART
if(task.lower() == 'fin'):
print("{0}\n".format(line))
print("Open the finished picklist as .csv\n")
print("{0}\n".format(altline))
print("Öffne die fertig gestellte Pickliste im .csv Format\n")
shipment_file['filepath'] = askopenfilename(initialdir=reportpath
, title="Finished picklist from the shipment"
, filetypes=[ ("csv files" ,"*.csv" ) ] )
# detect the encoding of the file
with open(shipment_file['filepath'], mode='rb') as item:
raw_data = item.read()
shipment_file['encoding'] = chardet.detect(raw_data)['encoding']
try:
plenty_Data = {}
plenty_Data = finishShipment(picklist=shipment_file, folder=reportpath)
writeNewCsv(dataset=plenty_Data['data'],
path=uploadpath,
header=plenty_Data['fields'],
name='Plenty_Stock')
except Exception as Err:
print("Something went terribly wrong...")
print(Err)
# NEW FBA SHIPMENT PART
if(task.lower() == 'fba'):
print("Open the stock report with the calculated shipment.\n")
print("\n{0}\n".format(line))
shipment_file['filepath'] = askopenfilename(initialdir=reportpath,
title="Latest stock report from Amazon",
filetypes=[ ("csv files", "*.csv") ])
# detect the encoding of the file
with open(shipment_file['filepath'], mode='rb') as item:
raw_data = item.read()
shipment_file['encoding'] = chardet.detect(raw_data)['encoding']
importAmazonOrder(export=export_file, reportfolder=reportpath, folder=uploadpath,
orderid=order, plentyid=configid, stockreport=shipment_file
)
print("\npress ENTER to continue...")
input()
# PLENTY EXPORT PART
if(task.lower() == 'exp'):
print("\n{0}\n".format(line))
print("Open the current plenty location export ID49\n")
print("Use the options: positive physical quantity and FNSKU\n")
print("\n{0}\n".format(altline))
print("Öffne den derzeitigen plenty Lagerplatz Export ID49\n")
print("Nutze die Optionen: positiver physischer Lagerbestand und FNSKU\n")
print("\n{0}\n".format(line))
locationexport={'filepath':'',
'encoding':''}
locationexport['filepath'] = askopenfilename(initialdir=reportpath,
title="Storage quantity export Plentymarkets",
filetypes=[ ("csv files", "*.csv") ])
# detect the encoding of the file
with open(locationexport['filepath'], mode='rb') as item:
raw_data = item.read()
locationexport['encoding'] = chardet.detect(raw_data)['encoding']
plentyExport(plentyexport=locationexport,folder=uploadpath)
print("\npress ENTER to continue...")
input()
if __name__ == '__main__':
main()