v1.6 init on gitea

This commit is contained in:
2025-10-02 08:33:11 +02:00
commit e617ad71b4
10 changed files with 786 additions and 0 deletions

42
Install_requirements.bat Normal file
View File

@@ -0,0 +1,42 @@
@echo off
rem Ermittle und zeige den aktuellen Pfad an
set "scriptPath=%~dp0"
echo Der aktuelle Pfad ist: %scriptPath%
rem Überprüfe, ob Python installiert ist
python --version > nul 2>&1
if %errorlevel% neq 0 (
msg * Python ist nicht installiert. Bitte installiere Python und führe das Skript erneut aus.
exit /b
)
rem Überprüfe, ob pip installiert ist
pip --version > nul 2>&1
if %errorlevel% neq 0 (
msg * pip ist nicht installiert. Bitte installiere pip und führe das Skript erneut aus.
exit /b
)
rem Installiere Abhängigkeiten mit pip
pip install -r .\Script\requirements.txt
rem Überprüfe, ob die Installation erfolgreich war
if %errorlevel% neq 0 (
msg * Fehler: Die pip-Installation ist fehlgeschlagen. Bitte überprüfe die obige Fehlermeldung.
exit /b
)
msg * Pip-Installation erfolgreich.
rem Erstelle eine Verknüpfung zu P4U-Converter.bat
set "shortcutTarget=%scriptPath%Script/P4U-Converter.bat"
set "shortcutName=%scriptPath%P4U-Converter.lnk"
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "%shortcutName%" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "%shortcutTarget%" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript /nologo CreateShortcut.vbs
del CreateShortcut.vbs

60
ReadMe.txt Normal file
View File

@@ -0,0 +1,60 @@
#################################################################################
#
# P4U Script for converting Baskets from Digikey / Mouser to P4U format
# Created by Jonas Lingua & Noah Piqué
# Date: 02.10.2025
# Version 1.6
#
################################################################################
## New:
- Use via website
## Infos:
- python3 script
# Instruction Windows:
- Install Python 3 via Softwarekiosk
- Execute"Install_requirements.bat" # You only have to run this command once!
- Execute "P4U-Converter" # This link should be displayed when the requirements have been successfully installed. Drag this link to the place you want.
# Instruction Linux/MacOS:
- Install Python 3 via Softwarekiosk
cd Script
pip install -r requirements.txt # You only have to run this command once!
python app.py # for web-based upload
or
python main.py [mouser/digikey] [filename] [fasttrack] # for console-use
evt. python3, depending on the installation environment
# Console changes
If you still want to use the console, please put your xls/csv files in the "uploads" folder.
Your new carts will be saved in the "exports" folder.
# Distributor informations
- mouser -> xls file in euros!
- digikey -> csv file in chf!
- please dont change this file
# using the app.py script for any distributor:
- go to distributor and create cart
- then set currency to euros/chf (See "Distributor informations")
- download cart xls/csv (See "Distributor informations")
- excute the link/command
- upload the file in the webinterface
- click on download
- now you can upload this file to p4u
# using the main.py script for any distributor:
- go to distributor and create cart
- then set currency to euros/chf (See "Distributor informations")
- download cart xls/csv (See "Distributor informations")
- put the file in the same folder as the main.py script
- execute the command from "Instruction Windows/Linux/MacOS":
python main.py mouser name_of_my_basket.xls
- OR execute this command for fasttrack order:
python main.py mouser name_of_my_basket.xls fasttrack
- outputs file -> Warenkorb_distributor.xlsx
- now you can upload this file to p4u

6
Script/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
.idea
*.xls
*.csv
__pycache__
Warenkorb_*.xlsx
*.lnk

30
Script/P4U-Converter.bat Normal file
View File

