Shipping note/rework

This commit is contained in:
Luca Haid
2025-03-20 12:14:34 +00:00
parent 96ed8caaeb
commit d6d84088fb
13 changed files with 764 additions and 1020 deletions

View File

@@ -7,12 +7,14 @@ class WarehouseShippingNoteController extends TTCrud {
//@formatter:off
protected array $columns = [
['key' => 'id', 'text' => 'LS-Nr.', 'required' => false, 'modal' => false, 'table' => ['class' => 'text-nowrap']],
['key' => 'billingAddressId', 'text' => 'Rechnungsadresse', 'required' => true, 'type' => 'autocomplete', 'table' => ['class' => 'text-nowrap', 'filter' => 'autocomplete'], 'modal' => ['apiUrl' => 'Address/api?do=findAddress', 'items' => '/Address/Api?do=findAddress', 'type' => 'autocomplete']],
['key' => 'billingAddressId', 'text' => 'Rechnungsadresse', 'type' => 'autocomplete', 'table' => ['class' => 'text-nowrap', 'filter' => 'autocomplete'], 'modal' => ['apiUrl' => 'Address/api?do=findAddress', 'items' => '/Address/Api?do=findAddress', 'type' => 'autocomplete']],
['key' => 'status', 'text' => 'Status', 'required' => true, 'table' => ['filter' => 'iconSelect'], 'modal' => ['type' => 'iconSelect', 'items' => [
['value' => 'new', 'text' => 'Neu', 'icon' => 'fas fa-star text-primary'],
['value' => 'in_progress', 'text' => 'In Bearbeitung', 'icon' => 'fas fa-cog text-warning'],
['value' => 'accepted', 'text' => 'Akzeptiert', 'icon' => 'fas fa-check text-success'],
['value' => 'invoiced', 'text' => 'In Rechnung gestellt', 'icon' => 'fas fa-file-invoice-dollar text-info'],
['value' => 'cancelled', 'text' => 'Storniert', 'icon' => 'fas fa-ban text-danger'],
['value' => 'on_hold', 'text' => 'In Wartestellung', 'icon' => 'fas fa-pause text-warning'],
]]],
['key' => 'deliveryAddressName', 'text' => 'L.-Adr. Name', 'required' => true],
['key' => 'deliveryAddressLine', 'text' => 'L.-Adr.', 'required' => true],
@@ -26,11 +28,6 @@ class WarehouseShippingNoteController extends TTCrud {
protected array $defaultOrder = ['key' => 'create', 'order' => 'DESC'];
protected array $additionalActions = [['key' => 'openHistory', 'title' => 'Historie', 'class' => 'fas fa-history text-primary'],
['key' => 'print', 'title' => 'Drucken', 'class' => 'fas fa-print text-primary'],
['key' => 'printWithPrice', 'title' => 'Drucken mit Preis', 'class' => 'fas fa-print text-success'],
];
protected array $additionalJSVariables = ['WAREHOUSE_ADMIN' => true];
protected array $infoMessages = ['create' => 'Lieferschein wurde erstellt.',
@@ -40,189 +37,117 @@ class WarehouseShippingNoteController extends TTCrud {
//@formatter:on
protected function prepareCrudConfig() {
$users = array_map(function ($user) {
return ['value' => intval($user->id), 'text' => $user->name];
}, UserModel::search(['employee' => true]));
$this->columns[array_search('createBy', array_column($this->columns, 'key'))]['modal']['items'] = $users;
if (!$this->user->can('WarehouseAdmin')) {
$this->additionalJSVariables['WAREHOUSE_ADMIN'] = false;
}
if (!$this->user->can('WarehouseAdmin')) $this->additionalJSVariables['WAREHOUSE_ADMIN'] = false;
}
protected function beforeCreate($postData): bool {
// if postdata status is not new we return an error
if ($postData['status'] !== 'new') {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Status muss "Neu" sein']);
die();
}
foreach ($postData['hoursEntries'] as $hoursEntry) {
if (!preg_match('/^[0-9,.]*$/', $hoursEntry['hourCount'])) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Stundenanzahl darf nur Zahlen, Komma oder Punkt enthalten']);
die();
}
}
$this->validate($postData, [
fn($p) => $p['status'] === 'new' ?: 'Status muss "Neu" sein',
fn($p) => $this->validateHours($p['hoursEntries'])
]);
$postData['positions'] = json_encode($postData['positions']);
return true;
}
protected function customAutoCompleteBillingAddressId($id) {
$address = new Address($id);
if ($address->id) {
$result = ['id' => $address->id,
'title' => str_replace("'", "\\'", str_replace(["\n",
"\r"], " ", $address->getCompanyOrName())) . " (" . $address->zip . " " . $address->city . ", " . $address->street . ")" . (($address->customer_number) ? " [" . $address->customer_number . "]" : "")];
return $result;
}
return null;
}
protected function beforeUpdate($postData): bool {
$shippingNote = WarehouseShippingNoteModel::get($postData['id']);
if ($shippingNote->status === 'accepted' || $shippingNote->status === 'invoiced') {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Änderungen nicht mehr möglich']);
die();
}
foreach ($postData['hoursEntries'] as $hoursEntry) {
if (!preg_match('/^[0-9,.]*$/', $hoursEntry['hourCount'])) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Stundenanzahl darf nur Zahlen, Komma oder Punkt enthalten']);
die();
}
}
$this->validate($postData, [
fn($p) => !in_array(WarehouseShippingNoteModel::get($p['id'])->status,
['accepted', 'invoiced']) ?: 'Änderungen nicht mehr möglich',
fn($p) => $this->validateHours($p['hoursEntries'])
]);
$postData['positions'] = json_encode($postData['positions']);
(new WarehouseHistoryController)->create($postData, $this->mod);
return true;
}
protected function getHistoryAction() {
$historyEntries = [];
// remove all history elements where key is positions
foreach ((new WarehouseHistoryController)->getHistory($this->request->id, $this->mod, $this->columns) as $entry) {
if ($entry['key'] !== 'positions') {
$historyEntries[] = $entry;
private function validateHours($entries): bool {
foreach ($entries as $e) {
if (!preg_match('/^[\d,.]*$/', $e['hourCount'])) {
$this->sendError('Stundenanzahl darf nur Zahlen, Komma oder Punkt enthalten');
}
}
return true;
}
// $historyEntries = array_filter($historyEntries, function ($entry) {
// return $entry['key'] !== 'positions';
// });
private function validate($data, array $rules): void {
foreach ($rules as $rule) {
if (($result = $rule($data)) !== true) {
$this->sendError(is_string($result) ? $result : 'Validation failed');
}
}
}
self::returnJson($historyEntries);
protected function customAutoCompleteBillingAddressId($id) {
$address = new Address($id);
if (!$address->id) return null;
return [
'id' => $address->id,
'title' => sprintf(
"%s (%s %s, %s)%s",
str_replace(["'", "\n", "\r"], ["\\'", ' ', ' '], $address->getCompanyOrName()),
$address->zip,
$address->city,
$address->street,
$address->customer_number ? " [{$address->customer_number}]" : ''
)
];
}
protected function getHistoryAction() {
self::returnJson(array_values(
array_filter(
(new WarehouseHistoryController)->getHistory($this->request->id, $this->mod, $this->columns),
fn($e) => $e['key'] !== 'positions'
)
));
}
protected function getArticleAddressPriceAction() {
$articleId = $this->request->articleId;
$addressId = $this->request->addressId;
empty($this->request->articleId) && $this->sendError('Keine Artikel ID gefunden');
empty($this->request->addressId) && $this->sendError('Keine Adress ID gefunden');
if (strlen($articleId) < 1) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Keine Artikel ID gefunden']);
}
// TODO: we use verkauf as default now, later we will need to use from address
$priceTypes = WarehouseArticlePriceTypeModel::getAll(['title' => 'Verkauf']);
if (empty($priceTypes)) $this->sendError('Keine Preiskategorie gefunden');
$priceType = $priceTypes[0]->title;
if (strlen($addressId) < 1) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Keine Adress ID gefunden']);
}
$article = WarehouseArticleModel::get($this->request->articleId);
$prices = json_decode($article->cheapestSellPrice, true);
//TODO: implement a select to select price category for each address
// for now we default with price with name "Verkauf"
$prices = WarehouseArticlePriceTypeModel::getAll(['title' => 'Verkauf']);
// if array is empty we return an error
if (empty($prices)) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Keine Preiskategorie gefunden']);
}
$priceType = $prices[0]->title;
foreach ($prices as $price)
if ($price['title'] === $priceType)
self::returnJson(['success' => true, 'price' => $price['price']]);
$article = WarehouseArticleModel::get($articleId);
$sellPrices = json_decode($article->cheapestSellPrice, true);
$sellPrice = array_search($priceType, array_column($sellPrices, 'title'));
if (empty($sellPrice)) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Kein Preis gefunden']);
}
self::returnJson(['success' => true, 'price' => $sellPrices[$sellPrice]['price']]);
}
protected function getDeliveryAddressesAction() {
$billingAddressId = $this->request->billingAddressId;
if (strlen($billingAddressId) < 1) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Keine Rechnungsadresse gefunden']);
}
$deliveryAddresses = WarehouseShippingNoteModel::getAll(['billingAddressId' => $billingAddressId]);
// TODO: maybe this should be improved as it is kinda hacky
$result = [];
foreach ($deliveryAddresses as $deliveryAddress) {
$found = false;
foreach ($result as $r) {
if ($r->deliveryAddressName == $deliveryAddress->deliveryAddressName && $r->deliveryAddressLine == $deliveryAddress->deliveryAddressLine) {
$found = true;
break;
}
}
if ($found) {
continue;
}
$result[] = $deliveryAddress;
}
self::returnJson($result);
}
protected function getAllTextElementsAction() {
$textElements = WarehouseShippingNoteTextElementModel::getAll();
self::returnJson($textElements);
$this->sendError('Kein Preis gefunden');
}
protected function signAction() {
$id = $this->request->id;
if (strlen($id) < 1) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Lieferschein wurde nicht gefunden']);
}
$shippingNote = WarehouseShippingNoteModel::get($id);
if (empty($id) || !$shippingNote = (array) WarehouseShippingNoteModel::get($id)) $this->sendError('Lieferschein nicht gefunden');
if ($shippingNote["signature"] || $shippingNote["signatureName"]) $this->sendError('Bereits unterschrieben');
if ($shippingNote->signature || $shippingNote->signatureName) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Lieferschein wurde bereits unterschrieben']);
}
$post = json_decode(file_get_contents('php://input'), true);
$shippingNote = (array) $shippingNote;
$shippingNote['signature'] = $post['signature'];
$shippingNote['signatureName'] = $post['signatureName'];
if (strlen($shippingNote['signature']) < 1 || strlen($shippingNote['signatureName']) < 1) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Unterschrift oder Name fehlt']);
if (empty($post['signature']) || empty($post['signatureName'])) {
$this->sendError('Unterschrift/Name fehlt');
}
try {
$shippingNote['signatureDate'] = date("Y-m-d");
WarehouseShippingNoteModel::update($shippingNote);
self::returnJson(['success' => true, 'message' => 'Unterschrift wurde gespeichert']);
WarehouseShippingNoteModel::update(array_merge($shippingNote, ['signature' => $post['signature'], 'signatureName' => $post['signatureName'], 'signatureDate' => date('Y-m-d')]));
self::returnJson(['success' => true, 'message' => 'Unterschrift gespeichert']);
} catch (Exception $e) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Unterschrift konnte nicht gespeichert werden']);
$this->sendError('Speichern fehlgeschlagen');
}
}
private function sendSuccess(string $message) {
self::returnJson(['success' => true, 'message' => $message]);
}
public function createPDFAction($returnFilename = false, $idOverride = null) {
$id = $idOverride ?? $this->request->id;
if (strlen($id) < 1) {
@@ -231,7 +156,7 @@ class WarehouseShippingNoteController extends TTCrud {
}
$shippingNote = WarehouseShippingNoteModel::get($id);
$address = AddressModel::getOne($shippingNote->billingAddressId);
if (!empty($shippingNote->billingAddressId)) $address = AddressModel::getOne($shippingNote->billingAddressId);
$positions = [];
// loop through all positions and add articleTitle and articleDescription to each position entry
@@ -265,6 +190,7 @@ class WarehouseShippingNoteController extends TTCrud {
}
}
// json decode hoursEntries and add to positions
$hoursEntries = json_decode($shippingNote->hoursEntries, true);
foreach ($hoursEntries as $hoursEntry) {
@@ -274,31 +200,64 @@ class WarehouseShippingNoteController extends TTCrud {
$articleTitle = "Arbeitsstunden (50% Zuschlag)";
} elseif (isset($hoursEntry['priceType']) && $hoursEntry['priceType'] == 100) {
$articleTitle = "Arbeitsstunden (100% Zuschlag)";
} elseif (isset($hoursEntry['hourType']) && $hoursEntry['hourType'] == '50') {
$articleTitle = "Arbeitsstunden (+50% Zuschlag)";
} elseif (isset($hoursEntry['hourType']) && $hoursEntry['hourType'] == '100') {
$articleTitle = "Arbeitsstunden (+100% Zuschlag)";
} elseif (isset($hoursEntry['hourType']) && $hoursEntry['hourType'] == 'regie') {
$articleTitle = "Arbeitsstunden (Regie)";
}
if (floatval(str_replace(",", ".", $hoursEntry['hourCount'])) > 0) {
$userText = '';
if (!empty($hoursEntry['userId'])) {
$user = UserModel::getOne($hoursEntry['userId']);
$userText = $user->name;
} else {
$userText = $hoursEntry['userId_text'];
}
$articleDescription = "Datum: ". date("d.m.Y", strtotime($hoursEntry['date'])) . " | Mitarbeiter: " . $userText;
if (isset($hoursEntry['comment'])) {
$articleDescription .= " | Zusatz: " . $hoursEntry['comment'];
}
$positions[] = [
'articleTitle' => $articleTitle,
'articleDescription' => "Datum: ". date("d.m.Y", strtotime($hoursEntry['date'])) . " | Mitarbeiter: " . UserModel::getOne($hoursEntry['userId'])->name,
'articleDescription' => $articleDescription,
'articleUnit' => 'Std.',
'amount' => $hoursEntry['hourCount'],
'price' => $hoursEntry['hourlyPrice'] * $hoursEntry['hourCount'] ?? 0,
];
}
if ($hoursEntry['carId']) {
if (!empty($hoursEntry['externalCar']) && !empty($hoursEntry['kilometerCount']) && $hoursEntry['kilometerCount'] > 0 && $hoursEntry['externalCar'] == 1) {
$positions[] = [
'articleTitle' => "Fahrkostenpauschale (hin und retour)",
'articleDescription' => "Datum: ". date("d.m.Y", strtotime($hoursEntry['date'])) . " | Externes Fahrzeug",
'articleUnit' => 'km',
'amount' => $hoursEntry['kilometerCount'] * 2,
'price' => 2 * $hoursEntry['kilometerCount'] ?? 0,
];
} else if (!empty($hoursEntry['carId']) && $hoursEntry['kilometerCount'] > 0) {
$hoursEntry['carId'] = intval($hoursEntry['carId']);
$positions[] = [
'articleTitle' => "Fahrkostenpauschale (hin und retour)",
'articleDescription' => "Datum: ". date("d.m.Y", strtotime($hoursEntry['date'])) . " | Fahrzeug: " . TimerecordingCarModel::getOne($hoursEntry['carId'])->number_plate,
'articleUnit' => 'Km',
'articleUnit' => 'km',
'amount' => $hoursEntry['kilometerCount'] * 2,
'price' => 2 * $hoursEntry['kilometerCount'] ?? 0,
];
} else if (!empty($hoursEntry['carId_text']) && $hoursEntry['kilometerCount'] > 0) {
$positions[] = [
'articleTitle' => "Fahrkostenpauschale (hin und retour)",
'articleDescription' => "Datum: ". date("d.m.Y", strtotime($hoursEntry['date'])) . " | Fahrzeug: " . $hoursEntry['carId_text'],
'articleUnit' => 'km',
'amount' => $hoursEntry['kilometerCount'] * 2,
'price' => 2 * $hoursEntry['kilometerCount'] ?? 0,
];
}
}
usort($positions, function ($a, $b) {
$aHasMitarbeiter = str_contains($a['articleDescription'], 'Mitarbeiter');
$bHasMitarbeiter = str_contains($b['articleDescription'], 'Mitarbeiter');
@@ -347,12 +306,13 @@ class WarehouseShippingNoteController extends TTCrud {
$headerHtml = str_replace("{{ addressLine_3 }}", $shippingNote->deliveryAddressPLZ . " " . $shippingNote->deliveryAddressCity, $headerHtml);
$headerHtml = str_replace("{{ addressLine_4 }}", "", $headerHtml);
$headerHtml = str_replace("{{ addressLine_5 }}", "", $headerHtml);
$headerHtml = str_replace("{{ billingAddressLine_1 }}", $address->getCompanyOrName(), $headerHtml);
$headerHtml = str_replace("{{ billingAddressLine_2 }}", $address->street, $headerHtml);
$headerHtml = str_replace("{{ billingAddressLine_3 }}", $address->zip . " " . $address->city, $headerHtml);
$headerHtml = str_replace("{{ billingAddressHeader }}", !isset($address) ? '' : "Rechnungsadresse", $headerHtml);
$headerHtml = str_replace("{{ billingAddressLine_1 }}", !isset($address) ? '' : $address->getCompanyOrName(), $headerHtml);
$headerHtml = str_replace("{{ billingAddressLine_2 }}", !isset($address) ? '' : $address->street, $headerHtml);
$headerHtml = str_replace("{{ billingAddressLine_3 }}", !isset($address) ? '' : $address->zip . " " . $address->city, $headerHtml);
$headerHtml = str_replace("{{ billingAddressLine_4 }}", "", $headerHtml);
$headerHtml = str_replace("{{ billingAddressLine_5 }}", "", $headerHtml);
$headerHtml = str_replace("{{ customerNumber }}", $address->customer_number, $headerHtml);
$headerHtml = str_replace("{{ customerNumber }}", !isset($address) ? '' : $address->customer_number, $headerHtml);
$headerHtml = str_replace("{{ shippingNoteNumber }}", $shippingNoteNumber, $headerHtml);
$headerHtml = str_replace("{{ shippingNoteDate }}", date("d.m.Y", $shippingNote->create), $headerHtml);
@@ -434,6 +394,8 @@ class WarehouseShippingNoteController extends TTCrud {
'in_progress' => 'In Bearbeitung',
'accepted' => 'Akzeptiert',
'invoiced' => 'In Rechnung gestellt',
'cancelled' => 'Storniert',
'on_hold' => 'In Wartestellung',
];
self::returnJson(['success' => true, 'message' => 'Status wurde auf ' . $statusNiceText[$status] . ' geändert']);
}
@@ -465,9 +427,8 @@ class WarehouseShippingNoteController extends TTCrud {
protected function timerecordingCarForUserAction() {
$timerecordingCars = TimerecordingCarModel::getAll();
$out = null;
foreach ($timerecordingCars as $timerecordingCar) {
if ($timerecordingCar->user_id == $this->user->id) {
if ($timerecordingCar->user_id == $this->request->userId) {
header('Content-Type: application/json');
die(json_encode(['success' => true, 'id' => $timerecordingCar->id]));
}
@@ -502,7 +463,7 @@ class WarehouseShippingNoteController extends TTCrud {
$lon = $this->request->lon;
$url = "https://nominatim.haid.in/reverse?lat=$lat&lon=$lon&format=json";
$data = json_decode(file_get_contents($url), true);
self::returnJson($data);
self::returnJson(is_array($data) ? $data : ['data' => $data]);
}
@@ -587,4 +548,51 @@ class WarehouseShippingNoteController extends TTCrud {
self::returnJson(['success' => true, 'distance' => $roundedDistanceKm]);
}
protected function uploadFileAction() {
$file = $_FILES['file'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
self::returnJson(['error' => 'File upload failed']);
exit;
}
try {
$uploaded = mfUpload::handleFormUpload("file", false, "/WarehouseShippingNote");
self::returnJson(['success' => true, 'fileId' => $uploaded->id]);
} catch (Exception $e) {
self::returnJson(['error' => 'Upload error: ' . $e->getMessage()]);
}
}
protected function createNewLogAction() {
$postData = json_decode(file_get_contents('php://input'), true);
if (empty($postData['shippingNoteId'])) {
self::returnJson(['success' => false, 'message' => 'ShippingNoteId fehlt']);
return;
}
$log = [
"table" => "WarehouseShippingNote",
"rowId" => intval($postData['shippingNoteId']),
"type" => 'noChanges',
"fileIds" => $postData['fileIds'] ?? null,
"message" => $postData['note'] ?? null,
"createBy" => intval($this->user->id),
"create" => time()
];
WarehouseLogModel::create($log);
self::returnJson(['success' => true, 'message' => 'Logeintrag erfolgreich erstellt']);
}
protected function getLogAction() {
$shippingNoteId = $this->request->shippingNoteId;
if (empty($shippingNoteId)) {
self::returnJson(['success' => false, 'message' => 'ShippingNoteId fehlt']);
return;
}
$logs = WarehouseLogModel::getAll(['table' => 'WarehouseShippingNote','rowId' => $shippingNoteId], null, 0, ['order' => 'DESC', 'key' => 'create']);
self::returnJson($logs);
}
}

View File

@@ -2,7 +2,7 @@
class WarehouseShippingNoteModel extends TTCrudBaseModel {
public int $id;
public int $billingAddressId;
public ?int $billingAddressId;
public string $deliveryAddressName;
public string $deliveryAddressLine;
public string $deliveryAddressPLZ;