Files
YMS/webgui/equipment.php
T
2024-04-19 13:25:56 +02:00

556 lines
20 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 'filter':
$flt = array();
$flt['cat'] = gpc_get_int($_POST, 'flt_category');
$flt['manuf'] = gpc_get_int($_POST, 'flt_manuf');
$flt['supp'] = gpc_get_int($_POST, 'flt_supp');
$flt['txt'] = gpc_get_string($_POST, 'flt_txt');
db_save_filter($flt, 200);
$action = ACT_DEFAULT;
break;
case 'insert':
$p[':vid'] = $user->vid;
$p[':ename'] = gpc_get_string($_POST, 'ename');
$p[':ecat'] = gpc_get_int($_POST, 'category');
$p[':manufacturer'] = gpc_get_int($_POST, 'manufacturer');
$p[':model'] = gpc_get_string($_POST, 'model');
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
$id = db_exec_insert('equipment', $p);
$action = ACT_VIEW;
break;
case 'update':
$p[':eid'] = $id;
$p[':ename'] = gpc_get_string($_POST, 'ename');
$p[':shortname'] = gpc_get_string($_POST, 'shortname', 20);
$p[':model'] = gpc_get_string($_POST, 'model');
$p[':serial'] = gpc_get_string($_POST, 'serial');
$p[':weight'] = min(gpc_get_float($_POST, 'weight'), 999.99); // limit max value
$p[':price'] = gpc_get_currency($_POST, 'price');
$p[':purchdate'] = gpc_get_date($_POST, 'purchdate');
$p[':supplier'] = gpc_get_int($_POST, 'supplier');
if ($p[':supplier'] <= 0) $p[':supplier'] = NULL;
$p[':manufacturer'] = gpc_get_int($_POST, 'manufacturer');
if ($p[':manufacturer'] <= 0) $p[':manufacturer'] = NULL;
$p[':ecat'] = gpc_get_int($_POST, 'category');
if ($p[':ecat'] <= 0) $p[':ecat'] = NULL;
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
db_exec_update('equipment', $p, 'eid');
$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 =======================================
// load filter from db
$flt = db_get_filter($user->id, 200);
$sort = array(
1 => 'ename',
2 => 'ename DESC'
);
$w = array('vid=:vid');
$p = array(':vid' => $user->vid);
if ($flt->cat == -1) {
$w[] = 'ecat IS NULL';
} elseif ($flt->cat > 0) {
$w[] = 'ecat=:ecat';
$p[':ecat'] = $flt->cat;
}
if ($flt->manuf > 0) {
$w[] = 'manufacturer=:manuf';
$p[':manuf'] = $flt->manuf;
}
if ($flt->supp > 0) {
$w[] = 'supplier=:supp';
$p[':supp'] = $flt->supp;
}
if (strlen($flt->txt) > 1) {
$w[] = '(ename LIKE :txt OR model LIKE :txt OR remarks LIKE :txt)';
$p[':txt'] = '%'.$flt->txt.'%';
}
$where = join(' AND ', $w);
$order = ' ORDER BY ename';
// get total recond count for pagination and limit
$sth = $pdo->prepare("SELECT COUNT(*) FROM equipment WHERE " . $where);
try {
$sth->execute($p);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
$g_error->Add($sql);
$g_error->Add(print_r($p, true));
}
$numrows = $sth->fetchColumn();
$lastpage = ceil($numrows/$g_rows_pp);
$page = gpc_get_int($_REQUEST, 'p', 1);
$sql = "SELECT eid, ename, manufacturer, model, serial, remarks,"
. " TIMESTAMPDIFF(MONTH, purchdate, NOW()) AS age_mon "
. "FROM equipment";
$sql .= ' WHERE ' . $where;
$sql .= $order;
// if pagination:
$sql .= ' LIMIT ' . ($page - 1) * $g_rows_pp . ',' . $g_rows_pp;
$sth = $pdo->prepare($sql);
$sth->execute($p);
$res = $sth->fetchAll();
echo "<h1>$pagetitle</h1>\n";
// Filter
$opt_special = array(
-2 => _('&horbar; all &horbar;'),
-1 => _('&horbar; none &horbar;')
);
?>
<form method="post" action="<?=$g_scriptname?>">
<div id="filter" class="card">
<div class="card-header">Filter</div>
<div class="card-body">
<label for="flt_category">Category</label>
<select id="flt_category" name="flt_category">
<?php
foreach ($opt_special + $opt_ecat as $k => $v) {
echo '<option value="', $k, '"';
if ($k == $flt->cat) {
echo ' selected';
}
echo '>', $v, '</option>';
}
?>
</select>
<label for="flt_manuf">Manufacturer</label>
<select id="flt_manuf" name="flt_manuf">
<?php
foreach ($opt_special + $opt_manufacturer as $k => $v) {
echo '<option value="', $k,'"';
if ($k == $flt->manuf) {
echo ' selected';
}
echo '>', $v, '</option>';
}
?>
</select>
<label for="flt_supp">Supplier</label>
<select id="flt_supp" name="flt_supp">
<?php
foreach ($opt_special + $opt_supplier as $k => $v) {
echo '<option value="', $k,'"';
if ($k == $flt->supp) {
echo ' selected';
}
echo '>', $v, '</option>';
}
?>
</select>
<label for="flt_txt">Text</label>
<input type="text" name="flt_txt" size="15" maxlength="30" value="<?=$flt->txt?>">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
</div>
</div>
</form>
<?php
// Pagination on top
$pagination = get_pagination($g_scriptname, $page, $lastpage);
echo $pagination;
// 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 of %d'), count($res), $numrows); ?></td></tr>
</tfoot>
</table>
<?php
echo $pagination;
form_add_button($g_scriptname);
elseif ($action == ACT_ADD):
// ========== VARIANT: add record =============================================
// filter used to preselect fields
$flt = db_get_filter($user->id, 200);
?>
<h2><?=_('Add Equipment')?></h2>
<form method="post" action="<?=$g_scriptname?>">
<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'), [-1 => '--- none ---'] + $opt_ecat, $flt->cat);
form_create_select('manufacturer', _('Manufacturer'), $opt_manufacturer, $flt->manuf);
?>
<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, shortname, 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>', _('Short name'),"</th><td>", $equipment->shortname, "</td></tr>\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=? "
. "ORDER BY d.doctype";
$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 '<img width="120" src="dl.php?id=', $row['docid'], '&t=s" alt="', $row['title'], '">';
// 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);
// Maintenance records
echo '<h3>', _('Maintenances'), "</h3>";
$sql = "SELECT maintid, series, activities FROM maintenance WHERE eid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
if ($sth->rowCount() > 0) {
echo "<ul>\n";
foreach ($sth->fetchAll() as $row) {
echo "<li>", $row['activities'], ' ';
echo '<a title="', _('View'), '" href="maintenance.php?f=view&id=', $row['maintid'], '"><i class="bi-eye"></i></a>';
echo "</li>\n";
}
echo "</ul>\n";
} else {
echo '<p>', _('No maintenance records found.'), "<p>\n";
}
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, shortname, 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>
<div class="mb-3">
<label for="shortname" class="form-label"><?=_('Short name')?></label>
<input type="text" class="form-control" id="shortname" name="shortname" value="<?=$equipment->shortname ?>">
</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'), [-1 => _('--- unknown ---')] + $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';