@@ -0,0 +1,30 @@
@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
set "script_directory=%~dp0"
:: Überprüfe, ob 'python3' oder 'python' verfügbar ist
set python_cmd=
for %%P in (python3 python) do (
%%P --version >nul 2>&1
if !errorlevel! equ 0 (
set python_cmd=%%P
goto :found_python
)
)
:found_python
if "%python_cmd%"=="" (
echo [FEHLER] Kein funktionierender Python-Interpreter gefunden.
exit /b 1
)
echo [INFO] Python-Interpreter gefunden: %python_cmd%
cd /d "%script_directory%"
:: Starte die Python-Anwendung und zeige die Ausgabe in der Konsole
echo [INFO] Starte die Python-Anwendung...
%python_cmd% "app.py"
exit /b 0

112
Script/app.py Normal file
View File

@@ -0,0 +1,112 @@
#################################################################################
#
# P4U Script for converting Baskets from Digikey / Mouser to P4U format
# Created by Jonas Lingua & Noah Piqué
# Date: 02.10.2025
# Version 1.6
#
################################################################################
# Importieren der erforderlichen Module
from flask import Flask, request, render_template, send_file
import os
import main
import csv
import webbrowser
url = "http://127.0.0.1:5000"
webbrowser.open_new_tab(url)
# Erstellen einer Flask-App-Instanz
app = Flask(__name__)
# Überprüfe, ob der Ausgabeordner existiert, und erstelle ihn, falls nicht
if not os.path.exists('exports'):
os.makedirs('exports')
# Überprüfe, ob der Eingabeordner existiert, und erstelle ihn, falls nicht
if not os.path.exists('uploads'):
os.makedirs('uploads')
# Festlegen des Upload-Verzeichnisses
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Globale Variable zur Speicherung des Slider-Status
fasttrack_status = True
# Routen-Handler für die Startseite
@app.route('/')
def index():
return render_template('index.html')
# Routen-Handler für das Aktualisieren des Slider-Status
@app.route('/update_slider_status', methods=['POST'])
def update_slider_status():
global fasttrack_status
data = request.get_json()
new_status = data.get('fasttrack_status')
fasttrack_status = new_status
return 'Slider-Status aktualisiert'
# Routen-Handler für das Hochladen von Dateien
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' in request.files:
file = request.files['file']
if file:
# Speichern der hochgeladenen Datei im Upload-Verzeichnis
uploaded_file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(uploaded_file_path)
dist = distributor(uploaded_file_path)
global new_file
new_file = 'Warenkorb_' + dist + '.xlsx'
web_in = ['main.py', dist, file.filename]
if fasttrack_status:
web_in.append('fasttrack')
else:
web_in = web_in[0:3]
main.p4u(web_in)
clearFolder("uploads")
return main.printout
return 'Error uploading the file. See console'
# Routen-Handler für das Herunterladen der output-Datei
@app.route('/download_output')
def download_output_file():
output_file_path = os.path.join('exports', new_file)
return send_file(output_file_path, as_attachment=True)
def clearFolder(path):
try:
dateien = os.listdir(path)
for datei in dateien:
datei_pfad = os.path.join(path, datei)
if os.path.isfile(datei_pfad):
os.remove(datei_pfad) # Lösche die Datei
elif os.path.isdir(datei_pfad):
os.rmdir(datei_pfad) # Lösche den Ordner
except Exception as e:
print(f"Error during deleting the folder: {str(e)}")
def distributor(filename):
if filename[-4:] == '.csv':
try:
with open(filename, 'r') as CSV:
read_csv = csv.reader(CSV, delimiter=",")
read_csv = list(read_csv)
if read_csv[1][2][-3:] == '-ND':
return 'digikey'
else:
return 'not found'
except:
print("Error: could not open the file")
exit(1)
else:
return 'mouser'
# Starten der Flask-Anwendung, wenn die Datei direkt ausgeführt wird
if __name__ == '__main__':
app.run(debug=False)
clearFolder('exports')

208
Script/main.py Normal file
View File

