Files
YMS/webgui/equipment.php
T
2024-04-09 10:26:32 +02:00

475 lines
18 KiB
PHP

<?php
/******************************************************************************
* YMS - Yacht Management Software
* Copyright (C) 2024 Thomas Hooge
*
* SPDX-License-Identifier: WTFPL
******************************************************************************/
require 'globals.inc';
$pagetitle = _('Equipment');
$id = gpc_get_int($_REQUEST, 'id', 0);
$opt_supplier = db_get_opt_supp(array(-1 => _('unknown')));
$opt_manufacturer = db_get_opt_manuf(array(-1 => _('unknown')));
$opt_ecat = db_get_options(4); // Equipment categories
// ========== ACTIONS START ===================================================
switch ($submit = form_get_action()) {
case NULL: break;
case 'add': $action = ACT_ADD; break;
case 'view': $action = ACT_VIEW; break;
case 'edit': $action = ACT_EDIT; break;
case 'del': $action = ACT_DELETE; break;
case 'insert':
$ename = gpc_get_string($_POST, 'ename');
$ecat = gpc_get_int($_POST, 'category');
$manufacturer = gpc_get_int($_POST, 'manufacturer');
$model = gpc_get_string($_POST, 'model');
$remarks = gpc_get_string($_POST, 'remarks', 150);
$sql = "INSERT INTO equipment "
. " (vid, ename, manufacturer, model, ecat, remarks) "
. "VALUES "
. " (:vid, :ename, :manufacturer, :model, :ecat, :remarks)";
$sth = $pdo->prepare($sql);
$sth->bindValue(':vid', $user->vid, PDO::PARAM_INT);
$sth->bindValue(':ename', $ename, PDO::PARAM_STR);
$sth->bindValue(':model', $model, PDO::PARAM_STR);
$sth->bindValue(':ecat', $ecat, PDO::PARAM_INT);
$sth->bindValue(':manufacturer', $manufacturer, PDO::PARAM_INT);
$sth->bindValue(':remarks', $remarks, PDO::PARAM_STR);
try {
$sth->execute();
} catch (PDOException $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
}
$id = $pdo->lastInsertId();
$action = ACT_VIEW;
break;
case 'update':
$ename = gpc_get_string($_POST, 'ename');
$model = gpc_get_string($_POST, 'model');
$serial = gpc_get_string($_POST, 'serial');
$weight = min(gpc_get_float($_POST, 'weight'), 999.99); // limit max value
$price = gpc_get_currency($_POST, 'price');
$purchdate = gpc_get_date($_POST, 'purchdate');
$supplier = gpc_get_int($_POST, 'supplier');
$manufacturer = gpc_get_int($_POST, 'manufacturer');
$ecat = gpc_get_int($_POST, 'category');
$remarks = gpc_get_string($_POST, 'remarks', 150);
$sql = "UPDATE equipment "
. "SET ename=:ename,"
. " model=:model,"
. " serial=:serial,"
. " weight=:weight,"
. " price=:price,"
. " purchdate=:purchdate,"
. " supplier=:supplier,"
. " manufacturer=:manufacturer,"
. " ecat=:ecat,"
. " remarks=:remarks "
. "WHERE eid=:eid";
$sth = $pdo->prepare($sql);
$sth->bindValue(':eid', $id, PDO::PARAM_INT);
$sth->bindValue(':ename', $ename, PDO::PARAM_STR);
$sth->bindValue(':model', $model, PDO::PARAM_STR);
$sth->bindValue(':serial', $serial, PDO::PARAM_STR);
$sth->bindValue(':weight', $weight);
$sth->bindValue(':price', $price);
$sth->bindValue(':purchdate', $purchdate, PDO::PARAM_STR);
$sth->bindValue(':supplier', $supplier, PDO::PARAM_INT);
$sth->bindValue(':manufacturer', $manufacturer, PDO::PARAM_INT);
$sth->bindValue(':ecat', $ecat, PDO::PARAM_INT);
$sth->bindValue(':remarks', $remarks, PDO::PARAM_STR);
try {
$sth->execute();
} catch (PDOException $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
}
$action = ACT_VIEW;
break;
case 'delete':
// Security token needed!
if (gpc_get_string($_POST, 'token', 16) != $_SESSION['token']) {
$g_error->Add(_('Delete prohibited, invalid security token!'));
$action = ACT_VIEW;
break;
}
unset($_SESSION['token']);
$sth = $pdo->prepare("DELETE FROM docref WHERE reftype='equipment' AND refid=?");
try {
$sth->execute([$id]);
} catch (PDOException $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
}
$refcount = $sth->rowCount();
$sth = $pdo->prepare("DELETE FROM equipment WHERE eid=?");
try {
$sth->execute([$id]);
} catch (PDOException $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
}
$g_message->Add(sprintf(_('Deleted equipment no. %d'), $id));
if ($refcount > 0) {
$g_message->Add(sprintf(_('%d document links were removed'), $refcount));
}
$action = ACT_DEFAULT;
break;
case 'upload':
$action = ACT_VIEW;
if (!isset($_FILES['files'])) {
$g_warning->Add(_('No files for upload submitted'));
break;
}
$extensions = ['jpg', 'png'];
$mimetypes = ['image/png', 'image/jpeg', 'image/svg+xml', 'application/pdf'];
$all_files = count($_FILES ["files"]["tmp_name"]);
$nerr = 0;
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));
// $file = $g_doc_basepath . '/' . $file_name;
$file_mimetype = mime_content_type($file_tmp);
if (!in_array($file_mimetype, $mimetypes)) {
$g_error->Add(sprintf(_("Mimetype '%s' not allowed for upload."), $file_mimetype));
$nerr += 1;
}
if (!in_array($file_ext, $extensions)) {
$g_error->Add(_('Filetype not allowed for upload:') . ' ' . $file_type);
$nerr += 1;
}
if ($file_size > 2097152) {
$g_error->Add(sprintf(_('File to big: %s.%s'), $file_name, $file_type));
$nerr += 1;
}
if ($nerr > 0) {
break;
}
$file_hash = md5_file($file_tmp);
$file_timestamp = date('Y-m-d H:i:s', filemtime($file_tmp));
// check whether the file already exists, in this case issue
// a message and just create a link to the already known file
$sql = "SELECT docid FROM document WHERE hash=?";
$sth = $pdo->prepare($sql);
$sth->execute([$file_hash]);
$row = $sth->fetch();
if (!$row) {
$sql = "INSERT INTO document"
. " (doctype, filename, extension, hash, doctime, docsize, mimetype) "
. "VALUES"
. " (?, ?, ?, ?, ?, ?, ?)";
$sth = $pdo->prepare($sql);
$sth->execute(['picture', $file_name, $file_ext, $file_hash, $file_timestamp, $file_size, $file_mimetype]);
$docid = $pdo->lastInsertId();
$file_techname = $g_doc_basepath . '/pic-'.$file_hash.'.'.$file_ext;
move_uploaded_file($file_tmp, $file_techname);
} else {
// A document record definitely exists here, now just
// connect it to the selected equipment
$docid = $row['docid'];
}
$sql = "INSERT INTO docref (docid, refid) VALUES (?, ?)";
$sth = $pdo->prepare($sql);
// Reference may already exist!
try {
$sth->execute([$docid, $id]);
} catch (PDOException $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
}
} // for
break;
default:
$g_error->Add(sprintf(_('Unknown function!'), $submit));
$valid = FALSE;
}
// ========== ACTIONS END =====================================================
require 'header.php';
// ========== PAGE CONTENT ====================================================
if ($action == ACT_DEFAULT):
// ========== VARIANT: default behavior =======================================
$sql = "SELECT eid, ename, manufacturer, model, serial, remarks,"
. " TIMESTAMPDIFF(MONTH, purchdate, NOW()) AS age_mon "
. "FROM equipment WHERE vid=? "
. "ORDER BY eid";
$sth = $pdo->prepare($sql);
$sth->execute([$user->vid]);
$res = $sth->fetchAll();
echo "<h1>$pagetitle</h1>\n";
// Filter
?>
<form method="post">
<div id="filter" class="card">
<div class="card-header">Filter</div>
<div class="card-body">
<label>Category</label>
<select>
<?php
foreach ($opt_ecat as $k => $v) {
echo '<option value="', $k,'">', $v, '</option>';
}
?>
</select>
<button class="btn btn-sm btn-primary" title="<?=_('Apply')?>">Go</button>
</div>
</div>
</form>
<?php
// Data
echo '<table class="table table-striped">', "\n";
echo "<thead>\n";
echo "<tr>";
echo "<th>" . _('Description') . "</th>";
echo "<th>" . _('Manufacturer') . "</th>";
echo "<th>" . _('Model') . "</th>";
echo "<th>" . _('Serial') . "</th>";
echo "<th>" . _('Age') . "</th>";
echo "<th>" . _('Remarks') . "</th>";
echo "<th>&nbsp;</th>";
echo "</tr>\n";
echo "</thead>\n";
foreach ($res as $row) {
// calc nice age display
if (!isset($row['age_mon'])) {
$age = '';
} elseif ($row['age_mon'] < 12) {
$age = sprintf(_('%dm'), $row['age_mon']);
} else {
$age = sprintf(_('%dy'), intdiv($row['age_mon'], 12));
}
echo "<tr>\n";
echo "<td>". $row['ename'] ."</td>\n";
echo "<td>". $opt_manufacturer[$row['manufacturer']] ."</td>\n";
echo "<td>". $row['model'] ."</td>\n";
echo "<td>". $row['serial'] ."</td>\n";
echo "<td>". $age ."</td>\n";
echo "<td>". $row['remarks'] ."</td>\n";
// Action buttons
form_action_buttons($g_scriptname, $row['eid']);
}
?>
<tfoot>
<tr><td colspan="6"><?php printf(_('%d records'), count($res)); ?></td></tr>
</tfoot>
</table>
<nav>
<ul class="pagination justify-content-center">
<li class="page-item"><a class="page-link" href="#">Previous</a></li>
<li class="page-item"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">Next</a></li>
</ul>
</nav>
<?php
form_add_button($g_scriptname);
elseif ($action == ACT_ADD):
// ========== VARIANT: add record =============================================
?>
<h2><?=_('Add Equipment')?></h2>
<form method="post">
<div class="mb-3">
<label for="ename" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="ename" name="ename">
</div>
<?php
form_create_select('category', _('Category'), $opt_ecat);
form_create_select('manufacturer', _('Manufacturer'), $opt_manufacturer);
?>
<div class="mb-3">
<label for="model" class="form-label"><?=_('Model')?></label>
<input type="text" class="form-control" id="model" name="model">
</div>
<div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"></textarea>
</div>
<div class="container-fluid px-0 my-3">
<button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button>
<a href="<?=$g_scriptname?>" class="btn btn-secondary"><?=_('Back')?></a>
</div>
</form>
<?php
elseif ($action == ACT_VIEW):
// ========== VARIANT: view single record =====================================
$sql = "SELECT eid, ename, model, serial, purchdate, price, weight, "
. " supplier, manufacturer, ecat, remarks "
. "FROM equipment "
. "WHERE eid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
$equipment = $sth->fetch(PDO::FETCH_OBJ);
echo "<h2>", $equipment->ename, "</h2>\n";
// Bootstrap grid
echo '<div class="container">';
echo '<div class="row">';
echo '<div class="col">';
echo '<table class="table">', "\n";
echo '<tr><th>', _('Manufacturer'),"</th><td>", $opt_manufacturer[$equipment->manufacturer], "</td></tr>\n";
echo '<tr><th>', _('Model'),"</th><td>", $equipment->model, "</td></tr>\n";
echo '<tr><th>', _('Serial'),"</th><td>", $equipment->serial, "</td></tr>\n";
echo '<tr><th>', _('Weight'),"</th><td>", format_float($equipment->weight, 2, 'kg'), "</td></tr>\n";
echo '<tr><th>', _('Price'),"</th><td>", format_currency($equipment->price), "</td></tr>\n";
echo '<tr><th>', _('Purchase date'),"</th><td>", $equipment->purchdate, "</td></tr>\n";
echo '<tr><th>', _('Supplier'),"</th><td>", $opt_supplier[$equipment->supplier], "</td></tr>\n";
echo '<tr><th>', _('Category'),"</th><td>", $opt_ecat[$equipment->ecat], "</td></tr>\n";
echo '<tr><th>', _('Remarks'),"</th><td>", $equipment->remarks, "</td></tr>\n";
echo "</table>\n";
echo '</div>'; // Column break
echo '<div class="col">';
?>
<p>Images and documents go here</p>
<?php
$sql = "SELECT d.docid, d.doctype, d.title "
. "FROM docref AS r INNER JOIN document AS d using (docid) "
. "WHERE r.refid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
$res = $sth->fetchAll();
foreach ($res as $row) {
if ($row['doctype'] == 'picture') {
echo '<a href="dl.php?id=', $row['docid'], '">';
// echo '<img width="120" src="doc/pic-', $row['hash'], '.', $row['extension'],'">';
echo '<img width="120" src="dl.php?id=', $row['docid'], '" alt="', $row['title'], '">';
echo "</a>\n";
} elseif ($row['doctype'] == 'generic') {
echo '<a href="dl.php?id=', $row['docid'], '">';
echo $row['title'];
echo "</a>\n";
}
}
?>
<form method="post" enctype="multipart/form-data" action="<?=$g_scriptname?>">
<input type="hidden" name="id" value="<?=$id?>">
<div class="card">
<div class="card-body">
<input type="file" name="files[]" multiple accept="image/*" capture="camera">
<input type="submit" name="submit[upload]" value="Upload">
</div>
</div>
</form>
<?php
echo '</div>'; // col
echo '</div>'; // row
echo '</div>'; // container
// Buttons at bottom of data area
form_view_buttons($g_scriptname, $id);
elseif ($action == ACT_EDIT):
// ========== VARIANT: edit single record =====================================
$sql = "SELECT compid, compname FROM company WHERE comptype=1 ORDER BY compname";
$sth = $pdo->query($sql);
$supplier = array();
foreach ($sth->fetchAll() as $row) {
$supplier[$row['compid']] = $row['compname'];
}
$sql = "SELECT eid, ename, model, serial, weight, price, purchdate,"
. " supplier, manufacturer, ecat, remarks "
. "FROM equipment "
. "WHERE eid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
$equipment = $sth->fetch(PDO::FETCH_OBJ);
?>
<h2><?=_('Edit Equipment')?></h2>
<form method="post" action="<?=$g_scriptname?>">
<input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3">
<label for="ename" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="ename" name="ename" value="<?=$equipment->ename ?>">
</div>
<?php form_create_select('manufacturer', _('Manufacturer'), $opt_manufacturer, $equipment->manufacturer); ?>
<div class="mb-3">
<label for="model" class="form-label"><?=_('Model')?></label>
<input type="text" class="form-control" id="model" name="model" value="<?=$equipment->model ?>">
</div>
<div class="mb-3">
<label for="serial" class="form-label"><?=_('Serial')?></label>
<input type="text" class="form-control" id="serial" name="serial" value="<?=$equipment->serial ?>">
</div>
<div class="mb-3">
<label for="weight" class="form-label"><?=_('Weight, kg')?></label>
<input type="text" class="form-control" id="weight" name="weight" value="<?=format_float($equipment->weight); ?>">
</div>
<div class="mb-3">
<label for="price" class="form-label"><?=sprintf(_('Price, %s'), $g_lconv['currency_symbol']); ?></label>
<input type="text" class="form-control" id="price" name="price" value="<?=format_float($equipment->price) ?>">
</div>
<div class="mb-3">
<label for="purchdate"><?=_('Purchase date')?></label>
<input type="date" class="form-control" id="startdate" name="purchdate" value="<?=$equipment->purchdate ?>">
</div>
<?php
form_create_select('supplier', _('Supplier'), $opt_supplier, $equipment->supplier);
form_create_select('category', _('Category'), $opt_ecat, $equipment->ecat);
?>
<div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$equipment->remarks ?></textarea>
</div>
<button type="submit" name="submit[update]" class="btn btn-primary"><?=_('Save')?></button>
<a href="<?=$g_scriptname?>?f=view&id=<?=$id?>" class="btn btn-secondary"><?=_('Back')?></a>
</form>
<?php
elseif ($action == ACT_DELETE):
// ========== VARIANT: delete record ==========================================
$_SESSION['token'] = bin2hex(random_bytes(8));
$sql = "SELECT ename, remarks FROM equipment WHERE eid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
$equipment = $sth->fetch(PDO::FETCH_OBJ);
echo '<h2>', _('Delete equipment'),"</h2>\n";
echo '<p>', sprintf(_('Record no. %d'), $id), "</p>\n";
echo '<p>Name: ', $equipment->ename, "</p>";
echo '<p>Remarks: ', $equipment->remarks, "</p>";
echo '<p>', _('Deleting an equipment item is final. There is no way back. Only delete if you are absolute sure.'), "</p>\n";
form_delete_buttons($g_scriptname, $id, $_SESSION['token']);
else:
// ========== ERROR UNKNOWN VARIANT ===========================================
echo '<p>', _('Unknown function call: Please report to system development!'), "</p>\n";
endif; // $action == ...
// ========== END OF VARIANTS =================================================
include 'footer.php';