@@ -0,0 +1,208 @@
#################################################################################
#
# P4U Script for converting Baskets from Digikey / Mouser to P4U format
# Created by Jonas Lingua & Noah Piqué
# Date: 02.10.2025
# Version 1.6
#
################################################################################
from xlrd import open_workbook
from openpyxl import load_workbook
import sys
import csv
printout = ""
def prints(string):
global printout
printout += str(string) + "<br />"
print(string)
# converting mouser xls file to array
def load_mouser(file_mouser, fast=False):
try:
wb = open_workbook(file_mouser)
except:
prints("Error(Mouser): could not open the file")
return 0
prints('Reading File Succeded')
sh = wb.sheet_by_index(0)
col = sh.col_values(0)
offset_mouser = col.index(1)
if offset_mouser == -1:
prints('Error(Mouser): did not find a part')
return 0
nparts = col.index('', offset_mouser) - offset_mouser
if nparts <= -1:
prints('Error(Mouser): did not the end of the file')
return 0
vertrag = 'Mouser Electronics, Elsenheimerstrasse 11, 80687, München, DE (EUR)'
if fast:
vertrag = 'Mouser Electronics (EUR) (Fasttrack)'
part_mouser = ['', '', vertrag, 'Mouser Electronics', '', '', '', '', '', 820, 0, 'Stück', '', '', '', '', '', '8.1', 0, 'EUR']
parts_mouser = []
for part in range(nparts):
parts_mouser.append(part_mouser.copy())
for x, y in enumerate(range(offset_mouser, offset_mouser + nparts)):
parts_old = sh.row_values(y, 0, 11)
parts_mouser[x][0] = str(int(parts_old[0]))
parts_mouser[x][1] = parts_old[1]
parts_mouser[x][4] = parts_old[3]
parts_mouser[x][5] = parts_old[2]
parts_mouser[x][6] = parts_old[3] + " " + parts_old[2]
parts_mouser[x][7] = parts_old[5]
parts_mouser[x][10] = int(parts_old[8])
w = parts_old[9][-1]
if w != '':
prints('Error: please change mouser currency to euro and retry')
return 0
try:
p = float(parts_old[9][0:-2].replace(',', '.'))
except ValueError:
prints("Error: mouser price is not in right format")
return 0
parts_mouser[x][18] = p
#prints(parts_mouser)
return parts_mouser
# converting digikey csv file to array
def load_digikey(file_digikey, fast=False):
try:
with open(file_digikey, 'r') as CSV:
read_csv = csv.reader(CSV, delimiter=",")
read_csv = list(read_csv)
except:
prints("Error: could not open the file")
return 0
prints('Reading File Succeded')
offset_digikey = -1
for i, row in enumerate(read_csv):
if (row[0]) == '1':
offset_digikey = i
break
if offset_digikey <= -1:
prints('Error(Digikey): did not the start of the file')
return 0
nparts = len(read_csv) - offset_digikey
vertrag = 'Digi-Key Corporation, Brooks Avenue South 701, 56701, Thief River Falls, US (CHF)'
if fast:
vertrag = 'Digi-Key Corporation (CHF) (Fasttrack)'
# Index,"Menge","Teilenummer","Hersteller-Teilenummer","Beschreibung","Kundenreferenz","Verfügbar","Lieferrückstände","Stückpreis","Gesamtpreis EUR"
# Position Artikelnummer Vertrag Lieferant Hersteller Herstellernummer Kurztext Langtext Materialnummer Standardwarengruppe Menge Einheiten ppppp MwSt-Satz Preis Währung
part_digikey = ['', '', vertrag, 'Digi-Key Corporation', '', '', '', '', '', 820, 0, 'Stück', '', '', '', '', '', '8.1', 0, 'CHF']
parts_digikey = []
for part in range(nparts):
parts_digikey.append(part_digikey.copy())
for x, y in enumerate(range(offset_digikey, offset_digikey + nparts)):
parts_old = read_csv[y]
parts_digikey[x][0] = str(int(parts_old[0]))
parts_digikey[x][1] = parts_old[2]
parts_digikey[x][5] = parts_old[3]
parts_digikey[x][6] = parts_old[3]
parts_digikey[x][7] = parts_old[4]
parts_digikey[x][10] = int(parts_old[1])
w = parts_old[9][-3:]
if w != 'Fr.':
prints('Error: please change digikey currency to chf and retry')
return 0
try:
p = float(parts_old[8].replace(',', '.'))
except ValueError:
prints("Error: digikey price is not in right format")
return 0
parts_digikey[x][18] = p
# prints(parts_digikey)
return parts_digikey
load_functions = {'mouser': load_mouser, 'digikey': load_digikey}
fasttrack = ['mouser', 'digikey']
def p4u(args):
global printout
printout = ""
if len(args) <= 2:
prints("Error: please specify a type(mouser/digikey) and a file")
return 0
else:
file_type = args[1]
file = "uploads/" + args[2]
fast = ''
if len(args) == 4:
fast = args[3]
parts = []
if file_type in load_functions.keys():
prints("Found load function for " + file_type)
try:
if fast == 'fasttrack' and file_type in fasttrack:
prints('Fasttrack Order found')
parts.extend(load_functions[file_type](file, True))
else:
prints('No Fasttrack')
parts.extend(load_functions[file_type](file))
except:
prints("Error: could not open the file")
return 0
else:
prints("Error: wrong type of file(mouser/digikey)")
return 0
if not parts:
prints('Error: no data recieved (empty files?)(wrong filename?)')
return 0
new_file = './Warenkorb_' + file_type + '.xlsx'
prints('Writing to new File: ' + new_file)
try:
wb_neu = load_workbook('./templates/Warenkorb.xlsx')
except:
prints("Error: template Warenkorb.xlsx is missing, please put it back in the templates folder")
return 0
sh_neu = wb_neu.active
offset = 0
for i, row in enumerate(sh_neu.values):
if (row[0]) == 'Position':
offset = i + 1
for i in range(len(parts)):
for j in range(len(parts[i])):
sh_neu.cell(offset + i + 1, j + 1, parts[i][j])
wb_neu.save('./exports/' + new_file)
prints('Finished')
return new_file
if __name__ == '__main__':
if(not p4u(sys.argv)):
print(printout)
sys.exit(1)
print("Done")
#print(printout)

44
Script/requirements.txt Normal file
View File

@@ -0,0 +1,44 @@
altgraph==0.17.4
attrs==23.1.0
auto-py-to-exe==2.41.0
blinker==1.7.0
bottle==0.12.25
bottle-websocket==0.2.9
certifi==2023.7.22
cffi==1.16.0
click==8.1.7
colorama==0.4.6
Eel==0.16.0
et-xmlfile==1.1.0
Flask==3.0.0
future==0.18.3
gevent==23.9.1
gevent-websocket==0.10.1
greenlet==3.0.1
h11==0.14.0
idna==3.4
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.3
openpyxl==3.0.10
outcome==1.3.0.post0
packaging==23.2
pefile==2023.2.7
pycparser==2.21
pyinstaller==6.1.0
pyinstaller-hooks-contrib==2023.10
pyparsing==3.1.1
PySocks==1.7.1
pywin32-ctypes==0.2.2
selenium==4.15.2
sniffio==1.3.0
sortedcontainers==2.4.0
trio==0.23.1
trio-websocket==0.11.1
urllib3==2.0.7
Werkzeug==3.0.1
whichcraft==0.6.1
wsproto==1.2.0
xlrd==2.0.1
zope.event==5.0
zope.interface==6.1

Binary file not shown.

284
Script/templates/index.html Normal file
View File

@@ -0,0 +1,284 @@
<!------------------------------------------------------------------------------
#
# P4U Script for converting Baskets from Digikey / Mouser to P4U format
# Created by Jonas Lingua & Noah Piqué
# Date: 30.11.2023
# Version 1.4
#
------------------------------------------------------------------------------->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Titel der Webseite -->
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE edge" />
<meta lang="en" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Favicon -->
<link rel="icon" href="logo.png" type="image/x-icon" />
<link rel="shortcut icon" href="logo.png" type="image/x-icon" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
/>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title>P4U-Converter</title>
<!-- Styling für den Bereich, in den Dateien gezogen werden können -->
<style>
body {
margin: 20px;
font-family: "Roboto", sans-serif;
background-color: #f8f9fa;
color: #495057;
}
.container {
padding: 20px;
border: 1px solid #ced4da;
margin: 20px;
background-color: #ffffff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 10px;
}
#dropArea {
border: 2px dashed #6c757d;
padding: 30px;
text-align: center;
margin: 10px 0;
background-color: #f1f1f1;
border-radius: 10px;
transition: border-color 0.3s ease;
}
#dropArea.dragover {
border-color: #007bff;
background-color: #e8f0fe;
}
h1 {
color: #007bff;
}
#infoField {
margin-top: 20px;
}
.custom-control {
margin: 10px 0; /* Abstand über und unter dem On-Off-Slider */
}
#uploadButton:hover,
#exitButton:hover,
#fileInput-label:hover,
#download-label:hover {
background-color: #007bff;
color: #fff;
}
#creatorField {
position: absolute;
bottom: 0;
right: 0;
color: #6c757d;
margin: 10px;
}
#fileInput {
display: none;
}
#fileInput-label,
#download-label {
font-size: 1.2em;
padding: 8px 15px;
width: 200px;
text-align: center;
border: 1px solid #007bff; /* Blaue Rahmenfarbe */
border-radius: 8px;
cursor: pointer;
transition: background-color 0.3s ease; /* Sanfter Farbübergang bei Hover */
display: inline-block;
}
#fileInput-label:hover,
#download-label:hover {
background-color: #007bff; /* Farbänderung bei Hover */
color: #fff; /* Textfarbe ändern, um besser sichtbar zu sein */
}
</style>
</head>
<body>
<!-- Infofeld am Ende der Webseite -->
<div id="creatorField">
Created by <a href="mailto:jonas.lingua@psi.ch">Jonas Lingua</a> &
<a href="mailto:noah.pique@psi.ch">Noah Piqué</a>
</div>
<!-- Überschrift der Seite -->
<h1>P4U-Converter</h1>
<!-- Infofeld -->
<div id="infoField">
Upload-Informations: <br />
Convert your Digikey, Mouser and Farnell baskets to P4U standard. <br />
Just upload your files here. <br />
File conditions: <br />
Digikey -> csv file in chf! <br />
Mouser -> xls file in euros!
</div>
<!-- On-Off-Slider -->
<div class="custom-control custom-switch">
<input
type="checkbox"
class="custom-control-input"
id="mySwitch"
checked
/>
<label class="custom-control-label" for="mySwitch">Fasttrack</label>
</div>
<!-- Bereich (DropArea), in den Dateien gezogen werden können -->
<div
id="dropArea"
ondrop="handleDrop(event)"
ondragover="allowDrop(event)"
ondragleave="disallowDrop(event)"
>
Drop a file to upload
</div>
<!-- Formular zum manuellen Auswählen von Dateien -->
<form
method="POST"
action="/upload"
enctype="multipart/form-data"
id="uploadForm"
onsubmit="return false;"
>
<input type="file" name="file" id="fileInput" onchange="uploadFile()" />
<label id="fileInput-label" for="fileInput">Select a basket</label>
</form>
<!-- Anzeige von Meldungen nach dem Hochladen der Datei -->
<p id="uploadMessage"></p>
<!-- Button zum Öffnen der Unterseite /download_output -->
<button
id="downloadButton"
style="display: none"
onclick="openDownloadPage()"
>
Download Output
</button>
<label id="download-label" for="downloadButton" style="display: none"
>Download Output</label
>
<script>
const slider = document.getElementById("mySwitch");
slider.addEventListener("change", function () {
const newStatus = slider.checked;
updateSliderStatus(newStatus);
});
function updateSliderStatus(newStatus) {
fetch("/update_slider_status", {
method: "POST",
body: JSON.stringify({ fasttrack_status: newStatus }),
headers: {
"Content-Type": "application/json",
},
}).then((response) => {
if (response.ok) {
// Erfolgreiche Aktualisierung
console.log("Slider-Status aktualisiert");
} else {
// Fehler bei der Aktualisierung
console.error("Fehler bei der Aktualisierung des Slider-Status");
}
});
}
// Funktion zum Hochladen einer ausgewählten Datei
function uploadFile() {
const fileInput = document.getElementById("fileInput");
const file = fileInput.files[0];
if (file) {
const formData = new FormData();
formData.append("file", file);
// Senden des Formulardatenobjekts an den Server
sendFormData(formData);
}
}
// Funktion zum Senden von Formulardaten an den Server
function sendFormData(formData) {
fetch("/upload", {
method: "POST", // HTTP POST-Anfrage
body: formData, // Die Formulardaten, die die Datei enthalten
})
.then((response) => response.text())
.then((message) => {
// Anzeigen der Serverantwort (Nachricht) auf der Webseite
document.getElementById("uploadMessage").innerHTML = message;
clearFileInput(); // Zurücksetzen des Datei-Eingabefelds
// Anzeigen des Download-Buttons nach erfolgreichem Hochladen
document.getElementById("download-label").style.display = "block";
})
.catch((error) => {
console.error(error);
// Anzeigen einer Fehlermeldung im Falle eines Fehlers
document.getElementById("uploadMessage").textContent =
"Error during uploading the file.";
});
}
// Zurücksetzen des Datei-Eingabefelds
function clearFileInput() {
const fileInput = document.getElementById("fileInput");
fileInput.value = "";
}
// Funktion zum Verarbeiten des Ziehens und Ablegens von Dateien in den Bereich
function handleDrop(event) {
event.preventDefault();
const dropArea = document.getElementById("dropArea");
dropArea.style.borderColor = "#ccc"; // Ändern der Rahmenfarbe auf Grau
dropArea.classList.remove("dragover"); // Entfernen der Klasse für die Schraffierung
const formData = new FormData();
const file = event.dataTransfer.files[0];
if (file) {
formData.append("file", file);
// Senden des Formulardatenobjekts an den Server (ähnlich wie bei uploadFile)
sendFormData(formData);
}
}
// Funktion zum Erlauben des Ziehens von Dateien in den Bereich
function allowDrop(event) {
event.preventDefault();
const dropArea = document.getElementById("dropArea");
dropArea.style.borderColor = "blue"; // Ändern der Rahmenfarbe auf Blau
dropArea.classList.add("dragover"); // Hinzufügen der Klasse für die Schraffierung
}
// Funktion zum Verbieten des Ziehens von Dateien in den Bereich
function disallowDrop(event) {
event.preventDefault();
const dropArea = document.getElementById("dropArea");
dropArea.style.borderColor = "#ccc"; // Ändern der Rahmenfarbe auf Grau
dropArea.classList.remove("dragover"); // Entfernen der Klasse für die Schraffierung
}
// Funktion zum Öffnen der Unterseite /download_output
function openDownloadPage() {
window.location.href = "/download_output";
// Ausblenden des Buttons nach dem Klicken
document.getElementById("download-label").style.display = "none";
document.getElementById("uploadMessage").innerHTML = "";
}
</script>
</body>
</html>

BIN
Script/templates/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB