59 Commits
Author SHA1 Message Date
thooge 09387280fc Native gui usable for data editing. Lots of fixes and improvenemts 2026-11-11 18:58:02 +01:00
thooge a6abdaa614 Include updater for web gui 2026-11-08 07:39:52 +01:00
thooge 198063fc8d Work on editable lists in native gui 2026-11-04 20:38:19 +01:00
thooge 669c15109a Implement record locking for native gui 2026-11-04 17:21:39 +01:00
thooge 1a6674c819 Native gui make almost every data editable 2026-11-04 12:45:16 +01:00
thooge b8ac8d0185 Fix missing config value load and date event in box 2026-10-30 13:24:42 +01:00
thooge 8ac72e717e Added data change event system to native gui 2026-10-30 13:08:20 +01:00
thooge f6ab45c465 Fix ymsgui.py: missing parenthesis 2026-10-30 11:50:37 +01:00
thooge 5fe9a52f15 Webgui code improvements and fixes 2026-10-30 11:40:59 +01:00
thooge dacf32b401 Fixes for sane module and scanner feature 2026-10-30 09:43:45 +01:00
thooge 7aa5d2af3b More work on native gui. Make data editable. 2026-10-29 18:59:21 +01:00
thooge 5641e1706f Webgui fixed cables and fuses, parts of code reorganized 2026-10-25 09:03:24 +01:00
thooge 9d09b1e120 Webgui improve filter functions 2026-10-24 10:47:44 +02:00
thooge b3825cb1b3 Webgui improve series handling and plan date precision 2026-10-22 22:03:04 +02:00
thooge c2df7e8013 Webgui improve maintenance list and filter 2026-10-21 20:06:15 +02:00
thooge 06a9834688 Native gui first steps: storage, box and companies are editable 2026-10-21 17:16:55 +02:00
thooge 1eea4058bf Webgui translation update and improvement 2026-10-18 19:47:25 +02:00
thooge aee50ecb4f Prepare combo list reload with revisions and fix box/storage in webgui 2026-10-18 10:35:35 +02:00
thooge ee947b772f Work on localization and some small fixes 2026-10-17 08:34:54 +02:00
thooge 3a43f749f5 More webgui code improvements and some new vessel data 2026-10-11 18:42:25 +02:00
thooge 72571ede53 Webgui code improvements for dropdown handling 2026-10-01 18:10:57 +02:00
thooge 131af7d9e7 Work on native gui. Display records and add missing tasks and measurements. 2026-09-30 16:18:44 +02:00
thooge c3109b9d2a Fixed console password utility ymspass.py 2026-09-26 09:08:10 +02:00
thooge 99df0287be Added custom properties and backup settings 2026-09-25 17:36:11 +02:00
thooge 53ea5af9e7 Improve file access rights in webgui 2026-09-24 09:17:41 +02:00
thooge 5dcda3fe81 Fix debian packaging for native gui 2026-09-23 07:44:05 +02:00
thooge f6b37c9f26 Fixed generic data and added english version 2026-09-22 17:51:00 +02:00
thooge c5dff82da7 Added missing debian changelog 2026-09-22 17:26:05 +02:00
thooge d7e2ffdace Fix remarks display in webgui edit forms 2026-09-22 12:38:17 +02:00
thooge ed229ac7c7 Fix initial config creation 2026-09-22 10:20:22 +02:00
thooge 0adb07d75b Work on native gui: list views for objects; set version to 0.2.2 2026-09-21 19:07:59 +02:00
thooge d61faf2e71 Fix install script and add useful generic data 2026-09-21 09:32:56 +02:00
thooge 397d2de94f Fixed typo in webgui db.inc 2026-09-20 09:28:02 +02:00
thooge 5fd6c68b4f Added position to equipment 2026-09-20 09:19:18 +02:00
thooge 2fc74c0677 Fixes for webgui and more native gui development 2026-09-16 19:07:10 +02:00
thooge 9b45fd3700 Webgui: improve box, maintenance and date handling 2026-09-16 06:12:50 +02:00
thooge a76848e1da Box improvement and some experimental signalk code in webgui 2026-09-15 08:42:56 +02:00
thooge 57c42d1398 Some database improvements and associated changes in webgui 2026-09-14 10:12:32 +02:00
thooge 2250fb9743 Native gui: ongoing work, cables and fuses 2026-09-13 17:19:37 +02:00
thooge d72147c012 Native gui: implement data lists for all modules 2026-09-12 19:36:03 +02:00
thooge 4bc8dd8280 Some improvements and fixes for webgui 2026-09-12 11:05:09 +02:00
thooge 82dea5800d Work on native gui base features 2026-09-09 15:56:34 +02:00
thooge 25505757a6 Added missing view files to native gui 2026-09-09 12:25:16 +02:00
thooge b21a6beffd Work on native gui: views and database model 2026-09-09 12:20:57 +02:00
thooge 66f017567e Improve debian packet description and Makefile 2026-08-30 19:29:56 +02:00
thooge 4f5c8b0f0a Fix table cable and some more sample data 2026-08-29 14:48:55 +02:00
thooge 125a7bba56 Webgui: fix and improve cables and fuses 2026-08-29 14:27:16 +02:00
thooge ac4b994398 Debian packaging add missing files and create db user 2026-08-28 20:19:36 +02:00
thooge 1bb98f2515 Prepare optional webgui setup (Apache, nginx, lighttpd) 2026-08-28 20:00:10 +02:00
thooge 93095c630c More work on Debian packaging 2026-08-28 18:27:38 +02:00
thooge c549f7b131 Replace @PREFIX@ in idesktop link 2026-08-28 17:21:47 +02:00
thooge 3072ef1a9c Replace @PREFIX@ in desktop entry 2026-08-28 15:35:15 +02:00
thooge 52d7ee4ba1 Update build and translation handling 2026-08-28 14:50:11 +02:00
thooge 8d2fa0be77 Add initial Debian packaging 2026-08-28 14:10:46 +02:00
thooge 6896a00f31 Foreign keys, bugfixes and output sanitation 2026-08-28 10:22:05 +02:00
thooge 9e35a1c099 Database fixes and improvements 2026-08-20 11:09:00 +02:00
thooge a550d98720 Fix webgui inventory 2026-08-20 08:15:01 +02:00
thooge 80ad142d52 Fix installer error 2026-08-19 14:30:21 +02:00
thooge ed2d1c1e84 Improve database schema and install components 2026-08-19 14:15:20 +02:00
139 changed files with 31038 additions and 5148 deletions

No files matched your search

+11 -1
View File
@@ -1,5 +1,15 @@
*~ *~
__pycache__/ __pycache__/
compare_*
*.txt *.txt
*.bak *.bak
*.pot
compare_*
# Debian package build artifacts
/debian/.debhelper/
/debian/debhelper-build-stamp
/debian/files
/debian/*.debhelper
/debian/*.debhelper.log
/debian/*.substvars
/debian/yms/
+46
View File
@@ -0,0 +1,46 @@
CHANGELOG
=========
0.3.0 - 2026-11-11
------------------
* native gui: can create and edit all kind of records
* native gui: implemented record locking
* updater script for web gui
* many bugs fixed in webgui
* prepare list revision feature (reload support)
* database localization tool
* new property table for generic key/value store
* webgui: set file access rights
* fix debian packaging
0.2.2 - 2026-09-21
------------------
* native gui: prepared list views for main objects
* added position to equipment
* box improved with dimensions, net weight and price
* experimental signalk integration
* added config for currency symbol support
* database prepared for lazy record locking feature
* some small database improvements
* webgui: some improvements and fixes
* work on native gui: display data lists
* prepare dynamic language support for webgui
* improve image uploading and scaling code
* added date formatting code
0.2.1 - 2026-08-28
------------------
* fix and improve install script
* fix messagebox call in ymsgui
* customizable main menu
* sanitized html input fields
* added foreign keys and constraints to database
* added manpage
0.2.0 - 2026-08-18
------------------
* initial public release
+20 -12
View File
@@ -14,8 +14,11 @@ Yacht Management Software (YMS) Installation
1.2 Native GUI 1.2 Native GUI
- Python GTK3 - Python GTK3
- python3-gi - python3-gi
- python3-fitz
- python3-pyudev
- python3-dateutil
- gir1.2-gtk-3.0 - gir1.2-gtk-3.0
- gir-rsvg-2.0 - gir1.2-rsvg-2.0
1.3 Web GUI 1.3 Web GUI
- Webserver - Webserver
@@ -50,11 +53,16 @@ According to your desired language import minimal required dataset into your
new database. For german use new database. For german use
mariadb yms < minimal.sql mariadb yms < minimal.sql
or alternatively for english language
or alternatively for english language
mariadb yms < minimal_en.sql mariadb yms < minimal_en.sql
It is strongly recommended to import the following data.
These are selection lists that are typically always required.
mariadb yms < generic.sql
or alternatively for english language
mariadb yms < generic_en.sql
Optional import some sample data Optional import some sample data
mariadb yms < mariadb_sample.sql mariadb yms < mariadb_sample.sql
@@ -62,10 +70,10 @@ Optional import some sample data
4. Initialize document storage 4. Initialize document storage
Customize path and access rights to your needs Customize path and access rights to your needs
mkdir /var/local/yms mkdir /var/local/lib/yms
mkdir /var/local/yms/thumb mkdir /var/local/lib/yms/thumb
chown -R www-data /var/local/yms chown -R www-data /var/local/lib/yms
chmod -R 750 /var/local/yms chmod -R 750 /var/local/lib/yms
To grant access for the local gui the directory has to be writeable by a special To grant access for the local gui the directory has to be writeable by a special
group (here as example 'yms'). The user which runs the local gui (here group (here as example 'yms'). The user which runs the local gui (here
@@ -75,11 +83,11 @@ group (here as example 'yms'). The user which runs the local gui (here
groupadd yms groupadd yms
usermod -aG yms www-data usermod -aG yms www-data
usermod -aG yms guiuser usermod -aG yms guiuser
chgrp yms /var/local/yms chgrp yms /var/local/lib/yms
chgrp yms /var/local/yms/thumb chgrp yms /var/local/lib/yms/thumb
chmod -R 770 /var/local/yms chmod -R 770 /var/local/lib/yms
4. Setup local GUI 5. Setup local GUI
Create a local database user with same name as your computer user and allow Create a local database user with same name as your computer user and allow
database access with current unix credentials. E.g if your current unix user database access with current unix credentials. E.g if your current unix user
+39 -2
View File
@@ -1,9 +1,35 @@
# Translation helper # Targets
.PHONY: all prepare translation orig deb clean
# Package information
VERSION := $(shell dpkg-parsechangelog -S Version | sed 's/-.*//')
PACKAGE := yms
# Default target
all: prepare
# Debian source archive
orig:
git archive \
--format=tar \
--prefix=$(PACKAGE)-$(VERSION)/ \
HEAD \
':(exclude)debian' \
':(exclude)locale/*.pot' \
':(exclude)locale/de/LC_MESSAGES' \
| xz -9 > ../$(PACKAGE)_$(VERSION).orig.tar.xz
# Debian package
deb: orig
dpkg-buildpackage -us -uc
# Translation files
prepare: ymsgui.py yms/*.py yms/ui/*.ui prepare: ymsgui.py yms/*.py yms/ui/*.ui
xgettext -L Python -o locale/program.pot ymsgui.py yms/*.py xgettext -L Python -o locale/program.pot ymsgui.py yms/*.py
xgettext -L Python -o locale/views.pot ymsgui.py yms/view/*.py
xgettext -L Glade -o locale/ui.pot yms/ui/*.ui xgettext -L Glade -o locale/ui.pot yms/ui/*.ui
msgcat -o locale/combined.pot locale/program.pot locale/ui.pot db/localize.py db/mariadb.sql > locale/db.pot
msgcat -o locale/combined.pot locale/program.pot locale/views.pot locale/ui.pot locale/db.pot
msgmerge -U locale/de.po locale/combined.pot msgmerge -U locale/de.po locale/combined.pot
translation: locale/de/LC_MESSAGES/ymsgui.mo translation: locale/de/LC_MESSAGES/ymsgui.mo
@@ -11,3 +37,14 @@ translation: locale/de/LC_MESSAGES/ymsgui.mo
locale/de/LC_MESSAGES/ymsgui.mo: locale/de.po locale/de/LC_MESSAGES/ymsgui.mo: locale/de.po
mkdir -p locale/de/LC_MESSAGES mkdir -p locale/de/LC_MESSAGES
msgfmt locale/de.po -o locale/de/LC_MESSAGES/ymsgui.mo msgfmt locale/de.po -o locale/de/LC_MESSAGES/ymsgui.mo
# Clean generated files
clean:
find . -type d -name "__pycache__" -prune -exec rm -rf {} +
find . -type f -name "*.pyc" -delete
rm -f locale/program.pot
rm -f locale/views.pot
rm -f locale/ui.pot
rm -f locale/combined.pot
rm -f locale/de/LC_MESSAGES/ymsgui.mo
dh_clean
+22 -6
View File
@@ -1,16 +1,32 @@
YMS - Yacht Management System YMS - Open Source Yacht Management System
Prototype Preview Version
Many features are incomplete, buggy or missing. Free, self-hosted software for managing your boat's equipment,
inventory, documents, maintenance, projects, tasks and some
other things.
Your boat. Your data. Your software.
This is work in progress:
Many features can be incomplete, buggy or missing.
Use at your own risk! Use at your own risk!
Please read installation instructions in INSTALL
If inserting a new user you have also to insert a setting value If inserting a new user you have also to insert a setting value
to assign boat 0. to assign boat 0.
To set your own passwords via console there is a helper script To set your own passwords via console there is a helper script
ymspass.py ymspass.py
Use it to get an SQL-statement for changing passwords. Use it to get an SQL-statement for changing passwords.
For further information go to https://computerclub.hoogi.de/yms For users using idesktop there is a prepared link file "yms.lnk".
(currently german only) Copy it to your private .idesktop directory to create a
desktop link.
For further information go to the international project site:
https://yms.hoogi.de/yms
Documentation in german language is available at:
https://computerclub.hoogi.de/yms
+28
View File
@@ -0,0 +1,28 @@
Web GUI
-------
There is a script for updating the files for the web gui:
python update_web.py -d <path_to_webgui> -b <path_to_backup_dir>
Just execute with target path to your YMS installation and optional
a path to a backup directory e.g. /var/backups.
If you are unsure use the switch --dryrun to check beforehand.
Native GUI
----------
Follow the instructions in INSTALL
Database
--------
Compare the running database schema with the schema delivered
in db/mariadb.sql.
For easy comparison you can create a new empty database.
Then dump schema from running and new database and compare
the results.
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="151px" height="52.725px" viewBox="0 0 151 52.725" enable-background="new 0 0 151 52.725" xml:space="preserve">
<rect x="0.5" y="0.5" fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" width="150" height="51.725"/>
<path d="M61.714,6.535v0.277c6.063,4.344,10.033,11.473,10.033,19.55c0,7.237-3.192,13.712-8.216,18.109H150.5V6.535H61.714z"/>
<path fill="#FFFFFF" d="M88.588,16.993c-0.197,5.428-0.342,10.861-0.549,16.287h-0.027c-0.554-3.347-1.633-6.645-2.498-9.917h-2.005c-0.795,3.289-1.729,6.586-2.332,9.917h-0.028c0-5.426-0.369-10.867-0.575-16.287h-2.36l1.016,18.856h2.992l2.225-8.911h0.027c0.646,2.994,1.447,5.946,2.223,8.911h3.156l0.935-18.856H88.588z M99.652,19.312v16.537h-2.773V19.312h-4.775v-2.319h12.299v2.319H99.652z M110.221,19.256v6.258h6.532v2.263h-6.532v8.073h-2.662V16.993h9.553v2.263H110.221z M131.33,22.608c0,4.453-3.627,6.81-7.795,6.424c0,2.271,0,4.545,0,6.816h-2.663V16.993C125.359,16.742,131.33,16.541,131.33,22.608z M128.559,22.832c0-2.192-1.271-3.687-3.515-3.687c-1.435,0-1.51-0.167-1.51,1.157c0,2.119,0,4.237,0,6.356C126.254,27.184,128.559,25.727,128.559,22.832z M135.393,35.849V16.993h2.662v16.51h6.725v2.347H135.393z"/>
<path d="M43.725,4.708c-3.029,0-5.909,0.628-8.526,1.752c-2.617-1.124-5.497-1.752-8.527-1.752c-11.957,0-21.646,9.696-21.646,21.654s9.689,21.653,21.646,21.653c3.03,0,5.91-0.628,8.527-1.753c2.617,1.125,5.497,1.753,8.526,1.753c11.957,0,21.654-9.695,21.654-21.653S55.682,4.708,43.725,4.708z M43.745,41.475c-3.266,0-6.285-1.052-8.746-2.825c-2.46,1.773-5.486,2.825-8.751,2.825c-8.275,0-14.98-6.712-14.98-14.988c0-8.273,6.706-14.979,14.98-14.979c3.267,0,6.29,1.049,8.751,2.825c2.462-1.775,5.479-2.825,8.746-2.825c8.275,0,14.986,6.705,14.986,14.979C58.73,34.763,52.02,41.475,43.745,41.475z M41.6,17.558c2.452,5.629,2.501,13.314,0.003,13.541c-2.499,0.229-3.219-0.606-2.935-9.438l-7.099-0.034c0.532,8.717-1.084,10.232-3.269,9.274c-2.186-0.955-2.088-5.994,0.167-13.344h-7.123c-4.807,9.948-0.784,16.725,2.393,18.133c3.179,1.403,8.376,2.299,11.264-2.911c2.371,4.459,7.759,4.718,11.344,3.067c3.583-1.653,7.059-9.188,2.499-18.289L41.6,17.558L41.6,17.558z"/>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

+13
View File
@@ -0,0 +1,13 @@
Alias /yms /usr/share/yms/webgui
<Directory /usr/share/yms/webgui>
Options FollowSymLinks
AllowOverride None
Require all granted
<FilesMatch "\.inc$">
Require all denied
</FilesMatch>
DirectoryIndex index.php
</Directory>
+15
View File
@@ -0,0 +1,15 @@
location ^~ /yms/ {
alias /usr/share/yms/webgui/;
index index.php;
}
location ~ ^/yms/.*\.inc$ {
deny all;
}
location ~ ^/yms/(.+\.php)$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /usr/share/yms/webgui/$1;
fastcgi_param SCRIPT_NAME /yms/$1;
fastcgi_pass unix:@PHP_FPM_SOCKET@;
}
+203
View File
@@ -0,0 +1,203 @@
/* Generic data suitable for all kind of boats
* SPDX-License-Identifier: WTFPL
Add this data additionally after applying minmal.sql
*/
INSERT INTO user (userid, login, pass, displayname, role) VALUES
(2, 'helmsman', '$2y$10$LFl2jvrt2kB.c2KXBLaCI.RF2XAGNmFsoRc.V2tzLKrfCPiBCbI0e', 'Helmsman', 'helmsman'),
(3, 'sailor', '$2y$10$H5ZKd9r3KLAzI7W5u3ocgOCcXF4aDgjMAFYCzVC9Q9/Q9BqAV0MKS', 'Sailor', 'sailor');
INSERT INTO vessel (vid, htype, vesselname, model, loa, lwl, beam, draught, displacement, ballast, shapefile) VALUES
(1, 'mono', 'Generic vessel', 'Generic model', 10.0, 9.5, 3.0, 1.8, 4000, 1200, 'generic.svg');
INSERT INTO settings (userid, sno, valint) VALUES
(2, 1, 1), -- Vessel 1 for helmsman
(3, 1, 1); -- Vessel 1 for sailor
UPDATE settings SET valint=1 WHERE userid=1 AND sno=1; -- Vessel 1 for captain
INSERT INTO storage (sid, vid, sname, stype, x, y, z, remarks) VALUES
(0, 1, 'An Bord', 0, 0, 0, 0, 'Alles wo der Ort nicht spezifiziert werden kann');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(1, 1, 'Sloop'),
(1, 2, 'Kutter'),
(1, 3, 'Ketsch'),
(1, 4, 'Yawl'),
(1, 5, 'Schoner'),
(1, 6, 'Katamaran'),
(1, 7, 'Trimaran'),
(1, 8, 'Motorsegler'),
(1, 9, 'Motoryacht'),
(1, 10, 'Pilothouse'),
(1, 11, 'Trawler'),
(1, 12, 'Sonstiges');
INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
(2, 4, 'Dienstleister', NULL),
(2, 5, 'Segelmacher', NULL),
(2, 6, 'Yachthafen', NULL);
INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
(3, 3, 'Bilge', NULL),
(3, 4, 'Schwalbennest', NULL);
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(4, 1, 'Rumpf'),
(4, 2, 'Deck'),
(4, 3, 'Rigg'),
(4, 4, 'Segel'),
(4, 5, 'Motor'),
(4, 6, 'Elektrik'),
(4, 7, 'Elektronik'),
(4, 8, 'Navigation'),
(4, 9, 'Pantry'),
(4, 10, 'Solar'),
(4, 11, 'Sicherheit'),
(4, 12, 'Laufendes Gut');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(5, 1, 'Allgemein'),
(5, 2, 'Frischware'),
(5, 3, 'Trockenware'),
(5, 4, 'Konserven'),
(5, 5, 'Gefriergetrocknet'),
(5, 6, 'Snacks (süß)'),
(5, 7, 'Snacks (salzig)'),
(5, 8, 'Getränke');
INSERT INTO dropdown (ddid, ddval, ddtext, ddshort) VALUES
(6, 1, 'kg', 'kg'),
(6, 2, 'Liter', 'L'),
(6, 3, 'Stück', 'St'),
(6, 4, 'Packung', 'Pkg'),
(6, 5, 'Dose', 'Ds'),
(6, 6, 'Flasche', 'Fl'),
(6, 7, 'Tüte', 'Tue'),
(6, 8, 'Tafel', 'Ta'),
(6, 9, 'Glas', 'Gl');
INSERT INTO dropdown (ddid, ddval, ddtext, ddshort) VALUES
(7, 1, 'ATO/ATC-Stecksicherung', 'ATO'),
(7, 2, 'MAXI-Stecksicherung', 'Max'),
(7, 3, 'MIDI/AMI-Sicherung', 'MIDI'),
(7, 4, 'MEGA/AMG-Sicherung', 'MEGA'),
(7, 5, 'MRBF-Sicherung', 'MRBF'),
(7, 6, 'ANL-Sicherung', 'ANL'),
(7, 7, 'Class-T-Sicherung', 'Cl-T'),
(7, 8, 'Feinsicherung 5×20 mm', 'Fein'),
(7, 9, 'Glassicherung inline', 'Glas'),
(7, 10, 'Automat / Leitungsschutzschalter', 'Auto'),
(7, 11, 'Torpedosicherung', 'Torp'),
(7, 12, 'Streifensicherung', 'Str');
INSERT INTO dropdown (ddid, ddval, ddtext, ddshort) VALUES
(8, 2, 'Zentimeter', 'cm'),
(8, 3, 'Meter', 'm'),
(8, 4, 'Gramm', 'g'),
(8, 5, 'Kilogramm', 'kg'),
(8, 6, 'Watt', 'W'),
(8, 7, 'Kilowatt', 'kW'),
(8, 8, 'Ampere', 'A');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(9, 1, 'Plastikbox, klein'),
(9, 2, 'Plastikbox, groß'),
(9, 3, 'Sortimentskasten'),
(9, 4, 'Werkzeugkiste');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(11, 1, 'Einzelader'),
(11, 2, 'Steuerleitung'),
(11, 3, 'Datenkabel'),
(11, 4, 'Netzwerkkabel'),
(11, 5, 'Koaxialkabel'),
(11, 6, 'Antennenkabel'),
(11, 7, 'Lautsprecherkabel'),
(11, 8, 'Mikrofonkabel'),
(11, 9, 'Batteriekabel'),
(11, 10, 'Solarkabel'),
(11, 11, 'Gummileitung'),
(11, 12, 'Flachbandkabel'),
(11, 13, 'Telefonkabel'),
(11, 14, 'NMEA-Kabel'),
(11, 15, 'CAN-Bus-Kabel'),
(11, 16, 'USB-Kabel');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(12, 1, 'H05V-K'),
(12, 2, 'H07V-K'),
(12, 3, 'H05VV-F'),
(12, 4, 'H07RN-F'),
(12, 5, 'LiYY'),
(12, 6, 'LiYCY'),
(12, 7, 'LiYCY-TP'),
(12, 8, 'Cat 5e'),
(12, 9, 'Cat 6'),
(12, 10, 'RG-58'),
(12, 11, 'RG-213'),
(12, 12, 'RG-316'),
(12, 13, 'H-155'),
(12, 14, 'Aircell 5'),
(12, 15, 'Aircell 7'),
(12, 16, 'Ecoflex 10');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(13, 1, 'Leinen'),
(13, 2, 'Pantry'),
(13, 3, 'Werkzeug'),
(13, 4, 'Deck'),
(13, 5, 'Sicherkeit'),
(13, 6, 'Elektrik'),
(13, 7, 'Betriebsstoffe'),
(13, 8, 'Wartung'),
(13, 9, 'Sonstiges');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(15, 1, 'Vermessungsdaten'),
(15, 2, 'Rigg und Segel'),
(15, 3, 'Rumpf und Deck'),
(15, 4, 'Beschläge und Befestigungen'),
(15, 5, 'Abmessungen'),
(15, 6, 'Tanks und Volumen'),
(15, 7, 'Motor und Antrieb'),
(15, 8, 'Elektrik'),
(15, 9, 'Sonstiges');
/* supplier */
INSERT INTO company (comptype, compname, street, zip, city, country, phone, email, web) VALUES
(1, 'Compass24', NULL, NULL, 'Ascheberg', 'Deutschland', NULL, NULL, 'compass24.de'),
(1, 'Gründl', NULL, NULL, NULL, 'Deutschland', NULL, NULL, 'gruendl.de'),
(1, 'KlabauterShop', NULL, NULL, NULL, 'Deutschland', NULL, 'info@klabautershop.de', 'klabautershop.de'),
(1, 'SVB', NULL, NULL, 'Bremen', 'Deutschland', NULL, NULL, 'svb.de'),
(1, 'Toplicht', 'Notkestraße 97', '22607', 'Hamburg', 'Deutschland', '040 8890100', 'toplicht@toplicht.de', 'toplicht.de');
/* manufacturer */
INSERT INTO company (comptype, compname, street, zip, city, country, contact, phone, email, web) VALUES
(2, 'Airmar', NULL, NULL, NULL, 'USA', 'Sales', NULL, 'sales@airmar.com', 'airmar.com'),
(2, 'B&G', 'Marienthaler Str. 17', '24340', 'Eckernförde', 'Deutschland', 'Sales', '+49 4351 883290', 'sales.de@navico.com', 'bandg.com'),
(2, 'Blue Sea Systems', 'N85 W12545 Westbrook Crossing', '53051', 'Menomonee Falls', 'USA', 'Customer Service', '+1 800 307 6702', NULL, 'bluesea.com'),
(2, 'Dometic', 'Hemvärnsgatan 15', '171 54', 'Solna', 'Schweden', 'Customer Service', '+49 511 474046-400', 'contact.eu@dometic.com', 'dometic.com'),
(2, 'Garmin', 'Parkring 35', '85748', 'Garching', 'Deutschland', 'Zentrale', '+49 89 541999-700', 'impressum@garmin.de', 'garmin.com'),
(2, 'Harken', NULL, NULL, 'Pewaukee', 'USA', 'Customer Service', NULL, NULL, 'harken.com'),
(2, 'Hella Marine', NULL, NULL, 'Auckland', 'Neuseeland', 'Marine', NULL, NULL, 'hellamarine.com'),
(2, 'Icom', NULL, NULL, NULL, 'Japan', 'Marine', NULL, NULL, 'icomjapan.com'),
(2, 'Isotherm', NULL, NULL, NULL, 'Italien', 'Marine', NULL, NULL, 'indelwebastomarine.com'),
(2, 'Jabsco', '301 Water Street SE, Suite 200', '20003', 'Washington', 'USA', 'Xylem', '+1 978 281 0440', NULL, 'xylem.com'),
(2, 'Johnson Pump', NULL, NULL, NULL, 'Schweden', 'Marine', NULL, NULL, 'johnson-pump.com'),
(2, 'Lewmar', 'Southmoor Lane', 'PO9 1JJ', 'Havant', 'Vereinigtes Königreich', 'Customer Service', '+44 23 9247 1841', 'info@lewmar.com', 'lewmar.com'),
(2, 'Lofrans', 'Via Leonardo Da Vinci 6', '20040', 'Cambiago (MI)', 'Italien', 'Customer Service', '+39 02 36640684', NULL, 'lofrans.it'),
(2, 'Mastervolt', 'Snijdersbergweg 93', '1105 AN', 'Amsterdam', 'Niederlande', 'Customer Service', '+31 20 3422100', 'info.emea@OneASG.com', 'mastervolt.com'),
(2, 'Plastimo', NULL, NULL, 'Lorient', 'Frankreich', 'Marine', NULL, NULL, 'plastimo.com'),
(2, 'Quick', 'Via Piangipane 120/A', '48124', 'Piangipane (RA)', 'Italien', 'Headquarters', '+39 0544 415061', 'quick@quickitaly.com', 'quickitaly.com'),
(2, 'Raymarine', 'Atlantic-Haus, Zirkusweg 1', '20359', 'Hamburg', 'Deutschland', 'Support', '+49 40 2378080', NULL, 'raymarine.com'),
(2, 'Ronstan', NULL, NULL, 'Melbourne', 'Australien', 'Marine', NULL, NULL, 'ronstan.com'),
(2, 'Selden', 'Redegatan 11', '421 21', 'Västra Frölunda', 'Schweden', 'Headquarters', '+46 31 696900', 'info@seldenmast.com', 'seldenmast.com'),
(2, 'Simrad', NULL, NULL, NULL, 'Norwegen', 'Marine', NULL, NULL, 'simrad-yachting.com'),
(2, 'Spinlock', 'Birmingham Road', 'PO31 7BH', 'Cowes', 'Vereinigtes Königreich', 'Customer Service', '+44 1983 295555', NULL, 'spinlock.co.uk'),
(2, 'Torqeedo', NULL, NULL, NULL, 'Deutschland', 'Marine', NULL, NULL, 'torqeedo.com'),
(2, 'Vetus', 'Havenstraat 11', '3115 HC', 'Schiedam', 'Niederlande', 'Headquarters', '+31 884 884700', 'info@vetus.com', 'vetus.com'),
(2, 'Victron Energy', 'De Paal 35', '1351 JG', 'Almere', 'Niederlande', 'Headquarters', NULL, NULL, 'victronenergy.com'),
(2, 'Whale', NULL, NULL, NULL, 'Vereinigtes Königreich', 'Marine', NULL, NULL, 'whalepumps.com');
+201
View File
@@ -0,0 +1,201 @@
/* Generic data suitable for all kind of boats
* SPDX-License-Identifier: WTFPL
Add this data additionally after applying minmal.sql
*/
INSERT INTO user (userid, login, pass, displayname, role) VALUES
(2, 'helmsman', '$2y$10$LFl2jvrt2kB.c2KXBLaCI.RF2XAGNmFsoRc.V2tzLKrfCPiBCbI0e', 'Helmsman', 'helmsman'),
(3, 'sailor', '$2y$10$H5ZKd9r3KLAzI7W5u3ocgOCcXF4aDgjMAFYCzVC9Q9/Q9BqAV0MKS', 'Sailor', 'sailor');
INSERT INTO vessel (vid, vesselname, model, loa, lwl, beam, draught, displacement, ballast) VALUES
(1, 'Generic vessel', 'Generic model', 10.0, 9.5, 3.0, 1.8, 4000, 1200);
INSERT INTO settings (userid, sno, valint) VALUES
(2, 1, 1), -- Vessel 1 for helmsman
(3, 1, 1); -- Vessel 1 for sailor
INSERT INTO storage (sid, vid, sname, stype, x, y, z, remarks) VALUES
(0, 1, 'An Bord', 0, 0, 0, 0, 'Alles wo der Ort nicht spezifiziert werden kann');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(1, 1, 'Sloop'),
(1, 2, 'Cutter'),
(1, 3, 'Ketsch'),
(1, 4, 'Yawl'),
(1, 5, 'Schooner'),
(1, 6, 'Catamaran'),
(1, 7, 'Trimaran'),
(1, 8, 'Motorseailor'),
(1, 9, 'Motoryacht'),
(1, 10, 'Pilothouse'),
(1, 11, 'Trawler'),
(1, 12, 'Other');
INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
(2, 4, 'Service', NULL),
(2, 5, 'Sailmaker', NULL),
(2, 6, 'Marina', NULL);
INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
(3, 3, 'Bilge', NULL),
(3, 4, 'Quarter Berth', NULL);
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(4, 1, 'Hull'),
(4, 2, 'Deck'),
(4, 3, 'Rigging'),
(4, 4, 'Sails'),
(4, 5, 'Engine'),
(4, 6, 'Electrical'),
(4, 7, 'Electronics'),
(4, 8, 'Navigation'),
(4, 9, 'Galley'),
(4, 10, 'Solar'),
(4, 11, 'Safety'),
(4, 12, 'Running Rigging');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(5, 1, 'General'),
(5, 2, 'Drinks'),
(5, 3, 'Sweets'),
(5, 4, 'Tinned Food'),
(5, 5, 'Fresh Food'),
(5, 6, 'Dry Goods'),
(5, 7, 'Freeze-Dried Food'),
(5, 8, 'Savoury Snacks');
INSERT INTO dropdown (ddid, ddval, ddtext, ddshort) VALUES
(6, 1, 'kg', 'kg'),
(6, 2, 'Litre', 'L'),
(6, 3, 'Piece', 'pc'),
(6, 4, 'Pack', 'pk'),
(6, 5, 'Tin', 'tin'),
(6, 6, 'Bottle', 'btl'),
(6, 7, 'Bag', 'bag'),
(6, 8, 'Bar', 'bar'),
(6, 9, 'Jar', 'jar');
INSERT INTO dropdown (ddid, ddval, ddtext, ddshort) VALUES
(7, 1, 'ATO/ATC blade fuse', 'ATO'),
(7, 2, 'MAXI blade fuse', 'Max'),
(7, 3, 'MIDI/AMI fuse', 'MIDI'),
(7, 4, 'MEGA/AMG fuse', 'MEGA'),
(7, 5, 'MRBF fuse', 'MRBF'),
(7, 6, 'ANL fuse', 'ANL'),
(7, 7, 'Class-T fuse', 'Cl-T'),
(7, 8, '5×20 mm cartridge fuse', 'Cart'),
(7, 9, 'Glass inline fuse', 'Glas'),
(7, 10, 'Circuit breaker', 'Auto'),
(7, 11, 'Torpedo fuse', 'Torp'),
(7, 12, 'Strip fuse', 'Str');
INSERT INTO dropdown (ddid, ddval, ddshort, ddtext) VALUES
(8, 2, 'cm', 'Centimetre'),
(8, 3, 'g', 'Gram'),
(8, 4, 'kg', 'Kilogram'),
(8, 5, 'm', 'Metre'),
(8, 6, 'kW', 'Kilowatt'),
(8, 7, 'A', 'Ampere'),
(8, 8, 'L', 'Litre');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(9, 1, 'Small Plastic Box'),
(9, 2, 'Large Plastic Box'),
(9, 3, 'Parts Organiser'),
(9, 4, 'Toolbox');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(11, 1, 'Single-core cable'),
(11, 2, 'Control cable'),
(11, 3, 'Data cable'),
(11, 4, 'Network cable'),
(11, 5, 'Coaxial cable'),
(11, 6, 'Aerial cable'),
(11, 7, 'Speaker cable'),
(11, 8, 'Microphone cable'),
(11, 9, 'Battery cable'),
(11, 10, 'Solar cable'),
(11, 11, 'Rubber cable'),
(11, 12, 'Ribbon cable'),
(11, 13, 'Telephone cable'),
(11, 14, 'NMEA cable'),
(11, 15, 'CAN bus cable'),
(11, 16, 'USB cable');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(12, 1, 'H05V-K'),
(12, 2, 'H07V-K'),
(12, 3, 'H05VV-F'),
(12, 4, 'H07RN-F'),
(12, 5, 'LiYY'),
(12, 6, 'LiYCY'),
(12, 7, 'LiYCY-TP'),
(12, 8, 'Cat 5e'),
(12, 9, 'Cat 6'),
(12, 10, 'RG-58'),
(12, 11, 'RG-213'),
(12, 12, 'RG-316'),
(12, 13, 'H-155'),
(12, 14, 'Aircell 5'),
(12, 15, 'Aircell 7'),
(12, 16, 'Ecoflex 10');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(13, 1, 'Ropes'),
(13, 2, 'Pantry'),
(13, 3, 'Tools'),
(13, 4, 'Deck'),
(13, 5, 'Safety'),
(13, 6, 'Electrical'),
(13, 7, 'Operating Supplies'),
(13, 8, 'Maintenance'),
(13, 9, 'Miscellaneous');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(15, 1, 'Measurement Data'),
(15, 2, 'Rigging and Sails'),
(15, 3, 'Hull and Deck'),
(15, 4, 'Fittings and Fastenings'),
(15, 5, 'Dimensions'),
(15, 6, 'Tanks and Volumes'),
(15, 7, 'Engine and Propulsion'),
(15, 8, 'Electrical Systems'),
(15, 9, 'Miscellaneous');
/* supplier */
INSERT INTO company (comptype, compname, street, zip, city, country, phone, email, web) VALUES
(1, 'Compass24', NULL, NULL, 'Ascheberg', 'Deutschland', NULL, NULL, 'compass24.de'),
(1, 'Gründl', NULL, NULL, NULL, 'Deutschland', NULL, NULL, 'gruendl.de'),
(1, 'KlabauterShop', NULL, NULL, NULL, 'Deutschland', NULL, 'info@klabautershop.de', 'klabautershop.de'),
(1, 'SVB', NULL, NULL, 'Bremen', 'Deutschland', NULL, NULL, 'svb.de'),
(1, 'Toplicht', 'Notkestraße 97', '22607', 'Hamburg', 'Deutschland', '040 8890100', 'toplicht@toplicht.de', 'toplicht.de');
/* manufacturer */
INSERT INTO company (comptype, compname, street, zip, city, country, contact, phone, email, web) VALUES
(2, 'Airmar', NULL, NULL, NULL, 'USA', 'Sales', NULL, 'sales@airmar.com', 'airmar.com'),
(2, 'B&G', 'Marienthaler Str. 17', '24340', 'Eckernförde', 'Deutschland', 'Sales', '+49 4351 883290', 'sales.de@navico.com', 'bandg.com'),
(2, 'Blue Sea Systems', 'N85 W12545 Westbrook Crossing', '53051', 'Menomonee Falls', 'USA', 'Customer Service', '+1 800 307 6702', NULL, 'bluesea.com'),
(2, 'Dometic', 'Hemvärnsgatan 15', '171 54', 'Solna', 'Schweden', 'Customer Service', '+49 511 474046-400', 'contact.eu@dometic.com', 'dometic.com'),
(2, 'Garmin', 'Parkring 35', '85748', 'Garching', 'Deutschland', 'Zentrale', '+49 89 541999-700', 'impressum@garmin.de', 'garmin.com'),
(2, 'Harken', NULL, NULL, 'Pewaukee', 'USA', 'Customer Service', NULL, NULL, 'harken.com'),
(2, 'Hella Marine', NULL, NULL, 'Auckland', 'Neuseeland', 'Marine', NULL, NULL, 'hellamarine.com'),
(2, 'Icom', NULL, NULL, NULL, 'Japan', 'Marine', NULL, NULL, 'icomjapan.com'),
(2, 'Isotherm', NULL, NULL, NULL, 'Italien', 'Marine', NULL, NULL, 'indelwebastomarine.com'),
(2, 'Jabsco', '301 Water Street SE, Suite 200', '20003', 'Washington', 'USA', 'Xylem', '+1 978 281 0440', NULL, 'xylem.com'),
(2, 'Johnson Pump', NULL, NULL, NULL, 'Schweden', 'Marine', NULL, NULL, 'johnson-pump.com'),
(2, 'Lewmar', 'Southmoor Lane', 'PO9 1JJ', 'Havant', 'Vereinigtes Königreich', 'Customer Service', '+44 23 9247 1841', 'info@lewmar.com', 'lewmar.com'),
(2, 'Lofrans', 'Via Leonardo Da Vinci 6', '20040', 'Cambiago (MI)', 'Italien', 'Customer Service', '+39 02 36640684', NULL, 'lofrans.it'),
(2, 'Mastervolt', 'Snijdersbergweg 93', '1105 AN', 'Amsterdam', 'Niederlande', 'Customer Service', '+31 20 3422100', 'info.emea@OneASG.com', 'mastervolt.com'),
(2, 'Plastimo', NULL, NULL, 'Lorient', 'Frankreich', 'Marine', NULL, NULL, 'plastimo.com'),
(2, 'Quick', 'Via Piangipane 120/A', '48124', 'Piangipane (RA)', 'Italien', 'Headquarters', '+39 0544 415061', 'quick@quickitaly.com', 'quickitaly.com'),
(2, 'Raymarine', 'Atlantic-Haus, Zirkusweg 1', '20359', 'Hamburg', 'Deutschland', 'Support', '+49 40 2378080', NULL, 'raymarine.com'),
(2, 'Ronstan', NULL, NULL, 'Melbourne', 'Australien', 'Marine', NULL, NULL, 'ronstan.com'),
(2, 'Selden', 'Redegatan 11', '421 21', 'Västra Frölunda', 'Schweden', 'Headquarters', '+46 31 696900', 'info@seldenmast.com', 'seldenmast.com'),
(2, 'Simrad', NULL, NULL, NULL, 'Norwegen', 'Marine', NULL, NULL, 'simrad-yachting.com'),
(2, 'Spinlock', 'Birmingham Road', 'PO31 7BH', 'Cowes', 'Vereinigtes Königreich', 'Customer Service', '+44 1983 295555', NULL, 'spinlock.co.uk'),
(2, 'Torqeedo', NULL, NULL, NULL, 'Deutschland', 'Marine', NULL, NULL, 'torqeedo.com'),
(2, 'Vetus', 'Havenstraat 11', '3115 HC', 'Schiedam', 'Niederlande', 'Headquarters', '+31 884 884700', 'info@vetus.com', 'vetus.com'),
(2, 'Victron Energy', 'De Paal 35', '1351 JG', 'Almere', 'Niederlande', 'Headquarters', NULL, NULL, 'victronenergy.com'),
(2, 'Whale', NULL, NULL, NULL, 'Vereinigtes Königreich', 'Marine', NULL, NULL, 'whalepumps.com');
Executable
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/python3
# SPDX-License-Identifier: WTFPL
"""
Database localization helper tool
Parse enums and sets from sql schema script for translatable strings
"""
import os
import sys
import argparse
import re
__author__ = "Thomas Hooge"
__copyright__ = "Copyright 2026"
__version__ = "0.1"
__email__ = "thomas@hoogi.de"
__status__ = "Development"
COLUMN_RE = re.compile(
r"^\s*(?P<column>\w+)\s+(?P<type>enum|set)\s*"
r"\(\s*(?P<values>'[a-z]+'(?:\s*,\s*'[a-z]+')*)\s*\)",
re.IGNORECASE
)
TABLE_RE = re.compile(
r"CREATE TABLE (?P<table>\w+)",
re.IGNORECASE
)
def load_msgids(sql):
current_table = None
for lineno, line in enumerate(sql.splitlines(), 1):
table_match = TABLE_RE.search(line)
if table_match:
current_table = table_match.group("table")
column_match = COLUMN_RE.search(line)
if current_table and column_match:
column = column_match.group("column")
values = re.findall(
r"'([a-z]+)'",
column_match.group("values"),
)
context = f"{current_table}.{column}"
for value in values:
yield context, value, lineno
def write_pot(msgids, output, filename):
output.write(
'msgid ""\n'
'msgstr ""\n'
'"Content-Type: text/plain; charset=UTF-8\\n"\n'
'"Content-Transfer-Encoding: 8bit\\n"\n'
'"MIME-Version: 1.0\\n"\n'
'\n'
)
for context, msgid, lineno in sorted(set(msgids)):
output.write(f"#: {filename}:{lineno}\n")
output.write(f'msgctxt "{context}"\n')
output.write(f'msgid "{msgid}"\n')
output.write('msgstr ""\n\n')
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=(
"Database localization helper tool\n"
"Parse enums and sets from SQL schema script "
"for translatable strings"
),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"sql_file",
help="SQL schema file to parse",
)
parser.add_argument(
"--version",
action="version",
version=f"%(prog)s {__version__}",
)
args = parser.parse_args()
try:
with open(args.sql_file, "r", encoding="utf-8") as f:
sql = f.read()
except OSError as e:
parser.error(str(e))
write_pot(load_msgids(sql), sys.stdout, args.sql_file)
+235 -61
View File
@@ -3,10 +3,14 @@
/* MariaDB Scheme /* MariaDB Scheme
Version: 1 */ Version: 1 */
/* TODO /* REMARKS
- there are by design no created_at, updated_at, updates_by or similar fields
TODO
- check all values if unsigned can be used or not - check all values if unsigned can be used or not
- implement foreign keys where possible - add referential actions where appropriate
- rename provisions to provision(?) - rename provisions to provision(?)
- review defaults
*/ */
/* User /* User
@@ -60,10 +64,11 @@ CREATE TABLE dropdown (
ddtext varchar(50) NOT NULL, ddtext varchar(50) NOT NULL,
ddshort varchar(4) DEFAULT NULL, ddshort varchar(4) DEFAULT NULL,
color char(6) DEFAULT NULL, color char(6) DEFAULT NULL,
flags enum('locked','fixed') DEFAULT NULL, flags set('locked','fixed') DEFAULT NULL,
PRIMARY KEY (ddid, ddval) PRIMARY KEY (ddid, ddval)
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/* compid is signed because negative values needed for special purpose */
CREATE TABLE company ( CREATE TABLE company (
compid smallint(6) NOT NULL AUTO_INCREMENT, compid smallint(6) NOT NULL AUTO_INCREMENT,
compname varchar(60) NOT NULL, compname varchar(60) NOT NULL,
@@ -88,10 +93,17 @@ CREATE TABLE company (
CREATE TABLE vessel ( CREATE TABLE vessel (
vid smallint(6) NOT NULL AUTO_INCREMENT, vid smallint(6) NOT NULL AUTO_INCREMENT,
vtype enum('mono','cat','tri') NOT NULL DEFAULT 'mono', vtype tinyint(3) DEFAULT NULL,
htype enum('mono','cat','tri') NOT NULL DEFAULT 'mono',
vesselname varchar(40) NOT NULL, vesselname varchar(40) NOT NULL,
model varchar(20) DEFAULT NULL, model varchar(20) DEFAULT NULL,
shipyard smallint(6) DEFAULT NULL, shipyard smallint(6) DEFAULT NULL,
year_built year DEFAULT NULL,
hull_number varchar(20) DEFAULT NULL,
-- TODO perhaps as properties?
-- reg_number varchar(20) DEFAULT NULL,
-- mmsi varchar(10) DEFAULT NULL,
-- callsign varchar(6) DEFAULT NULL,
loa float(4,2) UNSIGNED DEFAULT NULL, loa float(4,2) UNSIGNED DEFAULT NULL,
lwl float(4,2) UNSIGNED DEFAULT NULL, lwl float(4,2) UNSIGNED DEFAULT NULL,
beam float(4,2) UNSIGNED DEFAULT NULL, beam float(4,2) UNSIGNED DEFAULT NULL,
@@ -107,6 +119,7 @@ CREATE TABLE vessel (
PRIMARY KEY (vid), PRIMARY KEY (vid),
FOREIGN KEY fk_vessel_shipyard (shipyard) FOREIGN KEY fk_vessel_shipyard (shipyard)
REFERENCES company(compid) REFERENCES company(compid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
CREATE TABLE storage ( CREATE TABLE storage (
@@ -115,7 +128,7 @@ CREATE TABLE storage (
sname varchar(40) NOT NULL, sname varchar(40) NOT NULL,
stype tinyint(3) NOT NULL DEFAULT 0, -- ddid=3 stype tinyint(3) NOT NULL DEFAULT 0, -- ddid=3
capacity smallint(6) DEFAULT NULL, capacity smallint(6) DEFAULT NULL,
capaunit enum('kg','l') DEFAULT NULL, capaunit enum('kg','l','pcs') DEFAULT NULL,
x smallint(6) UNSIGNED NOT NULL DEFAULT 0, x smallint(6) UNSIGNED NOT NULL DEFAULT 0,
y smallint(6) NOT NULL DEFAULT 0, y smallint(6) NOT NULL DEFAULT 0,
z smallint(6) NOT NULL DEFAULT 0, z smallint(6) NOT NULL DEFAULT 0,
@@ -125,9 +138,19 @@ CREATE TABLE storage (
angle smallint(4) NOT NULL DEFAULT 0, angle smallint(4) NOT NULL DEFAULT 0,
color char(6) DEFAULT NULL, color char(6) DEFAULT NULL,
remarks varchar(150) DEFAULT NULL, remarks varchar(150) DEFAULT NULL,
PRIMARY KEY (sid) PRIMARY KEY (sid),
FOREIGN KEY fk_storage_vessel (vid)
REFERENCES vessel(vid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/* intentionally after storage creation */
ALTER TABLE vessel
ADD CONSTRAINT fk_vessel_storage
FOREIGN KEY (sid_default)
REFERENCES storage(sid)
ON DELETE RESTRICT;
CREATE TABLE tag ( CREATE TABLE tag (
tagid smallint(6) UNSIGNED NOT NULL AUTO_INCREMENT, tagid smallint(6) UNSIGNED NOT NULL AUTO_INCREMENT,
tagname varchar(20) NOT NULL, tagname varchar(20) NOT NULL,
@@ -141,11 +164,15 @@ CREATE TABLE tagref (
tagid smallint(6) UNSIGNED NOT NULL, tagid smallint(6) UNSIGNED NOT NULL,
objid int(10) UNSIGNED NOT NULL, objid int(10) UNSIGNED NOT NULL,
objtype enum('equip','inv','prov','doc', 'proj', 'task', 'maint') NOT NULL, objtype enum('equip','inv','prov','doc', 'proj', 'task', 'maint') NOT NULL,
PRIMARY KEY (tagid, objid, objtype) PRIMARY KEY (tagid, objid, objtype),
INDEX ix_tagref_obj (objid, objtype),
FOREIGN KEY fk_tagref_tag (tagid)
REFERENCES tag(tagid)
ON DELETE CASCADE
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/* TODO Boxes can be nested via parent /* TODO Boxes can be nested via parent,
TODO boxsize: (LxWxH) in cm? */ very low priority because perhaps rarely used */
CREATE TABLE box ( CREATE TABLE box (
boxid smallint(6) UNSIGNED NOT NULL AUTO_INCREMENT, boxid smallint(6) UNSIGNED NOT NULL AUTO_INCREMENT,
sid smallint(6) UNSIGNED NOT NULL, sid smallint(6) UNSIGNED NOT NULL,
@@ -155,9 +182,20 @@ CREATE TABLE box (
color char(6) DEFAULT NULL, color char(6) DEFAULT NULL,
content varchar(60) DEFAULT NULL, content varchar(60) DEFAULT NULL,
weight float(5,2) UNSIGNED DEFAULT NULL, weight float(5,2) UNSIGNED DEFAULT NULL,
weight_net float(5,2) UNSIGNED DEFAULT NULL,
wx smallint(6) UNSIGNED NOT NULL DEFAULT 0, -- length
wy smallint(6) UNSIGNED NOT NULL DEFAULT 0, -- width
wz smallint(6) UNSIGNED NOT NULL DEFAULT 0, -- height
price decimal(12,2) DEFAULT NULL,
remarks varchar(150) DEFAULT NULL, remarks varchar(150) DEFAULT NULL,
PRIMARY KEY (boxid), PRIMARY KEY (boxid),
INDEX ix_label (label) INDEX ix_label (label),
FOREIGN KEY fk_box_storage (sid)
REFERENCES storage(sid)
ON DELETE RESTRICT,
FOREIGN KEY fk_box_parent (parent)
REFERENCES box(boxid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
CREATE TABLE equipment ( CREATE TABLE equipment (
@@ -165,7 +203,7 @@ CREATE TABLE equipment (
vid smallint(6) NOT NULL DEFAULT 1, vid smallint(6) NOT NULL DEFAULT 1,
ename varchar(80) NOT NULL, ename varchar(80) NOT NULL,
shortname varchar(20) DEFAULT NULL, shortname varchar(20) DEFAULT NULL,
model varchar(40), model varchar(40) DEFAULT NULL,
ecat tinyint(3) DEFAULT NULL, ecat tinyint(3) DEFAULT NULL,
serial varchar(30) DEFAULT NULL, serial varchar(30) DEFAULT NULL,
supplier smallint(6) DEFAULT NULL, supplier smallint(6) DEFAULT NULL,
@@ -173,28 +211,37 @@ CREATE TABLE equipment (
purchdate date DEFAULT NULL, purchdate date DEFAULT NULL,
price decimal(12,2) DEFAULT NULL, price decimal(12,2) DEFAULT NULL,
weight float(5,2) UNSIGNED DEFAULT NULL, weight float(5,2) UNSIGNED DEFAULT NULL,
x smallint(6) UNSIGNED NOT NULL DEFAULT 0,
y smallint(6) NOT NULL DEFAULT 0,
z smallint(6) NOT NULL DEFAULT 0,
econd enum('unknown','excellent','good','fair','bad','repairable','defect') NOT NULL default 'unknown',
remarks varchar(150) DEFAULT NULL, remarks varchar(150) DEFAULT NULL,
flags set('ordered','removed','deleted') DEFAULT NULL, flags set('ordered','removed','deleted') DEFAULT NULL,
PRIMARY KEY(eid) PRIMARY KEY(eid),
FOREIGN KEY fk_equipment_vessel (vid)
REFERENCES vessel(vid)
ON DELETE RESTRICT,
FOREIGN KEY fk_equipment_supplier (supplier)
REFERENCES company(compid)
ON DELETE RESTRICT,
FOREIGN KEY fk_equipment_manufacturer (manufacturer)
REFERENCES company(compid)
ON DELETE RESTRICT,
CONSTRAINT chk_equipment_pos CHECK (
(x IS NULL AND y IS NULL AND z IS NULL)
OR
(x IS NOT NULL AND y IS NOT NULL AND z IS NOT NULL)
)
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/*
convert to
sid SMALLINT UNSIGNED NULL,
boxid SMALLINT UNSIGNED NULL,
CHECK (
(sid IS NOT NULL AND boxid IS NULL)
OR
(sid IS NULL AND boxid IS NOT NULL)
)
*/
CREATE TABLE inventory ( CREATE TABLE inventory (
invid int(10) UNSIGNED NOT NULL AUTO_INCREMENT, invid int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
invname varchar(80) NOT NULL, invname varchar(80) NOT NULL,
icat tinyint(3) DEFAULT NULL,
conttype enum('storage','box') NOT NULL DEFAULT 'storage', conttype enum('storage','box') NOT NULL DEFAULT 'storage',
sid smallint(6) UNSIGNED NOT NULL DEFAULT 1, sid smallint(6) UNSIGNED DEFAULT NULL,
boxid smallint(6) UNSIGNED NOT NULL DEFAULT 1, boxid smallint(6) UNSIGNED DEFAULT NULL,
eid smallint(6) UNSIGNED DEFAULT NULL, eid smallint(6) UNSIGNED DEFAULT NULL, -- spare part reference to equipment
number smallint(6) UNSIGNED NOT NULL DEFAULT 1, number smallint(6) UNSIGNED NOT NULL DEFAULT 1,
weight float(5,2) UNSIGNED DEFAULT NULL, weight float(5,2) UNSIGNED DEFAULT NULL,
price decimal(12,2) DEFAULT NULL, price decimal(12,2) DEFAULT NULL,
@@ -203,16 +250,31 @@ CREATE TABLE inventory (
remarks varchar(150) DEFAULT NULL, remarks varchar(150) DEFAULT NULL,
flags set('ordered','removed','deleted') DEFAULT NULL, flags set('ordered','removed','deleted') DEFAULT NULL,
PRIMARY KEY (invid), PRIMARY KEY (invid),
INDEX ix_invname (invname) INDEX ix_invname (invname),
FOREIGN KEY fk_inventory_storage (sid)
REFERENCES storage(sid)
ON DELETE RESTRICT,
FOREIGN KEY fk_inventory_box (boxid)
REFERENCES box(boxid)
ON DELETE RESTRICT,
FOREIGN KEY fk_inventory_equipment (eid)
REFERENCES equipment(eid)
ON DELETE RESTRICT,
CONSTRAINT chk_inventory_stor CHECK (
(sid IS NOT NULL AND boxid IS NULL)
OR
(sid IS NULL AND boxid IS NOT NULL)
)
) ENGINE=InnoDB; ) ENGINE=InnoDB;
CREATE TABLE cable ( CREATE TABLE cable (
cableid smallint(6) UNSIGNED NOT NULL AUTO_INCREMENT, cableid smallint(6) UNSIGNED NOT NULL AUTO_INCREMENT,
vid smallint(6) NOT NULL DEFAULT 1, vid smallint(6) NOT NULL DEFAULT 1,
cablename varchar(80) NOT NULL, cablename varchar(80) NOT NULL,
cabletype varchar(40) DEFAULT NULL, -- e.g. H07RN-F cabletype tinyint(3) DEFAULT NULL, -- from dropdown id 11 e.g. antenna cable
techname tinyint(3) DEFAULT NULL, -- from dropdown id 12 e.g. H07RN-F
length float(5,2) UNSIGNED NOT NULL DEFAULT 0, -- total length in m length float(5,2) UNSIGNED NOT NULL DEFAULT 0, -- total length in m
conductors TINYINT(3) UNSIGNED NOT NULL DEFAULT 1, conductors tinyint(3) UNSIGNED NOT NULL DEFAULT 1,
diameter float(5,2) UNSIGNED DEFAULT NULL, -- outer diameter in mm diameter float(5,2) UNSIGNED DEFAULT NULL, -- outer diameter in mm
xsection float(5,2) UNSIGNED DEFAULT NULL, -- cross section in mm² xsection float(5,2) UNSIGNED DEFAULT NULL, -- cross section in mm²
weight float(5,2) UNSIGNED DEFAULT NULL, -- kg/meter weight float(5,2) UNSIGNED DEFAULT NULL, -- kg/meter
@@ -222,10 +284,19 @@ CREATE TABLE cable (
cablecond enum('unknown','new','excellent','good','fair','bad','repairable','defect') NOT NULL default 'unknown', cablecond enum('unknown','new','excellent','good','fair','bad','repairable','defect') NOT NULL default 'unknown',
remarks varchar(150) DEFAULT NULL, remarks varchar(150) DEFAULT NULL,
PRIMARY KEY (cableid), PRIMARY KEY (cableid),
INDEX ix_cablename (vid, cablename) INDEX ix_cablename (vid, cablename),
FOREIGN KEY fk_cable_vessel (vid)
REFERENCES vessel(vid)
ON DELETE RESTRICT,
FOREIGN KEY fk_cable_supplier (supplier)
REFERENCES company(compid)
ON DELETE RESTRICT,
FOREIGN KEY fk_cable_manufacturer (manufacturer)
REFERENCES company(compid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
CREATE table fuse ( CREATE TABLE fuse (
fuseid smallint(6) UNSIGNED NOT NULL AUTO_INCREMENT, fuseid smallint(6) UNSIGNED NOT NULL AUTO_INCREMENT,
vid smallint(6) NOT NULL DEFAULT 1, vid smallint(6) NOT NULL DEFAULT 1,
fnumber smallint(6) NOT NULL, fnumber smallint(6) NOT NULL,
@@ -235,9 +306,19 @@ CREATE table fuse (
eid smallint(6) UNSIGNED DEFAULT NULL, eid smallint(6) UNSIGNED DEFAULT NULL,
location tinyint(3) DEFAULT 0, -- from dropdown id 10 location tinyint(3) DEFAULT 0, -- from dropdown id 10
description varchar(60) DEFAULT NULL, description varchar(60) DEFAULT NULL,
color char(6) DEFAULT NULL,
remarks varchar(150) DEFAULT NULL, remarks varchar(150) DEFAULT NULL,
PRIMARY KEY (fuseid), PRIMARY KEY (fuseid),
UNIQUE INDEX ix_fusenumber (vid, fnumber) UNIQUE INDEX ix_fusenumber (vid, fnumber),
FOREIGN KEY fk_fuse_vessel (vid)
REFERENCES vessel(vid)
ON DELETE RESTRICT,
FOREIGN KEY fk_fuse_cable (cableid)
REFERENCES cable(cableid)
ON DELETE RESTRICT,
FOREIGN KEY fk_fuse_equipment (eid)
REFERENCES equipment(eid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
-- change vals to decimal(12,4)? -- change vals to decimal(12,4)?
@@ -245,6 +326,7 @@ CREATE TABLE measurement (
mid smallint(6) NOT NULL AUTO_INCREMENT, mid smallint(6) NOT NULL AUTO_INCREMENT,
mname varchar(80) NOT NULL, mname varchar(80) NOT NULL,
vid smallint(6) NOT NULL DEFAULT 1, vid smallint(6) NOT NULL DEFAULT 1,
eid smallint(6) UNSIGNED DEFAULT NULL,
nval tinyint(1) UNSIGNED NOT NULL DEFAULT 1, nval tinyint(1) UNSIGNED NOT NULL DEFAULT 1,
val1 int(10) NOT NULL, val1 int(10) NOT NULL,
val2 int(10) DEFAULT NULL, val2 int(10) DEFAULT NULL,
@@ -252,9 +334,15 @@ CREATE TABLE measurement (
unit tinyint(3) NOT NULL DEFAULT 1, unit tinyint(3) NOT NULL DEFAULT 1,
accuracy enum('unknown','precise','normal','rough','estimated') NOT NULL DEFAULT 'unknown', accuracy enum('unknown','precise','normal','rough','estimated') NOT NULL DEFAULT 'unknown',
mdate date DEFAULT NULL, mdate date DEFAULT NULL,
mcat tinyint(3) DEFAULT NULL,
note varchar(80) DEFAULT NULL, note varchar(80) DEFAULT NULL,
eid smallint(6) UNSIGNED DEFAULT NULL, PRIMARY KEY (mid),
PRIMARY KEY (mid) FOREIGN KEY fk_measurement_vessel (vid)
REFERENCES vessel(vid)
ON DELETE RESTRICT,
FOREIGN KEY fk_measurement_equipment (eid)
REFERENCES equipment(eid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
CREATE TABLE provisions ( CREATE TABLE provisions (
@@ -262,7 +350,7 @@ CREATE TABLE provisions (
provname varchar(40) NOT NULL, provname varchar(40) NOT NULL,
provcat tinyint(3) DEFAULT NULL, provcat tinyint(3) DEFAULT NULL,
sid smallint(6) UNSIGNED DEFAULT NULL, sid smallint(6) UNSIGNED DEFAULT NULL,
boxid smallint(6) UNSIGNED NOT NULL DEFAULT 1, boxid smallint(6) UNSIGNED DEFAULT NULL,
number smallint(6) UNSIGNED NOT NULL DEFAULT 1, number smallint(6) UNSIGNED NOT NULL DEFAULT 1,
target smallint(6) UNSIGNED DEFAULT NULL, -- for shopping list target smallint(6) UNSIGNED DEFAULT NULL, -- for shopping list
weight float(5,2) UNSIGNED DEFAULT NULL, weight float(5,2) UNSIGNED DEFAULT NULL,
@@ -273,7 +361,13 @@ CREATE TABLE provisions (
shelflife date DEFAULT NULL, shelflife date DEFAULT NULL,
price decimal(12,2) DEFAULT NULL, price decimal(12,2) DEFAULT NULL,
remarks varchar(150) DEFAULT NULL, remarks varchar(150) DEFAULT NULL,
PRIMARY KEY (provid) PRIMARY KEY (provid),
FOREIGN KEY fk_provisions_storage (sid)
REFERENCES storage(sid)
ON DELETE RESTRICT,
FOREIGN KEY fk_provisions_box (boxid)
REFERENCES box(boxid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/* TODO /* TODO
@@ -301,34 +395,44 @@ CREATE TABLE document (
CREATE TABLE docref ( CREATE TABLE docref (
drid int(10) NOT NULL AUTO_INCREMENT, drid int(10) NOT NULL AUTO_INCREMENT,
reftype enum('vessel','box','equipment','project','task','user','company') NOT NULL DEFAULT 'vessel', reftype enum('vessel','box','equipment','project','maint', 'task','user','company') NOT NULL DEFAULT 'vessel',
docid smallint(6) NOT NULL, docid smallint(6) NOT NULL,
refid int(10) NOT NULL, refid int(10) NOT NULL,
PRIMARY KEY (drid), PRIMARY KEY (drid),
UNIQUE INDEX ix_docref (docid, refid, reftype), UNIQUE INDEX ix_docref (docid, refid, reftype),
INDEX ix_docref_ref (refid, reftype),
FOREIGN KEY fk_docref_doc (docid) FOREIGN KEY fk_docref_doc (docid)
REFERENCES document (docid) REFERENCES document (docid)
ON DELETE RESTRICT ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/* TODO optional fields: plan date, target date, completion date /* TODO optional fields: target date?
interval_hours, last_hours responsible?
signalk: operating hours current vs maint every n operating hours in separate signalk: operating hours current vs maint every n operating hours in separate
*/ */
CREATE TABLE maintenance ( CREATE TABLE maintenance (
maintid int(10) NOT NULL AUTO_INCREMENT, maintid int(10) NOT NULL AUTO_INCREMENT,
vid smallint(6) NOT NULL DEFAULT 1, vid smallint(6) NOT NULL DEFAULT 1,
eid smallint(6) UNSIGNED DEFAULT NULL, eid smallint(6) UNSIGNED DEFAULT NULL,
series smallint(6) DEFAULT NULL, series smallint(6) UNSIGNED DEFAULT NULL,
activities varchar(40) NOT NULL, activities varchar(40) NOT NULL,
plan_date DATE DEFAULT NULL,
plan_precision enum('day','week','month','quarter') NOT NULL DEFAULT 'day',
completion_date DATE DEFAULT NULL,
interval_hours smallint(6) DEFAULT NULL,
last_hours int(10) DEFAULT NULL,
remarks varchar(150) DEFAULT NULL, remarks varchar(150) DEFAULT NULL,
maintstate enum('new','planned','ongoing','done') NOT NULL DEFAULT 'new', maintstate enum('new','plan','ongoing','skipped','missed','done') NOT NULL DEFAULT 'new',
PRIMARY KEY (maintid) PRIMARY KEY (maintid),
FOREIGN KEY fk_maintenance_vessel (vid)
REFERENCES vessel(vid)
ON DELETE RESTRICT,
FOREIGN KEY fk_maintenance_equipment (eid)
REFERENCES equipment(eid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/* TODO? time recording */ /* TODO time recording? */
CREATE TABLE project ( CREATE TABLE project (
projid smallint(6) NOT NULL AUTO_INCREMENT, projid smallint(6) NOT NULL AUTO_INCREMENT,
projname varchar(40) NOT NULL, projname varchar(40) NOT NULL,
@@ -340,9 +444,16 @@ CREATE TABLE project (
costs_final decimal(12,2) DEFAULT NULL, costs_final decimal(12,2) DEFAULT NULL,
remarks varchar(150) DEFAULT NULL, remarks varchar(150) DEFAULT NULL,
projstate enum('new','plan','ongoing','paused','finished') NOT NULL DEFAULT 'new', projstate enum('new','plan','ongoing','paused','finished') NOT NULL DEFAULT 'new',
PRIMARY KEY (projid) PRIMARY KEY (projid),
FOREIGN KEY fk_project_vessel (vid)
REFERENCES vessel(vid)
ON DELETE RESTRICT,
FOREIGN KEY fk_project_user (responsible)
REFERENCES user(userid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/* TODO executed_by : company or user? or both? */
CREATE TABLE task ( CREATE TABLE task (
taskid int(10) NOT NULL AUTO_INCREMENT, taskid int(10) NOT NULL AUTO_INCREMENT,
vid smallint(6) DEFAULT NULL, vid smallint(6) DEFAULT NULL,
@@ -356,51 +467,87 @@ CREATE TABLE task (
started datetime DEFAULT NULL, started datetime DEFAULT NULL,
finished datetime DEFAULT NULL, finished datetime DEFAULT NULL,
responsible smallint(6) NOT NULL, responsible smallint(6) NOT NULL,
/* TODO executed_by : company or user? or both? */ remarks varchar(150) DEFAULT NULL,
PRIMARY KEY (taskid), PRIMARY KEY (taskid),
FOREIGN KEY fk_task_user (responsible) FOREIGN KEY fk_task_user (responsible)
REFERENCES user(userid) REFERENCES user(userid)
ON DELETE RESTRICT,
FOREIGN KEY fk_task_vessel (vid)
REFERENCES vessel(vid)
ON DELETE RESTRICT,
FOREIGN KEY fk_task_project (projid)
REFERENCES project(projid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/* Notes can be assigned to tasks,maintenances and equipment */ /* Notes can be assigned to tasks, maintenances and equipment */
CREATE TABLE note ( CREATE TABLE note (
noteid int(10) NOT NULL AUTO_INCREMENT, noteid int(10) NOT NULL AUTO_INCREMENT,
notetype enum('task','maint','equip') NOT NULL DEFAULT 'task', notetype enum('task','maint','equip') NOT NULL DEFAULT 'task',
refid int(10) NOT NULL, refid int(10) NOT NULL,
annotation text NOT NULL, annotation text NOT NULL,
PRIMARY KEY (noteid) created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_by smallint(6) DEFAULT NULL,
PRIMARY KEY (noteid),
FOREIGN KEY fk_note_user (created_by)
REFERENCES user(userid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/* generic key value store for main objects */
CREATE TABLE property (
propid int(10) NOT NULL AUTO_INCREMENT,
objid int(10) UNSIGNED NOT NULL,
objtype enum('vessel','equip','inv','proj','maint'),
keyname varchar(32) NOT NULL,
valstr varchar(200) DEFAULT NULL,
valint int(10) DEFAULT NULL,
PRIMARY KEY (propid),
INDEX ix_prop_obj (objid, objtype)
);
CREATE TABLE checklist ( CREATE TABLE checklist (
clid smallint(6) NOT NULL AUTO_INCREMENT, clid smallint(6) NOT NULL AUTO_INCREMENT,
title varchar(30) NOT NULL, title varchar(30) NOT NULL,
parent smallint(6) DEFAULT NULL, parent smallint(6) DEFAULT NULL,
clstate enum('new','open','closed') NOT NULL DEFAULT 'new', clstate enum('new','open','closed') NOT NULL DEFAULT 'new',
PRIMARY KEY (clid) PRIMARY KEY (clid),
FOREIGN KEY fk_checklist_parent (parent)
REFERENCES checklist(clid)
ON DELETE RESTRICT
) ENGINE=InnoDB;
CREATE TABLE checkgroup (
groupid smallint(6) UNSIGNED NOT NULL,
title varchar(30) NOT NULL,
PRIMARY KEY (groupid)
) ENGINE=InnoDB; ) ENGINE=InnoDB;
CREATE TABLE checkitem ( CREATE TABLE checkitem (
checkid int(10) NOT NULL AUTO_INCREMENT, checkid int(10) NOT NULL AUTO_INCREMENT,
checkname varchar(60) NOT NULL, checkname varchar(60) NOT NULL,
groupid tinyint(3) DEFAULT NULL, groupid smallint(6) UNSIGNED DEFAULT NULL,
checkresult enum('unchecked','checked','unused') NOT NULL DEFAULT 'unused', checkresult enum('unchecked','checked','unused') NOT NULL DEFAULT 'unused',
PRIMARY KEY (checkid) PRIMARY KEY (checkid),
FOREIGN KEY fk_checkitem_group (groupid)
REFERENCES checkgroup(groupid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
CREATE TABLE checkref ( CREATE TABLE checkref (
clid smallint(6) NOT NULL, clid smallint(6) NOT NULL,
checkid int(10) NOT NULL, checkid int(10) NOT NULL,
sort smallint(6) DEFAULT NULL, sort smallint(6) DEFAULT NULL,
PRIMARY KEY (clid, checkid) PRIMARY KEY (clid, checkid),
FOREIGN KEY fk_checkref_checklist (clid)
REFERENCES checklist(clid)
ON DELETE CASCADE,
FOREIGN KEY fk_checkref_checkitem (checkid)
REFERENCES checkitem(checkid)
ON DELETE CASCADE
) ENGINE=InnoDB; ) ENGINE=InnoDB;
CREATE TABLE checkgroup ( /* Expansion for future use: signalk mapping (experimental) */
groupid int(10) NOT NULL,
title varchar(30) NOT NULL,
PRIMARY KEY (groupid)
) ENGINE=InnoDB;
/* Expansion for future use: signalk mapping (just an idea) */
CREATE TABLE signalk ( CREATE TABLE signalk (
skid int(10) NOT NULL AUTO_INCREMENT, skid int(10) NOT NULL AUTO_INCREMENT,
vid smallint(6) NOT NULL, vid smallint(6) NOT NULL,
@@ -408,7 +555,34 @@ CREATE TABLE signalk (
objid int(10) NOT NULL, objid int(10) NOT NULL,
datatype enum('engine_hours','tank_level') NOT NULL, datatype enum('engine_hours','tank_level') NOT NULL,
skpath varchar(255) NOT NULL, skpath varchar(255) NOT NULL,
mid smallint(6) DEFAULT NULL,
PRIMARY KEY (skid), PRIMARY KEY (skid),
UNIQUE KEY ix_signalk UNIQUE KEY ix_signalk
(vid, objtype, objid, datatype) (vid, objtype, objid, datatype),
FOREIGN KEY fk_signalk_vessel (vid)
REFERENCES vessel(vid)
ON DELETE RESTRICT
) ENGINE=InnoDB; ) ENGINE=InnoDB;
/* Token
- Python: secrets.token_hex(8)
- PHP: bin2hex(random_bytes(8)) */
CREATE TABLE recordlock (
lock_table varchar(40) NOT NULL,
lock_key int(10) NOT NULL,
token varchar(16) NOT NULL,
userid smallint(6) NOT NULL,
created_at timestamp NOT NULL DEFAULT current_timestamp,
last_seen timestamp NOT NULL DEFAULT current_timestamp,
PRIMARY KEY (lock_table, lock_key),
UNIQUE KEY ix_lock_token (token)
) ENGINE=MEMORY;
/* Use with: UPDATE revision SET changed=CURRENT_TIMESTAMP WHERE revtype=? AND revid=? */
CREATE TABLE revision (
revtype enum('dropdown','table') NOT NULL,
revid smallint(6) UNSIGNED NOT NULL,
changed timestamp NOT NULL,
PRIMARY KEY (revtype, revid),
INDEX ix_revision_ts (changed) -- for select by timestamp
) ENGINE=MEMORY;
-78
View File
@@ -1,78 +0,0 @@
/* Generic data suitable for all kind of boats
* SPDX-License-Identifier: WTFPL
*/
INSERT INTO user (userid, login, pass, displayname, role) VALUES
(2, 'helmsman', '$2y$10$4keuVm.WD/JeRmAqp2h4MeSxxKITsKv2q07XZrxPUuT/V80CTPbje', 'Helmsman', 'helmsman'),
(3, 'sailor', '$2y$10$4keuVm.WD/JeRmAqp2h4MeSxxKITsKv2q07XZrxPUuT/V80CTPbje', 'Sailor', 'sailor');
INSERT INTO settings (userid, sno, valint) VALUES
(2, 1, 1), -- Vessel 1 for helmsman
(3, 1, 1); -- Vessel 1 for sailor
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(1, 1, 'Einrumpf'), -- Mono
(1, 2, 'Katamaran'),
(1, 3, 'Trimaran');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(2, 3, 'Dienstleister'), -- Service
(2, 4, 'Werft'), -- Shipyard
(2, 5, 'Segelmacher'), -- Sailmaker
(2, 6, 'Yachthafen'), -- Marina
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(3, 2, 'Bilge'),
(3, 3, 'Schwalbennest');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(4, 1, 'Rumpf'),
(4, 2, 'Decks'),
(4, 3, 'Rigg'),
(4, 4, 'Segel'),
(4, 5, 'Motor'),
(4, 6, 'Elektrik'),
(4, 7, 'Elektronik'),
(4, 8, 'Navigation'),
(4, 9, 'Pantry');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(5, 1, 'Allgemein'),
(5, 2, 'Getränke');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(6, 1, 'kg'),
(6, 2, 'Liter'),
(6, 3, 'Stück'),
(6, 4, 'Packung'),
(6, 5, 'Dose'),
(6, 6, 'Flasche');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(7, 1, 'ATO'),
(7, 2, 'Streifensicherung'),
(7, 3, 'Feinsicherung (GS)'),
(7, 4, 'Torpedosicherung'),
(7, 5, 'T-Sicherung');
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES
(8, 1, 'mm'),
(8, 2, 'cm'),
(8, 3, 'g'),
(8, 4, 'kg');
INSERT INTO storage (sid, vid, sname, stype, x, y, z, remarks) VALUES
(0, 1, 'An Bord', 0, 0, 0, 0, 'Alles wo der Ort nicht spezifiziert werden kann');
/* Eine Liste mit häufig verwendeten Herstellern
comptype=2
*/
INSERT INTO company (comptype, compname) VALUES
(2, 'Garmin'),
(2, 'Watcheye'),
(2, 'Digital Yacht'),
(2, 'B&G'),
(2, 'Raymarine'),
(2, 'Harken'),
(2, 'Selden');
+30
View File
@@ -0,0 +1,30 @@
INSERT INTO measurement (mname, val1, accuracy) VALUES
('SA - Segelflaeche', 0, 'unknown'),
('P - Großsegel-Vorliek', 0, 'unknown'),
('E - Großsegel-Unterliek', 0, 'unknown'),
('I - Höhe des Vorsegeldreiecks', 0, 'unknown'),
('J - Basis des Vorsegeldreiecks', 0, 'unknown'),
('ISP - Höhe des Spinnakerfalls', 0, 'unknown'),
('SPL - Länge des Spinnakerbaums', 0, 'unknown'),
('TPS - Abstand Tackpunkt - Mast', 0, 'unknown'),
('FL - Vorstaglänge', 0, 'unknown'),
('IG - Höhe des inneren Vorsegelfalls', 0, 'unknown'),
('JH - Höhe des Vorsegelfalls', 0, 'unknown'),
('BAS - Großbaumhöhe', 0, 'unknown'),
('LP - Abstand Schothorn - Vorliek Fock', 0, 'unknown'),
('LPG - Abstand Schothorn Vorliek Genua', 0, 'unknown'),
('MW - Großsegelbreite', 0, 'unknown')
('MUW - Obere Großsegelbreite', 0, 'unknown')
('MTW - Großsegelbreite am Kopf', 0, 'unknown')
('MGU - Großsegel oberer Meßpunkt', 0, 'unknown')
('MGM - Großsegel mittlerer Meßpunkt', 0, 'unknown')
('MGL - Großsegel unterer Meßpunkt', 0, 'unknown')
('SHW - Halbe Spinnakerbreite', 0, 'unknown')
('SMG - Spinnaker Mid-Girth', 0, 'unknown')
('SFL - Spinnaker-Unterliekslänge', 0, 'unknown')
('LOA - Länge ueber alles', 0, 'unknown')
('LWL - Wasserlinienlänge', 0, 'unknown')
('BOA - Grösste Breite', 0, 'unknown')
('BWL - Breite an der Wasserlinie', 0, 'unknown')
('D - Tiefgang', 0, 'unknown')
('DISP - Verdrängung', 0, 'unknown');
+40 -20
View File
@@ -11,18 +11,28 @@ UPDATE user SET userid=0 WHERE userid=1;
INSERT INTO user (userid, login, pass, displayname, role) VALUES INSERT INTO user (userid, login, pass, displayname, role) VALUES
(1, 'captain', '$2y$10$naVMnC4S6bZ3IakxLJPJK.iSazlkYxVLeiRt9CB/j0jSExQZU1SCK', 'Captain', 'captain'); (1, 'captain', '$2y$10$naVMnC4S6bZ3IakxLJPJK.iSazlkYxVLeiRt9CB/j0jSExQZU1SCK', 'Captain', 'captain');
INSERT INTO settings (userid, sno, valint) VALUES INSERT INTO settings (userid, sno, valint, valstr) VALUES
(0, 0, 1), -- Database schema version (0, 0, 1, NULL), -- Database schema version
(0, 1, 0), -- No vessel assignment to SYSTEM (0, 1, 0, NULL), -- No vessel assignment to SYSTEM
(1, 1, 0), -- No vessel assignment to user "captain" (1, 1, 0, NULL), -- No vessel assignment to user "captain"
(0, 20, 1280), -- Image width limit (0, 20, 1280, NULL), -- Image width limit
(0, 21, 1024); -- Image height limit (0, 21, 1024, NULL), -- Image height limit
(0, 4, NULL, '€'), -- Currency symbol
(0, 5, 0, 'http://127.0.0.1:3000'), -- Signal K: to enable set valint=1
(0, 6, 0, 'localhost:2597'); -- NMEA2000 (for future use)
/* setting descriptions */ /* setting descriptions */
INSERT INTO settings (userid, sno, valstr) VALUES INSERT INTO settings (userid, sno, valstr) VALUES
(-1, 0, 'database schema version'),
(-1, 1, 'vessel id'), (-1, 1, 'vessel id'),
(-1, 2, 'date format'), (-1, 2, 'date format'),
(-1, 3, 'user menu'), (-1, 3, 'user menu'),
(-1, 4, 'currency symbol e.g. €, $, £, ¥'),
(-1, 5, 'signalk connection'),
(-1, 6, 'nmea2000 connection'),
(-1, 7, 'usb backup device serial'),
(-1, 8, 'usb backup partition uuid'),
(-1, 9, 'last backup'),
(-1, 10, 'rows in table'), (-1, 10, 'rows in table'),
(-1, 20, 'maximum image width'), (-1, 20, 'maximum image width'),
(-1, 21, 'maximum image height'), (-1, 21, 'maximum image height'),
@@ -53,20 +63,24 @@ INSERT INTO settings (userid, sno, valstr) VALUES
(-1, 211, 'cable filter json'), (-1, 211, 'cable filter json'),
(-1, 212, 'fuse filter json'); (-1, 212, 'fuse filter json');
/* Liste der Listen wird immer benötigt */ /* List of lists is always required */
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
(0, 0, 'Liste der Listen'), (0, 0, 'Liste der Listen', 'locked'),
(0, 1, 'Rumpftypen'), (0, 1, 'Bootstypen', NULL),
(0, 2, 'Firmentypen'), (0, 2, 'Firmentypen', NULL),
(0, 3, 'Stauraumtypen'), (0, 3, 'Stauraumtypen', NULL),
(0, 4, 'Ausrüstungskategorien'), (0, 4, 'Ausrüstungskategorien', NULL),
(0, 5, 'Proviantkategorien'), (0, 5, 'Proviantkategorien', NULL),
(0, 6, 'Provianteinheiten'), (0, 6, 'Provianteinheiten', NULL),
(0, 7, 'Sicherungstypen'), (0, 7, 'Sicherungstypen', NULL),
(0, 8, 'Einheiten'), (0, 8, 'Einheiten', NULL),
(0, 9, 'Kistentypen'), (0, 9, 'Kistentypen', NULL),
(0, 10, 'Sicherungsblöcke'), -- fuse locations (0, 10, 'Sicherungsblöcke', NULL), -- fuse locations
(0, 11, 'Kabeltypen'); (0, 11, 'Kabeltypen', NULL),
(0, 12, 'Technische Kabel-Bezeichnung', NULL),
(0, 13, 'Inventarkategorien', NULL),
(0, 14, 'BBN vessel.data Felder', 'locked'),
(0, 15, 'Messungskategorien', NULL);
INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
(2, 1, 'Lieferant', 'fixed'), (2, 1, 'Lieferant', 'fixed'),
@@ -78,3 +92,9 @@ INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
(3, 0, 'Stauraum allgemein', 'fixed'), (3, 0, 'Stauraum allgemein', 'fixed'),
(3, 1, 'Tank', 'fixed'), (3, 1, 'Tank', 'fixed'),
(3, 2, 'Extern', 'fixed'); -- not on board (3, 2, 'Extern', 'fixed'); -- not on board
INSERT INTO dropdown (ddid, ddval, ddtext, ddshort, flags) VALUES
(8, 1, 'Millimeter', 'mm', 'fixed');
INSERT INTO company (compid, compname, comptype) VALUES
(-3, 'Eigenbau', 3);
+42 -21
View File
@@ -11,17 +11,27 @@ UPDATE user SET userid=0 WHERE userid=1;
INSERT INTO user (userid, login, pass, displayname, role) VALUES INSERT INTO user (userid, login, pass, displayname, role) VALUES
(1, 'captain', '$2y$10$naVMnC4S6bZ3IakxLJPJK.iSazlkYxVLeiRt9CB/j0jSExQZU1SCK', 'Captain', 'captain'); (1, 'captain', '$2y$10$naVMnC4S6bZ3IakxLJPJK.iSazlkYxVLeiRt9CB/j0jSExQZU1SCK', 'Captain', 'captain');
INSERT INTO settings (userid, sno, valint) VALUES INSERT INTO settings (userid, sno, valint, valstr) VALUES
(0, 0, 1), -- Database schema version (0, 0, 1, NULL), -- Database schema version
(0, 1, 0), -- No vessel assignment to SYSTEM (0, 1, 0, NULL), -- No vessel assignment to SYSTEM
(1, 1, 0), -- No vessel assignment to user "captain" (1, 1, 0, NULL), -- No vessel assignment to user "captain"
(0, 20, 1280), -- Image width limit (0, 20, 1280, NULL), -- Image width limit
(0, 21, 1024); -- Image height limit (0, 21, 1024, NULL), -- Image height limit
(0, 4, NULL, '€'), -- Currency symbol
(0, 5, 0, 'http://127.0.0.1:3000'), -- Signal K: to enable set valint=1
(0, 6, 0, 'localhost:2597'); -- NMEA2000 (for future use)
/* setting descriptions */ /* setting descriptions */
INSERT INTO settings (userid, sno, valstr) VALUES INSERT INTO settings (userid, sno, valstr) VALUES
(-1, 1, 'vessel id'), (-1, 1, 'vessel id'),
(-1, 2, 'date format'), (-1, 2, 'date format'),
(-1, 3, 'user menu'),
(-1, 4, 'currency symbol e.g. €, $, £, ¥'),
(-1, 5, 'signalk connection'),
(-1, 6, 'nmea2000 connection'),
(-1, 7, 'usb backup device serial'),
(-1, 8, 'usb backup partition uuid'),
(-1, 9, 'last backup'),
(-1, 10, 'rows in table'), (-1, 10, 'rows in table'),
(-1, 20, 'maximum image width'), (-1, 20, 'maximum image width'),
(-1, 21, 'maximum image height'), (-1, 21, 'maximum image height'),
@@ -52,20 +62,24 @@ INSERT INTO settings (userid, sno, valstr) VALUES
(-1, 211, 'cable filter json'), (-1, 211, 'cable filter json'),
(-1, 212, 'fuse filter json'); (-1, 212, 'fuse filter json');
/* list of lists always needed */ /* List of lists is always required */
INSERT INTO dropdown (ddid, ddval, ddtext) VALUES INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
(0, 0, 'list of lists'), (0, 0, 'list of lists', NULL),
(0, 1, 'hull type'), (0, 1, 'vessel type', NULL),
(0, 2, 'company type'), (0, 2, 'company type', NULL),
(0, 3, 'storage type'), (0, 3, 'storage type', NULL),
(0, 4, 'equipment category'), (0, 4, 'equipment category', NULL),
(0, 5, 'provision category'), (0, 5, 'provision category', NULL),
(0, 6, 'provision unit'), (0, 6, 'provision unit', NULL),
(0, 7, 'fuse type'), (0, 7, 'fuse type', NULL),
(0, 8 , 'unit'); (0, 8, 'unit', NULL),
(0, 9, 'box types'), (0, 9, 'box types', NULL),
(0.10, 'fuse blocks'), (0, 10, 'fuse blocks', NULL),
(0,11, 'cable types'); (0, 11, 'cable types', NULL),
(0, 12, 'cable desc. technical', NULL),
(0, 13, 'inventory category', NULL),
(0, 14, 'BBN vessel.data fields', 'locked'),
(0, 15, 'measurement category', NULL);
INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
(2, 1, 'Supplier', 'fixed'), (2, 1, 'Supplier', 'fixed'),
@@ -75,4 +89,11 @@ INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES INSERT INTO dropdown (ddid, ddval, ddtext, flags) VALUES
(3, 0, 'Generic storage', 'fixed'), (3, 0, 'Generic storage', 'fixed'),
(3, 1, 'Tank', 'fixed'); (3, 1, 'Tank', 'fixed'),
(3, 2, 'External', 'fixed');
INSERT INTO dropdown (ddid, ddval, ddtext, ddshort, flags) VALUES
(8, 1, 'mm', 'Millimetre', 'fixed');
INSERT INTO company (compid, compname, comptype) VALUES
(-3, 'Custom built', 3);
+99
View File
@@ -0,0 +1,99 @@
/* Generic data suitable for all kind of boats
* SPDX-License-Identifier: WTFPL
Hinzufügen um das System kennenzulernen
Hängt von generic.sql ab
*/
INSERT INTO storage (sid, sname, color) VALUES
(1, 'An Bord', 'F9F06B'),
(2, 'Vorpiek', 'F9F06B'),
(3, 'Achterpiek', 'F9F06B'),
(4, 'Salon BB', 'F9F06B'),
(5, 'Salon STB', 'F9F06B'),
(6, 'Pantry', 'F9F06B'),
(7, 'Ankerkasten', 'F9F06B'),
(8, 'An Deck', 'F9F06B'),
(9, 'Backskiste BB', 'F9F06B'),
(10, 'Backskiste STB', 'F9F06B'),
(11, 'Bilge', 'F9F06B'),
(12, 'Gaskasten', 'F9F06B'),
(13, 'Salonkoje BB', 'F9F06B'),
(14, 'Salonkoje STB ', 'F9F06B');
INSERT INTO box (boxid, label) VALUES
(1, 'Werkzeugkiste'),
(2, 'Kiste, klein'),
(3, 'Kiste, groß');
INSERT INTO equipment (eid, ename) VALUES
(1, 'Großsegel'),
(2, 'Fock'),
(3, 'Genua'),
(4, 'Spinnaker'),
(5, 'Vorstang'),
(6, 'Achterstan'),
(7, 'Oberwant BB'),
(8, 'Unterwant BB'),
(9, 'Oberwant STB'),
(10, 'Unterwant STB'),
(11, 'Motor'),
(12, 'Außenborder'),
(13, 'Schlauchboot'),
(14, 'AIS Transcsiver'),
(15, 'Funkgerät'),
(16, 'Kartenplotter'),
(17, 'Batterie');
INSERT INTO inventory (invid, invname, icat, conttype, sid, boxid, eid, number,
weight, price, purchdate, invcond, remarks, flags) VALUES
(1, 'Bootshaken', NULL, 'storage', 1, NULL, NULL, 1, NULL, NULL, NULL, 'unknown', NULL, NULL),
(2, 'Fender', NULL, 'storage', 1, NULL, NULL, 4, NULL, NULL, NULL, 'unknown', NULL, NULL),
(3, 'Winschkurbel', NULL, 'storage', 1, NULL, NULL, 1, NULL, NULL, NULL, 'unknown', NULL, NULL),
(4, 'Landanschlußkabel', NULL, 'storage', 1, NULL, NULL, 1, NULL, NULL, NULL, 'unknown', NULL, NULL),
(5, 'Kochtopf', NULL, 'storage', 24, NULL, NULL, 1, NULL, NULL, NULL, 'unknown', NULL, NULL),
(6, 'Pfanne', NULL, 'storage', 24, NULL, NULL, 1, NULL, NULL, NULL, 'unknown', NULL, NULL),
(7, 'Kombizange', NULL, 'box', NULL, 6, NULL, 1, NULL, NULL, NULL, 'unknown', NULL, NULL),
(8, 'Hammer', NULL, 'box', NULL, 6, NULL, 1, NULL, NULL, NULL, 'unknown', NULL, NULL),
(9, 'Rohrzange', NULL, 'box', NULL, 6, NULL, 1, NULL, NULL, NULL, 'good', NULL, NULL),
(10, 'Schraubenzieher, groß', NULL, 'box', NULL, 6, NULL, 1, NULL, NULL, NULL, 'unknown', NULL, NULL);
INSERT INTO provisions (provname) VALUES
('Kaffee'),
('Zucker'),
('Salz'),
('Pfeffer'),
('Milch'),
('Müsliriegel'),
('Erbsensuppe'),
('Gulaschsuppe'),
('Kekse');
INSERT INTO checklist (clid, title) VALUES
(1, 'Einwintern'),
(2, 'Auswintern'),
(3, 'Mast legen');
INSERT INTO checkitem (checkid, checkname) VALUES
(1, 'Bilge trocknen'),
(2, 'Frostschutz in Motor einfüllen'),
(3, 'Windpilot abbauen'),
(4, 'Plane über Boot'),
(5, 'Plane Vorschiff unterstützen'),
(5, 'Salinge unterstützen'),
(6, 'Polster ausräumen'),
(7, 'Gardinen abnehmen'),
(8, 'Kleiderschrank leeräumen'),
(9, 'Lebensmittel von Bord');
INSERT INTO checkref (clid, checkid) VALUES
(1, 1),
(1, 2),
(1, 3),
(1, 4),
(1, 5),
(1, 6),
(1, 7),
(1, 8),
(1, 9);
+7
View File
@@ -0,0 +1,7 @@
/* Some sample data
* SPDX-License-Identifier: WTFPL
Add this to get to know the system
Depends on generic_en.sql
*/
+36
View File
@@ -0,0 +1,36 @@
yms (0.3.0-1) unstable; urgency=medium
* native gui: can create and edit all kind of records
* native gui: implemented record locking
* updater script for web gui
* many bugs fixed in webgui
* prepare list revision feature (reload support)
* database localization tool
* new property table for generic key/value store
* webgui: set file access rights
* fix debian packaging
-- Thomas Hooge <thomas@hoogi.de> Wed, 11 Nov 2026 19:00:00 +0200
yms (0.2.2-1) unstable; urgency=medium
* native gui: prepared list views for main objects
* added position to equipment
* box improved with dimensions, net weight and price
* experimental signalk integration
* added config for currency symbol support
* database prepared for lazy record locking feature
* some small database improvements
* webgui: some improvements and fixes
* work on native gui: display data lists
* prepare dynamic language support for webgui
* improve image uploading and scaling code
* added date formatting code
-- Thomas Hooge <thomas@hoogi.de> Mon, 21 Sep 2026 19:00:00 +0200
yms (0.2.1-1) unstable; urgency=medium
* Initial Debian packaging.
-- Thomas Hooge <thomas@hoogi.de> Fri, 28 Aug 2026 11:30:00 +0200
Vendored Executable
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -e
. /usr/share/debconf/confmodule
db_input high yms/db-name || true
db_input high yms/db-user || true
db_input high yms/db-password || true
db_input high yms/webgui || true
db_go
+40
View File
@@ -0,0 +1,40 @@
Source: yms
Section: misc
Priority: optional
Maintainer: Thomas Hooge <thomas@hoogi.de>
Build-Depends:
debhelper-compat (= 13),
gettext
Standards-Version: 4.7.2
Rules-Requires-Root: no
Package: yms
Architecture: all
Depends:
mariadb-server,
python3,
python3-gi,
gir1.2-gtk-3.0,
gir1.2-rsvg-2.0,
python3-mysqldb,
python3-dateutil,
python3-fitz,
python3-bcrypt,
python3-pyudev,
php (>= 8.0),
php-mysql,
php-xml,
gettext,
mupdf-tools
Suggests:
python3-sane
Description: Yacht Management Software
Yacht Management Software (YMS) is an application for managing yachts and
sailboats. It provides a native GTK desktop interface and a web interface.
.
YMS helps manage vessel equipment, inventory, provisions, documents,
maintenance work and tasks. It uses MariaDB for data storage and is
designed to be self-hosted.
.
The software is suitable for private boats, crews, sailing clubs and
boat projects.
Vendored
+2
View File
@@ -0,0 +1,2 @@
README
INSTALL
+36
View File
@@ -0,0 +1,36 @@
# Database
db/*.sql usr/share/yms/db/
# Native GUI
ymsgui.py usr/lib/yms/
yms/*.py usr/lib/yms/yms/
yms/model/*.py usr/lib/yms/yms/model/
yms/view/*.py usr/lib/yms/yms/view/
# GTK UI
yms/ui/* usr/share/yms/ui/
# Web-GUI
webgui/*.php usr/share/yms/webgui/
webgui/globals.inc usr/share/yms/webgui/
webgui/lib/*.inc usr/share/yms/webgui/lib/
webgui/css/* usr/share/yms/webgui/css/
webgui/js/* usr/share/yms/webgui/js/
webgui/img/* usr/share/yms/webgui/img/
webgui/bootstrap usr/share/yms/webgui/
webgui/locale/de_DE/LC_MESSAGES/yms.mo usr/share/yms/webgui/locale/de_DE/LC_MESSAGES/
webgui/sailboat.svg usr/share/yms/webgui/
webgui/config.inc-sample usr/share/yms/
# Shared static data
shapes/* usr/share/yms/shapes/
icons/* usr/share/yms/icons/
# Desktop entry
yms.desktop usr/share/applications/
# Idesktop link file
yms.lnk usr/share/yms/
# Webserver
config/apache/yms.conf /etc/apache2/conf-available/
+2
View File
@@ -0,0 +1,2 @@
/etc/yms/config.inc /usr/share/yms/webgui/config.inc
/usr/share/yms/icons /usr/lib/yms/icons
+1
View File
@@ -0,0 +1 @@
yms.1
Vendored Executable
+104
View File
@@ -0,0 +1,104 @@
#!/bin/sh
set -e
. /usr/share/debconf/confmodule
detect_webservers()
{
WEB_SERVERS=""
if dpkg-query -W -f='${Status}' apache2 2>/dev/null |
grep -q 'install ok installed'; then
WEB_SERVERS="$WEB_SERVERS apache2"
fi
if dpkg-query -W -f='${Status}' nginx 2>/dev/null |
grep -q 'install ok installed'; then
WEB_SERVERS="$WEB_SERVERS nginx"
fi
if dpkg-query -W -f='${Status}' lighttpd 2>/dev/null |
grep -q 'install ok installed'; then
WEB_SERVERS="$WEB_SERVERS lighttpd"
fi
WEB_SERVERS="${WEB_SERVERS# }"
}
db_get yms/db-name
DB_NAME="$RET"
db_get yms/db-user
DB_USER="$RET"
db_get yms/db-password
DB_PASSWORD="$RET"
echo "Configuring YMS..."
echo "Checking MariaDB database '${DB_NAME}'..."
if mariadb -N -B -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${DB_NAME}'" | grep -Fxq "${DB_NAME}"; then
echo "Database '${DB_NAME}' already exists."
else
echo "Database '${DB_NAME}' does not exist."
echo "Creating database '${DB_NAME}'..."
mariadb -e "CREATE DATABASE \`${DB_NAME}\`"
echo "Database '${DB_NAME}' created."
echo "Initializing database schema..."
mariadb "${DB_NAME}" < /usr/share/yms/db/mariadb.sql
mariadb "${DB_NAME}" < /usr/share/yms/db/minimal.sql
echo "Database schema initialized."
mariadb -e "CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASSWORD}'"
mariadb -e "GRANT SELECT, INSERT, UPDATE, DELETE ON \`${DB_NAME}\`.* TO '${DB_USER}'@'localhost'"
fi
echo "Initializing document storage..."
if ! getent group yms >/dev/null; then
addgroup --system yms
fi
if ! id -nG www-data | tr ' ' '\n' | grep -qx yms; then
adduser www-data yms
fi
mkdir -p /var/lib/yms/thumb
chown -R www-data:yms /var/lib/yms
db_get yms/webgui
if [ "$RET" = "true" ]; then
detect_webservers
case "$WEB_SERVERS" in
"")
echo "No supported webserver installed."
;;
apache2)
echo "Apache detected."
a2enconf yms
invoke-rc.d apache2 reload
echo "Web GUI for apache2 enabled."
;;
nginx)
echo "nginx detected."
;;
lighttpd)
echo "lighttpd detected."
;;
*)
echo "Multiple webservers detected: $WEB_SERVERS"
;;
esac
if [ ! -f /etc/yms/config.inc ]; then
# create initial configuration
sed \
-e "s|@DB_USERNAME@|$DB_USER|g" \
-e "s|@DB_PASSWORD@|$DB_PASSWORD|g" \
-e "s|@DB_SCHEMA@|$DB_NAME|g" \
/usr/share/yms/config.inc-sample \
> /etc/yms/config.inc
chmod 0640 /etc/yms/config.inc
chown root:www-data /etc/yms/config.inc
fi
fi
exit 0
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
set -e
. /usr/share/debconf/confmodule
case "$1" in
remove|purge)
db_input high yms/remove-info || true
db_go || true
;;
esac
exit 0
Vendored Executable
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/make -f
# Standard Debian build
%:
dh $@
# No build via Makefile
override_dh_auto_build:
# Generate translation and install generated files
override_dh_install:
mkdir -p debian/yms/usr/share/locale/de/LC_MESSAGES
msgfmt locale/de.po -o debian/yms/usr/share/locale/de/LC_MESSAGES/ymsgui.mo
install -D -m 0644 icons/yms.svg debian/yms/usr/share/icons/hicolor/scalable/apps/yms.svg
install -D -m 0644 icons/yms48.png debian/yms/usr/share/icons/hicolor/48x48/apps/yms.png
install -D -m 0644 icons/yms64.png debian/yms/usr/share/icons/hicolor/64x64/apps/yms.png
install -D -m 0755 debian/yms-launcher debian/yms/usr/bin/yms
dh_install
sed -i 's#@PREFIX@#/usr#g' debian/yms/usr/share/applications/yms.desktop
sed -i 's#@PREFIX@#/usr#g' debian/yms/usr/share/yms/yms.lnk
# Installation is handled by debian/install
override_dh_auto_install:
override_dh_installdebconf:
dh_installdebconf
+1
View File
@@ -0,0 +1 @@
3.0 (quilt)
+34
View File
@@ -0,0 +1,34 @@
Template: yms/db-name
Type: string
Default: yms
Description: Database name:
Please enter the name of the MariaDB database used by YMS.
Template: yms/db-user
Type: string
Default: ymsweb
Description: Web GUI database user:
Please enter the MariaDB user used by the YMS web interface.
Template: yms/db-password
Type: password
Description: Web GUI database password:
Please enter the password for the YMS web interface database user.
Template: yms/webgui
Type: boolean
Default: false
Description: Enable the YMS web interface?
The YMS package includes a web interface that can be served
by a web server.
.
Do you want to enable the web interface?
Template: yms/remove-info
Type: note
Description: YMS document storage was not removed
The YMS package has been removed, but the document storage
remains on the system.
.
The directory /var/lib/yms and its contents have not been
deleted.
Vendored Executable
+2
View File
@@ -0,0 +1,2 @@
#!/bin/sh
exec /usr/bin/python3 /usr/lib/yms/ymsgui.py "$@"
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 784 B

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

+1
View File
@@ -9,3 +9,4 @@ rm /var/www/html/index.html
rm /var/www/html/README rm /var/www/html/README
rm /var/www/html/TODO rm /var/www/html/TODO
rm /var/www/html/locale/de_DE.po rm /var/www/html/locale/de_DE.po
rm /var/www/html/Makefile
+27 -6
View File
@@ -7,6 +7,7 @@ BINDIR="${PREFIX}/bin"
DESKTOPDIR="${PREFIX}/share/applications" DESKTOPDIR="${PREFIX}/share/applications"
ICONDIR="${PREFIX}/share/icons/hicolor" ICONDIR="${PREFIX}/share/icons/hicolor"
DOCDIR="${PREFIX}/share/doc/yms" DOCDIR="${PREFIX}/share/doc/yms"
MANDIR="${PREFIX}/share/man/man1"
LOCALEDIR="${PREFIX}/share/locale" LOCALEDIR="${PREFIX}/share/locale"
SOURCEDIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) SOURCEDIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
@@ -14,11 +15,20 @@ SOURCEDIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
if [ "$1" = "uninstall" ]; then if [ "$1" = "uninstall" ]; then
echo "Uninstalling YMS..." echo "Uninstalling YMS..."
if [ "$(id -u)" -ne 0 ]; then
echo "Error: this script must be run as root."
echo "Please use:"
echo " sudo $0"
exit 1
fi
rm -f "${BINDIR}/yms"
rm -rf "${LIBDIR}" rm -rf "${LIBDIR}"
rm -rf "${SHAREDIR}" rm -rf "${SHAREDIR}"
rm -f "${BINDIR}/yms" rm -f "${SHAREDIR}/yms.lnk"
rm -f "${DESKTOPDIR}/yms.desktop" rm -f "${DESKTOPDIR}/yms.desktop"
rm -rf "${DOCDIR}" rm -rf "${DOCDIR}"
rm -f "${MANDIR}/yms.1"
rm -f "${LOCALEDIR}/de/LC_MESSAGES/ymsgui.mo" rm -f "${LOCALEDIR}/de/LC_MESSAGES/ymsgui.mo"
rm -f "${ICONDIR}/scalable/apps/yms.svg" rm -f "${ICONDIR}/scalable/apps/yms.svg"
@@ -57,12 +67,17 @@ rm -rf "${LIBDIR}/yms/ui"
# Static resources # Static resources
install -d "${SHAREDIR}" install -d "${SHAREDIR}"
install -d "${SHAREDIR}/ui" install -d "${SHAREDIR}/ui"
install -m 0644 \ cp -a \
"${SOURCEDIR}/yms/ui/main.ui" \ "${SOURCEDIR}/yms/ui/." \
"${SHAREDIR}/ui/main.ui" "${SHAREDIR}/ui/"
cp -a \ cp -a \
"${SOURCEDIR}/shapes/." \ "${SOURCEDIR}/shapes/." \
"${SHAREDIR}/shapes/" "${SHAREDIR}/shapes/"
sed "s#@PREFIX@#${PREFIX}#g" \
"${SOURCEDIR}/yms.lnk" \
> "${SHAREDIR}/yms.lnk"
chmod 0644 "${SHAREDIR}/yms.lnk"
chown -R root:root ${SHAREDIR}
# Documentation # Documentation
echo "Installing documentation..." echo "Installing documentation..."
@@ -76,6 +91,10 @@ install -m 0644 \
install -m 0644 \ install -m 0644 \
"${SOURCEDIR}/COPYING" \ "${SOURCEDIR}/COPYING" \
"${DOCDIR}/COPYING" "${DOCDIR}/COPYING"
install -d "${MANDIR}"
install -m 0644 \
"${SOURCEDIR}/yms.1" \
"${MANDIR}/yms.1"
echo "Installing translations..." echo "Installing translations..."
make translation make translation
@@ -107,9 +126,11 @@ chmod 0755 "${BINDIR}/yms"
echo "Installing desktop entry..." echo "Installing desktop entry..."
install -d "${DESKTOPDIR}" install -d "${DESKTOPDIR}"
install -m 0644 \ sed "s#@PREFIX@#${PREFIX}#g" \
"${SOURCEDIR}/yms.desktop" \ "${SOURCEDIR}/yms.desktop" \
"${DESKTOPDIR}/yms.desktop" > "${DESKTOPDIR}/yms.desktop"
chmod 0644 "${DESKTOPDIR}/yms.desktop"
# TODO webgui? or separately? # TODO webgui? or separately?
+1976 -51
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
Executable
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/python
"""
Updater for web gui
"""
import os
import sys
import getopt
import re
import shutil
import glob
import tarfile
from datetime import datetime
source_dir = "./webgui"
target_dir = "/var/www/html/yms"
backup_dir = "/var/backups"
backup = False
accept = False
dryrun = False
__author__ = "Thomas Hooge"
__copyright__ = "Copyleft 2024-2026, all rights reversed"
__version__ = "0.1"
__email__ = "thomas@hoogi.de"
__status__ = "Test"
# Update files on top level
update_files = ["*.php", "*.css", "globals.inc", "manifest.json", "sailboat.svg"]
# Totally replace target dirs with new ones
update_dirs_full = ["bootstrap", "css", "js", "lib", "shapes", "img"]
# Locale: translation files
locales = ["de_DE"]
def ask_yn(prompt):
answer = input(f"{prompt} (y/n): ").strip().lower()
return answer in ("y", "yes")
def read_version(globalfile):
if os.path.isfile(globalfile):
with open(globalfile, "r", encoding="utf-8") as fh:
content = fh.read(4096)
pattern = r"\$g_version\s*=\s*'(v\d+\.\d+\.\d+)';"
match = re.search(pattern, content)
if match:
return tuple(map(int, match.group(1).lstrip("v").split(".")))
return None
def create_backup(source_dir, backup_dir, dryrun=False):
if not os.path.isdir(backup_dir):
print(f"Backup directory '{backup_dir}' does not exist.")
return None
if not os.access(backup_dir, os.W_OK):
print(f"Backup directory '{backup_dir}' is not writeable.")
return None
dir_name = os.path.basename(os.path.normpath(source_dir))
date_stamp = datetime.now().strftime("%Y%m%d")
backup_file = os.path.join(backup_dir, f"{dir_name}_{date_stamp}.tar.gz")
def exclude_config(member):
if member.name == f"{dir_name}/config.inc":
return None
return member
if not dryrun:
with tarfile.open(backup_file, "w:gz") as tar:
tar.add(source_dir, arcname=dir_name, filter=exclude_config)
else:
print(f"creating backup of '{source_dir}' in '{backup_file}'")
return backup_file
def copy_dir_replace(dirname, source_dir, target_dir, dryrun=False):
# Complete replaces old directory with new one
source_path = os.path.join(source_dir, dirname)
target_path = os.path.join(target_dir, dirname)
print(f"full replace dir '{source_path}' -> '{target_path}'")
if os.path.exists(target_path):
if not dryrun:
shutil.rmtree(target_path)
else:
print(f"remove directory tree '{target_path}'")
else:
if dryrun:
print(f"directory '{target_path}' does not exist yet")
if not dryrun:
shutil.copytree(source_path, target_dir)
else:
print(f"copy directory tree '{source_path}' -> '{target_dir}'")
def copy_wildcard(source_dir, target_dir, pattern, dryrun=False):
print(f"copy pattern '{pattern}' from '{source_dir}' -> '{target_dir}'")
if not dryrun:
os.makedirs(target_dir, exist_ok=True)
if dryrun:
print(f"processing pattern '{pattern}'")
for source_file in glob.glob(os.path.join(source_dir, pattern)):
if os.path.isfile(source_file):
target_file = os.path.join(target_dir, os.path.basename(source_file))
if not dryrun:
shutil.copy2(source_file, target_file)
else:
print(f"copy file '{source_file}' -> '{target_file}'")
def usage():
print("{} v{}".format(os.path.basename(__file__), __version__))
print(__copyright__)
print()
print("Command line options")
print(f" -d --dir Target directory (default={target_dir})")
print(" -b --backup Backup directory (no backup if missing)")
print(" -h --help Show this help")
print(" -y --accept Skip security questions")
print(" --dryrun Test mode")
print()
if __name__ == "__main__":
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "d:b:yh",
["dir=", "backup=", "accept", "help", "dryrun"])
except getopt.GetoptError as err:
print(str(err))
sys.exit(2)
for opt, arg in opts:
if opt in ("-d", "--dir"):
target_dir = arg
elif opt in ("-b", "--backup"):
backup = True
backup_dir = arg
elif opt in ("-y", "--accept"):
accept = True
elif opt in ("-h", "--help"):
usage()
sys.exit(0)
elif opt in ("--dryrun"):
dryrun = True
# Check if target dir exists
if not os.path.isdir(target_dir):
print(f"Target directory '{target_dir}' does not exist. Aborting.")
sys.exit(1)
# Check if target dir contains a valid yms installation
# globals.inc must exist and contain version info in $g_version
globalfile = os.path.join(target_dir, 'globals.inc')
version = read_version(globalfile)
if not version:
print("Target contains no valid yms installation. Aborting.")
sys.exit(1)
# Check if version in source dir is greater than installed version
version_new = read_version(os.path.join(source_dir, 'globals.inc'))
if False: #version >= version_new:
versionstring = "v" + ".".join(map(str,version))
versionstring_new = "v" + ".".join(map(str,version_new))
print(f"Version {versionstring_new} is not newer than installed version {versionstring}. Aborting.")
sys.exit(1)
# Check if target is writeable
if False: #not os.access(target_dir, os.W_OK):
print(f"Target directory '{target_dir}' is not writeable, Aborting.")
sys.exit(1)
# Query for updating found installation
versionstring = "v" + ".".join(map(str,version))
if not accept and not ask_yn(f"Update yms {versionstring} installation in {target_dir}"):
print("Update cancelled by user")
sys.exit(0)
# Create backup
if backup and not create_backup(target_dir, backup_dir, dryrun):
print("Aborting.")
sys.exit(1)
# First complete directories
for dir in update_dirs_full:
source = os.path.join(source_dir, dir)
copy_dir_replace(dir, source_dir, target_dir, dryrun)
# Second update files in main directory
for pattern in update_files:
copy_wildcard(source_dir, target_dir, pattern, dryrun)
# At last the locales
for language in locales:
source_path = os.path.join(source_dir, "locale", language, "LC_MESSAGES")
target_path = os.path.join(target_dir, "locale", language, "LC_MESSAGES")
copy_wildcard(source_path, target_path, "*.mo", dryrun)
print("Done.")
+14
View File
@@ -0,0 +1,14 @@
# .PHONY php translation
FILES = *.php globals.inc lib/*.inc
all: php
php: yms.pot
yms.pot: $(FILES)
xgettext -L PHP -o yms.pot -p locale $(FILES) --from-code=UTF-8 --keyword="pgettext:1c,2"
msgmerge -U locale/de_DE.po locale/yms.pot
translation: locale/de_DE.po
msgfmt locale/de_DE.po -o locale/de_DE/LC_MESSAGES/yms.mo
+61 -15
View File
@@ -14,7 +14,9 @@ There can be a difference because not all items have a weight entered
*/ */
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Boxes'); $pagetitle = _('Boxes');
@@ -30,7 +32,7 @@ foreach ($sth->fetchAll() as $row) {
$opt_storage[$row['sid']] = $row['sname']; $opt_storage[$row['sid']] = $row['sname'];
} }
$opt_boxtype = db_get_options(9); $opt_boxtype = db_get_options(DD_BOX_TYPE);
// ========== ACTIONS START =================================================== // ========== ACTIONS START ===================================================
@@ -49,6 +51,7 @@ switch ($submit = form_get_action()) {
$p[':content'] = gpc_get_string($_POST, 'content'); $p[':content'] = gpc_get_string($_POST, 'content');
$p[':remarks'] = gpc_get_string($_POST, 'remarks'); $p[':remarks'] = gpc_get_string($_POST, 'remarks');
$id = db_exec_insert('box', $p); $id = db_exec_insert('box', $p);
db_set_revision('table', TBL_BOXES);
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -59,7 +62,12 @@ switch ($submit = form_get_action()) {
$p[':label'] = gpc_get_string($_POST, 'label'); $p[':label'] = gpc_get_string($_POST, 'label');
$p[':content'] = gpc_get_string($_POST, 'content'); $p[':content'] = gpc_get_string($_POST, 'content');
$p[':color'] = gpc_get_color($_POST, 'color'); $p[':color'] = gpc_get_color($_POST, 'color');
$p[':wx'] = gpc_get_int($_POST, 'wx');
$p[':wy'] = gpc_get_int($_POST, 'wy');
$p[':wz'] = gpc_get_int($_POST, 'wz');
$p[':weight'] = min(gpc_get_float($_POST, 'weight'), 99.99); $p[':weight'] = min(gpc_get_float($_POST, 'weight'), 99.99);
$p[':weight_net'] = min(gpc_get_float($_POST, 'weight_net'), 99.99);
$p[':price'] = gpc_get_currency($_POST, 'price');
$p[':sid'] = gpc_get_uint($_POST, 'sid'); $p[':sid'] = gpc_get_uint($_POST, 'sid');
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150); $p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
db_exec_update('box', $p, 'boxid'); db_exec_update('box', $p, 'boxid');
@@ -82,10 +90,12 @@ if ($action == ACT_DEFAULT):
echo "<h1>$pagetitle</h1>\n"; echo "<h1>$pagetitle</h1>\n";
$sql = "SELECT boxid, boxtype, sid, label, color, content, weight, remarks " $sql = "SELECT b.boxid, b.boxtype, b.sid, b.label, b.color, b.content, b.weight, b.remarks "
. "FROM box " . "FROM box AS b JOIN storage AS s USING (sid) "
. "ORDER BY label"; . "WHERE s.vid=? "
$sth = $pdo->query($sql); . "ORDER BY b.label";
$sth = $pdo->prepare($sql);
$sth->execute([$user->vid]);
$res = $sth->fetchAll(); $res = $sth->fetchAll();
echo '<table class="table table-striped">', "\n"; echo '<table class="table table-striped">', "\n";
echo "<thead>\n"; echo "<thead>\n";
@@ -109,7 +119,7 @@ foreach ($res as $row) {
echo '<td>', ($opt_boxtype[$row['boxtype']] ?? ''), "</td>\n"; echo '<td>', ($opt_boxtype[$row['boxtype']] ?? ''), "</td>\n";
echo '<td>', format_color(strtoupper($row['color'])), "</td>\n"; echo '<td>', format_color(strtoupper($row['color'])), "</td>\n";
echo '<td>', $row['content'], "</td>\n"; echo '<td>', $row['content'], "</td>\n";
echo '<td class="text-end">', format_float($row['weight'], 2), "</td>\n"; echo '<td class="text-end">', format_float($row['weight'], 2, 'kg'), "</td>\n";
// Edit current record button // Edit current record button
echo "<td>"; echo "<td>";
echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['boxid'], '"><i class="bi-pencil"></i></a>', "\n"; echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['boxid'], '"><i class="bi-pencil"></i></a>', "\n";
@@ -117,8 +127,8 @@ foreach ($res as $row) {
echo "</tr>\n"; echo "</tr>\n";
} }
// Table summary // Table summary
$numrows = count($res); //$numrows = count($res);
table_rec_summary($i, $numrows, $numrows, 5); //table_rec_summary(1, $numrows, $numrows, 6);
echo "</table>\n"; echo "</table>\n";
form_add_button('box.php'); form_add_button('box.php');
@@ -162,14 +172,15 @@ foreach ($opt_storage as $k => $v) {
elseif ($action == ACT_VIEW): elseif ($action == ACT_VIEW):
// ========== VARIANT: view single record ===================================== // ========== VARIANT: view single record =====================================
$sql = "SELECT boxtype, label, content, box.color, weight, box.remarks, box.sid, sname " $sql = "SELECT boxtype, label, content, box.color, weight, weight_net, price, "
. "box.wx, box.wy, box.wz, box.sid, box.remarks, sname "
. "FROM box LEFT JOIN storage USING (sid) " . "FROM box LEFT JOIN storage USING (sid) "
. "WHERE boxid=?"; . "WHERE boxid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([$id]); $sth->execute([$id]);
$box = $sth->fetch(PDO::FETCH_OBJ); $box = $sth->fetch(PDO::FETCH_OBJ);
echo '<h2>', $box->label, "</h2>\n"; echo '<h2>', sprintf(_('Box: %s'), h($box->label)), "</h2>\n";
// Bootstrap grid // Bootstrap grid
echo '<div class="container">'; echo '<div class="container">';
@@ -180,11 +191,15 @@ echo '<table class="table">', "\n";
echo '<tr><th style="width:20%">', _('Box type'),"</th><td>", ($opt_boxtype[$box->boxtype] ?? ''), "</td></tr>\n"; echo '<tr><th style="width:20%">', _('Box type'),"</th><td>", ($opt_boxtype[$box->boxtype] ?? ''), "</td></tr>\n";
echo '<tr><th>', _('Content'),"</th><td>", $box->content, "</td></tr>\n"; echo '<tr><th>', _('Content'),"</th><td>", $box->content, "</td></tr>\n";
echo '<tr><th>', _('Color'), '</th><td>', format_color($box->color), "</td></tr>\n"; echo '<tr><th>', _('Color'), '</th><td>', format_color($box->color), "</td></tr>\n";
echo '<tr><th>', _('Dimensions'), '</th><td>', format_measurement(3, 'mm', $box->wx, $box->wy, $box->wz), "</td></tr>\n";
# TODO also show sum of content weights for comparison
echo '<tr><th>', _('Weight'), '</th><td>', format_float($box->weight, 2, 'kg'), "</td></tr>\n"; echo '<tr><th>', _('Weight'), '</th><td>', format_float($box->weight, 2, 'kg'), "</td></tr>\n";
echo '<tr><th>', _('Empty&nbsp;Weight'), '</th><td>', format_float($box->weight_net, 2, 'kg'), "</td></tr>\n";
echo '<tr><th>', _('Price'),"</th><td>", format_currency($box->price), "</td></tr>\n";
echo '<tr><th>', _('Storage'),"</th><td>", $box->sname, '&nbsp;'; echo '<tr><th>', _('Storage'),"</th><td>", $box->sname, '&nbsp;';
echo '<a title="', _('View'), '" href="storage.php?f=view&id=', $box->sid, '"><i class="bi-eye"></i></a>'; echo '<a title="', _('View'), '" href="storage.php?f=view&id=', $box->sid, '"><i class="bi-eye"></i></a>';
echo "</td></tr>\n"; echo "</td></tr>\n";
echo '<tr><th>', _('Remarks'),"</th><td>", $box->remarks, "</td></tr>\n"; echo '<tr><th>', _('Remarks'),"</th><td>", h($box->remarks, br:true), "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
form_view_buttons($g_scriptname, $id); form_view_buttons($g_scriptname, $id);
@@ -275,10 +290,13 @@ if ($res) {
echo '<p>', _('Box is empty'), "</p>\n"; echo '<p>', _('Box is empty'), "</p>\n";
} }
# TODO provisions in box
elseif ($action == ACT_EDIT): elseif ($action == ACT_EDIT):
// ========== VARIANT: edit single record ===================================== // ========== VARIANT: edit single record =====================================
$sql = "SELECT boxtype, label, content, color, weight, sid, remarks " $sql = "SELECT boxtype, label, content, color, weight, weight_net, price, "
. "sid, wx, wy, wz, remarks "
. "FROM box " . "FROM box "
. "WHERE boxid=?"; . "WHERE boxid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -293,25 +311,53 @@ echo '<h2>', _('Edit Box'), "</h2>\n";
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3"> <div class="mb-3">
<label for="label" class="form-label"><?=_('Label')?></label> <label for="label" class="form-label"><?=_('Label')?></label>
<input type="text" class="form-control" id="label" name="label" value="<?=$box->label ?>"> <input type="text" class="form-control" id="label" name="label" value="<?=h($box->label)?>">
</div> </div>
<?php form_create_select('boxtype', _('Box type'), $opt_none + $opt_boxtype, $box->boxtype); ?> <?php form_create_select('boxtype', _('Box type'), $opt_none + $opt_boxtype, $box->boxtype); ?>
<div class="mb-3"> <div class="mb-3">
<label for="content" class="form-label"><?=_('Content')?></label> <label for="content" class="form-label"><?=_('Content')?></label>
<input type="text" class="form-control" id="content" name="content" value="<?=$box->content ?>"> <input type="text" class="form-control" id="content" name="content" value="<?=h($box->content)?>">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="color"><?=_('Color')?></label> <label for="color"><?=_('Color')?></label>
<input type="color" class="form-control" id="color" name="color" value="#<?=$box->color ?>"> <input type="color" class="form-control" id="color" name="color" value="#<?=$box->color ?>">
</div> </div>
<div class="mb-3">
<label class="form-label"><?=_('Dimensions (L × W × H)')?></label>
<div class="input-group">
<input type="number" class="form-control" name="wx"
value="<?=$box->wx;?>" min="0" step="1"
aria-label="<?=_('Length')?>">
<span class="input-group-text">×</span>
<input type="number" class="form-control" name="wy"
value="<?=$box->wy;?>" min="0" step="1"
aria-label="<?=_('Width')?>">
<span class="input-group-text">×</span>
<input type="number" class="form-control" name="wz"
value="<?=$box->wz;?>" min="0" step="1"
aria-label="<?=_('Height')?>">
<span class="input-group-text">mm</span>
</div>
<div class="form-text">
<?=_('Length × Width × Height')?>
</div>
</div>
<div class="mb-3"> <div class="mb-3">
<label for="weight" class="form-label"><?=_('Weight, kg')?></label> <label for="weight" class="form-label"><?=_('Weight, kg')?></label>
<input type="text" class="form-control" id="weight" name="weight" value="<?=format_float($box->weight); ?>"> <input type="text" class="form-control" id="weight" name="weight" value="<?=format_float($box->weight); ?>">
</div> </div>
<div class="mb-3">
<label for="weight_net" class="form-label"><?=_('Weight net, kg')?></label>
<input type="text" class="form-control" id="weight_net" name="weight_net" value="<?=format_float($box->weight_net); ?>">
</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($box->price) ?>">
</div>
<?php form_create_select('sid', _('Storage'), $opt_storage, $box->sid); ?> <?php form_create_select('sid', _('Storage'), $opt_storage, $box->sid); ?>
<div class="mb-3"> <div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label> <label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$box->remarks ?></textarea> <textarea class="form-control" id="remarks" name="remarks" rows="3"><?=h($box->remarks)?></textarea>
</div> </div>
<?php <?php
+59 -69
View File
@@ -7,13 +7,16 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Cables'); $pagetitle = _('Cables');
$id = gpc_get_int($_REQUEST, 'id', 0); $id = gpc_get_int($_REQUEST, 'id', 0);
$opt_cabletype = db_get_options(11); $opt_cabletype = db_get_options(DD_CABLE_TYPE);
$opt_techname = db_get_options(DD_CABLE_TECHNAME);
$opt_cablecond = db_load_enum('cable', 'cablecond', true, true); $opt_cablecond = db_load_enum('cable', 'cablecond', true, true);
// ========== ACTIONS START =================================================== // ========== ACTIONS START ===================================================
@@ -29,6 +32,7 @@ switch ($submit = form_get_action()) {
case 'filter': case 'filter':
$flt = array(); $flt = array();
$flt['type'] = gpc_get_int($_POST, 'flt_type');
$flt['txt'] = gpc_get_string($_POST, 'flt_txt'); $flt['txt'] = gpc_get_string($_POST, 'flt_txt');
db_save_filter($flt, 211); db_save_filter($flt, 211);
$action = ACT_DEFAULT; $action = ACT_DEFAULT;
@@ -45,6 +49,7 @@ switch ($submit = form_get_action()) {
$p[':conductors'] = gpc_get_int($_POST, 'conductors'); $p[':conductors'] = gpc_get_int($_POST, 'conductors');
$p[':xsection'] = gpc_get_float($_POST, 'xsection'); $p[':xsection'] = gpc_get_float($_POST, 'xsection');
$id = db_exec_insert('cable', $p); $id = db_exec_insert('cable', $p);
db_set_revision('table', TBL_CABLES);
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -52,6 +57,7 @@ switch ($submit = form_get_action()) {
$p[':cableid'] = $id; $p[':cableid'] = $id;
$p[':cablename'] = gpc_get_string($_POST, 'cablename'); $p[':cablename'] = gpc_get_string($_POST, 'cablename');
$p[':cabletype'] = gpc_get_int($_POST, 'cabletype'); $p[':cabletype'] = gpc_get_int($_POST, 'cabletype');
$p[':techname'] = gpc_get_int($_POST, 'techname');
$p[':length'] = gpc_get_float($_POST, 'length'); $p[':length'] = gpc_get_float($_POST, 'length');
$p[':conductors'] = gpc_get_int($_POST, 'conductors'); $p[':conductors'] = gpc_get_int($_POST, 'conductors');
$p[':xsection'] = gpc_get_float($_POST, 'xsection'); $p[':xsection'] = gpc_get_float($_POST, 'xsection');
@@ -91,7 +97,24 @@ if ($action == ACT_DEFAULT):
// ========== VARIANT: default behavior ======================================= // ========== VARIANT: default behavior =======================================
// load filter from db // load filter from db
$flt = db_get_filter($user->id, 211); $flt = db_get_filter($user->id, 211, ['txt', 'type']);
$w = array('vid=:vid');
$p = array(':vid' => $user->vid);
if (strlen($flt->txt) > 1) {
$w[] = 'cablename LIKE :txt OR remarks LIKE :txt';
$p[':txt'] = '%'.$flt->txt.'%';
}
if ($flt->type == -1) {
$w[] = 'cabletype IS NULL';
} elseif ($flt->type > 0) {
$w[] = 'cabletype=:cabletype';
$p[':type'] = $flt->type;
}
$where = join(' AND ', $w);
$order = ' ORDER BY cablename';
echo "<h1>$pagetitle</h1>\n"; echo "<h1>$pagetitle</h1>\n";
@@ -101,10 +124,10 @@ echo "<h1>$pagetitle</h1>\n";
<div id="filter" class="card"> <div id="filter" class="card">
<div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div> <div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div>
<div class="card-body d-flex flex-wrap gap-3"> <div class="card-body d-flex flex-wrap gap-3">
<div class="d-flex flex-nowrap gap-2"> <?php
<label for="flt_txt">Text</label> filter_create_select('flt_type', _('Type'), $g_opt_all + $g_opt_none + $opt_cabletype, $flt->type);
<input type="text" class="form-control" name="flt_txt" maxlength="30" value="<?=$flt->txt ?? ''?>"> filter_create_text('flt_txt', _('Text'), $flt->text, 30, 45);
</div> ?>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
@@ -114,17 +137,22 @@ echo "<h1>$pagetitle</h1>\n";
</form> </form>
<?php <?php
$sql = "SELECT cableid, cablename, conductors, length, xsection, color, cablecond " $sql = "SELECT cableid, cablename, cabletype, conductors, length, xsection, color, cablecond "
. "FROM cable " . "FROM cable ";
. "ORDER BY cablename"; $sql .= ' WHERE ' . $where;
$sth = $pdo->query($sql); $sql .= $order;
$sth = $pdo->prepare($sql);
$sth->execute($p);
$res = $sth->fetchAll(); $res = $sth->fetchAll();
echo '<table class="table table-striped">', "\n"; echo '<table class="table table-striped">', "\n";
echo "<thead>\n"; echo "<thead>\n";
echo "<tr>\n"; echo "<tr>\n";
echo '<th>#</th>'; echo '<th>#</th>';
echo '<th>', _('Cable'), "</th>"; echo '<th>', _('Cable'), "</th>";
echo '<th>', _('Name'), "</th>"; echo '<th>', _('Name'), "</th>";
echo '<th>', _('Type'), "</th>";
echo '<th>', _('Conductors'), "</th>"; echo '<th>', _('Conductors'), "</th>";
echo '<th>', _('Length'), "</th>"; echo '<th>', _('Length'), "</th>";
echo '<th>', _('Cross section'), "</th>"; echo '<th>', _('Cross section'), "</th>";
@@ -142,18 +170,19 @@ foreach ($res as $row) {
echo "</td>\n"; echo "</td>\n";
echo "<td>", $row['cableid'], "</td>\n"; echo "<td>", $row['cableid'], "</td>\n";
echo "<td>", $row['cablename'], "</td>\n"; echo "<td>", $row['cablename'], "</td>\n";
echo "<td>", $row['cabletype'], "</td>\n";
echo "<td>", $row['conductors'], "</td>\n"; echo "<td>", $row['conductors'], "</td>\n";
echo "<td>", $row['length'], "m</td>\n"; echo "<td>", $row['length'], "m</td>\n";
echo "<td>", $row['xsection'], "mm²</td>\n"; echo "<td>", $row['xsection'], "mm²</td>\n";
echo "<td>", format_color($row['color']), "</td>\n"; echo "<td>", format_color($row['color']), "</td>\n";
echo "<td>", $row['condition'], "</td>\n"; echo "<td>", get_enum($row['cablecond']), "</td>\n";
echo "<td>"; echo "<td>";
echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['cableid'], '"><i class="bi-pencil"></i></a>', "\n"; echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['cableid'], '"><i class="bi-pencil"></i></a>', "\n";
echo "</td>\n"; echo "</td>\n";
echo "</tr>\n"; echo "</tr>\n";
} }
// Table summary // Table summary
table_rec_summary($i0, $i, $numrows, 6); // table_rec_summary(1, $i-1, $i-1, 10);
echo "</table>\n"; echo "</table>\n";
form_add_button($g_scriptname); form_add_button($g_scriptname);
@@ -165,33 +194,20 @@ echo '<h2>', _('Add Cable'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<div class="mb-3">
<label for="tagname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="cablename" name="cablename" required autofocus>
</div>
<div class="mb-3">
<label for="note" class="form-label"><?=_('Length, m')?></label>
<input type="text" class="form-control" id="length" name="length">
</div>
<?php <?php
form_create_text('cablename', _('Name'), 80, NULL, TRUE, TRUE);
form_create_numeric('length', _('Length, m'), step: 0.01);
form_create_select('cabletype', _('Type'), $g_opt_none + $opt_cabletype); form_create_select('cabletype', _('Type'), $g_opt_none + $opt_cabletype);
?> form_create_numeric('number', _('Number of conductors'), NULL, 1, 99, 1);
<div class="mb-3"> form_create_numeric('xsection', _('Cross section, mm²'), NULL, 0, 999, 0.1);
<label for="note" class="form-label"><?=_('Conductors')?></label>
<input type="text" class="form-control" id="conductors" name="conductors">
</div>
<div class="mb-3">
<label for="note" class="form-label"><?=_('Cross section, mm²')?></label>
<input type="text" class="form-control" id="xsection" name="xsection">
</div>
<?php
form_new_buttons($g_scriptname); form_new_buttons($g_scriptname);
echo "</form>\n"; echo "</form>\n";
elseif ($action == ACT_VIEW): elseif ($action == ACT_VIEW):
// ========== VARIANT: view single record ===================================== // ========== VARIANT: view single record =====================================
$sql = "SELECT cablename, cabletype, length, conductors, diameter, xsection," $sql = "SELECT cablename, cabletype, techname, length, conductors, diameter, xsection,"
. " weight, color, supplier, manufacturer, cablecond, remarks " . " weight, color, supplier, manufacturer, cablecond, remarks "
. "FROM cable " . "FROM cable "
. "WHERE cableid=?"; . "WHERE cableid=?";
@@ -204,6 +220,7 @@ echo '<h2>', _('View cable'), "</h2>\n";
echo '<table class="table">', "\n"; echo '<table class="table">', "\n";
echo '<tr><th style="width:20%">', _('Cable'),"</th><td>", $cable->cablename, "</td></tr>\n"; echo '<tr><th style="width:20%">', _('Cable'),"</th><td>", $cable->cablename, "</td></tr>\n";
echo '<tr><th>', _('Type'),"</th><td>", $opt_cabletype[$cable->cabletype], "</td></tr>\n"; echo '<tr><th>', _('Type'),"</th><td>", $opt_cabletype[$cable->cabletype], "</td></tr>\n";
echo '<tr><th>', _('Techname'),"</th><td>", $opt_techname[$cable->techname], "</td></tr>\n";
echo '<tr><th>', _('Length'),"</th><td>", format_float($cable->length, 1, 'm'), "</td></tr>\n"; echo '<tr><th>', _('Length'),"</th><td>", format_float($cable->length, 1, 'm'), "</td></tr>\n";
echo '<tr><th>', _('Conductors'),"</th><td>", $cable->conductors, "</td></tr>\n"; echo '<tr><th>', _('Conductors'),"</th><td>", $cable->conductors, "</td></tr>\n";
echo '<tr><th>', _('Diameter'),"</th><td>", format_float($cable->diameter, 1, 'mm'), "</td></tr>\n"; echo '<tr><th>', _('Diameter'),"</th><td>", format_float($cable->diameter, 1, 'mm'), "</td></tr>\n";
@@ -211,7 +228,7 @@ echo '<tr><th>', _('Cross section'),"</th><td>", format_float($cable->xsection,
echo '<tr><th>', _('Weight'),"</th><td>", format_float($cable->weight, 2, 'kg/m'), "</td></tr>\n"; echo '<tr><th>', _('Weight'),"</th><td>", format_float($cable->weight, 2, 'kg/m'), "</td></tr>\n";
echo '<tr><th>', _('Color'),"</th><td>", format_color($cable->color), "</td></tr>\n"; echo '<tr><th>', _('Color'),"</th><td>", format_color($cable->color), "</td></tr>\n";
echo '<tr><th>', _('Condition'),"</th><td>", $opt_cablecond[$cable->cablecond], "</td></tr>\n"; echo '<tr><th>', _('Condition'),"</th><td>", $opt_cablecond[$cable->cablecond], "</td></tr>\n";
echo "<tr><th>", _('Remarks'), "</th><td>", nl2br($cable->remarks), "</td></tr>\n"; echo "<tr><th>", _('Remarks'), "</th><td>", h($cable->remarks, br:true), "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
form_view_buttons($g_scriptname, $id); form_view_buttons($g_scriptname, $id);
@@ -219,7 +236,7 @@ form_view_buttons($g_scriptname, $id);
elseif ($action == ACT_EDIT): elseif ($action == ACT_EDIT):
// ========== VARIANT: edit single record ===================================== // ========== VARIANT: edit single record =====================================
$sql = "SELECT cablename, cabletype, length, conductors, diameter, xsection," $sql = "SELECT cablename, cabletype, techname, length, conductors, diameter, xsection,"
. " weight, color, supplier, manufacturer, cablecond, remarks " . " weight, color, supplier, manufacturer, cablecond, remarks "
. "FROM cable " . "FROM cable "
. "WHERE cableid=?"; . "WHERE cableid=?";
@@ -231,45 +248,18 @@ echo '<h2>', _('Edit cable'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3">
<label for="mname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="cablename" name="cablename" value="<?=$cable->cablename;?>">
</div>
<?php <?php
form_create_text('cablename', _('Name'), 80, $cable->cablename, TRUE, TRUE);
form_create_select('cabletype', _('Type'), $g_opt_none + $opt_cabletype, $cable->cabletype); form_create_select('cabletype', _('Type'), $g_opt_none + $opt_cabletype, $cable->cabletype);
?> form_create_select('techname', _('Techname'), $g_opt_none + $opt_techname, $cable->techname);
<div class="mb-3"> form_create_numeric('length', _('Length, m'), format_float($cable->length, 1), 0, 9999, 0.01);
<label for="note" class="form-label"><?=_('Length, m')?></label> form_create_numeric('number', _('Number of conductors'), $cable->conductors, 1, 99, 1);
<input type="text" class="form-control" id="length" name="length" value="<?=format_float($cable->length, 1);?>"> form_create_numeric('diameter', ('Diameter, mm'), format_float($cable->diameter, 1), 0, 999, 0.1);
</div> form_create_numeric('xsection', _('Cross section, mm²'), format_float($cable->xsection, 1), 0, 999, 0.1);
<div class="mb-3"> form_create_numeric('weight', _('Weight, kg/m'), format_float($cable->weight, 2), 0, 9999, 0.01);
<label for="note" class="form-label"><?=_('Conductors')?></label> form_create_color('color', _('Color'), $cable->color);
<input type="text" class="form-control" id="conductors" name="conductors" value="<?=$cable->conductors;?>">
</div>
<div class="mb-3">
<label for="note" class="form-label"><?=_('Diameter, mm')?></label>
<input type="text" class="form-control" id="diameter" name="diameter" value="<?=format_float($cable->diameter, 1);?>">
</div>
<div class="mb-3">
<label for="note" class="form-label"><?=_('Cross section, mm²')?></label>
<input type="text" class="form-control" id="xsection" name="xsection" value="<?=format_float($cable->xsection, 1);?>">
</div>
<div class="mb-3">
<label for="note" class="form-label"><?=_('Weight, kg/m')?></label>
<input type="text" class="form-control" id="weight" name="weight" value="<?=$cable->weight;?>">
</div>
<div class="mb-3">
<label for="color" class="form-label"><?=_('Color')?></label>
<input type="color" name="color" id="color" class="form-control" value="#<?=$cable->color;?>">
</div>
<?php
form_create_select('cablecond', _('Condition'), $opt_cablecond, $cable->cablecond); form_create_select('cablecond', _('Condition'), $opt_cablecond, $cable->cablecond);
?> form_create_textarea('remarks', _('Remarks'), 3, 150, $cable->remarks);
<div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$cable->remarks ?></textarea>
</div>
<?php
form_edit_buttons($g_scriptname, $id); form_edit_buttons($g_scriptname, $id);
echo "</form>\n"; echo "</form>\n";
+13 -10
View File
@@ -7,7 +7,9 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Checklists'); $pagetitle = _('Checklists');
@@ -86,10 +88,17 @@ $res = $sth->fetchAll();
<?php <?php
foreach ($res as $row) { foreach ($res as $row) {
echo "<tr>\n"; echo "<tr>\n";
echo '<td>', $row['clid'], "</td>\n"; echo '<td>', $row['clid'];
echo '<a class="text-nowrap" title="', _('View'), '" href="', $g_scriptname, '?f=view&id=', $row['clid'], '"><i class="bi bi-eye ms-2"></i></a>', "\n";
// TODO view icon
echo "</td>\n";
echo '<td>', $row['title'], "</td>\n"; echo '<td>', $row['title'], "</td>\n";
echo '<td>', $row['clstate'], "</td>\n"; echo '<td>', $row['clstate'], "</td>\n";
form_action_buttons($g_scriptname, $row['clid']); // Edit current record button
echo '<td>';
echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['clid'], '"><i class="bi-pencil"></i></a>', "\n";
echo "</td>\n";
echo "</tr>\n"; echo "</tr>\n";
} }
// Table summary // Table summary
@@ -104,11 +113,8 @@ elseif ($action == ACT_ADD):
echo '<h2>', _('Add Checklist'), "</h2>\n"; echo '<h2>', _('Add Checklist'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<div class="mb-3">
<label for="title" class="form-label"><?=_('Title')?></label>
<input type="text" class="form-control" id="title" name="title">
</div>
<?php <?php
form_create_text('title', _('Title'), 30);
form_new_buttons($g_scriptname); form_new_buttons($g_scriptname);
echo "</form>\n"; echo "</form>\n";
@@ -149,11 +155,8 @@ echo '<h2>', _('Edit checklist'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3">
<label for="provname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="title" name="title" value="<?=$checklist->title ?>">
</div>
<?php <?php
form_create_text('title', _('Title'), 30, $checklist->title);
form_create_select('clstate', _('State'), $opt_clstate, $checklist->clstate); form_create_select('clstate', _('State'), $opt_clstate, $checklist->clstate);
form_edit_buttons($g_scriptname, $id); form_edit_buttons($g_scriptname, $id);
+64 -113
View File
@@ -7,12 +7,14 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle=_('Company'); $pagetitle=_('Company');
$id = gpc_get_int($_REQUEST, 'id', 0); $id = gpc_get_int($_REQUEST, 'id', 0);
$opt_comptype = db_get_options(2); $opt_comptype = db_get_options(DD_COMPANY_TYPE);
// ========== ACTIONS START =================================================== // ========== ACTIONS START ===================================================
@@ -29,12 +31,17 @@ switch ($submit = form_get_action()) {
$flt = array(); $flt = array();
$flt['type'] = gpc_get_int($_POST, 'flt_type'); $flt['type'] = gpc_get_int($_POST, 'flt_type');
$flt['txt'] = gpc_get_string($_POST, 'flt_txt'); $flt['txt'] = gpc_get_string($_POST, 'flt_txt');
$allowed = db_load_enum('company', 'flags');
$flt['flags'] = gpc_get_set($_POST, 'flt_flags', $allowed);
db_save_filter($flt, 208); db_save_filter($flt, 208);
$action = ACT_DEFAULT; $action = ACT_DEFAULT;
break; break;
case 'freset': case 'freset':
db_clear_filter(208); //db_clear_filter(208);
// set status checkboxes to useful defaults
$flt = array('flags' => ['historic']);
db_save_filter($flt, 208);
$action = ACT_DEFAULT; $action = ACT_DEFAULT;
break; break;
@@ -42,6 +49,7 @@ switch ($submit = form_get_action()) {
$p[':compname'] = gpc_get_string($_POST, 'compname'); $p[':compname'] = gpc_get_string($_POST, 'compname');
$p[':comptype'] = gpc_get_int($_POST, 'comptype'); $p[':comptype'] = gpc_get_int($_POST, 'comptype');
$id = db_exec_insert('company', $p); $id = db_exec_insert('company', $p);
db_set_revision('table', TBL_COMPANIES);
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -101,7 +109,7 @@ if ($action == ACT_DEFAULT):
page_caption_search($pagetitle); page_caption_search($pagetitle);
// load filter from db // load filter from db
$flt = db_get_filter($user->id, 208, ['type','txt']); $flt = db_get_filter($user->id, 208, ['type','txt','flags']);
$w = array(); $w = array();
$p = array(); $p = array();
@@ -113,6 +121,19 @@ if (strlen($flt->txt) > 1) {
$w[] = '(compname LIKE :txt OR remarks LIKE :txt)'; $w[] = '(compname LIKE :txt OR remarks LIKE :txt)';
$p[':txt'] = '%'.$flt->txt.'%'; $p[':txt'] = '%'.$flt->txt.'%';
} }
// condition for multiple flags is OR
$parts = ["flags=''", 'flags IS NULL'];
foreach ($flt->flags as $f) {
$parts[] = "FIND_IN_SET('$f', flags)";
}
if (!empty($parts)) {
if (count($parts) > 1) {
$w[] = '(' . join(' OR ', $parts) . ')';
} else {
$w[] = $parts[0];
}
}
$where = join(' AND ', $w); $where = join(' AND ', $w);
$order = ' ORDER BY comptype, compname'; $order = ' ORDER BY comptype, compname';
@@ -157,32 +178,17 @@ try {
$res = $sth->fetchAll(); $res = $sth->fetchAll();
// Filter // Filter
$opt_special = array(
-2 => _('&horbar; all &horbar;'),
);
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form id="filterform" method="post" action="<?=$g_scriptname?>">
<div id="filter" class="card"> <div id="filter" class="card">
<div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div> <div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div>
<div class="card-body d-flex flex-wrap gap-3"> <div class="card-body d-flex flex-wrap gap-3">
<div class="d-flex flex-nowrap gap-2">
<label for="flt_type">Type</label>
<select id="flt_type" class="form-select" name="flt_type">
<?php <?php
foreach ($opt_special + $opt_comptype as $k => $v) { filter_create_select('flt_type', _('Type'), $g_opt_all + $opt_comptype, $flt->type);
echo '<option value="', $k,'"'; filter_create_text('flt_txt', _('Text'), $flt->txt, 15, 30);
if ($k == $flt->type) { $opt_flags = db_load_enum('company', 'flags', true, true, false);
echo ' selected'; filter_create_checks('flt_flags', _('Also show '), $opt_flags, $flt->flags ?? []);
}
echo '>', $v, '</option>';
}
?> ?>
</select>
</div>
<div class="d-flex flex-nowrap gap-2">
<label for="flt_txt">Text</label>
<input type="text" class="form-control" name="flt_txt" size="15" maxlength="30" value="<?=$flt->txt;?>">
</div>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
@@ -247,11 +253,10 @@ elseif ($action == ACT_ADD):
echo '<h2>', _('Add Company'), "</h2>\n"; echo '<h2>', _('Add Company'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<div class="mb-3"> <?php
<label for="compname" class="form-label"><?=_('Name')?></label> form_create_text('compname', _('Name'), 60);
<input type="text" class="form-control" id="compname" name="compname"> form_create_select('comptype', _('Company type'), $opt_comptype);
</div> ?>
<?php form_create_select('comptype', _('Company type'), $opt_comptype); ?>
<button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button> <button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button>
<a href="<?=$g_scriptname?>" class="btn btn-secondary"><?=_('Back')?></a> <a href="<?=$g_scriptname?>" class="btn btn-secondary"><?=_('Back')?></a>
</form> </form>
@@ -271,39 +276,39 @@ $company = $sth->fetch(PDO::FETCH_OBJ);
echo "<h2>", $company->compname, "</h2>\n"; echo "<h2>", $company->compname, "</h2>\n";
echo '<table class="table">', "\n"; echo '<table class="table">', "\n";
echo '<tr><th scope="row" style="width:20%">', _('Name'),"</th><td>", $company->compname, "</td></tr>\n"; echo '<tr><th scope="row" style="width:20%">', _('Name'),"</th><td>", h($company->compname), "</td></tr>\n";
echo '<tr><th scope="row">', _('Short name'),"</th><td>", $company->shortname, "</td></tr>\n"; echo '<tr><th scope="row">', _('Short name'),"</th><td>", h($company->shortname), "</td></tr>\n";
echo '<tr><th scope="row">', _('Type'),"</th><td>", $opt_comptype[$company->comptype], "</td></tr>\n"; echo '<tr><th scope="row">', _('Type'),"</th><td>", $opt_comptype[$company->comptype], "</td></tr>\n";
echo '<tr><th scope="row">', _('Secondary type'),"</th><td>", $company->comptype2 ? $opt_comptype[$company->comptype2] : '-', "</td></tr>\n"; echo '<tr><th scope="row">', _('Secondary type'),"</th><td>", $company->comptype2 ? $opt_comptype[$company->comptype2] : '-', "</td></tr>\n";
echo '<tr><th scope="row">', _('Street'),"</th><td>", $company->street, "</td></tr>\n"; echo '<tr><th scope="row">', _('Street'),"</th><td>", h($company->street), "</td></tr>\n";
echo '<tr><th scope="row">', _('Zip, City'),"</th><td>", $company->zip, ' ', $company->city, "</td></tr>\n"; echo '<tr><th scope="row">', _('Zip, City'),"</th><td>", $company->zip, ' ', $company->city, "</td></tr>\n";
echo '<tr><th scope="row">', _('Country'),"</th><td>", $company->country, "</td></tr>\n"; echo '<tr><th scope="row">', _('Country'),"</th><td>", h($company->country), "</td></tr>\n";
echo '<tr><th scope="row">', _('Contact'),"</th><td>", $company->contact, "</td></tr>\n"; echo '<tr><th scope="row">', _('Contact'),"</th><td>", h($company->contact), "</td></tr>\n";
echo '<tr><th scope="row">', _('Phone'),"</th><td>"; echo '<tr><th scope="row">', _('Phone'),"</th><td>";
echo make_phonelink($company->phone),' ', $company->phone, "</td></tr>\n"; echo make_phonelink($company->phone),' ', h($company->phone), "</td></tr>\n";
echo '<tr><th scope="row">', _('Email'),"</th><td>"; echo '<tr><th scope="row">', _('Email'),"</th><td>";
echo make_maillink($company->email),' ', $company->email, "</td></tr>\n"; echo make_maillink($company->email),' ', h($company->email), "</td></tr>\n";
echo '<tr><th scope="row">', _('Web'),"</th><td>"; echo '<tr><th scope="row">', _('Web'),"</th><td>";
// echo '<a title="', _('Go to website'), '" href="', // echo '<a title="', _('Go to website'), '" href="',
echo make_weblink($company->web), ' ', $company->web, "</td></tr>\n"; echo make_weblink($company->web), ' ', h($company->web), "</td></tr>\n";
echo '<tr><th scope="row">', _('Customer no.'),"</th><td>", $company->customerno, "</td></tr>\n"; echo '<tr><th scope="row">', _('Customer no.'),"</th><td>", h($company->customerno), "</td></tr>\n";
echo '<tr><th scope="row">', _('Contract no.'),"</th><td>", $company->contractno, "</td></tr>\n"; echo '<tr><th scope="row">', _('Contract no.'),"</th><td>", h($company->contractno), "</td></tr>\n";
echo '<tr><th scope="row">', _('Remarks'),"</th><td>", $company->remarks, "</td></tr>\n"; echo '<tr><th scope="row">', _('Remarks'),"</th><td>", h($company->remarks, br:true), "</td></tr>\n";
echo '<tr><th scope="row">', _('Flags'),"</th><td>", $company->flags, "</td></tr>\n"; echo '<tr><th scope="row">', _('Flags'),"</th><td>", $company->flags, "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
form_view_buttons($g_scriptname, $id); form_view_buttons($g_scriptname, $id);
// show referenced equipment // show referenced equipment for current vessel
$sql = "SELECT eid, ename FROM equipment WHERE supplier=:id OR manufacturer=:id"; $sql = "SELECT eid, ename FROM equipment WHERE vid=:vid AND (supplier=:id OR manufacturer=:id)";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([':id' => $id]); $sth->execute([':vid' => $user->vid, ':id' => $id]);
if ($sth->rowCount() > 0) { if ($sth->rowCount() > 0) {
echo "<p>Referenced in equipment:</p>\n"; echo '<p>', _('Referenced in equipment'), ":</p>\n";
echo "<ul>\n"; echo "<ul>\n";
foreach ($sth->fetchAll() as $row) { foreach ($sth->fetchAll() as $row) {
echo "<li>", $row['ename'], ' '; echo "<li>", $row['ename'], ' ';
@@ -351,76 +356,22 @@ $company = $sth->fetch(PDO::FETCH_OBJ);
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3">
<label for="compname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="compname" name="compname" value="<?=$company->compname ?>">
</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="<?=$company->shortname ?>">
</div>
<div class="mb-3">
<label for="comptype" class="form-label"><?=_('Company type')?></label>
<select name="comptype" class="form-control">
<?php
foreach ($opt_comptype as $k => $v) {
echo '<option value="', $k ,'"';
if ($company->comptype == $k) {
echo ' selected';
}
echo '>', $v, "</option>\n";
}
?>
</select>
</div>
<?php <?php
form_create_text('compname', _('Name'), 60, $company->compname);
form_create_text('shortname', _('Short name'), 20, $company->shortname);
form_create_select('comptype', _('Company type'), $opt_comptype, $company->comptype);
form_create_select('comptype2', _('Secondary company type'), $g_opt_none + $opt_comptype, $company->comptype2); form_create_select('comptype2', _('Secondary company type'), $g_opt_none + $opt_comptype, $company->comptype2);
?> form_create_text('street', _('Street'), 40, $company->street);
<div class="mb-3"> form_create_text('zip', _('Zip'), 10, $company->zip);
<label for="street" class="form-label"><?=_('Street')?></label> form_create_text('city', _('City'), 30, $company->city);
<input type="text" class="form-control" id="street" name="street" value="<?=$company->street ?>"> form_create_text('country', _('Country'), 30, $company->country);
</div> form_create_text('contact', _('Contact'), 30, $company->contact);
<div class="mb-3"> form_create_text('phone', _('Phone'), 30, $company->phone);
<label for="zip" class="form-label"><?=_('Zip')?></label> form_create_text('email', _('Email'), 50, $company->email);
<input type="text" class="form-control" id="zip" name="zip" value="<?=$company->zip ?>"> form_create_text('web', _('Web'), 40, $company->web);
</div> form_create_text('customerno', _('Customer no.'), 20, $company->customerno);
<div class="mb-3"> form_create_text('contractno', _('Contract no.'), 20, $company->contracno);
<label for="city" class="form-label"><?=_('City')?></label> form_create_textarea('remarks', _('Remarks'), 3, 150, $company->remarks);
<input type="text" class="form-control" id="city" name="city" value="<?=$company->city ?>">
</div>
<div class="mb-3">
<label for="country" class="form-label"><?=_('Country')?></label>
<input type="text" class="form-control" id="country" name="country" value="<?=$company->country ?>">
</div>
<div class="mb-3">
<label for="contact" class="form-label"><?=_('Contact')?></label>
<input type="text" class="form-control" id="contact" name="contact" value="<?=$company->contact ?>">
</div>
<div class="mb-3">
<label for="phone" class="form-label"><?=_('Phone')?></label>
<input type="text" class="form-control" id="phone" name="phone" value="<?=$company->phone ?>">
</div>
<div class="mb-3">
<label for="email" class="form-label"><?=_('Email')?></label>
<input type="text" class="form-control" id="email" name="email" value="<?=$company->email ?>">
</div>
<div class="mb-3">
<label for="web" class="form-label"><?=_('Web')?></label>
<input type="text" class="form-control" id="web" name="web" value="<?=$company->web ?>">
</div>
<div class="mb-3">
<label for="customerno" class="form-label"><?=_('Customer no.')?></label>
<input type="text" class="form-control" id="customerno" name="customerno" value="<?=$company->customerno ?>">
</div>
<div class="mb-3">
<label for="contractno" class="form-label"><?=_('Contract no.')?></label>
<input type="text" class="form-control" id="contractno" name="contractno" value="<?=$company->contractno ?>">
</div>
<div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$company->remarks ?></textarea>
</div>
<?php
$opt_flags = db_load_enum('company', 'flags', true, true, false); $opt_flags = db_load_enum('company', 'flags', true, true, false);
form_create_checks('flags', _('Flags'), $opt_flags, explode(',', $company->flags)); form_create_checks('flags', _('Flags'), $opt_flags, explode(',', $company->flags));
?> ?>
@@ -439,8 +390,8 @@ $company = $sth->fetch(PDO::FETCH_OBJ);
echo '<h2>', _('Delete Company'), "</h2>\n"; echo '<h2>', _('Delete Company'), "</h2>\n";
echo '<p>', sprintf(_('Record no. %d'), $id), "</p>\n"; echo '<p>', sprintf(_('Record no. %d'), $id), "</p>\n";
echo '<p>Name: ', $company->compname, "</p>"; echo '<p>Name: ', h($company->compname), "</p>";
echo '<p>Remarks: ', $company->remarks, "</p>"; echo '<p>Remarks: ', h($company->remarks, br:true), "</p>";
// Still used as a supplier or manufacturer for equipment? // Still used as a supplier or manufacturer for equipment?
$sql = "SELECT COUNT(*) FROM equipment WHERE supplier=:id OR manufacturer=:id"; $sql = "SELECT COUNT(*) FROM equipment WHERE supplier=:id OR manufacturer=:id";
+5 -6
View File
@@ -17,9 +17,9 @@ define('APP_ILLUSTRATION', 'sailboat.svg');
// database connection // database connection
$g_db_host = 'localhost'; $g_db_host = 'localhost';
$g_db_username = 'ymsweb'; $g_db_username = '@DB_USERNAME@';
$g_db_password = 'changeme!'; $g_db_password = '@DB_PASSWORD@';
$g_db_schema = 'yms'; $g_db_schema = '@DB_SCHEMA@';
// mail settings // mail settings
$g_mail_enable = FALSE; $g_mail_enable = FALSE;
@@ -29,13 +29,13 @@ $g_mailto_webmaster = 'webmaster@example.com';
// localization // localization
$g_textdomain = 'yms'; $g_textdomain = 'yms';
$g_timezone = 'Europe/Berlin'; $g_timezone = 'Europe/Berlin';
$g_locale = 'de_DE.UTF-8'; $g_locale = 'en_GB.UTF-8';
// vessel base shapes directory // vessel base shapes directory
$g_shapedir = '/usr/local/share/yms/shapes'; $g_shapedir = '/usr/local/share/yms/shapes';
// documents and images // documents and images
$g_doc_basepath = '/var/local/yms'; $g_doc_basepath = '/var/local/lib/yms';
$g_doc_maxsize = 1024*1024*16; // 16 MB, please adjust php.ini accordingly! $g_doc_maxsize = 1024*1024*16; // 16 MB, please adjust php.ini accordingly!
$g_doc_typemap = array( $g_doc_typemap = array(
'generic' => 'doc', 'generic' => 'doc',
@@ -50,4 +50,3 @@ $g_storage_limit = 1024; // MB
$g_thumb_size = 120; $g_thumb_size = 120;
$g_rows_pp = 10; // pagination limit $g_rows_pp = 10; // pagination limit
+1
View File
@@ -18,6 +18,7 @@
*/ */
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/fileutils.inc'; require 'lib/fileutils.inc';
+58 -74
View File
@@ -15,7 +15,9 @@ doctype icons
*/ */
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
require 'lib/fileutils.inc'; require 'lib/fileutils.inc';
$pagetitle = _('Documents'); $pagetitle = _('Documents');
@@ -89,7 +91,21 @@ switch ($submit = form_get_action()) {
$g_warning->Add(sprintf(_("Mimetype mismatch: '%s'."), $file_type)); $g_warning->Add(sprintf(_("Mimetype mismatch: '%s'."), $file_type));
} }
// TODO for images check maximum size and scale down if needed // for images check maximum size and scale down if needed
if (($file_mimetype == 'image/png') or ($file_mimetype == 'image/jpeg')) {
if (isset($_POST['noscale'])) {
$g_message->Add(_('Image has not been scaled down'));
} else {
// scale down if dimensions exceed limits
$img_maxx= $pdo->query("SELECT valint FROM settings WHERE userid=0 AND sno=20")->fetchColumn();
$img_maxy= $pdo->query("SELECT valint FROM settings WHERE userid=0 AND sno=21")->fetchColumn();
[$width, $height] = getimagesize($file_tmp);
$factor = min($img_maxx / $width, $img_maxy / $height);
if ($factor < 1) {
image_scale($file_tmp, $file_mimetype, $width, $height, $factor);
}
}
}
// ok let's go // ok let's go
$file_hash = md5_file($file_tmp); $file_hash = md5_file($file_tmp);
@@ -138,6 +154,7 @@ switch ($submit = form_get_action()) {
$id = db_exec_insert('document', $p); $id = db_exec_insert('document', $p);
$file_techname = sprintf('%s/%s-%06d.%s', $g_doc_basepath, $prefix, $id, $file_ext); $file_techname = sprintf('%s/%s-%06d.%s', $g_doc_basepath, $prefix, $id, $file_ext);
move_uploaded_file($file_tmp, $file_techname); move_uploaded_file($file_tmp, $file_techname);
chmod($file_techname, 0640);
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -304,7 +321,7 @@ $page = gpc_get_int($_REQUEST, 'p', 1);
$rows_pp = gpc_get_int($_REQUEST, 'n', $user->rows_pp); $rows_pp = gpc_get_int($_REQUEST, 'n', $user->rows_pp);
$lastpage = ceil($numrows/$rows_pp); $lastpage = ceil($numrows/$rows_pp);
$sql = "SELECT d.docid, d.doctype, d.filename, d.title, COUNT(r.drid) AS refcount " $sql = "SELECT d.docid, d.doctype, d.mimetype, d.filename, d.title, COUNT(r.drid) AS refcount "
. "FROM document AS d LEFT OUTER JOIN docref AS r USING (docid)"; . "FROM document AS d LEFT OUTER JOIN docref AS r USING (docid)";
if ($where) $sql .= ' WHERE ' . $where; if ($where) $sql .= ' WHERE ' . $where;
$sql .= " GROUP BY d.docid, d.doctype, d.filename, d.title"; $sql .= " GROUP BY d.docid, d.doctype, d.filename, d.title";
@@ -318,58 +335,21 @@ $sth->execute($p);
$res = $sth->fetchAll(); $res = $sth->fetchAll();
// Filter // Filter
$opt_special = array(
'all' => _('&horbar; all &horbar;'),
);
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form id="filterform" method="post" action="<?=$g_scriptname?>">
<div id="filter" class="card"> <div id="filter" class="card">
<div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div> <div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div>
<div class="card-body d-flex flex-wrap gap-3"> <div class="card-body d-flex flex-wrap gap-3">
<div class="d-flex flex-nowrap gap-2">
<label for="flt_doctype">Type</label>
<select class="form-select" id="flt_doctype" name="flt_doctype">
<?php <?php
foreach ($opt_special + $opt_doctype as $k => $v) { filter_create_select('flt_doctype', _('Type'), $g_opt_all + $opt_doctype, $flt->doctype);
echo '<option value="', $k,'"'; filter_create_select('flt_reftype', _('Reference'), $g_opt_none + $opt_reftype, $flt->reftype);
if ($k == $flt->doctype) { filter_create_text('flt_txt', _('Text'), $flt->txt, 15, 30);
echo ' selected';
}
echo '>', $v, '</option>';
}
?> ?>
</select>
</div> </div>
<div class="d-flex flex-nowrap gap-2">
<label for="flt_reftype"><?=_('Reference')?></label>
<select class="form-select" id="flt_reftype" name="flt_reftype">
<?php
$opt_special['none'] = _('&horbar; none &horbar;');
foreach ($opt_special + $opt_reftype as $k => $v) {
echo '<option value="', $k,'"';
if ($k == $flt->reftype) {
echo ' selected';
}
echo '>', $v, '</option>';
}
?>
</select>
</div>
<div class="d-flex flex-nowrap gap-2">
<label for="flt_txt">Text</label>
<input type="text" class="form-control" name="flt_txt" size="15" maxlength="30" value="<?=$flt->txt ?>">
</div>
</div>
<div class="card-footer"> <div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
<button name="submit[freset]" class="btn btn-sm btn-secondary float-end" title="<?=_('Reset filter to defaults')?>"><?=_('Clear')?></button> <button name="submit[freset]" class="btn btn-sm btn-secondary float-end" title="<?=_('Reset filter to defaults')?>"><?=_('Clear')?></button>
</div> </div>
</div> </div>
</form> </form>
@@ -399,7 +379,17 @@ foreach ($res as $row) {
echo "<td>", $i; echo "<td>", $i;
echo '<a title="', _('View'), '" href="', $g_scriptname, '?f=view&id=', $row['docid'], '"><i class="bi-eye ms-2"></i></a>', "\n"; echo '<a title="', _('View'), '" href="', $g_scriptname, '?f=view&id=', $row['docid'], '"><i class="bi-eye ms-2"></i></a>', "\n";
echo "</td>\n"; echo "</td>\n";
echo "<td>", $opt_doctype[$row['doctype']], "</td>\n"; echo "<td>";
if ($row['mimetype'] == 'application/pdf') {
echo '<i class="bi bi-file-earmark-pdf"></i>';
} else if ($row['mimetype'] == 'image/svg+xml') {
echo '<i class="bi bi-file-earmark-easel"></i>';
} else if ($row['mimetype'] == 'image/jpeg' or $row['mimetype'] == 'image/png') {
echo '<i class="bi bi-file-earmark-image"></i>';
} else {
echo '<i class="bi bi-file-earmark"></i>';
}
echo ' ', $opt_doctype[$row['doctype']], "</td>\n";
echo "<td>", $row['filename'], "</td>\n"; echo "<td>", $row['filename'], "</td>\n";
echo "<td>", $row['title'], "</td>\n"; echo "<td>", $row['title'], "</td>\n";
echo "<td>", $row['refcount'], "</td>\n"; echo "<td>", $row['refcount'], "</td>\n";
@@ -423,14 +413,10 @@ elseif ($action == ACT_ADD):
echo '<h2>', _('Add Document'), "</h2>\n"; echo '<h2>', _('Add Document'), "</h2>\n";
?> ?>
<form method="post" enctype="multipart/form-data" action="<?=$g_scriptname?>"> <form method="post" enctype="multipart/form-data" action="<?=$g_scriptname?>">
<div class="mb-3"> <?php
<label for="title" class="form-label"><?=_('Title')?></label> form_create_text('title', _('Title'), 40);
<input type="text" class="form-control" id="title" name="title" value="<?=$title ?? ''?>"> form_create_textarea('remarks', _('Remarks'), 3, 150, $storage->remarks);
</div> ?>
<div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$remarks ?? ''?></textarea>
</div>
<div class="mb-3"> <div class="mb-3">
<label for="files" class="form-label"><?=_('Document')?></label> <label for="files" class="form-label"><?=_('Document')?></label>
<input class="form-control" type="file" id="files" name="files" onchange="preview()"> <input class="form-control" type="file" id="files" name="files" onchange="preview()">
@@ -488,7 +474,7 @@ if ($document->doctype == 'picture') {
echo '<div class="image-gallery">'; echo '<div class="image-gallery">';
echo '<a href="#" data-bs-toggle="modal" data-bs-target="#imageModal">'; echo '<a href="#" data-bs-toggle="modal" data-bs-target="#imageModal">';
// echo '<img width="', $g_thumb_size, '" src="dl.php?id=', $document->docid, '&t=s" alt="', $document->title, '">'; // echo '<img width="', $g_thumb_size, '" src="dl.php?id=', $document->docid, '&t=s" alt="', $document->title, '">';
echo '<img width="', $g_thumb_size, '" src="dl.php?id=', $document->docid, '" alt="', $document->title, '">'; echo '<img width="', $g_thumb_size, '" src="dl.php?id=', $document->docid, '" alt="', h($document->title), '">';
echo '</a>'; echo '</a>';
echo '</div>'; // gallery echo '</div>'; // gallery
?> ?>
@@ -535,11 +521,12 @@ if ($document->docsize == 0) {
} }
echo '<tr><th scope="row">', _('Mimetype'),"</th><td>", $document->mimetype, "</td></tr>\n"; echo '<tr><th scope="row">', _('Mimetype'),"</th><td>", $document->mimetype, "</td></tr>\n";
echo '<tr><th scope="row">', _('Filename'),"</th><td>", $document->filename, "</td></tr>\n"; echo '<tr><th scope="row">', _('Filename'),"</th><td>", h($document->filename), "</td></tr>\n";
echo '<tr><th scope="row">', _('File size'),"</th><td>", format_filesize($document->docsize), "</td></tr>\n"; echo '<tr><th scope="row">', _('File size'),"</th><td>", format_filesize($document->docsize), "</td></tr>\n";
echo '<tr><th scope="row">', _('Upload date'),"</th><td>", $document->doctime, "</td></tr>\n"; echo '<tr><th scope="row">', _('Upload date'),"</th><td>", $document->doctime, "</td></tr>\n";
echo '<tr><th scope="row">', _('Title'),"</th><td>", $document->title, "</td></tr>\n"; echo '<tr><th scope="row">', _('Title'),"</th><td>", h($document->title), "</td></tr>\n";
echo '<tr><th scope="row">', _('Remarks'),"</th><td>", $document->remarks, "</td></tr>\n"; echo '<tr><th scope="row">', _('Access'),"</th><td>", get_enum($document->roleaccess), "</td></tr>\n";
echo '<tr><th scope="row">', _('Remarks'),"</th><td>", h($document->remarks, br:true), "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
echo "</div>\n", '<div class="col text-center">', "\n"; // column break echo "</div>\n", '<div class="col text-center">', "\n"; // column break
@@ -577,9 +564,9 @@ foreach ($sth->fetchAll() as $row) {
$eids = array(); $eids = array();
$sql = "SELECT drid, reftype, refid, ename AS target " $sql = "SELECT drid, reftype, refid, ename AS target "
. "FROM docref INNER JOIN equipment ON (docref.reftype='equipment' AND docref.refid=equipment.eid) " . "FROM docref INNER JOIN equipment ON (docref.reftype='equipment' AND docref.refid=equipment.eid) "
. "WHERE docid=?"; . "WHERE docid=? AND vid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([$id]); $sth->execute([$id, $user->vid]);
foreach ($sth->fetchAll() as $row) { foreach ($sth->fetchAll() as $row) {
$references[] = $row; $references[] = $row;
$eids[] = $row['refid']; $eids[] = $row['refid'];
@@ -742,13 +729,15 @@ elseif ($action == ACT_EDIT):
echo '<h2>', _('Edit Document'), "</h2>\n"; echo '<h2>', _('Edit Document'), "</h2>\n";
$sql = "SELECT docid, doctype, mimetype, filename, extension, hash, title, remarks " $sql = "SELECT docid, doctype, mimetype, filename, extension, hash, title, roleaccess, remarks "
. "FROM document " . "FROM document "
. "WHERE docid=?"; . "WHERE docid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([$id]); $sth->execute([$id]);
$document = $sth->fetch(PDO::FETCH_OBJ); $document = $sth->fetch(PDO::FETCH_OBJ);
// TODO check roleaccess!
if ($document->doctype == 'picture') { if ($document->doctype == 'picture') {
echo '<img width="', $g_thumb_size, '" src="dl.php?id=', $document->docid, '">'; echo '<img width="', $g_thumb_size, '" src="dl.php?id=', $document->docid, '">';
} }
@@ -756,15 +745,10 @@ if ($document->doctype == 'picture') {
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3">
<label for="title" class="form-label"><?=_('Filename')?></label>
<input type="text" class="form-control" id="filename" name="filename" value="<?=$document->filename ?>">
</div>
<div class="mb-3">
<label for="title" class="form-label"><?=_('Title')?></label>
<input type="text" class="form-control" id="title" name="title" value="<?=$document->title ?>">
</div>
<?php <?php
form_create_text('filename', _('Filename'), 200, $document->filename);
form_create_text('title', _('Title'), 40, $document->title);
if ($document->mimetype == 'application/pdf') { if ($document->mimetype == 'application/pdf') {
echo '<div class="mb-3">', "\n"; echo '<div class="mb-3">', "\n";
$opt_doctype = array( $opt_doctype = array(
@@ -777,13 +761,13 @@ if ($document->mimetype == 'application/pdf') {
} else { } else {
echo '<input type="hidden" name="doctype" value="', $document->doctype, '">', "\n"; echo '<input type="hidden" name="doctype" value="', $document->doctype, '">', "\n";
} }
form_create_textarea('remarks', _('Remarks'), 3, 150, $document->remarks);
?> ?>
<div class="mb-3"> <div class="container-fluid px-0 my-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label> <button type="submit" name="submit[update]" class="btn btn-primary"><?=_('Save')?></button>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$document->remarks ?></textarea> <a href="<?=$g_scriptname?>?f=view&id=<?=$id?>" class="btn btn-secondary"><?=_('Back')?></a>
</div> </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> </form>
<?php <?php
+10 -4
View File
@@ -7,7 +7,9 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Lists'); $pagetitle = _('Lists');
@@ -83,6 +85,8 @@ switch ($submit = form_get_action()) {
break; break;
case 'update': case 'update':
# changing ddval would need to update all dependent data
# so this is not intended here!
$p[':ddtext'] = gpc_get_string($_POST, 'ddtext'); $p[':ddtext'] = gpc_get_string($_POST, 'ddtext');
$p[':ddshort'] = gpc_get_string($_POST, 'ddshort'); $p[':ddshort'] = gpc_get_string($_POST, 'ddshort');
$p[':color'] = gpc_get_color($_POST, 'color'); $p[':color'] = gpc_get_color($_POST, 'color');
@@ -131,7 +135,7 @@ $sth = $pdo->query($sql);
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) { foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$num[$row[0]] = $row[1]; $num[$row[0]] = $row[1];
} }
$sql = "SELECT ddval, ddtext FROM dropdown WHERE ddid=0 AND ddval>0"; $sql = "SELECT ddval, ddtext, flags FROM dropdown WHERE ddid=0 AND ddval>0";
$sth = $pdo->query($sql); $sth = $pdo->query($sql);
echo "<h1>$pagetitle</h1>\n"; echo "<h1>$pagetitle</h1>\n";
@@ -157,9 +161,12 @@ foreach ($sth->fetchAll() as $row) {
echo '</td>'; echo '</td>';
echo '<td>', $row['ddtext'], '</td>'; echo '<td>', $row['ddtext'], '</td>';
echo '<td>', $num[$row['ddval']] ?? 0, '</td>'; echo '<td>', $num[$row['ddval']] ?? 0, '</td>';
// form_action_buttons($g_scriptname, $row['ddval']);
echo "<td>"; echo "<td>";
echo '<a class="text-nowrap" title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['ddval'], '"><i class="bi bi-pencil ms-2"></i></a>'; if ($row['flags'] == 'locked') {
echo _('Locked');
} else {
echo '<a class="text-nowrap" title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['ddval'], '"><i class="bi bi-pencil ms-2"></i></a>';
}
echo "</td>\n"; echo "</td>\n";
echo "</tr>\n"; echo "</tr>\n";
} }
@@ -261,7 +268,6 @@ foreach ($sth->fetchAll() as $row) {
echo '<i class="bi-trash"></i>'; echo '<i class="bi-trash"></i>';
echo '</td>', "\n"; echo '</td>', "\n";
// TODO extend function to accept additional parameters // TODO extend function to accept additional parameters
// form_action_buttons($g_scriptname, $row['ddid'];
} }
echo "</tr>\n"; echo "</tr>\n";
} }
+129 -46
View File
@@ -7,8 +7,11 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
require 'lib/fileutils.inc'; require 'lib/fileutils.inc';
require 'lib/signalk.inc';
$pagetitle = _('Equipment'); $pagetitle = _('Equipment');
@@ -16,8 +19,8 @@ $id = gpc_get_int($_REQUEST, 'id', 0);
$opt_supplier = db_get_opt_supp($g_opt_unknown); $opt_supplier = db_get_opt_supp($g_opt_unknown);
$opt_manufacturer = db_get_opt_manuf($g_opt_unknown); $opt_manufacturer = db_get_opt_manuf($g_opt_unknown);
$opt_ecat = db_get_options(4); // Equipment categories $opt_ecat = db_get_options(DD_EQUIPMENT_CATEGORY);
$opt_unit = db_get_options(8); $opt_unit = db_get_options(DD_UNIT);
// ========== ACTIONS START =================================================== // ========== ACTIONS START ===================================================
@@ -43,7 +46,9 @@ switch ($submit = form_get_action()) {
break; break;
case 'freset': case 'freset':
db_clear_filter(200); // set status checkboxes to useful defaults
$flt = array('flags' => ['ordered']);
db_save_filter($flt, 200);
$action = ACT_DEFAULT; $action = ACT_DEFAULT;
break; break;
@@ -55,6 +60,7 @@ switch ($submit = form_get_action()) {
$p[':model'] = gpc_get_string($_POST, 'model'); $p[':model'] = gpc_get_string($_POST, 'model');
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150); $p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
$id = db_exec_insert('equipment', $p); $id = db_exec_insert('equipment', $p);
db_set_revision('table', TBL_EQUIPMENT);
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -73,6 +79,9 @@ switch ($submit = form_get_action()) {
if ($p[':manufacturer'] <= 0) $p[':manufacturer'] = NULL; if ($p[':manufacturer'] <= 0) $p[':manufacturer'] = NULL;
$p[':ecat'] = gpc_get_int($_POST, 'category'); $p[':ecat'] = gpc_get_int($_POST, 'category');
if ($p[':ecat'] <= 0) $p[':ecat'] = NULL; if ($p[':ecat'] <= 0) $p[':ecat'] = NULL;
$p[':x'] = gpc_get_uint($_POST, 'x');
$p[':y'] = gpc_get_int($_POST, 'y');
$p[':z'] = gpc_get_int($_POST, 'z');
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150); $p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
$allowed = db_load_enum('equipment', 'flags'); $allowed = db_load_enum('equipment', 'flags');
$p[':flags'] = gpc_get_set($_POST, 'flags', $allowed, true, NULL); $p[':flags'] = gpc_get_set($_POST, 'flags', $allowed, true, NULL);
@@ -197,6 +206,7 @@ switch ($submit = form_get_action()) {
$docid = $pdo->lastInsertId(); $docid = $pdo->lastInsertId();
$file_techname = file_get_docname($docid, 'picture', $file_ext); $file_techname = file_get_docname($docid, 'picture', $file_ext);
move_uploaded_file($file_tmp, $g_doc_basepath . '/' . $file_techname); move_uploaded_file($file_tmp, $g_doc_basepath . '/' . $file_techname);
chmod($g_doc_basepath . '/' . $file_techname, 0640);
} else { } else {
// A document record definitely exists here, now just // A document record definitely exists here, now just
// connect it to the selected equipment // connect it to the selected equipment
@@ -316,29 +326,21 @@ $opt_none_male = array(-1 => pgettext('male', '&horbar; none &horbar;'));
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<div id="filter" class="card"> <div id="filter" class="card">
<div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div> <div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div>
<div class="card-body d-flex flex-wrap gap-3"> <div class="card-body d-flex flex-wrap gap-3">
<?php <?php
filter_create_select('flt_category', _('Category'), $g_opt_all + $g_opt_none + $opt_ecat, $flt->cat); filter_create_select('flt_category', _('Category'), $g_opt_all + $g_opt_none + $opt_ecat, $flt->cat);
filter_create_select('flt_manuf', _('Manufacturer'), $g_opt_all + $opt_none_male + $opt_manufacturer, $flt->manuf); filter_create_select('flt_manuf', _('Manufacturer'), $g_opt_all + $opt_none_male + $opt_manufacturer, $flt->manuf);
filter_create_select('flt_supp', _('Supplier'), $g_opt_all + $opt_none_male + $opt_supplier, $flt->supp); filter_create_select('flt_supp', _('Supplier'), $g_opt_all + $opt_none_male + $opt_supplier, $flt->supp);
?> filter_create_text('flt_txt', _('Text'), $flt->txt, 15, 30);
<div class="d-flex flex-nowrap gap-2">
<label for="flt_txt"><?=_('Text')?></label>
<input type="text" class="form-control" name="flt_txt" maxlength="30" value="<?=$flt->txt ?>">
</div>
<div class="d-flex flex-nowrap gap-2">
<?php
$opt_flags = db_load_enum('equipment', 'flags', true, true, false); $opt_flags = db_load_enum('equipment', 'flags', true, true, false);
filter_create_checks('flt_flags', _('Flags'), $opt_flags, $flt->flags ?? []); filter_create_checks('flt_flags', _('Also show '), $opt_flags, $flt->flags ?? []);
?> ?>
</div> </div>
</div> <div class="card-footer">
<div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
<button name="submit[freset]" class="btn btn-sm btn-secondary float-end" title="<?=_('Reset filter to defaults')?>"><?=_('Clear')?></button> <button name="submit[freset]" class="btn btn-sm btn-secondary float-end" title="<?=_('Reset filter to defaults')?>"><?=_('Clear')?></button>
</div> </div>
</div> </div>
</form> </form>
@@ -393,7 +395,7 @@ foreach ($res as $row) {
echo "<td>", $row['model'], "</td>\n"; echo "<td>", $row['model'], "</td>\n";
echo "<td>", $row['serial'], "</td>\n"; echo "<td>", $row['serial'], "</td>\n";
echo "<td>", $age, "</td>\n"; echo "<td>", $age, "</td>\n";
echo "<td>", $row['remarks'], "</td>\n"; echo "<td>", h($row['remarks'], br:true), "</td>\n";
// Edit current record button // Edit current record button
echo "<td>"; echo "<td>";
echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['eid'], '"><i class="bi-pencil"></i></a>', "\n"; echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['eid'], '"><i class="bi-pencil"></i></a>', "\n";
@@ -415,22 +417,13 @@ $flt = db_get_filter($user->id, 200);
?> ?>
<h2><?=_('Add Equipment')?></h2> <h2><?=_('Add Equipment')?></h2>
<form method="post" action="<?=$g_scriptname?>"> <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 <?php
form_create_text('ename', _('name'), 80);
form_create_select('category', _('Category'), $g_opt_none + $opt_ecat, $flt->cat); form_create_select('category', _('Category'), $g_opt_none + $opt_ecat, $flt->cat);
form_create_select('manufacturer', _('Manufacturer'), $opt_manufacturer, $flt->manuf); form_create_select('manufacturer', _('Manufacturer'), $opt_manufacturer, $flt->manuf);
form_create_text('model', _('Model'), 40);
form_create_textarea('remarks', _('Remarks'), 3, 150);
?> ?>
<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" maxlength="150"></textarea>
</div>
<div class="container-fluid px-0 my-3"> <div class="container-fluid px-0 my-3">
<button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button> <button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button>
<a href="<?=$g_scriptname?>" class="btn btn-secondary"><?=_('Back')?></a> <a href="<?=$g_scriptname?>" class="btn btn-secondary"><?=_('Back')?></a>
@@ -441,7 +434,8 @@ elseif ($action == ACT_VIEW):
// ========== VARIANT: view single record ===================================== // ========== VARIANT: view single record =====================================
$sql = "SELECT eid, ename, model, serial, purchdate, price, weight, " $sql = "SELECT eid, ename, model, serial, purchdate, price, weight, "
. " supplier, manufacturer, ecat, shortname, remarks, flags " . "supplier, manufacturer, ecat, shortname, x, y, z, flags, "
. "remarks "
. "FROM equipment " . "FROM equipment "
. "WHERE eid=?"; . "WHERE eid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -455,19 +449,37 @@ echo '<div class="row">';
echo '<div class="col">'; echo '<div class="col">';
echo '<table class="table">', "\n"; echo '<table class="table">', "\n";
echo '<tr><th>', _('Short name'),"</th><td>", $equipment->shortname, "</td></tr>\n"; echo '<tr><th>', _('Short name'),"</th><td>", h($equipment->shortname), "</td></tr>\n";
echo '<tr><th>', _('Manufacturer'),"</th><td>", $opt_manufacturer[$equipment->manufacturer]; echo '<tr><th>', _('Manufacturer'),"</th><td>", $opt_manufacturer[$equipment->manufacturer];
echo '&nbsp;<a title="', _('View'), '" href="company.php?f=view&id=', $equipment->manufacturer, '"><i class="bi-eye"></i></a>'; echo '&nbsp;<a title="', _('View'), '" href="company.php?f=view&id=', $equipment->manufacturer, '"><i class="bi-eye"></i></a>';
echo "</td></tr>\n"; echo "</td></tr>\n";
echo '<tr><th>', _('Model'),"</th><td>", $equipment->model, "</td></tr>\n"; echo '<tr><th>', _('Model'),"</th><td>", h($equipment->model), "</td></tr>\n";
echo '<tr><th>', _('Serial'),"</th><td>", $equipment->serial, "</td></tr>\n"; echo '<tr><th>', _('Serial'),"</th><td>", h($equipment->serial), "</td></tr>\n";
echo '<tr><th>', _('Weight'),"</th><td>", format_float($equipment->weight, 2, 'kg'), "</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>', _('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>', _('Purchase date'),"</th><td>", format_date($equipment->purchdate), "</td></tr>\n";
echo '<tr><th>', _('Supplier'),"</th><td>", $equipment->supplier ? $opt_supplier[$equipment->supplier] : 'n/a', "</td></tr>\n"; echo '<tr><th>', _('Supplier'),"</th><td>", $equipment->supplier ? $opt_supplier[$equipment->supplier] : 'n/a', "</td></tr>\n";
echo '<tr><th>', _('Category'),"</th><td>", $opt_ecat[$equipment->ecat], "</td></tr>\n"; echo '<tr><th>', _('Category'),"</th><td>", $opt_ecat[$equipment->ecat], "</td></tr>\n";
echo '<tr><th>', _('Remarks'),"</th><td>", nl2br($equipment->remarks), "</td></tr>\n"; if (!empty($equipment->x)) {
echo '<tr><th>', _('Location (x, y, z)'),"</th><td>(", $equipment->x, ', ', $equipment->y, ', ', $equipment->z, ")</td></tr>\n";
}
echo '<tr><th>', _('Remarks'),"</th><td>", h($equipment->remarks, br:true), "</td></tr>\n";
echo '<tr><th>', _('Flags'),"</th><td>", $equipment->flags, "</td></tr>\n"; echo '<tr><th>', _('Flags'),"</th><td>", $equipment->flags, "</td></tr>\n";
// Custom properties
$sql = "SELECT keyname, valstr, valint FROM property WHERE objtype='equip' AND objid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
foreach ($sth->fetchAll() as $row) {
echo "<tr><th>{$row['keyname']}</th><td>";
if (isset($row['valstr'])) {
echo $row['valstr'];
} else {
echo $row['valint'];
}
echo "</td></tr>\n";
}
echo "</table>\n"; echo "</table>\n";
echo '</div>'; // Column break echo '</div>'; // Column break
@@ -545,6 +557,30 @@ echo '</div>'; // container
// Buttons at bottom of data area // Buttons at bottom of data area
form_view_buttons($g_scriptname, $id); form_view_buttons($g_scriptname, $id);
// Annotations
echo '<h3>', _('Annotations'), "</h3>\n";
$sql = "SELECT noteid, annotation "
. "FROM note "
. "WHERE notetype='equip' AND refid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
if ($sth->rowCount() > 0) {
$n = 0;
foreach ($sth->fetchAll() as $row) {
$n += 1;
echo "<p>($n) {$row['annotation']}";
echo ' <a title="', _('Edit'), '" href="note.php?f=edit&id=', $row['noteid'], '"><i class="bi-pencil"></i></a>';
echo "</p>\n";
}
} else {
echo '<p>', _('No annotations for this equipment'), "</p>\n";
}
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<a href="note.php?f=add&t=equip&id=', $id, '" class="btn btn-primary" role="button">';
echo _('Add note'), "</a>\n";
echo "</div>\n";
// Maintenance records // Maintenance records
echo '<h3>', _('Maintenances'), "</h3>"; echo '<h3>', _('Maintenances'), "</h3>";
@@ -590,6 +626,39 @@ echo '<a href="measurement.php?f=add&id=', $id, '" class="btn btn-primary" role=
echo _('Add measurement'), "</a>\n"; echo _('Add measurement'), "</a>\n";
echo "</div>\n"; echo "</div>\n";
// Signal-K Integration
$res = $pdo->query("SELECT valint, valstr FROM settings WHERE userid=0 AND sno=5");
$sk_active = false;
$sk_url = NULL;
if ($res !== false) {
$row = $res->fetch(PDO::FETCH_ASSOC);
if ($row !== false && $row['valint'] == 1
&& !empty($row['valstr'])
&& filter_var($settings['valstr'], FILTER_VALIDATE_URL))
{
$sk_active = true;
$sk_url = rtrim($row['valstr'], '/');
}
}
if ($sk_active) {
// TODO this ist just experimental
$sql = "SELECT skpath FROM signalk WHERE vid=? AND objid=? AND objtype='equipment'";
$sth = $pdo->prepare($sql);
$sth->execute([$user->vid, $id]);
if ($sth->rowCount() > 0) {
echo '<h3>', _('Signal K data'), "</h3>";
$skpath = $sth->fetchColumn();
// REST Example:
// GET http://127.0.0.1:3000/signalk/v1/api/vessels/self/propulsion/mainEngine/runTime
try {
$data = signalk_get($url, $skpath);
print_r($data);
} catch (Exception $e) {
echo "<p>signalk-timeout!</p>\n";
}
}
}
// Spare parts // Spare parts
echo '<h3>', _('Spare parts'), "</h3>"; echo '<h3>', _('Spare parts'), "</h3>";
@@ -636,8 +705,8 @@ foreach ($sth->fetchAll() as $row) {
$supplier[$row['compid']] = $row['compname']; $supplier[$row['compid']] = $row['compname'];
} }
$sql = "SELECT eid, ename, model, serial, weight, price, purchdate," $sql = "SELECT eid, ename, model, serial, weight, price, purchdate, "
. " supplier, manufacturer, ecat, shortname, remarks, flags " . "supplier, manufacturer, ecat, shortname, x, y, z, remarks, flags "
. "FROM equipment " . "FROM equipment "
. "WHERE eid=?"; . "WHERE eid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -649,20 +718,20 @@ $equipment = $sth->fetch(PDO::FETCH_OBJ);
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3"> <div class="mb-3">
<label for="ename" class="form-label"><?=_('Name')?></label> <label for="ename" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="ename" name="ename" value="<?=$equipment->ename ?>"> <input type="text" class="form-control" id="ename" name="ename" value="<?=h($equipment->ename)?>">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="shortname" class="form-label"><?=_('Short name')?></label> <label for="shortname" class="form-label"><?=_('Short name')?></label>
<input type="text" class="form-control" id="shortname" name="shortname" value="<?=$equipment->shortname ?>"> <input type="text" class="form-control" id="shortname" name="shortname" value="<?=h($equipment->shortname)?>">
</div> </div>
<?php form_create_select('manufacturer', _('Manufacturer'), $opt_manufacturer, $equipment->manufacturer); ?> <?php form_create_select('manufacturer', _('Manufacturer'), $opt_manufacturer, $equipment->manufacturer); ?>
<div class="mb-3"> <div class="mb-3">
<label for="model" class="form-label"><?=_('Model')?></label> <label for="model" class="form-label"><?=_('Model')?></label>
<input type="text" class="form-control" id="model" name="model" value="<?=$equipment->model ?>"> <input type="text" class="form-control" id="model" name="model" value="<?=h($equipment->model)?>">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="serial" class="form-label"><?=_('Serial')?></label> <label for="serial" class="form-label"><?=_('Serial')?></label>
<input type="text" class="form-control" id="serial" name="serial" value="<?=$equipment->serial ?>"> <input type="text" class="form-control" id="serial" name="serial" value="<?=h($equipment->serial)?>">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="weight" class="form-label"><?=_('Weight, kg')?></label> <label for="weight" class="form-label"><?=_('Weight, kg')?></label>
@@ -680,9 +749,23 @@ $equipment = $sth->fetch(PDO::FETCH_OBJ);
form_create_select('supplier', _('Supplier'), $opt_supplier, $equipment->supplier); form_create_select('supplier', _('Supplier'), $opt_supplier, $equipment->supplier);
form_create_select('category', _('Category'), $g_opt_unknown + $opt_ecat, $equipment->ecat); form_create_select('category', _('Category'), $g_opt_unknown + $opt_ecat, $equipment->ecat);
?> ?>
<div class="mb-3">
<label class="form-label"><?=_('Position (x, y, z) in mm')?></label>
<div class="row">
<div class="col">
<input type="number" class="form-control" id="x" name="x" min="0" value="<?=$equipment->x ?>">
</div>
<div class="col">
<input type="number" class="form-control" id="y" name="y" value="<?=$equipment->y ?>">
</div>
<div class="col">
<input type="number" class="form-control" id="z" name="z" value="<?=$equipment->z ?>">
</div>
</div>
</div>
<div class="mb-3"> <div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label> <label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$equipment->remarks ?></textarea> <textarea class="form-control" id="remarks" name="remarks" rows="3"><?=h($equipment->remarks, br:false)?></textarea>
</div> </div>
<?php <?php
$opt_flags = db_load_enum('equipment', 'flags', true, true, false); $opt_flags = db_load_enum('equipment', 'flags', true, true, false);
@@ -705,8 +788,8 @@ $equipment = $sth->fetch(PDO::FETCH_OBJ);
echo '<h2>', _('Delete equipment'),"</h2>\n"; echo '<h2>', _('Delete equipment'),"</h2>\n";
echo '<p>', sprintf(_('Record no. %d'), $id), "</p>\n"; echo '<p>', sprintf(_('Record no. %d'), $id), "</p>\n";
echo '<p>Name: ', $equipment->ename, "</p>"; echo '<p>Name: ', h($equipment->ename), "</p>";
echo '<p>Remarks: ', $equipment->remarks, "</p>"; echo '<p>Remarks: ', h($equipment->remarks, br:true), "</p>";
echo '<p>', _('Deleting an equipment item is final. There is no way back. Only delete if you are absolute sure.'), "</p>\n"; echo '<p>', _('Deleting an equipment item is final. There is no way back. Only delete if you are absolute sure.'), "</p>\n";
+55 -37
View File
@@ -7,14 +7,16 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Fuses'); $pagetitle = _('Fuses');
$id = gpc_get_int($_REQUEST, 'id', 0); $id = gpc_get_int($_REQUEST, 'id', 0);
$opt_ftype = db_get_options(7); $opt_ftype = db_get_options(DD_FUSE_TYPE);
$opt_location = db_get_options(10); $opt_location = db_get_options(DD_FUSE_BLOCK);
// ========== ACTIONS START =================================================== // ========== ACTIONS START ===================================================
@@ -30,6 +32,7 @@ switch ($submit = form_get_action()) {
case 'filter': case 'filter':
$flt = array(); $flt = array();
$flt['location'] = gpc_get_int($_POST, 'flt_location'); $flt['location'] = gpc_get_int($_POST, 'flt_location');
$flt['type'] = gpc_get_int($_POST, 'flt_type');
$flt['txt'] = gpc_get_string($_POST, 'flt_txt'); $flt['txt'] = gpc_get_string($_POST, 'flt_txt');
db_save_filter($flt, 212); db_save_filter($flt, 212);
$action = ACT_DEFAULT; $action = ACT_DEFAULT;
@@ -42,26 +45,28 @@ switch ($submit = form_get_action()) {
case 'insert': case 'insert':
$p[':vid'] = $user->vid; $p[':vid'] = $user->vid;
$p[':fnumber'] = gpc_get_int($_POST, 'fnumber');; $p[':fnumber'] = gpc_get_int($_POST, 'fnumber');
$p[':ftype'] = gpc_get_int($_POST, 'ftype');; $p[':ftype'] = gpc_get_int($_POST, 'ftype', NULL, -1);
$p[':current'] = gpc_get_int($_POST, 'current');; $p[':current'] = gpc_get_int($_POST, 'current');
$p[':location'] = gpc_get_int($_POST, 'location');; $p[':location'] = gpc_get_int($_POST, 'location');
$p[':description'] = gpc_get_string($_POST, 'description'); $p[':description'] = gpc_get_string($_POST, 'description');
$id = db_exec_insert('fuse', $p); $id = db_exec_insert('fuse', $p);
db_set_revision('table', TBL_FUSES);
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
case 'update': case 'update':
$p[':fuseid'] = $id; $p[':fuseid'] = $id;
$p[':fnumber'] = gpc_get_string($_POST, 'fuseid'); $p[':fnumber'] = gpc_get_int($_POST, 'fnumber');
$p[':ftype'] = gpc_get_int($_POST, 'ftype', [-1]);
$p[':current'] = gpc_get_float($_POST, 'current'); $p[':current'] = gpc_get_float($_POST, 'current');
$p[':cableid'] = gpc_get_int($_POST, 'cableid'); $p[':color'] = gpc_get_color($_POST, 'color');
$p[':eid'] = gpc_get_int($_POST, 'id'); $p[':cableid'] = gpc_get_int($_POST, 'cableid', NULL, -1);
$p[':weight'] = min(gpc_get_float($_POST, 'weight'), 9.99); // limit max value $p[':eid'] = gpc_get_int($_POST, 'id', [-1]);
$p[':location'] = gpc_get_int($_POST, 'location'); $p[':location'] = gpc_get_int($_POST, 'location', NULL, -1);
$p[':description'] = gpc_get_string($_POST, 'description'); $p[':description'] = gpc_get_string($_POST, 'description');
$p[':remarks'] = gpc_get_string($_POST, 'remarks'); $p[':remarks'] = gpc_get_string($_POST, 'remarks');
db_exec_update('tag', $p, 'tagid'); db_exec_update('fuse', $p, 'fuseid');
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -94,10 +99,10 @@ if ($action == ACT_DEFAULT):
// ========== VARIANT: default behavior ======================================= // ========== VARIANT: default behavior =======================================
// lookup tables // lookup tables
$opt_ftype_short = db_get_options(7, '', true); $opt_ftype_short = db_get_options(DD_FUSE_TYPE, '', true);
// load filter from db // load filter from db
$flt = db_get_filter($user->id, 212); $flt = db_get_filter($user->id, 212, ['txt', 'location', 'type']);
$w = array('vid=:vid'); $w = array('vid=:vid');
$p = array(':vid' => $user->vid); $p = array(':vid' => $user->vid);
@@ -108,6 +113,12 @@ if ($flt->location == -1) {
$w[] = 'location=:location'; $w[] = 'location=:location';
$p[':location'] = $flt->location; $p[':location'] = $flt->location;
} }
if ($flt->type == -1) {
$w[] = 'ftype IS NULL';
} elseif ($flt->type > 0) {
$w[] = 'ftype=:ftype';
$p[':ftype'] = $flt->type;
}
if (strlen($flt->txt) > 1) { if (strlen($flt->txt) > 1) {
$w[] = 'description LIKE :txt'; $w[] = 'description LIKE :txt';
$p[':txt'] = '%'.$flt->txt.'%'; $p[':txt'] = '%'.$flt->txt.'%';
@@ -125,11 +136,9 @@ echo "<h1>$pagetitle</h1>\n";
<div class="card-body d-flex flex-wrap gap-3"> <div class="card-body d-flex flex-wrap gap-3">
<?php <?php
filter_create_select('flt_location', _('Location'), $g_opt_all + $g_opt_none + $opt_location, $flt->location); filter_create_select('flt_location', _('Location'), $g_opt_all + $g_opt_none + $opt_location, $flt->location);
filter_create_select('flt_type', _('Type'), $g_opt_all + $g_opt_none + $opt_ftype, $flt->type);
filter_create_text('flt_txt', _('Description'), $flt->text, 30, 45);
?> ?>
<div class="d-flex flex-nowrap gap-2">
<label for="flt_txt"><?=_('Description')?></label>
<input type="text" class="form-control" name="flt_txt" size="15" maxlength="30" value="<?=$flt->txt ?? ''?>">
</div>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
@@ -139,7 +148,7 @@ filter_create_select('flt_location', _('Location'), $g_opt_all + $g_opt_none + $
</form> </form>
<?php <?php
$sql = "SELECT fuseid, fnumber, ftype, location, current, description " $sql = "SELECT fuseid, fnumber, ftype, location, current, color, description "
. "FROM fuse"; . "FROM fuse";
$sql .= ' WHERE ' . $where; $sql .= ' WHERE ' . $where;
$sql .= $order; $sql .= $order;
@@ -155,6 +164,7 @@ echo '<th>#</th>';
echo '<th>', pgettext('number', 'Number'), "</th>"; echo '<th>', pgettext('number', 'Number'), "</th>";
echo '<th>', _('Type'), "</th>"; echo '<th>', _('Type'), "</th>";
echo '<th>', _('Current'), "</th>"; echo '<th>', _('Current'), "</th>";
echo '<th>', _('Color'), "</th>";
echo '<th>', _('Location'), "</th>"; echo '<th>', _('Location'), "</th>";
echo '<th>', _('Description'), "</th>"; echo '<th>', _('Description'), "</th>";
echo "<th></th>"; echo "<th></th>";
@@ -169,16 +179,17 @@ foreach ($res as $row) {
echo "<td>F", $row['fnumber'], "</td>\n"; echo "<td>F", $row['fnumber'], "</td>\n";
echo "<td>",$opt_ftype_short[$row['ftype']], "</td>\n"; echo "<td>",$opt_ftype_short[$row['ftype']], "</td>\n";
echo "<td>", $row['current'], "A</td>\n"; echo "<td>", $row['current'], "A</td>\n";
echo '<td>', format_color(strtoupper($row['color'])), "</td>\n";
echo "<td>", $opt_location[$row['location']], "</td>\n"; echo "<td>", $opt_location[$row['location']], "</td>\n";
echo "<td>", $row['description'], "</td>\n"; echo "<td>", $row['description'], "</td>\n";
// Edit current record button // Edit current record button
echo "<td>"; echo "<td>";
echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['fusevid'], '"><i class="bi bi-pencil"></i></a>', "\n"; echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['fuseid'], '"><i class="bi bi-pencil"></i></a>', "\n";
echo "</td>\n"; echo "</td>\n";
echo "</tr>\n"; echo "</tr>\n";
} }
// Table summary // Table summary
table_rec_summary($i0, $i, $numrows, 6); //table_rec_summary(1, $i-1, $i-1, 6);
echo "</table>\n"; echo "</table>\n";
form_add_button($g_scriptname); form_add_button($g_scriptname);
@@ -188,7 +199,7 @@ elseif ($action == ACT_ADD):
echo '<h2>', _('Add fuse'), "</h2>\n"; echo '<h2>', _('Add fuse'), "</h2>\n";
// calc next free fuse number for convenience // FIXME calc next free fuse number for convenience
$sql = "SELECT max(fnumber) FROM fuse WHERE vid=?"; $sql = "SELECT max(fnumber) FROM fuse WHERE vid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([$user->vid]); $sth->execute([$user->vid]);
@@ -204,7 +215,9 @@ $fnumber = $sth->fetchColumn() + 1;
<label for="note" class="form-label"><?=_('Description')?></label> <label for="note" class="form-label"><?=_('Description')?></label>
<input type="text" class="form-control" id="description" name="description" autofocus> <input type="text" class="form-control" id="description" name="description" autofocus>
</div> </div>
<?php form_create_select('ftype', _('Type'), $opt_ftype); ?> <?php
form_create_select('ftype', _('Type'), $g_opt_none + $opt_ftype);
?>
<div class="mb-3"> <div class="mb-3">
<label for="current" class="form-label"><?=_('Current, Ampere')?></label> <label for="current" class="form-label"><?=_('Current, Ampere')?></label>
<input type="text" class="form-control" id="current" name="current" required> <input type="text" class="form-control" id="current" name="current" required>
@@ -217,11 +230,11 @@ echo "</form>\n";
elseif ($action == ACT_VIEW): elseif ($action == ACT_VIEW):
// ========== VARIANT: view single record ===================================== // ========== VARIANT: view single record =====================================
$sql = "SELECT fnumber, ftype, current, cableid, eid, location, description, remarks " $sql = "SELECT fnumber, ftype, current, cableid, eid, location, description, color, remarks "
. "FROM fuse " . "FROM fuse "
. "WHERE fuseid=?"; . "WHERE vid=? AND fuseid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([$id]); $sth->execute([$user->vid, $id]);
$fuse = $sth->fetch(PDO::FETCH_OBJ); $fuse = $sth->fetch(PDO::FETCH_OBJ);
echo '<h2>', _('View fuse'), "</h2>\n"; echo '<h2>', _('View fuse'), "</h2>\n";
@@ -231,10 +244,11 @@ echo '<tr><th style="width:20%">', _('Fuse'),"</th><td>F", $fuse->fnumber, "</td
echo '<tr><th>', _('Description'),"</th><td>", $fuse->description, "</td></tr>\n"; echo '<tr><th>', _('Description'),"</th><td>", $fuse->description, "</td></tr>\n";
echo '<tr><th>', _('Type'),"</th><td>", $opt_ftype[$fuse->ftype], "</td></tr>\n"; echo '<tr><th>', _('Type'),"</th><td>", $opt_ftype[$fuse->ftype], "</td></tr>\n";
echo '<tr><th>', _('Current'),"</th><td>", $fuse->current, "A</td></tr>\n"; echo '<tr><th>', _('Current'),"</th><td>", $fuse->current, "A</td></tr>\n";
echo '<tr><th>', _('Color'),"</th><td>", format_color($fuse->color), "</td></tr>\n";
echo '<tr><th>', _('Location'),"</th><td>", $opt_location[$fuse->location], "</td></tr>\n"; echo '<tr><th>', _('Location'),"</th><td>", $opt_location[$fuse->location], "</td></tr>\n";
echo '<tr><th>', _('Cable'),"</th><td>", $fuse->cableid, "</td></tr>\n"; echo '<tr><th>', _('Cable'),"</th><td>", $fuse->cableid, "</td></tr>\n";
echo '<tr><th>', _('Equipment'),"</th><td>", $fuse->eid, "</td></tr>\n"; echo '<tr><th>', _('Equipment'),"</th><td>", $fuse->eid, "</td></tr>\n";
echo '<tr><th>', _('Remarks'),"</th><td>", nl2br($fuse->remarks), "</td></tr>\n"; echo '<tr><th>', _('Remarks'),"</th><td>", h($fuse->remarks, br:true), "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
form_view_buttons($g_scriptname, $id); form_view_buttons($g_scriptname, $id);
@@ -242,7 +256,10 @@ form_view_buttons($g_scriptname, $id);
elseif ($action == ACT_EDIT): elseif ($action == ACT_EDIT):
// ========== VARIANT: edit single record ===================================== // ========== VARIANT: edit single record =====================================
$sql = "SELECT fnumber, description " $opt_cable = db_get_opt_cable($user->vid);
$opt_equipment = db_get_opt_equip($user->vid);
$sql = "SELECT fnumber, ftype, current, cableid, eid, location, description, color, remarks "
. "FROM fuse " . "FROM fuse "
. "WHERE fuseid=?"; . "WHERE fuseid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -253,15 +270,16 @@ echo '<h2>', _('Edit fuse'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3"> <?php
<label for="mname" class="form-label"><?=pgettext('number', 'Number')?></label> form_create_numeric('fnumber', _('Fuse number'), $fuse->fnumber, 1, 9999, 1, TRUE, TRUE);
<input type="text" class="form-control" id="fnumber" name="fnumber" value="<?=$fuse->fnumber ?>"> form_create_select('ftype', _('Type'), $g_opt_none + $opt_ftype, $fuse->ftype);
</div> form_create_text('description', _('Description'), 60, $fuse->description);
<div class="mb-3"> form_create_numeric('current', _('Current, A'), format_float($fuse->current), 1, 999, 1);
<label for="note" class="form-label"><?=_('Description')?></label> form_create_color('color', _('Color'), $fuse->color);
<input type="text" class="form-control" id="description" name="description" value="<?=$fuse->description ?>"> form_create_select('location', _('Location'), $g_opt_none + $opt_location, $fuse->location);
</div> form_create_select('cableid', _('Cable'), $g_opt_none + $opt_cable, $fuse->cableid);
<?php form_create_select('eid', _('Equipment'), $g_opt_none + $opt_equipment, $fuse->eid);
form_create_textarea('remarks', _('Remarks'), 3, 150, $fuse->remarks);
form_edit_buttons($g_scriptname, $id); form_edit_buttons($g_scriptname, $id);
echo "</form>\n"; echo "</form>\n";
+204 -594
View File
@@ -12,7 +12,10 @@
* # Date Changes by * # Date Changes by
* ------ ------------ ---------------------------------------------- ----- * ------ ------------ ---------------------------------------------- -----
* 0.1.0 2024-03-12 Started development tho * 0.1.0 2024-03-12 Started development tho
' 0.2.0 2026-08-18 First public release tho * 0.2.0 2026-08-18 First public release tho
* 0.2.1 2026-08-28 Foreign keys, bugfixes and output sanitation tho
* 0.2.2 2026-09-21 Lots of improvements and fixes tho
* 2026-10-01 Dropdown constants for readability tho
* *
*/ */
@@ -45,16 +48,50 @@ define('ROLE_CAPTAIN', 'captain');
define('ROLE_HELMSMAN', 'helmsman'); define('ROLE_HELMSMAN', 'helmsman');
define('ROLE_SAILOR', 'sailor'); define('ROLE_SAILOR', 'sailor');
define('DD_VESSEL_TYPE', 1);
define('DD_COMPANY_TYPE', 2);
define('DD_STORAGE_TYPE', 3);
define('DD_EQUIPMENT_CATEGORY', 4);
define('DD_PROVISION_CATEGORY', 5);
define('DD_PROVISION_UNIT', 6);
define('DD_FUSE_TYPE', 7);
define('DD_UNIT', 8);
define('DD_BOX_TYPE', 9);
define('DD_FUSE_BLOCK', 10);
define('DD_CABLE_TYPE', 11);
define('DD_CABLE_TECHNAME', 12);
define('DD_INVENTORY_CATEGORY', 13);
define('DD_BBN_VESSELDATA', 14);
define('DD_MEASUREMENT_CATEGORY', 15);
// table indices which are used for combo lists
define('TBL_VESSEL', 1);
define('TBL_USERS', 2);
define('TBL_COMPANIES', 3);
define('TBL_STORAGE', 4);
define('TBL_BOXES', 5);
define('TBL_EQUIPMENT', 6);
// define('TBL_INVENTORY', 7);
define('TBL_PROJECTS', 8);
define('TBL_CABLES', 9);
define('TBL_FUSES', 10);
define('TBL_TAGS', 11);
// ========== PAGE START CODE ================================================= // ========== PAGE START CODE =================================================
// global version string // global version string
$g_version = 'v0.2.0'; $g_version = 'v0.3';
$g_scriptname = basename($_SERVER['SCRIPT_NAME']); $g_scriptname = basename($_SERVER['SCRIPT_NAME']);
require 'config.inc'; require 'config.inc';
umask(0027); // no rights for world!
// Localization // Localization
$lang = get_browser_lang(['de', 'en']);
setlocale(LC_ALL, $g_locale); setlocale(LC_ALL, $g_locale);
$g_lconv = localeconv(); $g_lconv = localeconv();
$g_lang = substr($g_locale, 0, 2); // short language identifier $g_lang = substr($g_locale, 0, 2); // short language identifier
@@ -110,14 +147,40 @@ try {
$sth = $pdo->query("SELECT valint FROM settings WHERE userid=0 AND sno=0"); $sth = $pdo->query("SELECT valint FROM settings WHERE userid=0 AND sno=0");
} catch (PDOException $e) { } catch (PDOException $e) {
if ($e->getCode() == 1146) { if ($e->getCode() == 1146) {
echo '<pre>'; echo "<pre>\n";
echo 'Settings table not found! Perhaps database is not initialized'; echo "Settings table not found! Perhaps database is not initialized?\n";
echo '</pre>'; echo "</pre>\n";
exit(1); exit(1);
} }
} }
$g_db_scheme_version = $sth->fetchColumn(); $g_db_scheme_version = $sth->fetchColumn();
// TODO Check version $g_db_scheme_required = 1;
// Schema version check
if ($g_db_scheme_version !== $g_db_scheme_required) {
// TODO if required schema version is smaller than found version then
// an database scheme update is neccessary
// otherwise our program code is outdated an should be updated
echo "<pre>\n";
echo "Database schema is wrong: detected version $g_db_scheme_version, but required version $g_db_scheme_required!\n";
echo "</pre>\n";
exit(1);
}
// currency symbol is global
$sth = $pdo->query("SELECT valint FROM settings WHERE userid=0 AND sno=4");
$g_currsym = $sth->fetchColumn();
// allowed date formats
$g_opt_datefmt = array(
'Y-m-d' => _('YYYY-MM-DD'), // ISO / international /technical
'd.m.Y' => _('DD.MM.YYYY'), // Germany / Central & Northern Europe
'd/m/Y' => _('DD/MM/YYYY'), // UK / France / Spain / Italy / Australia / NZ
'd-m-Y' => _('DD-MM-YYYY'), // Netherlands / Denmark / Belgium
'd M Y' => _('DD Mon YYYY'), // nautical documents / logbooks / unambiguous
'm.d.Y' => _('MM.DD.YYYY'), // USA
'm/d/Y' => _('MM/DD/YYYY'), // USA
'Y/m/d' => _('YYYY/MM/DD') // Japan / China
);
$user = User::GetInstance(); // There can be only one $user = User::GetInstance(); // There can be only one
if ($g_scriptname != 'login.php') { if ($g_scriptname != 'login.php') {
@@ -137,6 +200,7 @@ $g_opt_all = array(-2 => _('&horbar; all &horbar;'));
$g_opt_none = array(-1 => _('&horbar; none &horbar;')); $g_opt_none = array(-1 => _('&horbar; none &horbar;'));
$g_opt_empty = array('' => _('&horbar; none &horbar;')); $g_opt_empty = array('' => _('&horbar; none &horbar;'));
$g_opt_unknown = array(-1 => _('&horbar; unknown &horbar;')); $g_opt_unknown = array(-1 => _('&horbar; unknown &horbar;'));
$g_opt_new = array(-3 => _('&horbar; new &horbar;'));
// Initialize message system // Initialize message system
$g_message = new Message; $g_message = new Message;
@@ -243,6 +307,7 @@ class User {
public $datefmt; public $datefmt;
public $rows_pp; public $rows_pp;
public $menu; public $menu;
public $language;
private function __construct() { private function __construct() {
global $g_rows_pp; global $g_rows_pp;
@@ -254,6 +319,7 @@ class User {
$this->datefmt = 'Y-m-d'; $this->datefmt = 'Y-m-d';
$this->rows_pp = $g_rows_pp; $this->rows_pp = $g_rows_pp;
$this->menu = [1, 2, 3, 4, 5, 6]; $this->menu = [1, 2, 3, 4, 5, 6];
$this->language = 'en';
} }
public static function getInstance() { public static function getInstance() {
@@ -316,13 +382,14 @@ class User {
} }
$this->id = $_SESSION['userid']; $this->id = $_SESSION['userid'];
$sql = "SELECT displayname, role FROM user WHERE userid=?"; $sql = "SELECT displayname, role, language FROM user WHERE userid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([$this->id]); $sth->execute([$this->id]);
$row = $sth->fetch(); $row = $sth->fetch();
if ($row) { if ($row) {
$this->displayname = $row['displayname']; $this->displayname = $row['displayname'];
$this->role = $row['role']; $this->role = $row['role'];
$this->language = $row['language'];
} }
} }
@@ -397,182 +464,7 @@ function get_userlist() {
// ========== DATABASE FUNCTIONS ============================================== // ========== DATABASE FUNCTIONS ==============================================
function db_exec_insert($table, $params) { // TODO transfer to lib/db.inc
// $params must have keys corresponding to table fields prefixed with ':'
// e.g. $param[':field']
global $pdo;
global $g_error;
$keys = array_keys($params);
$fields = join(', ', array_map(function($s) { return ltrim($s, ':'); }, $keys));
$pnames = join(', ', $keys);
$sql = "INSERT INTO $table ($fields) VALUES ($pnames)";
// $sth = $pdo->prepare("INSERT INTO $table ($fields) VALUES ($pnames)");
$sth = $pdo->prepare($sql);
try {
$sth->execute($params);
} catch (PDOexception $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
$g_error->Add($sql);
$g_error->Add(print_r($params, true));
return false;
}
return $pdo->LastInsertId();
}
function db_exec_update($table, $params, $pk) {
// primary key can be a single field name or multiple fields: $pk is an array
global $pdo;
global $g_error;
// remove primary key fields from list of fields to update
if (is_array($pk)) {
if (count($pk) == 1) {
$pk = $pk[0];
$fields = $params;
unset($fields[':'.$pk]);
$where = "$pk=:$pk";
} else {
$pkparams = array_map(fn($value) => ':' . $value, $pk);
$fields = array_diff_key($params, array_flip($pkparams));
$where = join(' AND ', array_map(fn($s) => "$s=:$s", $pk));
}
} else {
$fields = $params;
unset($fields[':'.$pk]);
$where = "$pk=:$pk";
}
$fieldlist = join(', ', array_map(fn($s) => ltrim($s, ':') . '=' . $s, array_keys($fields)));
$sql = "UPDATE $table SET $fieldlist WHERE $where";
$sth = $pdo->prepare($sql);
try {
$sth->execute($params);
} catch (PDOexception $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
$g_error->Add($sql);
$g_error->Add(print_r($params, true));
return false;
}
return true;
}
function db_exec_delete($table, $condition, $params) {
// WIP untested!
// condition contains the where part of the sql statement
// params are values for placeholders in condition
// returns the number of deleted records
global $pdo;
global $g_error;
// convert params to array if single value is given
if (!is_array($params)) {
$params = [$params];
}
$sql = "DELETE FROM $table";
if (!empty($condition)) {
$sql .= ' WHERE ' . $condition;
}
$sth = $pdo->prepare($sql);
try {
$sth->execute($params);
} catch (PDOexception $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
$g_error->Add($sql);
$g_error->Add(print_r($params, true));
return -1;
}
return $sth->rowCount();
}
function db_clear_filter($sno) {
global $user;
global $pdo;
$sql = "DELETE FROM settings WHERE userid=? AND sno=?";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$user->id, $sno]);
} catch (PDOexception $e) {
$g_warning->Add('SQL-Error: '. $e->getMessage());
$g_warning->Add($sql);
$g_warning->Add('Setting: ', $sno);
return false;
}
return true;
}
function db_save_filter($flt, $sno) {
global $user;
global $pdo;
global $g_warning;
$sql = "UPDATE settings SET valstr=? WHERE userid=? AND sno=?";
$sth = $pdo->prepare($sql);
try {
$sth->execute([json_encode($flt), $user->id, $sno]);
} catch (PDOexception $e) {
$g_warning->Add('SQL-Error: '. $e->getMessage());
$g_warning->Add($sql);
$g_warning->Add(print_r($flt, true));
$g_warning->Add('Setting: ', $sno);
return false;
}
return true;
}
function get_enum($enum) {
// translate and beautify enums
$lookup = array(
'NULL' => _('n/a'),
'active' => _('Active'),
'bad' => _('Bad'),
'box' => _('Box'),
'cable' => _('Cable'),
'cat' => _('Catamaran'),
'completed' => _('Completed'),
'closed' => _('Closed'),
'company' => _('Company'),
'defect' => _('Defect'),
'deleted' => _('Deleted'),
'done' => _('Done'),
'drawing' => _('Drawing'),
'equipment' => _('Equipment'),
'estimated' => _('Estimated'),
'excellent' => _('Excellent'),
'fair' => _('Fair'),
'finished' => _('Finished'),
'fixed' => _('Fixed'),
'fuse' => _('Fuse'),
'generic' => _('Generic'),
'good' => _('Good'),
'high' => _('High'),
'historic' => _('Historic'),
'invoice' => _('Invoice'),
'locked' => _('Locked'),
'low' => _('Low'),
'manual' => _('Manual'),
'medium' => _('Medium'),
'mono' => _('Monohull'),
'new' => _('New'),
'none' => _('None'),
'normal' => _('Normal'),
'ongoing' => _('Ongoing'),
'open' => _('Open'),
'ordered' => _('Ordered'),
'paused' => _('Paused'),
'pending' => _('Pending'),
'picture' => _('Picture'),
'planned' => _('Planned'),
'precise' => _('Precise'),
'project' => _('Project'),
'removed' => _('Removed'),
'repairable' => _('Repairable'),
'rough' => _('Rough'),
'storage' => _('Storage'),
'task' => _('Task'),
'tri' => _('Trimaran'),
'unknown' => _('Unknown'),
'user' => _('User'),
'vessel' => _('Vessel'),
'waiting' => _('waiting')
);
return $lookup[$enum] ?? $enum;
}
function db_load_enum($table, $column, $lookup=false, $as_dict=false, $check_null=false) { function db_load_enum($table, $column, $lookup=false, $as_dict=false, $check_null=false) {
// returns array of enum-values as defined in database // returns array of enum-values as defined in database
@@ -742,229 +634,6 @@ function db_get_tag_target($objtype, $objid) {
return [$target, $desc]; return [$target, $desc];
} }
function db_get_ddtext($ddid, $ddval) {
// returns single value for dropdown
global $pdo;
global $g_error;
$sql = "SELECT ddtext FROM dropdown WHERE ddid=? AND ddval=?";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$ddid, $ddval]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
return '#err';
}
return $sth->fetchColumn();
}
// Functions to get option lists (key/value)
function db_get_options($ddid, $orderby = '', $short = False, $default = NULL) {
// returns list for dropdown
// if short is set the short value will be returned
global $pdo;
$list = array();
if ($default != NULL) {
$list[0] = $default;
}
if ($short) {
$sql = "SELECT ddval, ddshort";
} else {
$sql = "SELECT ddval, ddtext";
}
$sql .= " FROM dropdown WHERE ddid=?";
if ($orderby == 'ddtext') {
$sql .= ' ORDER BY ddtext';
} elseif ($orderby == 'sort') {
$sql .= ' ORDER BY sort';
} else {
$sql .= ' ORDER BY ddval';
}
$sth = $pdo->prepare($sql);
$sth->execute([$ddid]);
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
$list[$rec[0]] = $rec[1];
}
return $list;
}
function db_get_opt_vessel() {
global $pdo;
$list = array();
$sth = $pdo->query("SELECT vid, vesselname, model FROM vessel ORDER BY vid");
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$list[$rec[0]] = $rec[1];
}
return $list;
}
function db_get_opt_storage($vid) {
global $pdo;
global $g_error;
$list = array();
// exclude storage type "tank" from list
$sql = "SELECT sid, sname FROM storage WHERE vid=? AND stype<>1 ORDER BY sname";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$vid]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
}
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
$list[$rec[0]] = $rec[1];
}
return $list;
}
function db_get_opt_box($vid, $exclude=[]) {
global $pdo;
global $g_error;
$list = array();
$sql = "SELECT boxid, label, content "
. "FROM box INNER JOIN storage USING (sid) "
. "WHERE vid=? "
. "ORDER BY label";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$vid]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
}
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
if (! in_array($rec[0], $exclude)) {
$list[$rec[0]] = $rec[1] . ($rec[2] ? ' - '. $rec[2] : '');
}
}
return $list;
}
function db_get_opt_equip($vid, $default=NULL, $exclude=[]) {
global $pdo;
global $g_error;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT eid, ename FROM equipment WHERE vid=? ORDER BY ename";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$vid]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
}
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
if (! in_array($rec[0], $exclude)) {
$list[$rec[0]] = $rec[1];
}
}
return $list;
}
function db_get_opt_manuf($default=NULL) {
global $pdo;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT compid, compname FROM company WHERE comptype=2 ORDER BY compname";
$sth = $pdo->query($sql);
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$list[$row[0]] = $row[1];
}
return $list;
}
function db_get_opt_supp($default=NULL) {
global $pdo;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT compid, compname FROM company WHERE comptype=1 ORDER BY compname";
$sth = $pdo->query($sql);
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$list[$row[0]] = $row[1];
}
return $list;
}
function db_get_opt_user($userid, $default=NULL) {
global $pdo;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT userid, displayname FROM user WHERE userid>0 ORDER BY displayname";
$sth = $pdo->query($sql);
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$list[$row[0]] = $row[1];
}
return $list;
}
function db_get_opt_proj($vid, $exclude=[], $default=NULL) {
// exclude is a list of project states
global $pdo;
global $g_error;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT projid, projname FROM project WHERE vid=?";
$where = [];
foreach ($exclude as $excl) {
$where[] = "NOT FIND_IN_SET('$excl',projstate)";
}
if (! empty($where)) {
$sql .= ' AND '. implode(' AND ', $where);
}
$sql .= " ORDER BY projname";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$vid]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
}
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
$list[$rec[0]] = $rec[1];
}
return $list;
}
function db_get_filter($user, $sno, $fields = []) {
// if fields supplied empting missing field are created
global $pdo;
global $g_warning;
$flt = new stdClass();
$sth = $pdo->prepare("SELECT valstr FROM settings WHERE userid=? AND sno=?");
try {
$sth->execute([$user, $sno]);
$json = $sth->fetchColumn();
if ($json === false) {
// no settings record. create empty one for later updates
$sth = $pdo->prepare("INSERT INTO settings (userid, sno, valstr) VALUES (?, ?, '{}')");
$sth->execute([$user, $sno]);
} else {
$flt = json_decode($json);
}
// create missing fields
foreach ($fields as $f) {
if (!property_exists($flt, $f)) {
$flt->$f = null;
}
}
} catch (PDOexception $e) {
$g_warning->Add('SQL-Error: '. $e->getMessage());
$g_warning->PrintOut();
}
return $flt;
}
function db_get_default_storage($vesselid, $fallback=true) { function db_get_default_storage($vesselid, $fallback=true) {
global $pdo; global $pdo;
global $g_error, $g_warning; global $g_error, $g_warning;
@@ -1023,194 +692,6 @@ function float_to_sql($var) {
} }
} }
// ========== FORM FUNCTIONS ==================================================
function form_get_action() {
if (!isset($_POST['submit'])) {
if (isset($_GET['f'])) {
$submit = $_GET['f'];
// strip parameters
/* $pos = strpos($submit, '?');
if ($pos > 2) {
$submit = substr($submit, 0, $pos);
} */
} else {
$submit = NULL;
}
} else {
$submit = $_POST['submit'];
}
if (is_array($submit)) {
$submit = key($submit);
}
return strtolower($submit);
}
function form_create_input($fieldname, $label, $value) {
// TODO WIP
echo '<div class="mb-3">', "\n";
echo "</div>\n";
}
function form_create_text($fieldname, $label, $value) {
// TODO WIP
echo '<div class="mb-3">', "\n";
echo "</div>\n";
}
function form_create_check($fieldname, $label, $checked) {
// create single checkbox with assigned label
echo '<div class="mb-3">', "\n";
echo '<input type="checkbox" class="form-check-input" name="', $fieldname, '" id="', $fieldname, '"';
if ($checked) {
echo ' checked';
}
echo ">\n";
echo '<label for="', $fieldname, '">', $label, "</label>\n";
echo "</div>\n";
}
function form_create_select($fieldname, $label, $optlist, $selval=NULL, $multiple=FALSE) {
echo '<div class="mb-3">', "\n";
echo '<label for="', $fieldname, '">', $label, "</label>\n";
echo '<select class="form-select" name="', $fieldname,'" id="', $fieldname, $multiple ? ' multiple' : '', '">', "\n";
foreach ($optlist as $k => $v) {
echo '<option value="', $k, '"';
if (isset($selval) and ($k == $selval)) {
echo ' selected';
}
echo '>', $v, "</option>\n";
}
echo "</select>\n";
echo "</div>\n";
}
function form_create_checks($fieldname, $label, $optlist, $selected = []) {
// create multiple combined checkboxes with title
echo '<fieldset class="mb-3">';
echo '<legend class="fs-6 mb-1 border-bottom pb-1">', $label, "</legend>\n";
echo '<div class="d-flex flex-wrap gap-3">';
foreach ($optlist as $k => $v) {
echo '<div class="form-check">';
$checked = in_array($k, $selected, true) ? ' checked' : '';
echo '<label class="form-check-label">';
echo '<input type="checkbox" class="form-check-input" name="', $fieldname, '[', $k, ']"', $checked, '>';
echo $v;
echo '</label>';
echo '</div>';
}
echo '</div>';
echo '</fieldset>';
}
// TODO DEPRECATED for touch multiple adjacent buttuns are not well suited.
function form_action_buttons($script, $id) {
echo "<td>";
echo '<a title="', _('View'), '" href="', $script, '?f=view&id=', $id, '"><i class="bi-eye"></i></a>', "\n";
echo '<a title="', _('Edit'), '" href="', $script, '?f=edit&id=', $id, '"><i class="bi-pencil"></i></a>', "\n";
echo "</td>\n";
}
function form_add_button($script, $id=NULL, $idname='id') {
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<a href="', $script, '?f=add';
if (isset($id)) {
echo '&'.$idname.'='.$id;
}
echo '" class="btn btn-primary" role="button">', _('Add'), "</a>\n";
echo "</div>\n";
}
function form_view_buttons($script, $id, $backlink=NULL) {
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<a href="', $script, '?f=edit&id=', $id, '" class="btn btn-primary" role="button">', _('Edit'), "</a>\n";
echo '&nbsp;';
echo '<a href="', $script, '?f=del&id=', $id, '" class="btn btn-secondary" role="button">', _('Delete'), "</a>\n";
echo '&nbsp;';
echo '<a href="', $backlink ?? $script, '" class="btn btn-secondary">', _('Back'), "</a>\n";
echo "</div>\n";
}
function form_new_buttons($script) {
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<button type="submit" name="submit[insert]" class="btn btn-primary">', _('Save'), "</button>\n";
echo '<a href="', $script, '" class="btn btn-secondary">', _('Back'), "</a>\n";
echo "</div>\n";
}
function form_edit_buttons($script, $id) {
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<button type="submit" name="submit[update]" class="btn btn-primary">', _('Save'), "</button>\n";
echo '<a href="', $script, '?f=view&id=', $id, '" class="btn btn-secondary">', _('Back'), "</a>\n";
echo "</div>\n";
}
function form_delete_buttons($script, $id, $token) {
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<form method="post" action="', $script, '">', "\n";
echo '<input type="hidden" name="id" value="', $id .'">', "\n";
echo '<input type="hidden" name="token" value="', $token, '">', "\n";
echo '<button type="submit" name="submit[delete]" class="btn btn-primary">', _('Delete'), "</button>\n";
echo '<a href="', $script, '?f=view&id=', $id, '" class="btn btn-secondary">', _('Back'), "</a>\n";
echo "</form>\n";
echo "</div>\n";
}
function form_tag_assignment($script, $id, $tags) {
echo '<tr>';
echo '<th>', _('Tags'), "</th>\n";
echo '<td>', $tags, '</td>';
echo "</tr>\n<tr>";
echo '<th>', _('Tag assignment'), "</th>\n";
echo '<td><form method="post" action="', $script, '">', "\n";
echo '<div class="form-floating">';
echo '<input type="hidden" name="id" value="', $id .'">', "\n";
echo '<label>', _('(Separate by comma)'), '</label>', "\n";
echo '<input type="text" maxlength="80" class="form-control" name="tagstring" value="', $tags, '">', "\n";
echo '<input type="submit">', "\n";
echo "</div></form></td></td>\n";
echo "</tr>";
}
function filter_create_select($fieldname, $label, $optlist, $selval=NULL, $multiple=FALSE) {
// - Wenn multiple gesetzt ist, muß selval ein array sein
// ansonsten ein einfacher String
/* if ($multiple) {
if (!is_array($selval)) {
}
} */
echo '<div class="d-flex flex-nowrap gap-2">', "\n";
echo '<label for="', $fieldname,'">', $label,'</label>', "\n";
echo '<select class="form-select" id="', $fieldname, '" name="', $fieldname, '"', $multiple ? ' multiple' : '', ">\n";
foreach ($optlist as $k => $v) {
echo '<option value="', $k, '"';
if ($k == $selval) {
echo ' selected';
}
echo '>', $v, '</option>', "\n";
}
echo "</select>\n";
echo "</div>";
}
function filter_create_checks($fieldname, $label, $optlist, $selected = []) {
// TODO WIP
echo '<fieldset class="mb-3">';
echo '<legend class="fs-6 mb-1 border-bottom pb-1">', $label, "</legend>\n";
echo '<div class="d-flex flex-wrap gap-3">';
foreach ($optlist as $k => $v) {
echo '<div class="form-check">';
$checked = in_array($k, $selected, true) ? ' checked' : '';
echo '<label class="form-check-label">';
echo '<input type="checkbox" class="form-check-input" name="', $fieldname, '[', $k, ']"', $checked, '>';
echo $v;
echo '</label>';
echo '</div>';
}
echo '</div>';
echo '</fieldset>';
}
// ========== FORMAT FUNCTIONS ================================================ // ========== FORMAT FUNCTIONS ================================================
function format_float($val, $decimals = 2, $suffix = '') { function format_float($val, $decimals = 2, $suffix = '') {
@@ -1233,7 +714,37 @@ function format_currency($val) {
} }
} }
function format_date($date) {
// date is string in ISO format
global $user;
if (empty($date)) {
return '';
}
$timestamp = strtotime($date);
if ($timestamp === false) {
return '';
}
return date($user->datefmt, $timestamp);
}
function format_datetime($datetime, $seconds=false) {
// datetime is string in ISO format
global $user;
if (empty($datetime)) {
return '';
}
$timestamp = strtotime($datetime);
if ($timestamp === false) {
return '';
}
$timefmt = $seconds ? 'H:i:s' : 'H:i';
return date($user->datefmt. ' ' . $timefmt, $timestamp);
}
function format_color($color) { function format_color($color) {
if (empty($color)) {
return '';
}
$colstr = '<span style="'; $colstr = '<span style="';
$style = "padding:2px 4px;border-radius:4px;background-color:#".$color; $style = "padding:2px 4px;border-radius:4px;background-color:#".$color;
if (get_color_brightness($color) < 0.4) { if (get_color_brightness($color) < 0.4) {
@@ -1296,6 +807,16 @@ function format_measurement($n, $unit, $v1, $v2, $v3) {
// ========== COMMON FUNCTIONS ================================================ // ========== COMMON FUNCTIONS ================================================
function h($value, $br=false) {
// escape value coming from db for safe html output
// optional convert line breaks to <br> tags
if (!isset($value)) {
return '';
}
$value = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
return $br ? nl2br($value) : $value;
}
function header_location($location, $message=NULL) { function header_location($location, $message=NULL) {
if (is_array($message)) { if (is_array($message)) {
$valid_keys = array('succ', 'info', 'warn', 'err'); $valid_keys = array('succ', 'info', 'warn', 'err');
@@ -1309,6 +830,30 @@ function header_location($location, $message=NULL) {
exit; exit;
} }
function get_browser_lang($allowed, $default='en') {
$h = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
if (!$h) {
return $def;
}
$langs = [];
foreach (explode(',', $h) as $p) {
$p = explode(';q=', trim($p));
$l = strtolower($p[0]);
$q = isset($p[1]) ? (float) $p[1] : 1.0;
$langs[$l] = $q;
}
arsort($langs);
foreach ($langs as $bl => $q) {
foreach ($allowed as $l) {
$l = strtolower($l);
if ($bl === $l || str_starts_with($bl, $l . '-')) {
return $l;
}
}
}
return $default;
}
function pgettext($context, $msgid) { function pgettext($context, $msgid) {
// implement missing function // implement missing function
global $g_textdomain; global $g_textdomain;
@@ -1321,6 +866,71 @@ function pgettext($context, $msgid) {
} }
} }
function get_enum($enum) {
// translate and beautify enums
$lookup = array(
'NULL' => _('n/a'),
'active' => _('Active'),
'bad' => _('Bad'),
'box' => _('Box'),
'cable' => _('Cable'),
'cat' => _('Catamaran'),
'completed' => _('Completed'),
'closed' => _('Closed'),
'company' => _('Company'),
'day' => _('Day'),
'defect' => _('Defect'),
'deleted' => _('Deleted'),
'done' => _('Done'),
'drawing' => _('Drawing'),
'equipment' => _('Equipment'),
'estimated' => _('Estimated'),
'excellent' => _('Excellent'),
'fair' => _('Fair'),
'finished' => _('Finished'),
'fixed' => _('Fixed'),
'fuse' => _('Fuse'),
'generic' => _('Generic'),
'good' => _('Good'),
'high' => _('High'),
'historic' => _('Historic'),
'invoice' => _('Invoice'),
'locked' => _('Locked'),
'low' => _('Low'),
'manual' => _('Manual'),
'medium' => _('Medium'),
'missed' => _('Missed'),
'mono' => _('Monohull'),
'month' => _('Month'),
'new' => _('New'),
'none' => _('None'),
'normal' => _('Normal'),
'ongoing' => _('Ongoing'),
'open' => _('Open'),
'ordered' => _('Ordered'),
'paused' => _('Paused'),
'pending' => _('Pending'),
'picture' => _('Picture'),
'plan' => _('Planned'),
'precise' => _('Precise'),
'project' => _('Project'),
'quarter' => _('Quarter'),
'removed' => _('Removed'),
'repairable' => _('Repairable'),
'rough' => _('Rough'),
'skipped' => _('Skipped'),
'storage' => _('Storage'),
'task' => _('Task'),
'tri' => _('Trimaran'),
'unknown' => _('Unknown'),
'user' => _('User'),
'vessel' => _('Vessel'),
'waiting' => _('Waiting'),
'week' => _('Week'),
);
return $lookup[$enum] ?? $enum;
}
function get_color_brightness($color, $default=0.5) { function get_color_brightness($color, $default=0.5) {
// returns a value between 0 and 1 // returns a value between 0 and 1
// color is a 6 char hex string // color is a 6 char hex string
+77 -21
View File
@@ -7,11 +7,16 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
require 'lib/svg.inc'; require 'lib/svg.inc';
$pagetitle = _('Start'); $pagetitle = _('Start');
$opt_htype = db_load_enum('vessel', 'htype', true, true);
$opt_vtype = db_get_options(DD_VESSEL_TYPE);
// ========== ACTIONS START =================================================== // ========== ACTIONS START ===================================================
switch ($submit = form_get_action()) { switch ($submit = form_get_action()) {
@@ -45,6 +50,7 @@ switch ($submit = form_get_action()) {
$p[':model'] = gpc_get_string($_POST, 'model'); $p[':model'] = gpc_get_string($_POST, 'model');
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150); $p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
$id = db_exec_insert('vessel', $p); $id = db_exec_insert('vessel', $p);
db_set_revision('table', TBL_VESSEL);
// autoselect newly created vessel // autoselect newly created vessel
$sql = "UPDATE settings SET valint=? WHERE userid=? AND sno=1"; $sql = "UPDATE settings SET valint=? WHERE userid=? AND sno=1";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -63,9 +69,10 @@ switch ($submit = form_get_action()) {
break; break;
} }
$p[':vid'] = gpc_get_int($_POST, 'id'); $p[':vid'] = gpc_get_int($_POST, 'id');
// $p[':vtype'] = gpc_get_string($_POST, 'vtype'); $p[':htype'] = gpc_get_enum($_POST, 'htype', $opt_htype, 'mono');
$p[':vesselname'] = gpc_get_string($_POST, 'vesselname'); $p[':vtype'] = gpc_get_int($_POST, 'vtype', NULL, -1);
$p[':model'] = gpc_get_string($_POST, 'model'); $p[':vesselname'] = gpc_get_string($_POST, 'vesselname', 40);
$p[':model'] = gpc_get_string($_POST, 'model', 20);
$p[':loa'] = gpc_get_float($_POST, 'loa'); $p[':loa'] = gpc_get_float($_POST, 'loa');
$p[':lwl'] = gpc_get_float($_POST, 'lwl'); $p[':lwl'] = gpc_get_float($_POST, 'lwl');
$p[':beam'] = gpc_get_float($_POST, 'beam'); $p[':beam'] = gpc_get_float($_POST, 'beam');
@@ -75,11 +82,10 @@ switch ($submit = form_get_action()) {
$p[':ballast'] = gpc_get_int($_POST, 'ballast'); $p[':ballast'] = gpc_get_int($_POST, 'ballast');
$p[':beltpos_aft'] = gpc_get_float($_POST, 'beltpos_aft'); $p[':beltpos_aft'] = gpc_get_float($_POST, 'beltpos_aft');
$p[':beltpos_bow'] = gpc_get_float($_POST, 'beltpos_bow'); $p[':beltpos_bow'] = gpc_get_float($_POST, 'beltpos_bow');
$p[':shapefile'] = gpc_get_string($_POST, 'shapefile'); $p[':shapefile'] = gpc_get_string($_POST, 'shapefile', 40, NULL, '-1');
if ($p[':shapefile'] == '-1') { $p[':shipyard'] = gpc_get_int($_POST, 'shipyard', NULL, -1);
$p[':shapefile'] = NULL; $p[':year_built'] = gpc_get_int($_POST, 'year_built');
} $p[':hull_number'] = gpc_get_string($_POST, 'hull_number', 20);
$p[':shipyard'] = gpc_get_int($_POST, 'shipyard');
$p[':sid_default'] = gpc_get_uint($_POST, 'sid'); $p[':sid_default'] = gpc_get_uint($_POST, 'sid');
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150); $p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
db_exec_update('vessel', $p, 'vid'); db_exec_update('vessel', $p, 'vid');
@@ -115,7 +121,7 @@ $vid = ($res[0]);
// Get current vessel data // Get current vessel data
$sql = "SELECT vesselname, model, loa, lwl, beam, draught, draught_min," $sql = "SELECT vesselname, model, loa, lwl, beam, draught, draught_min,"
. " displacement, ballast, beltpos_aft, beltpos_bow, shapefile," . " displacement, ballast, beltpos_aft, beltpos_bow, shapefile,"
. " shipyard, remarks " . " shipyard, year_built, remarks "
. "FROM vessel " . "FROM vessel "
. "WHERE vid=?"; . "WHERE vid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -161,17 +167,21 @@ echo '<div class="col-1"></div>', "\n";
echo '<div class="col">'; echo '<div class="col">';
if ($vessel->shipyard && $vessel->shipyard > 0) { if ($vessel->shipyard && $vessel->shipyard > 0) {
if ($vessel->shipyard == -3) { if ($vessel->shipyard == -3) {
echo _('Custom-build'); echo sprintf(_('Custom-build %d'), ($vessel->year_built ?? ''));
} else { } else {
$sql = "SELECT compname FROM company WHERE compid=?"; $sql = "SELECT compname FROM company WHERE compid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([$vessel->shipyard]); $sth->execute([$vessel->shipyard]);
echo sprintf(_('Built by %s'), $sth->fetchColumn()); echo sprintf(_('Built %d by %s'), ($vessel->year_built ?? ''), $sth->fetchColumn());
// TODO year of build? }
} else {
if ($vessel->year_built && $vessel->year_built >= 1901) {
echo sprintf(_('Year built %d'), $vessel->year_built);
} }
} }
if (strlen($vessel->remarks) > 0) { if (strlen($vessel->remarks) > 0) {
echo nl2br($vessel->remarks); echo ' ', h($vessel->remarks, br:true);
} }
echo "</div>\n"; echo "</div>\n";
echo "</div>\n"; // row 2 echo "</div>\n"; // row 2
@@ -310,7 +320,13 @@ echo substr($xml, strpos($xml, "\n") + 1);
<tr><td><?=_('Lwl')?></td><td><?=format_float($vessel->lwl, 2, 'm')?></td></tr> <tr><td><?=_('Lwl')?></td><td><?=format_float($vessel->lwl, 2, 'm')?></td></tr>
<tr><td><?=_('Beam')?></td><td><?=format_float($vessel->beam, 2, 'm')?></td></tr> <tr><td><?=_('Beam')?></td><td><?=format_float($vessel->beam, 2, 'm')?></td></tr>
<tr><td><?=_('Draught')?></td><td><?=format_float($vessel->draught, 2, 'm')?></td></tr> <tr><td><?=_('Draught')?></td><td><?=format_float($vessel->draught, 2, 'm')?></td></tr>
<tr><td><?=_('Draught, min.')?></td><td><?=format_float($vessel->draught_min, 2, 'm')?></td></tr> <?php
if ($vessel->draught_min) {
echo '<tr><td>', _('Draught, min.'), '</td><td>';
format_float($vessel->draught_min, 2, 'm');
echo "</td></tr>\n";
}
?>
<tr><td><?=_('Displacement')?></td><td><?=$vessel->displacement?>&thinsp;kg</td></tr> <tr><td><?=_('Displacement')?></td><td><?=$vessel->displacement?>&thinsp;kg</td></tr>
<tr><td><?=_('Ballast')?></td><td><?=$vessel->ballast?>&thinsp;kg</td></tr> <tr><td><?=_('Ballast')?></td><td><?=$vessel->ballast?>&thinsp;kg</td></tr>
<tr><td><?=_('Belt position aft')?></td><td><?=format_float($vessel->beltpos_aft, 2, 'm')?></td></tr> <tr><td><?=_('Belt position aft')?></td><td><?=format_float($vessel->beltpos_aft, 2, 'm')?></td></tr>
@@ -336,7 +352,7 @@ if ($user->role == 'captain') {
// Storage: 0 - default, 1 - tank // Storage: 0 - default, 1 - tank
// $stype = [ 0 => _('Default'), 1 => _('Tank')]; // $stype = [ 0 => _('Default'), 1 => _('Tank')];
$stype = db_get_options(3); $stype = db_get_options(DD_STORAGE_TYPE);
$sql = "SELECT stype, COUNT(stype) " $sql = "SELECT stype, COUNT(stype) "
. "FROM storage " . "FROM storage "
. "WHERE vid=? " . "WHERE vid=? "
@@ -360,6 +376,8 @@ echo '<tr><td>&nbsp;</td><td>', _('Boxes'), '</td><td>', $sth->fetchColumn(), "<
$sth = $pdo->prepare("SELECT COUNT(*), SUM(weight) FROM equipment WHERE vid=?"); $sth = $pdo->prepare("SELECT COUNT(*), SUM(weight) FROM equipment WHERE vid=?");
$sth->execute([$user->vid]); $sth->execute([$user->vid]);
$row = $sth->fetch(PDO::FETCH_NUM); $row = $sth->fetch(PDO::FETCH_NUM);
$weight_equip = $row[1];
echo '<tr><td colspan="3">', _('Equipment') , "</td>"; echo '<tr><td colspan="3">', _('Equipment') , "</td>";
echo '<tr><td>&nbsp;</td><td>', _('Count'), '</td><td>', $row[0], "</td></tr>\n"; echo '<tr><td>&nbsp;</td><td>', _('Count'), '</td><td>', $row[0], "</td></tr>\n";
echo '<tr><td>&nbsp;</td><td>', _('Weight'), '</td><td>', format_float($row[1], 1, 'kg'), "</td></tr>\n"; echo '<tr><td>&nbsp;</td><td>', _('Weight'), '</td><td>', format_float($row[1], 1, 'kg'), "</td></tr>\n";
@@ -375,16 +393,41 @@ $sth = $pdo->prepare($sql);
$sth->bindValue(':vid', $user->vid, PDO::PARAM_INT); $sth->bindValue(':vid', $user->vid, PDO::PARAM_INT);
$sth->execute(); $sth->execute();
$row = $sth->fetch(PDO::FETCH_NUM); $row = $sth->fetch(PDO::FETCH_NUM);
$weight_inv = $row[1];
echo '<tr><td colspan="3">', _('Inventory') , "</td>"; echo '<tr><td colspan="3">', _('Inventory') , "</td>";
echo '<tr><td>&nbsp;</td><td>', _('Count'), '</td><td>', $row[0], "</td></tr>\n"; echo '<tr><td>&nbsp;</td><td>', _('Count'), '</td><td>', $row[0], "</td></tr>\n";
echo '<tr><td>&nbsp;</td><td>', _('Weight'), '</td><td>', format_float($row[1], 1, 'kg'), "</td></tr>\n"; echo '<tr><td>&nbsp;</td><td>', _('Weight'), '</td><td>', format_float($row[1], 1, 'kg'), "</td></tr>\n";
// Provisions
/*$sql = "SELECT SUM(n), SUM(w) FROM ("
. "SELECT COUNT(*) AS n, SUM(p.weight * p.number) as w FROM provisions AS p JOIN storage USING (sid) WHERE conttype='storage' AND vid=:vid "
. "UNION "
. "SELECT COUNT(*) AS n, SUM(p.weight * p.number) as w FROM provisions AS p JOIN box USING (boxid) JOIN storage ON (box.sid=storage.sid) WHERE conttype='box' AND vid=:vid"
. ") AS x"; */
// only storage assignment at the moment
$sql = "SELECT SUM(n), SUM(w) FROM ("
. "SELECT COUNT(*) AS n, SUM(p.weight * p.number) as w FROM provisions AS p JOIN storage USING (sid) WHERE storage.vid=:vid "
. ") AS x";
$sth = $pdo->prepare($sql);
$sth->bindValue(':vid', $user->vid, PDO::PARAM_INT);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_NUM);
$weight_prov = $row[1];
echo '<tr><td colspan="3">', _('Provisions') , "</td>";
echo '<tr><td>&nbsp;</td><td>', _('Count'), '</td><td>', $row[0], "</td></tr>\n";
echo '<tr><td>&nbsp;</td><td>', _('Weight'), '</td><td>', format_float($row[1], 1, 'kg'), "</td></tr>\n";
// Documents // Documents
$sth = $pdo->query("SELECT COUNT(*) FROM document"); $sth = $pdo->query("SELECT COUNT(*) FROM document");
echo '<tr><td colspan="3">', _('Documents') , "</td>"; echo '<tr><td colspan="3">', _('Documents') , "</td>";
echo '<tr><td>&nbsp;</td><td>', _('Count'), '</td><td>', $sth->fetchColumn(), "</td></tr>\n"; echo '<tr><td>&nbsp;</td><td>', _('Count'), '</td><td>', $sth->fetchColumn(), "</td></tr>\n";
$weight_total = $weight_equip + $weight_inv + $weight_prov;
echo '<tr><td colspan="2">', _('Total weight'), '</td>';
echo '<td>', format_float($weight_total, 1, 'kg'), "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
@@ -447,7 +490,7 @@ echo '<h2>', _('Add additional yacht'), "</h2>\n";
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label> <label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$project->remarks ?></textarea> <textarea class="form-control" id="remarks" name="remarks" rows="3"></textarea>
</div> </div>
<div class="container-fluid px-0 my-3"> <div class="container-fluid px-0 my-3">
<button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button> <button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button>
@@ -478,7 +521,7 @@ if (!file_exists($shapeindexfile)) {
} }
} }
} }
$opt_shapefiles = $g_opt_none + $shapeindex; $opt_shapefiles = $g_opt_none + ($shapeindex ?? []);
$opt_storage = db_get_opt_storage($user->vid); $opt_storage = db_get_opt_storage($user->vid);
@@ -489,9 +532,9 @@ foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$opt_shipyard[$row[0]] = $row[1]; $opt_shipyard[$row[0]] = $row[1];
} }
$sql = "SELECT vesselname, vtype, model, loa, lwl, beam, draught, draught_min," $sql = "SELECT vesselname, vtype, htype, model, loa, lwl, beam, draught, draught_min,"
. " displacement, ballast, beltpos_aft, beltpos_bow, shapefile," . " displacement, ballast, beltpos_aft, beltpos_bow, shapefile,"
. " shipyard, sid_default, remarks " . " shipyard, year_built, hull_number, sid_default, remarks "
. "FROM vessel " . "FROM vessel "
. "WHERE vid=?"; . "WHERE vid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -509,6 +552,13 @@ $vessel = $sth->fetch(PDO::FETCH_OBJ);
<label for="model" class="form-label"><?=_('Model')?></label> <label for="model" class="form-label"><?=_('Model')?></label>
<input type="text" class="form-control" id="model" name="model" value="<?=$vessel->model ?>"> <input type="text" class="form-control" id="model" name="model" value="<?=$vessel->model ?>">
</div> </div>
<?php
form_create_select('vtype', _('Vessel type'), $g_opt_unknown + $opt_vtype, $vessel->vtype);
?>
<div class="mb-3">
<label for="year_built" class="form-label"><?=_('Year built')?></label>
<input type="number" class="form-control" id="year_built" name="year_built" value="<?=$vessel->year_built ?>">
</div>
<div class="mb-3"> <div class="mb-3">
<label for="loa" class="form-label"><?=_('LoA')?>, m</label> <label for="loa" class="form-label"><?=_('LoA')?>, m</label>
<input type="text" class="form-control" id="loa" name="loa" value="<?=format_float($vessel->loa, 2) ?>"> <input type="text" class="form-control" id="loa" name="loa" value="<?=format_float($vessel->loa, 2) ?>">
@@ -550,14 +600,20 @@ $vessel = $sth->fetch(PDO::FETCH_OBJ);
<label for="shapefile" class="form-label"><?=_('Shapefile')?></label> <label for="shapefile" class="form-label"><?=_('Shapefile')?></label>
<input type="text" class="form-control" id="shapefile" name="shapefile" value="<?=$vessel->shapefile ?>"> <input type="text" class="form-control" id="shapefile" name="shapefile" value="<?=$vessel->shapefile ?>">
</div> */ </div> */
form_create_select('htype', _('Hull type'), $opt_htype, $vessel->htype);
form_create_select('shapefile', _('Shape file'), $opt_shapefiles, $vessel->shapefile); form_create_select('shapefile', _('Shape file'), $opt_shapefiles, $vessel->shapefile);
form_create_select('shipyard', _('Shipyard'), $opt_shipyard, $vessel->shipyard); form_create_select('shipyard', _('Shipyard'), $opt_shipyard, $vessel->shipyard);
?>
<div class="mb-3">
<label for="hull_number" class="form-label"><?=_('Hull number')?></label>
<input type="text" class="form-control" id="hull_number" name="hull_number" value="<?=$vessel->hull_number ?>">
</div>
<?php
form_create_select('sid', _('Default Storage'), $g_opt_none + $opt_storage, $vessel->sid_default); form_create_select('sid', _('Default Storage'), $g_opt_none + $opt_storage, $vessel->sid_default);
?> ?>
<div class="mb-3"> <div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label> <label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$vessel->remarks ?></textarea> <textarea class="form-control" id="remarks" name="remarks" rows="3"><?=h($vessel->remarks)?></textarea>
</div> </div>
<?php <?php
+70 -54
View File
@@ -7,16 +7,20 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle=_('Inventory'); $pagetitle=_('Inventory');
$id = gpc_get_int($_REQUEST, 'id', 0); $id = gpc_get_int($_REQUEST, 'id', 0);
$opt_conttype = db_load_enum('inventory', 'conttype', true, true);
$opt_storage = db_get_opt_storage($user->vid); $opt_storage = db_get_opt_storage($user->vid);
$opt_box = db_get_opt_box($user->vid); $opt_box = db_get_opt_box($user->vid);
$opt_invcond = db_load_enum('inventory', 'invcond', true, true); $opt_invcond = db_load_enum('inventory', 'invcond', true, true);
$opt_equipment = db_get_opt_equip($user->vid, [-1 => _('&horbar; none &horbar;')]); $opt_equipment = db_get_opt_equip($user->vid, [-1 => _('&horbar; none &horbar;')]);
$opt_icat = db_get_options(DD_INVENTORY_CATEGORY);
// ========== ACTIONS START =================================================== // ========== ACTIONS START ===================================================
@@ -48,8 +52,13 @@ switch ($submit = form_get_action()) {
$p[':invname'] = gpc_get_string($_POST, 'invname'); $p[':invname'] = gpc_get_string($_POST, 'invname');
$p[':number'] = gpc_get_int($_POST, 'number'); $p[':number'] = gpc_get_int($_POST, 'number');
$p[':conttype'] = gpc_get_string($_POST, 'conttype'); $p[':conttype'] = gpc_get_string($_POST, 'conttype');
$p[':sid'] = gpc_get_uint($_POST, 'sid', 0); if ($p[':conttype'] == 'storage') {
$p[':boxid'] = gpc_get_uint($_POST, 'boxid', 0); $p[':sid'] = gpc_get_uint($_POST, 'sid', 0);
$p[':boxid'] = NULL;
} else {
$p[':boxid'] = gpc_get_uint($_POST, 'boxid', 0);
$p[':sid'] = NULL;
}
if ($p[':sid'] == NULL && $p[':boxid'] == NULL) { if ($p[':sid'] == NULL && $p[':boxid'] == NULL) {
$p[':conttype'] = 'storage'; $p[':conttype'] = 'storage';
$sid = db_get_default_storage($user->vid); $sid = db_get_default_storage($user->vid);
@@ -69,8 +78,13 @@ switch ($submit = form_get_action()) {
$p[':invname'] = gpc_get_string($_POST, 'invname'); $p[':invname'] = gpc_get_string($_POST, 'invname');
$p[':number'] = gpc_get_int($_POST, 'number'); $p[':number'] = gpc_get_int($_POST, 'number');
$p[':conttype'] = gpc_get_string($_POST, 'conttype'); $p[':conttype'] = gpc_get_string($_POST, 'conttype');
$p[':sid'] = gpc_get_uint($_POST, 'sid', 0); if ($p[':conttype'] == 'storage') {
$p[':boxid'] = gpc_get_uint($_POST, 'boxid', 0); $p[':sid'] = gpc_get_uint($_POST, 'sid', NULL);
$p[':boxid'] = NULL;
} else {
$p[':boxid'] = gpc_get_uint($_POST, 'boxid', NULL);
$p[':sid'] = NULL;
}
if ($p[':sid'] == NULL && $p[':boxid'] == NULL) { if ($p[':sid'] == NULL && $p[':boxid'] == NULL) {
$p[':conttype'] = 'storage'; $p[':conttype'] = 'storage';
$sid = db_get_default_storage($user->vid); $sid = db_get_default_storage($user->vid);
@@ -84,8 +98,11 @@ switch ($submit = form_get_action()) {
$p[':price'] = gpc_get_currency($_POST, 'price'); $p[':price'] = gpc_get_currency($_POST, 'price');
$p[':purchdate'] = gpc_get_date($_POST, 'purchdate'); $p[':purchdate'] = gpc_get_date($_POST, 'purchdate');
$p[':invcond'] = gpc_get_string($_POST, 'invcond'); $p[':invcond'] = gpc_get_string($_POST, 'invcond');
$p[':icat'] = gpc_get_int($_POST, 'icat');
if ($p[':icat'] <= 0) $p[':icat'] = NULL;
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150); $p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
$p[':eid'] = gpc_get_int($_POST, 'eid'); $p[':eid'] = gpc_get_int($_POST, 'eid');
if ($p[':eid'] <= 0) $p[':eid'] = NULL;
db_exec_update('inventory', $p, 'invid'); db_exec_update('inventory', $p, 'invid');
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -141,7 +158,7 @@ if (strlen($flt->cond) > 2 ) {
$p[':invcond'] = $flt->cond; $p[':invcond'] = $flt->cond;
} }
if (strlen($flt->txt) > 1) { if (strlen($flt->txt) > 1) {
$w[] = 'invname LIKE :txt'; $w[] = 'invname LIKE :txt OR i.remarks LIKE :txt';
$p[':txt'] = '%'.$flt->txt.'%'; $p[':txt'] = '%'.$flt->txt.'%';
} }
$where = join(' AND ', $w); $where = join(' AND ', $w);
@@ -165,10 +182,12 @@ $page = gpc_get_int($_REQUEST, 'p', 1);
$rows_pp = gpc_get_int($_REQUEST, 'n', $user->rows_pp); $rows_pp = gpc_get_int($_REQUEST, 'n', $user->rows_pp);
$lastpage = ceil($numrows/$rows_pp); $lastpage = ceil($numrows/$rows_pp);
$sql = "SELECT i.invid, i.invname, i.number, i.invcond, i.eid, s.sname AS container " $sql = "SELECT i.invid, i.invname, i.number, i.invcond, i.eid, s.sname AS container,"
. " IF(CHAR_LENGTH(i.remarks)>40, CONCAT(LEFT(i.remarks, 40), '&hellip;'), i.remarks) AS remarks "
. "FROM inventory AS i JOIN storage AS s ON (i.conttype='storage' AND i.sid=s.sid)"; . "FROM inventory AS i JOIN storage AS s ON (i.conttype='storage' AND i.sid=s.sid)";
$sql .= ' WHERE ' . $where; $sql .= ' WHERE ' . $where;
$sql .= " UNION SELECT i.invid, i.invname, i.number, i.invcond, i.eid, b.label AS container " $sql .= " UNION SELECT i.invid, i.invname, i.number, i.invcond, i.eid, b.label AS container,"
. " IF(CHAR_LENGTH(i.remarks)>40, CONCAT(LEFT(i.remarks, 40), '&hellip;'), i.remarks) AS remarks "
. "FROM inventory AS i JOIN box AS b ON (i.conttype='box' AND i.boxid=b.boxid) " . "FROM inventory AS i JOIN box AS b ON (i.conttype='box' AND i.boxid=b.boxid) "
. " JOIN storage AS s ON (b.sid=s.sid) "; . " JOIN storage AS s ON (b.sid=s.sid) ";
$sql .= ' WHERE ' . $where; $sql .= ' WHERE ' . $where;
@@ -203,47 +222,16 @@ $opt_special = array(
// - selection for storage // - selection for storage
// - selection for box // - selection for box
// page specific filter end // page specific filter end
filter_create_select('flt_stor', _('Storage'), $g_opt_all + $g_opt_none + $opt_storage, $flt->stor);
filter_create_select('flt_cond', _('Condition'), $g_opt_all + $opt_invcond, $flt->cond);
filter_create_text('flt_text', _('Text'), $flt->txt, 15, 30);
?> ?>
<div class="d-flex flex-nowrap gap-2">
<label for="flt_stor"><?=_('Storage')?></label>
<select class="form-select" id="flt_stor" name="flt_stor">
<?php
foreach ($opt_special + $opt_storage as $k => $v) {
echo '<option value="', $k,'"';
if ($k == $flt->stor) {
echo ' selected';
}
echo '>', $v, '</option>';
}
?>
</select>
</div> </div>
<div class="d-flex flex-nowrap gap-2"> <div class="card-footer">
<label for="flt_cond"><?=_('Condition')?></label> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
<select class="form-select" id="flt_cond" name="flt_cond"> <button name="submit[freset]" class="btn btn-sm btn-secondary float-end" title="<?=_('Reset filter to defaults')?>"><?=_('Clear')?></button>
<?php </div>
$opt_special = array(
-2 => _('&horbar; all &horbar;'),
);
foreach ($opt_special + $opt_invcond as $k => $v) {
echo '<option value="', $k,'"';
if ($k == $flt->cond) {
echo ' selected';
}
echo '>', $v, '</option>';
}
?>
</select>
</div>
<div class="d-flex flex-nowrap gap-2">
<label for="flt_txt">Text</label>
<input type="text" class="form-control" name="flt_txt" size="15" maxlength="30" value="<?=$flt->txt ?>">
</div>
</div>
<div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
<button name="submit[freset]" class="btn btn-sm btn-secondary float-end" title="<?=_('Reset filter to defaults')?>"><?=_('Clear')?></button>
</div>
</div> </div>
</form> </form>
@@ -260,6 +248,7 @@ echo "<th>", _('Name'), "</th>\n";
echo "<th>", _('Container'), "</th>\n"; echo "<th>", _('Container'), "</th>\n";
echo "<th>", _('Number'), "</th>\n"; echo "<th>", _('Number'), "</th>\n";
echo "<th>", _('Condition'), "</th>\n"; echo "<th>", _('Condition'), "</th>\n";
echo "<th>", _('Remarks'), "</th>\n";
echo "<th>", _('Tags'), "</th>\n"; echo "<th>", _('Tags'), "</th>\n";
echo "<td></td>\n"; echo "<td></td>\n";
echo "</tr>\n"; echo "</tr>\n";
@@ -278,6 +267,7 @@ foreach ($res as $row) {
echo "<td>", $row['container'], "</td>\n"; echo "<td>", $row['container'], "</td>\n";
echo "<td>", $row['number'], "</td>\n"; echo "<td>", $row['number'], "</td>\n";
echo "<td>", ($opt_invcond[$row['invcond']] ?? ''), "</td>\n"; echo "<td>", ($opt_invcond[$row['invcond']] ?? ''), "</td>\n";
echo "<td>", $row['remarks'], "</td>\n";
echo "<td>", _('No tags assigned'), "</td>\n"; echo "<td>", _('No tags assigned'), "</td>\n";
// Edit current record button // Edit current record button
echo "<td>"; echo "<td>";
@@ -286,7 +276,7 @@ foreach ($res as $row) {
echo "</tr>\n"; echo "</tr>\n";
} }
// Table summary // Table summary
table_rec_summary($i0, $i, $numrows, 7); table_rec_summary($i0, $i, $numrows, 8);
echo "</table>\n"; echo "</table>\n";
echo $pagination; echo $pagination;
@@ -299,6 +289,10 @@ elseif ($action == ACT_ADD):
echo '<h2>', _('Add Inventory'), "</h2>\n"; echo '<h2>', _('Add Inventory'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<?php
form_create_text('invname', _('Name'), 80, NULL, TRUE, TRUE);
form_create_numeric('number', _('Number'), 0, 9999, 1);
/*
<div class="mb-3"> <div class="mb-3">
<label for="invname" class="form-label"><?=_('Name')?></label> <label for="invname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="invname" name="invname" autofocus> <input type="text" class="form-control" id="invname" name="invname" autofocus>
@@ -314,7 +308,9 @@ echo '<h2>', _('Add Inventory'), "</h2>\n";
<option value="box"><?=_('Box')?></option> <option value="box"><?=_('Box')?></option>
</select> </select>
</div> </div>
<?php */
form_create_select('conttype', _('Container type'), $opt_conttype, 'storage');
// load current filter setting for storage default setting // load current filter setting for storage default setting
$flt = db_get_filter($user->id, 201, ['stor','cond','txt']); $flt = db_get_filter($user->id, 201, ['stor','cond','txt']);
form_create_select('sid', _('Storage'), $g_opt_none + $opt_storage, $flt->stor); form_create_select('sid', _('Storage'), $g_opt_none + $opt_storage, $flt->stor);
@@ -331,7 +327,7 @@ elseif ($action == ACT_VIEW):
// ========== VARIANT: view single record ===================================== // ========== VARIANT: view single record =====================================
$sql = "SELECT invname, conttype, sid, boxid, number, weight, price, purchdate," $sql = "SELECT invname, conttype, sid, boxid, number, weight, price, purchdate,"
. " invcond, remarks " . " invcond, icat, remarks "
. "FROM inventory " . "FROM inventory "
. "WHERE invid=?"; . "WHERE invid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -383,13 +379,28 @@ echo "<tr><th>", _('Location ID'), "</th><td>", $inventory->locationid, "</td></
echo "<tr><th>", _('Number'), "</th><td>", $inventory->number, "</td></tr>\n"; echo "<tr><th>", _('Number'), "</th><td>", $inventory->number, "</td></tr>\n";
echo "<tr><th>", _('Weight'), "</th><td>", format_float($inventory->weight, 2, 'kg'), "</td></tr>\n"; echo "<tr><th>", _('Weight'), "</th><td>", format_float($inventory->weight, 2, 'kg'), "</td></tr>\n";
echo "<tr><th>", _('Price'), "</th><td>", format_currency($inventory->price), "</td></tr>\n"; echo "<tr><th>", _('Price'), "</th><td>", format_currency($inventory->price), "</td></tr>\n";
echo "<tr><th>", _('Purchase date'), "</th><td>", $inventory->purchdate, "</td></tr>\n"; echo "<tr><th>", _('Purchase date'), "</th><td>", format_date($inventory->purchdate), "</td></tr>\n";
echo "<tr><th>", _('Condition'), "</th><td>", $opt_invcond[$inventory->invcond], "</td></tr>\n"; echo "<tr><th>", _('Condition'), "</th><td>", $opt_invcond[$inventory->invcond], "</td></tr>\n";
echo "<tr><th>", _('Remarks'), "</th><td>", nl2br($inventory->remarks), "</td></tr>\n"; echo "<tr><th>", _('Category'), "</th><td>", $opt_icat[$inventory->icat], "</td></tr>\n";
echo "<tr><th>", _('Remarks'), "</th><td>", h($inventory->remarks, br:true), "</td></tr>\n";
$tags = db_load_taglist('inv', $id); $tags = db_load_taglist('inv', $id);
form_tag_assignment($g_scriptname, $id, $tags); form_tag_assignment($g_scriptname, $id, $tags);
// Custom properties
$sql = "SELECT keyname, valstr, valint FROM property WHERE objtype='inv' AND objid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
foreach ($sth->fetchAll() as $row) {
echo "<tr><th>{$row['keyname']}</th><td>";
if (isset($row['valstr'])) {
echo $row['valstr'];
} else {
echo $row['valint'];
}
echo "</td>\n";
}
echo "</table>\n"; echo "</table>\n";
form_view_buttons($g_scriptname, $id); form_view_buttons($g_scriptname, $id);
@@ -411,7 +422,7 @@ $inventory = $sth->fetch(PDO::FETCH_OBJ);
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3"> <div class="mb-3">
<label for="invname" class="form-label"><?=_('Name')?></label> <label for="invname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="invname" name="invname" value="<?=$inventory->invname ?>"> <input type="text" class="form-control" id="invname" name="invname" value="<?=h($inventory->invname)?>">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="number" class="form-label"><?=_('Number')?></label> <label for="number" class="form-label"><?=_('Number')?></label>
@@ -426,6 +437,8 @@ $opt_conttype = db_load_enum('inventory', 'conttype', true, true);
form_create_select('conttype', _('Container type'), $opt_conttype, $inventory->conttype); form_create_select('conttype', _('Container type'), $opt_conttype, $inventory->conttype);
form_create_select('sid', _('Storage'), $g_opt_none + $opt_storage, $inventory->sid); form_create_select('sid', _('Storage'), $g_opt_none + $opt_storage, $inventory->sid);
form_create_select('boxid', _('Box'), $g_opt_none + $opt_box, $inventory->boxid); form_create_select('boxid', _('Box'), $g_opt_none + $opt_box, $inventory->boxid);
// form_create_numeric
?> ?>
<div class="mb-3"> <div class="mb-3">
<label for="price" class="form-label"><?=sprintf(_('Price, %s'), $g_lconv['currency_symbol']); ?></label> <label for="price" class="form-label"><?=sprintf(_('Price, %s'), $g_lconv['currency_symbol']); ?></label>
@@ -450,10 +463,13 @@ foreach ($cond as $k => $v) {
?> ?>
</select> </select>
</div> </div>
<?php form_create_select('eid', _('Equipment'), $opt_equipment, $inventory->eid); ?> <?php
form_create_select('icat', _('Category'), $g_opt_none + $opt_icat, $inventory->icat);
form_create_select('eid', _('Equipment'), $opt_equipment, $inventory->eid);
?>
<div class="mb-3"> <div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label> <label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$inventory->remarks ?></textarea> <textarea class="form-control" id="remarks" name="remarks" rows="3"><?=h($inventory->remarks)?></textarea>
</div> </div>
<?php <?php
+453
View File
@@ -8,3 +8,456 @@
*/ */
// ========== GENERIC FUNCTIONS ===============================================
function db_exec_insert($table, $params) {
// $params must have keys corresponding to table fields prefixed with ':'
// e.g. $param[':field']
global $pdo;
global $g_error;
$keys = array_keys($params);
$fields = join(', ', array_map(function($s) { return ltrim($s, ':'); }, $keys));
$pnames = join(', ', $keys);
$sql = "INSERT INTO $table ($fields) VALUES ($pnames)";
// $sth = $pdo->prepare("INSERT INTO $table ($fields) VALUES ($pnames)");
$sth = $pdo->prepare($sql);
try {
$sth->execute($params);
} catch (PDOexception $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
$g_error->Add($sql);
$g_error->Add(print_r($params, true));
return false;
}
return $pdo->LastInsertId();
}
function db_exec_update($table, $params, $pk) {
// primary key can be a single field name or multiple fields: $pk is an array
global $pdo;
global $g_error;
// remove primary key fields from list of fields to update
if (is_array($pk)) {
if (count($pk) == 1) {
$pk = $pk[0];
$fields = $params;
unset($fields[':'.$pk]);
$where = "$pk=:$pk";
} else {
$pkparams = array_map(fn($value) => ':' . $value, $pk);
$fields = array_diff_key($params, array_flip($pkparams));
$where = join(' AND ', array_map(fn($s) => "$s=:$s", $pk));
}
} else {
$fields = $params;
unset($fields[':'.$pk]);
$where = "$pk=:$pk";
}
$fieldlist = join(', ', array_map(fn($s) => ltrim($s, ':') . '=' . $s, array_keys($fields)));
$sql = "UPDATE $table SET $fieldlist WHERE $where";
$sth = $pdo->prepare($sql);
try {
$sth->execute($params);
} catch (PDOexception $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
$g_error->Add($sql);
$g_error->Add(print_r($params, true));
return false;
}
return true;
}
function db_exec_delete($table, $condition, $params) {
// WIP untested!
// condition contains the where part of the sql statement
// params are values for placeholders in condition
// returns the number of deleted records
global $pdo;
global $g_error;
// convert params to array if single value is given
if (!is_array($params)) {
$params = [$params];
}
$sql = "DELETE FROM $table";
if (!empty($condition)) {
$sql .= ' WHERE ' . $condition;
}
$sth = $pdo->prepare($sql);
try {
$sth->execute($params);
} catch (PDOexception $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
$g_error->Add($sql);
$g_error->Add(print_r($params, true));
return -1;
}
return $sth->rowCount();
}
function db_get_setting($sno, $userid, $autocreate=false, $default=NULL) {
global $pdo;
global $g_error;
global $g_warning;
$sql = "SELECT valint, valstr FROM settings WHERE userid=? AND sno=?";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$userid, $sno]);
} catch (Exception $e) {
$g_error->Add('SQL-Error: '. $e->getMessage());
$g_error->Add($sql);
$g_error->Add("userid=$userid, sno=$sno", true);
return $default;
}
$row = $sth->fetch();
if ($row === false) {
if ($autocreate) {
// create empty settings record if it not exists
$p[':userid'] = $userid;
$p[':sno'] = $sno;
db_exec_insert('settings', $p);
$g_warning->Add("Added missing settings record with id=$sno");
}
return $default;
}
return $row;
}
function db_get_ddtext($ddid, $ddval) {
// returns single value for dropdown
global $pdo;
global $g_error;
$sql = "SELECT ddtext FROM dropdown WHERE ddid=? AND ddval=?";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$ddid, $ddval]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
return '#err';
}
return $sth->fetchColumn();
}
function db_set_revision($revtype, $revid) {
global $pdo;
global $g_error;
$sql = "INSERT INTO revision (revtype, revid, changed) "
. "VALUES (?, ?, NOW()) "
. "ON DUPLICATE KEY UPDATE changed = NOW()";
try {
$sth = $pdo->prepare($sql);
$sth->execute([$revtype, $revid]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
}
}
// ========== OPTION FUNCTIONS ================================================
// Functions to get option lists (key/value)
function db_get_options($ddid, $orderby = '', $short = False, $default = NULL) {
// returns list for dropdown
// if short is set the short value will be returned
global $pdo;
$list = array();
if ($default != NULL) {
$list[0] = $default;
}
if ($short) {
$sql = "SELECT ddval, ddshort";
} else {
$sql = "SELECT ddval, ddtext";
}
$sql .= " FROM dropdown WHERE ddid=?";
if ($orderby == 'ddtext') {
$sql .= ' ORDER BY ddtext';
} elseif ($orderby == 'sort') {
$sql .= ' ORDER BY sort';
} else {
$sql .= ' ORDER BY ddval';
}
$sth = $pdo->prepare($sql);
$sth->execute([$ddid]);
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
$list[$rec[0]] = h($rec[1]);
}
return $list;
}
function db_get_opt_vessel() {
global $pdo;
$list = array();
$sth = $pdo->query("SELECT vid, vesselname, model FROM vessel ORDER BY vid");
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$list[$row[0]] = h($row[1]);
}
return $list;
}
function db_get_opt_storage($vid) {
global $pdo;
global $g_error;
$list = array();
// exclude storage type "tank" from list
$sql = "SELECT sid, sname FROM storage WHERE vid=? AND stype<>1 ORDER BY sname";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$vid]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
}
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
$list[$rec[0]] = h($rec[1]);
}
return $list;
}
function db_get_opt_box($vid, $exclude=[]) {
global $pdo;
global $g_error;
$list = array();
$sql = "SELECT boxid, label, content "
. "FROM box INNER JOIN storage USING (sid) "
. "WHERE vid=? "
. "ORDER BY label";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$vid]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
}
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
if (! in_array($rec[0], $exclude)) {
$list[$rec[0]] = h($rec[1]) . ($rec[2] ? ' - '. h($rec[2]) : '');
}
}
return $list;
}
function db_get_opt_equip($vid, $default=NULL, $exclude=[]) {
global $pdo;
global $g_error;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT eid, ename FROM equipment WHERE vid=? ORDER BY ename";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$vid]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
}
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
if (! in_array($rec[0], $exclude)) {
$list[$rec[0]] = h($rec[1]);
}
}
return $list;
}
function db_get_opt_manuf($default=NULL) {
global $pdo;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT compid, compname FROM company WHERE comptype=2 ORDER BY compname";
$sth = $pdo->query($sql);
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$list[$row[0]] = h($row[1]);
}
return $list;
}
function db_get_opt_supp($default=NULL) {
global $pdo;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT compid, compname FROM company WHERE comptype=1 ORDER BY compname";
$sth = $pdo->query($sql);
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$list[$row[0]] = h($row[1]);
}
return $list;
}
function db_get_opt_user($default=NULL) {
global $pdo;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT userid, displayname FROM user WHERE userid>0 ORDER BY displayname";
$sth = $pdo->query($sql);
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$list[$row[0]] = h($row[1]);
}
return $list;
}
function db_get_opt_proj($vid, $exclude=[], $default=NULL) {
// exclude is a list of project states
global $pdo;
global $g_error;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT projid, projname FROM project WHERE vid=?";
$where = [];
foreach ($exclude as $excl) {
$where[] = "NOT FIND_IN_SET('$excl',projstate)";
}
if (! empty($where)) {
$sql .= ' AND '. implode(' AND ', $where);
}
$sql .= " ORDER BY projname";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$vid]);
} catch(PDOException $e) {
$g_error->Add($e->getMessage());
}
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
$list[$rec[0]] = h($rec[1]);
}
return $list;
}
function db_get_opt_cable($vid, $default=NULL) {
global $pdo;
if (isset($default)) {
$list = $default;
} else {
$list = array();
}
$sql = "SELECT cableid, cablename FROM cable WHERE vid=? ORDER BY cablename";
$sth = $pdo->prepare($sql);
$sth->execute([$vid]);
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $row) {
$list[$row[0]] = h($row[1]);
}
return $list;
}
// ========== FILTER FUNCTIONS ================================================
function db_get_filter($user, $sno, $fields = []) {
// if fields supplied empting missing field are created
global $pdo;
global $g_warning;
$flt = new stdClass();
$sth = $pdo->prepare("SELECT valstr FROM settings WHERE userid=? AND sno=?");
try {
$sth->execute([$user, $sno]);
$json = $sth->fetchColumn();
if ($json === false) {
// no settings record. create empty one for later updates
$sth = $pdo->prepare("INSERT INTO settings (userid, sno, valstr) VALUES (?, ?, '{}')");
$sth->execute([$user, $sno]);
} else {
$flt = json_decode($json);
}
// create missing fields
foreach ($fields as $f) {
if (!property_exists($flt, $f)) {
$flt->$f = null;
}
}
} catch (PDOexception $e) {
$g_warning->Add('SQL-Error: '. $e->getMessage());
$g_warning->PrintOut();
}
return $flt;
}
function db_clear_filter($sno) {
global $user;
global $pdo;
$sql = "DELETE FROM settings WHERE userid=? AND sno=?";
$sth = $pdo->prepare($sql);
try {
$sth->execute([$user->id, $sno]);
} catch (PDOexception $e) {
$g_warning->Add('SQL-Error: '. $e->getMessage());
$g_warning->Add($sql);
$g_warning->Add('Setting: ', $sno);
return false;
}
return true;
}
function db_save_filter($flt, $sno) {
global $user;
global $pdo;
global $g_warning;
$sql = "UPDATE settings SET valstr=? WHERE userid=? AND sno=?";
$sth = $pdo->prepare($sql);
try {
$sth->execute([json_encode($flt), $user->id, $sno]);
} catch (PDOexception $e) {
$g_warning->Add('SQL-Error: '. $e->getMessage());
$g_warning->Add($sql);
$g_warning->Add(print_r($flt, true));
$g_warning->Add('Setting: ', $sno);
return false;
}
return true;
}
// ========== LOCKING FUNCTIONS ===============================================
function db_lock_acquire($table, $key, $userid) {
global $pdo;
$token = bin2hex(random_bytes(8));
// first try new lock
$sql = "INSERT INTO recordlock (lock_table, lock_key, token, userid) "
. "VALUES (?, ?, ?, ?)";
try {
$sth = $pdo->prepare($sql);
$sth->execute([$table, $key, $token, $userid]);
return $token;
} catch (PDOException $e) {
if ($e->errorInfo[1] != 1062) {
throw $e;
}
}
// lazy locking: lock exists but is old, so we use it
$sql = "UPDATE recordlock "
. "SET token=?, userid=?, "
. "created_at=CURRENT_TIMESTAMP, last_seen=CURRENT_TIMESTAMP "
. "WHERE lock_table=? AND lock_key=? "
. "AND last_seen<CURRENT_TIMESTAMP-INTERVAL 5 MINUTE";
$sth = $pdo->prepare($sql);
$sth->execute([$token, $userid, $table, $key]);
if ($stmt->rowCount() === 1) {
return $token;
}
return null;
}
function db_lock_refresh($token) {
global $pdo;
$sql = "UPDATE recordlock "
. "SET last_seen=CURRENT_TIMESTAMP "
. "WHERE token=?";
$sth = $pdo->prepare($sql);
$sth->execute([$token]);
return $sth->rowCount() === 1;
}
function db_lock_release($token) {
global $pdo;
$sql = "DELETE FROM recordlock WHERE token=?";
$sth = $pdo->prepare($sql);
$sth->execute([$token]);
return $sth->rowCount() === 1;
}
+70
View File
@@ -43,3 +43,73 @@ function dir_get_size($path) {
} }
return $total; return $total;
} }
function image_scale($imagefile, $mimetype, $width, $height, $factor) {
// scales down image in place
// returns size in bytes for new scaled image or -1 in case of error
global $g_message, $g_error;
if ($factor <= 0 || $factor >= 1) {
$g_error->Add("Internal error: Invalid image scale factor");
return -1;
}
$width = (int)($width * $factor);
$height = (int)($height * $factor);
if ($width < 1 || $height < 1) {
$g_error->Add("Internal error: Scaled image dimensions are too small");
return -1;
}
if ($mimetype == 'image/jpeg') {
$orig = imagecreatefromjpeg($imagefile);
if ($orig === false) {
$g_error->Add("Internal error: imagecreatefromjpeg failed");
return -1;
}
$scaled = imagescale($orig, $width, $height, IMG_BICUBIC); // TODO IMG_BICUBIC_FIXED?
if ($scaled === false) {
imagedestroy($orig);
$g_error->Add("Internal error: jpeg imagescale failed");
return -1;
}
if (!imagejpeg($scaled, $imagefile, 85)) {
imagedestroy($scaled);
imagedestroy($orig);
$g_error->Add("Internal error: imagejpeg failed");
return -1;
}
} else if ($mimetype == 'image/png') {
$orig = imagecreatefrompng($imagefile);
if ($orig === false) {
$g_error->Add("Internal error: imagecreatefrompng failed");
return -1;
}
$scaled = imagescale($orig, $width, $height, IMG_BICUBIC);
if ($scaled === false) {
imagedestroy($orig);
$g_error->Add("Internal error: png imagescale failed");
return -1;
}
// Preserve PNG transparency
imagealphablending($scaled, false);
imagesavealpha($scaled, true);
if (!imagepng($scaled, $imagefile, 9)) {
imagedestroy($scaled);
imagedestroy($orig);
$g_error->Add("Internal error: imagepng failed");
return -1;
}
} else {
$g_error->Add(sprintf(_('Internal error: Unknown mimetype %s!'), $mimetype));
return -1;
}
$g_message->add(sprintf(_('Image scaled down to %dx%d'), $width, $height));
imagedestroy($scaled);
imagedestroy($orig);
clearstatcache(true, $imagefile);
$size = filesize($imagefile);
if ($size === false) {
$g_error->Add("Internal error: filesize failed");
return -1;
}
return $size;
}
+302
View File
@@ -0,0 +1,302 @@
<?php
/******************************************************************************
* YMS - Yacht Management Software
* Copyright (C) 2024-2026 Thomas Hooge
*
* SPDX-License-Identifier: WTFPL
******************************************************************************
TODO implement datalist
tel and/or email?
autocomplete?
*/
// ========== FORM FUNCTIONS ==================================================
function form_get_action() {
if (!isset($_POST['submit'])) {
if (isset($_GET['f'])) {
$submit = $_GET['f'];
// strip parameters
/* $pos = strpos($submit, '?');
if ($pos > 2) {
$submit = substr($submit, 0, $pos);
} */
} else {
$submit = NULL;
}
} else {
$submit = $_POST['submit'];
}
if (is_array($submit)) {
$submit = key($submit);
}
return strtolower($submit);
}
function form_tag_assignment($script, $id, $tags) {
echo '<tr>';
echo '<th>', _('Tags'), "</th>\n";
echo '<td>', $tags, '</td>';
echo "</tr>\n<tr>";
echo '<th>', _('Tag assignment'), "</th>\n";
echo '<td><form method="post" action="', $script, '">', "\n";
echo '<div class="form-floating">';
echo '<input type="hidden" name="id" value="', $id .'">', "\n";
echo '<label>', _('(Separate by comma)'), '</label>', "\n";
echo '<input type="text" maxlength="80" class="form-control" name="tagstring" value="', $tags, '">', "\n";
echo '<input type="submit">', "\n";
echo "</div></form></td></td>\n";
echo "</tr>";
}
// ========== FORM FIELDS =====================================================
function form_create_numeric($fieldname, $label, $value=NULL, $min=NULL, $max=NULL, $step=NULL, $required=FALSE, $autofocus=FALSE) {
// step = 'any'-> any float
// step = 0.01 -> float with limited decimal places
// step = 1 -> integer
echo '<div class="mb-3">', "\n";
echo '<label for="', $fieldname, '" class="form-label">', $label, "</label>\n";
echo '<input type="number" class="form-control" id="', $fieldname, '" name = "', $fieldname, '"';
if ($value !== NULL) {
echo ' value="', h($value), '"';
}
if ($min !== NULL) {
echo ' min="', $min, '"';
}
if ($max !== NULL) {
echo ' max="', $max, '"';
}
if ($step !== NULL) {
echo ' step="', $step, '"';
}
if ($required === TRUE) {
echo ' required';
}
if ($autofocus === TRUE) {
echo ' autofocus';
}
echo ">\n";
echo "</div>\n";
}
function form_create_text($fieldname, $label, $maxlen=NULL, $value=NULL, $required=FALSE, $autofocus=FALSE) {
// create generic text entry with assigned label
// TODO errortext
// perhaps support inputmode="numeric", pattern="[0-9]{1,3}"
echo '<div class="mb-3">', "\n";
echo '<label for="', $fieldname, '" class="form-label">', $label, "</label>\n";
echo '<input type="text" class="form-control" id="', $fieldname, '" name="', $fieldname, '"';
if ($maxlen !== NULL) {
echo ' maxlength="', $maxlen, '"';
}
if ($value !== NULL) {
echo ' value="', h($value), '"';
}
if ($required === TRUE) {
echo ' required';
}
if ($autofocus === TRUE) {
echo ' autofocus';
}
echo ">\n";
echo "</div>\n";
}
function form_create_textarea($fieldname, $label, $rows=3, $maxlen=NULL, $value=NULL) {
echo '<div class="mb-3">', "\n";
echo '<label for="', $fieldname, '" class="form-label">', $label, "</label>\n";
echo '<textarea class="form-control" id="', $fieldname, '" name="', $fieldname, '"';
echo ' rows="', $rows, '"';
if ($maxlen !== NULL) {
echo ' maxlength="', $maxlen, '"';
}
echo '>';
if ($value !== NULL) {
echo h($value);
}
echo "</textarea>\n";
echo "</div>\n";
}
function form_create_date($fieldname, $label, $value=NULL, $mindate=NULL, $maxdate=NULL) {
echo '<div class="mb-3">', "\n";
echo '<label for="', $fieldname, '" class="form-label">', $label, "</label>\n";
echo '<input type="date" class="form-control" id="', $fieldname, '" name="', $fieldname, '"';
if ($min !== NULL) {
echo ' min="', $mindate, '"';
}
if ($max !== NULL) {
echo ' max="', $maxdate, '"';
}
if ($value !== NULL) {
echo ' value="', h($value), '"';
}
echo ">\n";
echo "</div>\n";
}
function form_create_color($fieldname, $label, $value=NULL) {
// value has to be 6char hex
echo '<div class="mb-3">', "\n";
echo '<label for="', $fieldname, '" class="form-label">', $label, "</label>\n";
echo '<input type="color" class="form-control form-control-color" id="', $fieldname, '" name="', $fieldname, '"';
if ($value !== NULL) {
echo ' value="#', $value, '"';
}
echo ">\n";
echo "</div>\n";
}
function form_create_select($fieldname, $label, $optlist, $selval=NULL, $multiple=FALSE) {
echo '<div class="mb-3">', "\n";
echo '<label for="', $fieldname, '">', $label, "</label>\n";
echo '<select class="form-select" name="', $fieldname,'" id="', $fieldname, $multiple ? ' multiple' : '', '">', "\n";
foreach ($optlist as $k => $v) {
echo '<option value="', $k, '"';
if (isset($selval) and ($k == $selval)) {
echo ' selected';
}
echo '>', $v, "</option>\n";
}
echo "</select>\n";
echo "</div>\n";
}
function form_create_option($fieldname, $label) {
// TBD
}
function form_create_check($fieldname, $label, $checked) {
// create single checkbox with assigned label
echo '<div class="mb-3">', "\n";
echo '<input type="checkbox" class="form-check-input" name="', $fieldname, '" id="', $fieldname, '"';
if ($checked) {
echo ' checked';
}
echo ">\n";
echo '<label for="', $fieldname, '">', $label, "</label>\n";
echo "</div>\n";
}
function form_create_checks($fieldname, $label, $optlist, $selected = []) {
// create multiple combined checkboxes with title
echo '<fieldset class="mb-3">', "\n";
echo '<legend class="fs-6 mb-1 border-bottom pb-1">', $label, "</legend>\n";
echo '<div class="d-flex flex-wrap gap-3">';
foreach ($optlist as $k => $v) {
echo '<div class="form-check">', "\n";
$checked = in_array($k, $selected, true) ? ' checked' : '';
echo '<label class="form-check-label">';
echo '<input type="checkbox" class="form-check-input" name="', $fieldname, '[', $k, ']"', $checked, '>';
echo $v;
echo '</label>';
echo "</div>\n";
}
echo "</div>\n";
echo "</fieldset>\n";
}
// ========== FORM BUTTONS ====================================================
function form_add_button($script, $id=NULL, $idname='id') {
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<a href="', $script, '?f=add';
if (isset($id)) {
echo '&'.$idname.'='.$id;
}
echo '" class="btn btn-primary" role="button">', _('Add'), "</a>\n";
echo "</div>\n";
}
function form_view_buttons($script, $id, $backlink=NULL) {
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<a href="', $script, '?f=edit&id=', $id, '" class="btn btn-primary" role="button">', _('Edit'), "</a>\n";
echo '&nbsp;';
echo '<a href="', $script, '?f=del&id=', $id, '" class="btn btn-secondary" role="button">', _('Delete'), "</a>\n";
echo '&nbsp;';
echo '<a href="', $backlink ?? $script, '" class="btn btn-secondary">', _('Back'), "</a>\n";
echo "</div>\n";
}
function form_new_buttons($script) {
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<button type="submit" name="submit[insert]" class="btn btn-primary">', _('Save'), "</button>\n";
echo '<a href="', $script, '" class="btn btn-secondary">', _('Back'), "</a>\n";
echo "</div>\n";
}
function form_edit_buttons($script, $id) {
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<button type="submit" name="submit[update]" class="btn btn-primary">', _('Save'), "</button>\n";
echo '<a href="', $script, '?f=view&id=', $id, '" class="btn btn-secondary">', _('Back'), "</a>\n";
echo "</div>\n";
}
function form_delete_buttons($script, $id, $token) {
echo '<div class="container-fluid px-0 my-3">', "\n";
echo '<form method="post" action="', $script, '">', "\n";
echo '<input type="hidden" name="id" value="', $id .'">', "\n";
echo '<input type="hidden" name="token" value="', $token, '">', "\n";
echo '<button type="submit" name="submit[delete]" class="btn btn-primary">', _('Delete'), "</button>\n";
echo '<a href="', $script, '?f=view&id=', $id, '" class="btn btn-secondary">', _('Back'), "</a>\n";
echo "</form>\n";
echo "</div>\n";
}
// ========== FILTER FIELDS ===================================================
function filter_create_text($fieldname, $label, $value, $size=NULL, $maxlength=NULL) {
echo '<div class="d-flex flex-nowrap gap-2 align-items-start">', "\n";
echo '<label for="', $fieldname,'">', $label,'</label>', "\n";
echo '<input class="form-control" type="text" name="', $fieldname, '"';
if (isset($size)) {
echo ' size="', $size,'"';
}
if (isset($maxlength)) {
echo ' maxlength="', $maxlength, '"';
}
echo ' value="', h($value), '">', "\n";
echo "</div>\n";
}
function filter_create_select($fieldname, $label, $optlist, $selval=NULL, $multiple=FALSE) {
// - Wenn multiple gesetzt ist, muß selval ein array sein
// ansonsten ein einfacher String
/* if ($multiple) {
if (!is_array($selval)) {
}
} */
echo '<div class="d-flex flex-nowrap gap-2 align-items-start">', "\n";
echo '<label for="', $fieldname,'">', $label,'</label>', "\n";
echo '<select class="form-select" id="', $fieldname, '" name="', $fieldname, '"', $multiple ? ' multiple' : '', ">\n";
foreach ($optlist as $k => $v) {
echo '<option value="', $k, '"';
if ($k == $selval) {
echo ' selected';
}
echo '>', $v, '</option>', "\n";
}
echo "</select>\n";
echo "</div>\n";
}
function filter_create_checks($fieldname, $label, $optlist, $selected = []) {
// TODO WIP
echo '<fieldset class="mb-3">', "\n";
echo '<legend class="fs-6 mb-1 border-bottom pb-1">', $label, "</legend>\n";
echo '<div class="d-flex flex-wrap gap-3">', "\n";
foreach ($optlist as $k => $v) {
echo '<div class="form-check">', "\n";
$checked = in_array($k, $selected, true) ? ' checked' : '';
echo '<label class="form-check-label">', "\n";
echo '<input type="checkbox" class="form-check-input" name="', $fieldname, '[', $k, ']"', $checked, ">\n";
echo $v, "\n";
echo "</label>\n";
echo "</div>\n";
}
echo "</div>\n";
echo "</fieldset>\n";
}
+64 -18
View File
@@ -10,28 +10,41 @@
// ========== GPC FUNCTIONS =================================================== // ========== GPC FUNCTIONS ===================================================
function gpc_get_string(&$GPC, $varname, $maxlen = NULL, $default = NULL) { function gpc_get_string(&$GPC, $varname, $maxlen = NULL, $default = NULL, $nullvals = []) {
// TODO Parameter nullval: single value or array of values which considered as null // Parameter nullvals: single value or array of values which considered as null
// Default value for nullval is "-1" if (!isset($GPC[$varname]) || (strlen(trim($GPC[$varname])) == 0)) {
if (!isset($GPC[$varname]) or (strlen(trim($GPC[$varname])) == 0)) {
return $default; return $default;
} }
$s = trim($GPC[$varname]); $s = trim($GPC[$varname]);
if (isset($maxlen)) { if (isset($maxlen)) {
return substr($s, 0, $maxlen); $s = substr($s, 0, $maxlen);
}
if (!is_array($nullvals)) {
$nullvals = [$nullvals];
}
if (in_array($s, $nullvals, true)) {
return NULL;
} }
return $s; return $s;
} }
function gpc_get_int(&$GPC, $varname, $default = NULL) { function gpc_get_int(&$GPC, $varname, $default = NULL, $nullvals = []) {
if (!isset($GPC[$varname])) { // Parameter nullvals: single value or array of values which considered as null
if (!isset($GPC[$varname]) || $GPC[$varname] === '') {
return $default; return $default;
} }
return (int)$GPC[$varname]; $value = (int)$GPC[$varname];
if (!is_array($nullvals)) {
$nullvals = [$nullvals];
}
if (in_array($value, $nullvals, true)) {
return NULL;
}
return $value;
} }
function gpc_get_uint(&$GPC, $varname, $default = NULL) { function gpc_get_uint(&$GPC, $varname, $default = NULL) {
if (!isset($GPC[$varname])) { if (!isset($GPC[$varname]) || $GPC[$varname] === '') {
return $default; return $default;
} }
$val = (int)$GPC[$varname]; $val = (int)$GPC[$varname];
@@ -43,7 +56,7 @@ function gpc_get_uint(&$GPC, $varname, $default = NULL) {
function gpc_get_float(&$GPC, $varname, $default = NULL) { function gpc_get_float(&$GPC, $varname, $default = NULL) {
global $g_lconv; global $g_lconv;
if (!isset($GPC[$varname]) or (strlen(trim($GPC[$varname])) == 0)) { if (!isset($GPC[$varname]) || (strlen(trim($GPC[$varname])) == 0)) {
return $default; return $default;
} }
$var = str_replace($g_lconv['thousands_sep'], '', $GPC[$varname]); $var = str_replace($g_lconv['thousands_sep'], '', $GPC[$varname]);
@@ -55,7 +68,7 @@ function gpc_get_float(&$GPC, $varname, $default = NULL) {
function gpc_get_currency(&$GPC, $varname, $default = NULL) { function gpc_get_currency(&$GPC, $varname, $default = NULL) {
global $g_lconv; global $g_lconv;
if (!isset($GPC[$varname]) or (strlen(trim($GPC[$varname])) == 0)) { if (!isset($GPC[$varname]) || (strlen(trim($GPC[$varname])) == 0)) {
return $default; return $default;
} }
$var = str_replace($g_lconv['thousands_sep'], '', $GPC[$varname]); $var = str_replace($g_lconv['thousands_sep'], '', $GPC[$varname]);
@@ -83,11 +96,44 @@ function gpc_get_bool(&$GPC, $varname, $default = FALSE) {
} }
function gpc_get_date(&$GPC, $varname, $default = NULL) { function gpc_get_date(&$GPC, $varname, $default = NULL) {
// TODO improve global $g_opt_datefmt;
if (!isset($GPC[$varname]) || $GPC[$varname] == '') { if (!isset($GPC[$varname]) || !is_scalar($GPC[$varname])) {
return $default; return $default;
} }
return $GPC[$varname]; $value = trim((string)$GPC[$varname]);
if ($value === '') {
return $default;
}
foreach (array_keys($g_opt_datefmt) as $format) {
if (preg_match_all('/[Ymd]/', $format, $tokens) !== 3) {
continue;
}
$regex = preg_quote($format, '/');
$regex = str_replace('d', '(\d{2})', $regex);
$regex = str_replace('m', '(\d{2})', $regex);
$regex = str_replace('Y', '(\d{4})', $regex);
if (!preg_match('/^' . $regex . '$/', $value, $matches)) {
continue;
}
$year = $month = $day = NULL;
foreach ($tokens[0] as $i => $token) {
switch ($token) {
case 'Y':
$year = (int)$matches[$i + 1];
break;
case 'm':
$month = (int)$matches[$i + 1];
break;
case 'd':
$day = (int)$matches[$i + 1];
break;
}
}
if (checkdate($month, $day, $year)) {
return sprintf('%04d-%02d-%02d', $year, $month, $day);
}
}
return $default;
} }
function gpc_get_datetime(&$GPC, $varname, $default = NULL) { function gpc_get_datetime(&$GPC, $varname, $default = NULL) {
@@ -99,21 +145,21 @@ function gpc_get_datetime(&$GPC, $varname, $default = NULL) {
} }
function gpc_get_color(&$GPC, $varname, $default = NULL) { function gpc_get_color(&$GPC, $varname, $default = NULL) {
if (!isset($GPC[$varname]) or (strlen(trim($GPC[$varname])) == 0)) { if (!isset($GPC[$varname]) || (strlen(trim($GPC[$varname])) == 0)) {
return $default; return $default;
} }
$color = $GPC[$varname]; $color = $GPC[$varname];
if ((strlen($color) == 7) and (substr($color, 0, 1) == '#')) { if ((strlen($color) == 7) && (substr($color, 0, 1) == '#')) {
$color = substr($color, 1); $color = substr($color, 1);
} }
if ((strlen($color) != 6) or (! ctype_xdigit($color))) { if ((strlen($color) != 6) || (! ctype_xdigit($color))) {
return $default; return $default;
} }
return strtoupper($color); return strtoupper($color);
} }
function gpc_get_enum(&$GPC, $varname, $values, $default = NULL) { function gpc_get_enum(&$GPC, $varname, $values, $default = NULL) {
if (!isset($GPC[$varname]) or (strlen(trim($GPC[$varname])) == 0)) { if (!isset($GPC[$varname]) || (strlen(trim($GPC[$varname])) == 0)) {
return $default; return $default;
} }
if (! in_array($GPC[$varname], $values)) { if (! in_array($GPC[$varname], $values)) {
+31
View File
@@ -0,0 +1,31 @@
<?php
/******************************************************************************
* YMS - Yacht Management Software
* Copyright (C) 2024-2026 Thomas Hooge
*
* SPDX-License-Identifier: WTFPL
******************************************************************************
*/
function signalk_get($server, $skpath) {
$url = "$server/signalk/v1/api/" . str_replace('.', '/', $skpath);
var_dump($url);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 5,
]);
$json = curl_exec($ch);
if ($json === false) {
throw new RuntimeException('Signal K error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new RuntimeException('Signal K HTTP-error: ' . $httpCode);
}
return json_decode($json, true, 512, JSON_THROW_ON_ERROR);
}
+1
View File
@@ -13,6 +13,7 @@
function create_shapeindex($shapeindexfile) { function create_shapeindex($shapeindexfile) {
// an existing index file will be overwritten // an existing index file will be overwritten
global $g_shapedir; global $g_shapedir;
$shapeindex = array();
foreach (glob($g_shapedir.'/*.svg') as $f) { foreach (glob($g_shapedir.'/*.svg') as $f) {
$fh = fopen($f, 'r'); $fh = fopen($f, 'r');
$fname = basename($f); $fname = basename($f);
+785 -604
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+5 -5
View File
@@ -71,13 +71,13 @@ if (isset($err)) {
?> ?>
<button type="submit" class="btn btn-primary" title="<?php printf(_('Logon to %s'), APP_TITLE_SHORT); ?>" name="login" value="1"> <button type="submit" class="btn btn-primary" title="<?php printf(_('Logon to %s'), APP_TITLE_SHORT); ?>" name="login" value="1">
<span class="bi bi-caret-right"></span> <span class="bi bi-caret-right"></span>
<?=_('Login')?> <?=_('Login'), "\n"?>
</button> </button>
</form> </form>
</div> <?php /* card body */?> </div><?="\n" /* card body */ ?>
</div> <?php /* columns */?> </div><?="\n" /* columns */ ?>
</div> <?php /* rows */?> </div><?="\n" /* rows */ ?>
</div> <?phph /* card */?> </div><?="\n" /* card */ ?>
</section> </section>
</div> </div>
</body> </body>
+152 -35
View File
@@ -7,14 +7,33 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Maintenance'); $pagetitle = _('Maintenance');
$id = gpc_get_int($_REQUEST, 'id', 0); $id = gpc_get_int($_REQUEST, 'id', 0);
$opt_equipment = db_get_opt_equip($user->vid, [0 => _('*** unassigned ***')]); $opt_equipment = db_get_opt_equip($user->vid);
$opt_state = db_load_enum('maintenance', 'maintstate', true, true); $opt_state = db_load_enum('maintenance', 'maintstate', true, true);
$opt_planprec = db_load_enum('maintenance', 'plan_precision', true, true);
// series definition is derived from first maintenance record by plan_date
$opt_series = array();
$sql = "SELECT series, activities "
. "FROM ("
. "SELECT series, activities, "
. "ROW_NUMBER() OVER (PARTITION BY series ORDER BY plan_date ASC) AS n "
. "FROM maintenance "
. "WHERE series>0"
. ") AS ranked "
. "WHERE n=1";
$sth = $pdo->query($sql);
$res = $sth->fetchAll();
foreach ($res as $row) {
$opt_series[$row['series']] = $row['activities'];
}
// ========== ACTIONS START =================================================== // ========== ACTIONS START ===================================================
@@ -30,13 +49,18 @@ switch ($submit = form_get_action()) {
case 'filter': case 'filter':
$flt = array(); $flt = array();
$flt['equip'] = gpc_get_int($_POST, 'flt_equip'); $flt['equip'] = gpc_get_int($_POST, 'flt_equip');
$flt['series'] = gpc_get_int($_POST, 'flt_series');
$flt['txt'] = gpc_get_string($_POST, 'flt_txt'); $flt['txt'] = gpc_get_string($_POST, 'flt_txt');
$allowed = db_load_enum('maintenance', 'maintstate');
$flt['status'] = gpc_get_set($_POST, 'flt_status', $allowed);
db_save_filter($flt, 204); db_save_filter($flt, 204);
$action = ACT_DEFAULT; $action = ACT_DEFAULT;
break; break;
case 'freset': case 'freset':
db_clear_filter(204); // set status checkboxes to useful defaults
$flt = array('status' => ['new','plan','ongoing']);
db_save_filter($flt, 204);
$action = ACT_DEFAULT; $action = ACT_DEFAULT;
break; break;
@@ -52,9 +76,33 @@ switch ($submit = form_get_action()) {
$p[':maintid'] = $id; $p[':maintid'] = $id;
$p[':eid'] = gpc_get_int($_POST, 'eid'); $p[':eid'] = gpc_get_int($_POST, 'eid');
$p[':activities'] = gpc_get_string($_POST, 'activities', 80); $p[':activities'] = gpc_get_string($_POST, 'activities', 80);
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150); $series = gpc_get_int($_POST, 'series');
$p[':series'] = gpc_get_int($_POST, 'series'); if ($series == -3) {
// new series number by automatic
// TODO generic db function to create a new int val in column
$sql = "SELECT MIN(n.series) AS next_series "
. "FROM ("
. "SELECT 1 AS series "
. "UNION ALL "
. "SELECT DISTINCT series + 1 "
. "FROM maintenance "
. "WHERE series > 0"
. ") AS n "
. "LEFT JOIN maintenance m ON m.series=n.series "
. "WHERE m.series IS NULL";
$p[':series'] = $pdo->query($sql)->fetchColumn();
} else if ($series <= 0) {
$p[':series'] = NULL;
} else {
$p[':series'] = $series;
}
$p[':plan_date'] = gpc_get_date($_POST, 'plan_date');
$p[':plan_precision'] = gpc_get_enum($_POST, 'plan_precision', array_keys($opt_planprec));
$p[':interval_hours'] = gpc_get_int($_POST, 'interval_hours');
$p[':last_hours'] = gpc_get_int($_POST, 'last_hours');
$p[':completion_date'] = gpc_get_date($_POST, 'completion_date');
$p[':maintstate'] = gpc_get_string($_POST, 'maintstate'); $p[':maintstate'] = gpc_get_string($_POST, 'maintstate');
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
db_exec_update('maintenance', $p, 'maintid'); db_exec_update('maintenance', $p, 'maintid');
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -79,13 +127,14 @@ if ($action == ACT_DEFAULT):
page_caption_search($pagetitle); page_caption_search($pagetitle);
// load filter from db // load filter from db
$flt = db_get_filter($user->id, 204, ['equip','txt']); $flt = db_get_filter($user->id, 204, ['equip','series','txt']);
// Filter // Filter
$opt_special = array( $opt_special = array(
-2 => _('&horbar; all &horbar;'), -2 => _('&horbar; all &horbar;'),
-1 => _('&horbar; none &horbar;') -1 => _('&horbar; none &horbar;')
); );
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<div id="filter" class="card"> <div id="filter" class="card">
@@ -105,10 +154,16 @@ foreach ($opt_special + $opt_equipment as $k => $v) {
?> ?>
</select> </select>
</div> </div>
<?php
filter_create_select('flt_series', _('Series'), $g_opt_all + $g_opt_none + $opt_series, $flt->series);
?>
<div class="d-flex flex-nowrap gap-2"> <div class="d-flex flex-nowrap gap-2">
<label for="flt_txt">Text</label> <label for="flt_txt">Text</label>
<input type="text" class="form-control" name="flt_txt" maxlength="30" value="<?=$flt->txt ?? ''?>"> <input type="text" class="form-control" name="flt_txt" maxlength="30" value="<?=$flt->txt ?? ''?>">
</div> </div>
<?php
filter_create_checks('flt_status', _('Status'), $opt_state, $flt->status ?? []);
?>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
@@ -132,10 +187,28 @@ if (isset($flt->equip) and ($flt->equip == -1 or $flt->equip == 0)) {
$w[] = 'm.eid=:eid'; $w[] = 'm.eid=:eid';
$p[':eid'] = $flt->equip; $p[':eid'] = $flt->equip;
} }
if (isset($flt->series) and ($flt->series == -1)) {
$w[] = 'm.series IS NULL';
} elseif($flt->series > 0) {
$w[] = 'm.series=:series';
$p[':series'] = $flt->series;
}
if (strlen($flt->txt) > 1) { if (strlen($flt->txt) > 1) {
$w[] = '(m.activities LIKE :txt OR m.remarks LIKE :txt)'; $w[] = '(m.activities LIKE :txt OR m.remarks LIKE :txt)';
$p[':txt'] = '%'.$flt->txt.'%'; $p[':txt'] = '%'.$flt->txt.'%';
} }
// condition for multiple flags is OR
$parts = ['maintstate IS NULL']; // to get empty result
foreach ($flt->status as $s) {
$parts[] = "maintstate='$s'";
}
if (!empty($parts)) {
if (count($parts) > 1) {
$w[] = '(' . join(' OR ', $parts) . ')';
} else {
$w[] = $parts[0];
}
}
$where = join(' AND ', $w); $where = join(' AND ', $w);
$order = ' ORDER BY m.maintid'; $order = ' ORDER BY m.maintid';
@@ -155,11 +228,12 @@ $page = gpc_get_int($_REQUEST, 'p', 1);
$rows_pp = gpc_get_int($_REQUEST, 'n', $user->rows_pp); $rows_pp = gpc_get_int($_REQUEST, 'n', $user->rows_pp);
$lastpage = ceil($numrows/$rows_pp); $lastpage = ceil($numrows/$rows_pp);
$sql = "SELECT m.maintid, m.activities, m.remarks, e.ename " $sql = "SELECT m.maintid, m.activities, m.plan_date, m.interval_hours, m.maintstate, e.ename, "
. " IF(CHAR_LENGTH(m.remarks)>40, CONCAT(LEFT(m.remarks, 40), '\u{2026}'), m.remarks) AS remarks "
. "FROM maintenance AS m LEFT OUTER JOIN equipment AS e USING (eid)"; . "FROM maintenance AS m LEFT OUTER JOIN equipment AS e USING (eid)";
$sql .= ' WHERE ' . $where; $sql .= ' WHERE ' . $where;
$sql .= $order; $sql .= $order;
// if pagination: // if pagination:
$sql .= ' LIMIT ' . ($page - 1) * $rows_pp . ',' . $rows_pp; $sql .= ' LIMIT ' . ($page - 1) * $rows_pp . ',' . $rows_pp;
@@ -177,6 +251,8 @@ echo "<tr>";
echo '<th>#</th>'; echo '<th>#</th>';
echo "<th>", _('Activities'), "</th>"; echo "<th>", _('Activities'), "</th>";
echo "<th>", _('Equipment'), "</th>"; echo "<th>", _('Equipment'), "</th>";
echo "<th>", _('Upcoming'), "</th>"; // Date ou Hours
echo "<th>", _('Status'), "</th>";
echo "<th>", _('Remarks'), "</th>"; echo "<th>", _('Remarks'), "</th>";
echo "</tr>\n"; echo "</tr>\n";
echo "</thead>\n"; echo "</thead>\n";
@@ -189,9 +265,12 @@ foreach ($res as $row) {
echo '<td>', $i; echo '<td>', $i;
echo '<a title="', _('View'), '" href="', $g_scriptname, '?f=view&id=', $row['maintid'], '"><i class="bi-eye ms-2"></i></a>', "\n"; echo '<a title="', _('View'), '" href="', $g_scriptname, '?f=view&id=', $row['maintid'], '"><i class="bi-eye ms-2"></i></a>', "\n";
echo "</td>\n"; echo "</td>\n";
echo "<td>". $row['activities'] ."</td>\n"; echo "<td>", h($row['activities']) ,"</td>\n";
echo "<td>". $row['ename'] ."</td>\n"; echo "<td>", $row['ename'] ,"</td>\n";
echo "<td>". $row['remarks'] ."</td>\n"; // next plan date or hours
echo "<td>", format_date($row['plan_date']), "</td>\n";
echo "<td>", get_enum($row['maintstate']), "</td>\n";
echo "<td>", h($row['remarks']) ,"</td>\n";
echo "<td>"; echo "<td>";
// Edit current record button // Edit current record button
echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['maintid'], '"><i class="bi-pencil"></i></a>', "\n"; echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['maintid'], '"><i class="bi-pencil"></i></a>', "\n";
@@ -213,18 +292,16 @@ elseif ($action == ACT_ADD):
echo '<h2>', _('Add Maintenance'), "</h2>\n"; echo '<h2>', _('Add Maintenance'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<div class="mb-3">
<label for="activities" class="form-label"><?=_('Activities')?></label>
<input type="text" class="form-control" id="activities" name="activities">
</div>
<?php <?php
form_create_text('activities', _('Activities'), 40, NULL, TRUE, TRUE);
// TODO // TODO
// Add link to equipment, perhaps later with modal dialog? // Add link to equipment, perhaps later with modal dialog?
?> form_create_select('eid', _('Equipment'), $opt_equipment, $id);
<div class="mb-3">
/* <div class="mb-3">
<label for="eid" class="form-label"><?=_('Equipment')?></label> <label for="eid" class="form-label"><?=_('Equipment')?></label>
<select name="eid" id="eid" class="form-select"> <select name="eid" id="eid" class="form-select">
<?php
foreach ($opt_equipment as $k => $v) { foreach ($opt_equipment as $k => $v) {
echo '<option value="', $k, '"'; echo '<option value="', $k, '"';
if ($k == $id) { if ($k == $id) {
@@ -232,8 +309,10 @@ foreach ($opt_equipment as $k => $v) {
} }
echo '>', $v, "</option>\n"; echo '>', $v, "</option>\n";
} }
?>
</select> </select>
*/
?>
<div class="container-fluid px-0 my-3"> <div class="container-fluid px-0 my-3">
<button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button> <button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button>
<a href="<?=$g_scriptname?>" class="btn btn-secondary"><?=_('Back')?></a> <a href="<?=$g_scriptname?>" class="btn btn-secondary"><?=_('Back')?></a>
@@ -245,14 +324,17 @@ elseif ($action == ACT_VIEW):
echo '<h2>', _('View Maintenance'), "</h2>\n"; echo '<h2>', _('View Maintenance'), "</h2>\n";
$sql = "SELECT m.activities, m.eid, m.remarks, m.series, m.maintstate, e.ename " // load maintenance record
$sql = "SELECT m.activities, m.eid, m.remarks, m.series, m.maintstate, e.ename, "
. "m.plan_date, m.plan_precision, m.completion_date, m.interval_hours, "
. "m.last_hours "
. "FROM maintenance AS m LEFT OUTER JOIN equipment AS e USING (eid) " . "FROM maintenance AS m LEFT OUTER JOIN equipment AS e USING (eid) "
. "WHERE m.maintid=?"; . "WHERE m.maintid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([$id]); $sth->execute([$id]);
$maint = $sth->fetch(PDO::FETCH_OBJ); $maint = $sth->fetch(PDO::FETCH_OBJ);
if ($maint !== false && isset($maint->eid)) {
if (isset($maint->eid)) { // if available load document references
$sql = "SELECT r.docid, d.filename, d.title, d.hash, d.extension " $sql = "SELECT r.docid, d.filename, d.title, d.hash, d.extension "
. "FROM docref AS r INNER JOIN document AS d USING (docid) " . "FROM docref AS r INNER JOIN document AS d USING (docid) "
. "WHERE r.reftype='equipment' AND r.refid=?"; . "WHERE r.reftype='equipment' AND r.refid=?";
@@ -260,6 +342,7 @@ if (isset($maint->eid)) {
$sth->execute([$maint->eid]); $sth->execute([$maint->eid]);
$docs = $sth->fetchAll(); $docs = $sth->fetchAll();
} else { } else {
$maint = new stdClass();
$maint->ename = _('n/a'); $maint->ename = _('n/a');
unset($docs); unset($docs);
} }
@@ -271,26 +354,48 @@ echo '<div class="col">';
echo '<table class="table">', "\n"; echo '<table class="table">', "\n";
echo '<tr><th>', _('Activities'),"</th><td>", $maint->activities, "</td></tr>\n"; echo '<tr><th>', _('Activities'),"</th><td>", $maint->activities, "</td></tr>\n";
echo '<tr><th>', _('Equipment'),"</th><td>", $maint->ename; echo '<tr><th>', _('Equipment'),"</th><td>", h($maint->ename);
if (isset($maint->eid) and $maint->eid>0) { if (isset($maint->eid) and $maint->eid>0) {
// Link to equipment // Link to equipment
echo ' <a href="equipment.php?f=view&id=', $maint->eid, '"><i class="bi-eye"></i></a>'; echo ' <a href="equipment.php?f=view&id=', $maint->eid, '"><i class="bi-eye"></i></a>';
} }
echo "</td></tr>\n"; echo "</td></tr>\n";
echo '<tr><th>', _('Remarks'),"</th><td>", $maint->remarks, "</td></tr>\n"; echo '<tr><th>', _('Remarks'),"</th><td>", h($maint->remarks), "</td></tr>\n";
echo '<tr><th>', _('Series'),"</th><td>", $maint->series, "</td></tr>\n"; echo '<tr><th>', _('Series'),"</th><td>", $maint->series, "</td></tr>\n";
echo '<tr><th>', _('Interval'),"</th><td>", $maint->interval_hours, " h</td></tr>\n";
echo '<tr><th>', _('Last'),"</th><td>", $maint->last_hours, "</td></tr>\n";
echo '<tr><th>', _('Plan date'),"</th><td>", format_date($maint->plan_date), "</td></tr>\n";
echo '<tr><th>', _('Plan date precision'),"</th><td>", get_enum($maint->plan_precision), "</td></tr>\n";
echo '<tr><th>', _('Completion&nbsp;date'),"</th><td>", format_date($maint->completion_date), "</td></tr>\n";
echo '<tr><th scope="row">', _('State'),"</th><td>", get_enum($maint->maintstate), "</td></tr>\n"; echo '<tr><th scope="row">', _('State'),"</th><td>", get_enum($maint->maintstate), "</td></tr>\n";
// Custom properties
$sql = "SELECT keyname, valstr, valint FROM property WHERE objtype='maint' AND objid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
foreach ($sth->fetchAll() as $row) {
echo "<tr><th>{$row['keyname']}</th><td>";
if (isset($row['valstr'])) {
echo $row['valstr'];
} else {
echo $row['valint'];
}
echo "</td></tr>\n";
}
echo "</table>\n"; echo "</table>\n";
echo '</div>'; // Column break echo '</div>'; // Column break
echo '<div class="col">'; echo '<div class="col">';
// TODO Show documents for equipment // TODO Show documents for equipment
echo "<h4>Documents</h4>\n"; echo '<h4>Documents for ', h($maint->ename), "</h4>\n";
if (isset($docs)) { if (isset($docs)) {
echo '<ul>', "\n"; echo '<ul>', "\n";
foreach ($docs as $d) { foreach ($docs as $d) {
echo '<li>', $d['title'] ?? $d['filename'], ' (', $d['docid'], ")</li>\n"; echo '<li>', $d['title'] ?? $d['filename'], ' (', $d['docid'], ')';
echo ' <a href="documents.php?f=view&id=', $d['docid'], '"><i class="bi-eye"></i></a>';
echo "</li>\n";
} }
echo "</ul>\n"; echo "</ul>\n";
} else { } else {
@@ -329,7 +434,7 @@ echo "</div>\n";
elseif ($action == ACT_EDIT): elseif ($action == ACT_EDIT):
// ========== VARIANT: edit single record ===================================== // ========== VARIANT: edit single record =====================================
$sql = "SELECT activities, eid, remarks, series, maintstate " $sql = "SELECT activities, eid, remarks, series, plan_date, completion_date, maintstate "
. "FROM maintenance " . "FROM maintenance "
. "WHERE maintid=?"; . "WHERE maintid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -341,21 +446,33 @@ echo '<h2>', _('Edit Maintenance'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<?php
form_create_text('activities', _('Activities'), 40, $maint->activities);
form_create_select('eid', _('Equipment'), $opt_equipment, $maint->eid);
form_create_select('series', _('Series'), $g_opt_none + $g_opt_new + $opt_series, $maint->series);
?>
<div class="mb-3"> <div class="mb-3">
<label for="activities" class="form-label"><?=_('Activities')?></label> <label for="interval_hours" class="form-label"><?=_('Interval hours')?></label>
<input type="text" class="form-control" id="activities" name="activities" value="<?=$maint->activities ?>"> <input type="number" class="form-control" id="interval_hours" name="interval_hours" inputmode="numeric" maxlength="6" value="<?=$maint->interval_hours ?>">
</div>
<?php form_create_select('eid', _('Equipment'), $opt_equipment, $maint->eid); ?>
<div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$maint->remarks ?></textarea>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="series" class="form-label"><?=_('Series')?></label> <label for="last_hours" class="form-label"><?=_('Last hours')?></label>
<input type="text" class="form-control" id="series" name="series" maxlength="4" value="<?=$maint->series ?>"> <input type="number" class="form-control" id="last_hours" name="last_hours" inputmode="numeric" maxlength="6" value="<?=$maint->last_hours ?>">
</div>
<div class="mb-3">
<label for="plan_date"><?=_('Plan date')?></label>
<input type="date" class="form-control" id="plan_date" name="plan_date" value="<?=$maint->plan_date ?>">
</div>
<?php
form_create_select('plan_precision', _('Date plan precision'), $opt_planprec, $maint->plan_precision);
?>
<div class="mb-3">
<label for="completion_date"><?=_('Completion date')?></label>
<input type="date" class="form-control" id="completion_date" name="completion_date" value="<?=$maint->completion_date ?>">
</div> </div>
<?php <?php
form_create_select('maintstate', _('Status'), $opt_state, $maint->maintstate); form_create_select('maintstate', _('Status'), $opt_state, $maint->maintstate);
form_create_textarea('remarks', _('Remarks'), 3, 150, $maint->remarks);
form_edit_buttons($g_scriptname, $id); form_edit_buttons($g_scriptname, $id);
echo "</form>\n"; echo "</form>\n";
+1 -1
View File
@@ -16,7 +16,7 @@ require 'header.php';
<p class="p-3 mb-3 bg-info-subtle border border-info-subtle rounded"> <p class="p-3 mb-3 bg-info-subtle border border-info-subtle rounded">
<i class="bi bi-info-circle-fill me-2"></i> <i class="bi bi-info-circle-fill me-2"></i>
Hinweis: Es handelt sich hier um eine Vorschau (Version <?=$g_version?>)!<br> Hinweis: Es handelt sich hier um eine frühe Version (v<?=$g_version?>)!<br>
Einige Funktionen sind noch nicht oder nicht vollständig implementiert. Einige Funktionen sind noch nicht oder nicht vollständig implementiert.
Rückmeldungen sind immer willkommen!</p> Rückmeldungen sind immer willkommen!</p>
+52 -64
View File
@@ -7,7 +7,9 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
// TODO move to somewhere else // TODO move to somewhere else
function format_vals($n, $v1, $v2, $v3) { function format_vals($n, $v1, $v2, $v3) {
@@ -24,7 +26,8 @@ $pagetitle = _('Measurements');
$id = gpc_get_int($_REQUEST, 'id', 0); $id = gpc_get_int($_REQUEST, 'id', 0);
$opt_unit = db_get_options(8); $opt_unit = db_get_options(DD_UNIT);
$opt_category = db_get_options(DD_MEASUREMENT_CATEGORY);
$opt_accuracy = db_load_enum('measurement', 'accuracy', true, true); $opt_accuracy = db_load_enum('measurement', 'accuracy', true, true);
$opt_dimensions = array( $opt_dimensions = array(
1 => _('1D'), 1 => _('1D'),
@@ -51,8 +54,9 @@ switch ($submit = form_get_action()) {
case 'filter': case 'filter':
$flt = array(); $flt = array();
$flt['precision'] = gpc_get_string($_POST, 'flt_precision');
$flt['txt'] = gpc_get_string($_POST, 'flt_txt'); $flt['txt'] = gpc_get_string($_POST, 'flt_txt');
$flt['cat'] = gpc_get_string($_POST, 'flt_cat');
$flt['acc'] = gpc_get_string($_POST, 'flt_acc');
db_save_filter($flt, 207); db_save_filter($flt, 207);
$action = ACT_DEFAULT; $action = ACT_DEFAULT;
break; break;
@@ -101,6 +105,10 @@ switch ($submit = form_get_action()) {
$p[':unit'] = gpc_get_int($_POST, 'unit'); $p[':unit'] = gpc_get_int($_POST, 'unit');
$p[':accuracy'] = gpc_get_string($_POST, 'accuracy'); $p[':accuracy'] = gpc_get_string($_POST, 'accuracy');
$p[':mdate'] = gpc_get_date($_POST, 'mdate'); $p[':mdate'] = gpc_get_date($_POST, 'mdate');
$p[':mcat'] = gpc_get_int($_POST, 'mcat');
if ($p[':mcat'] == -1) {
$p[':mcat'] = NULL;
}
$p[':note'] = gpc_get_string($_POST, 'note'); $p[':note'] = gpc_get_string($_POST, 'note');
$p[':eid'] = gpc_get_int($_POST, 'eid'); $p[':eid'] = gpc_get_int($_POST, 'eid');
if ($p[':eid'] == -1) { if ($p[':eid'] == -1) {
@@ -139,7 +147,7 @@ if ($action == ACT_DEFAULT):
page_caption_search($pagetitle); page_caption_search($pagetitle);
// load filter from db // load filter from db
$flt = db_get_filter($user->id, 207, ['txt']); $flt = db_get_filter($user->id, 207, ['txt', 'cat', 'acc']);
$w = array('(vid=:vid OR vid IS NULL)'); $w = array('(vid=:vid OR vid IS NULL)');
$p = array(':vid' => $user->vid); $p = array(':vid' => $user->vid);
@@ -147,9 +155,20 @@ $p = array(':vid' => $user->vid);
// TODO precision additionally as filter // TODO precision additionally as filter
if (strlen($flt->txt) > 1) { if (strlen($flt->txt) > 1) {
$w[] = 'mname LIKE :txt'; $w[] = 'mname LIKE :txt OR note LIKE :txt';
$p[':txt'] = '%'.$flt->txt.'%'; $p[':txt'] = '%'.$flt->txt.'%';
} }
if ($flt->cat > 0) {
$w[] = 'mcat=:mcat';
$p[':mcat'] = $flt->cat;
} elseif ($flt->mcat == -1) {
$w[] = 'mcat IS NULL';
}
if ($flt->acc > 0) {
$w[] = 'accuracy=:accuracy';
$p[':accuracy'] = $flt->acc;
}
$where = join(' AND ', $w); $where = join(' AND ', $w);
$order = ' ORDER BY mname'; $order = ' ORDER BY mname';
@@ -174,14 +193,15 @@ $opt_special = array(
-1 => _('&horbar; none &horbar;') -1 => _('&horbar; none &horbar;')
); );
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form id="filterform" method="post" action="<?=$g_scriptname?>">
<div id="filter" class="card"> <div id="filter" class="card">
<div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div> <div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div>
<div class="card-body d-flex flex-wrap gap-3"> <div class="card-body d-flex flex-wrap gap-3">
<div class="d-flex flex-nowrap gap-2"> <?php
<label for="flt_txt">Text</label> filter_create_text('flt_txt', _('Text'), $flt->txt, 30, 45);
<input type="text" class="form-control" name="flt_txt" size="15" maxlength="30" value="<?=$flt->txt ?>"> filter_create_select('flt_cat', _('Category'), $g_opt_all + $g_opt_none + $opt_category, $flt->cat);
</div> filter_create_select('flt_acc', _('Accuracy'), $g_opt_all + $opt_accuracy, $flt->acc);
?>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
@@ -252,30 +272,13 @@ echo '<h2>', _('Add measurement'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<div class="mb-3">
<label for="mname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="mname" name="mname" required autofocus>
</div>
<div class="mb-3">
<label for="note" class="form-label"><?=_('Note')?></label>
<input type="text" class="form-control" id="note" name="note">
</div>
<?php <?php
form_create_text('mname', _('Name'), 80, TRUE, TRUE);
form_create_text('note', _('Note'), 80);
form_create_select('nval', _('Dimensions'), $opt_dimensions); form_create_select('nval', _('Dimensions'), $opt_dimensions);
?> form_create_numeric('val1', _('Value 1'));
<div class="mb-3"> form_create_numeric('val2', _('Value 2'));
<label for="val1" class="form-label"><?=_('Value 1')?></label> form_create_numeric('val3', _('Value 3'));
<input type="text" class="form-control" id="val1" name="val1">
</div>
<div class="mb-3">
<label for="val2" class="form-label"><?=_('Value 2')?></label>
<input type="text" class="form-control" id="val1" name="val2">
</div>
<div class="mb-3">
<label for="val3" class="form-label"><?=_('Value 3')?></label>
<input type="text" class="form-control" id="val3" name="val3">
</div>
<?php
form_create_select('unit', _('Unit'), $opt_unit); form_create_select('unit', _('Unit'), $opt_unit);
form_create_select('accuracy', _('Accuracy'), $opt_accuracy); form_create_select('accuracy', _('Accuracy'), $opt_accuracy);
form_create_select('eid', _('Equipment'), $opt_equipment, $id); form_create_select('eid', _('Equipment'), $opt_equipment, $id);
@@ -290,7 +293,7 @@ form_create_select('eid', _('Equipment'), $opt_equipment, $id);
elseif ($action == ACT_VIEW): elseif ($action == ACT_VIEW):
// ========== VARIANT: view single record ===================================== // ========== VARIANT: view single record =====================================
$sql = "SELECT mname, unit, nval, val1, val2, val3, accuracy, mdate, note, eid " $sql = "SELECT mname, unit, nval, val1, val2, val3, accuracy, mdate, mcat, note, eid "
. "FROM measurement " . "FROM measurement "
. "WHERE mid=?"; . "WHERE mid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -300,15 +303,16 @@ $measurement = $sth->fetch(PDO::FETCH_OBJ);
echo '<h2>', _('Measurement'), "</h2>\n"; echo '<h2>', _('Measurement'), "</h2>\n";
echo '<table class="table">', "\n"; echo '<table class="table">', "\n";
echo '<tr><th style="width:20%">', _('Name'),"</th><td>", $measurement->mname, "</td></tr>\n"; echo '<tr><th style="width:20%">', _('Name'),"</th><td>", h($measurement->mname), "</td></tr>\n";
echo '<tr><th>', _('Unit'),"</th><td>", $opt_unit[$measurement->unit], "</td></tr>\n"; echo '<tr><th>', _('Unit'), '</th><td>', $opt_unit[$measurement->unit], "</td></tr>\n";
echo '<tr><th>', _('Values'),"</th><td>$measurement->nval</td></tr>\n"; echo '<tr><th>', _('Values'), '</th><td>', $measurement->nval, "</td></tr>\n";
echo '<tr><th>', _('Value 1'),"</th><td>$measurement->val1</td></tr>\n"; echo '<tr><th>', _('Value 1'), '</th><td>', $measurement->val1, "</td></tr>\n";
echo '<tr><th>', _('Value 2'),"</th><td>$measurement->val2</td></tr>\n"; echo '<tr><th>', _('Value 2'), '</th><td>', $measurement->val2, "</td></tr>\n";
echo '<tr><th>', _('Value 3'),"</th><td>$measurement->val3</td></tr>\n"; echo '<tr><th>', _('Value 3'), '</th><td>', $measurement->val3, "</td></tr>\n";
echo '<tr><th>', _('Accuracy'),"</th><td>$measurement->accuracy</td></tr>\n"; echo '<tr><th>', _('Accuracy'), '</th><td>', get_enum($measurement->accuracy), "</td></tr>\n";
echo '<tr><th>', _('Date'),"</th><td>$measurement->mdate</td></tr>\n"; echo '<tr><th>', _('Date'), '</th><td>', format_date($measurement->mdate), "</td></tr>\n";
echo '<tr><th>', _('Note'),"</th><td>$measurement->note</td></tr>\n"; echo '<tr><th>', _('Note'), '</th><td>', h($measurement->note), "</td></tr>\n";
echo '<tr><th>', _('Category'),"</th><td>", $opt_category[$measurement->mcat] ?? 'n/a', "</td></tr>\n";
echo '<tr><th>', _('Equipment'), '</th><td>', $opt_equipment[$measurement->eid], "</td></tr>\n"; echo '<tr><th>', _('Equipment'), '</th><td>', $opt_equipment[$measurement->eid], "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
@@ -318,7 +322,7 @@ form_view_buttons($g_scriptname, $id);
elseif ($action == ACT_EDIT): elseif ($action == ACT_EDIT):
// ========== VARIANT: edit single record ===================================== // ========== VARIANT: edit single record =====================================
$sql = "SELECT mname, nval, val1, val2, val3, unit, accuracy, note, eid " $sql = "SELECT mname, nval, val1, val2, val3, unit, accuracy, note, eid, mcat "
. "FROM measurement " . "FROM measurement "
. "WHERE mid=?"; . "WHERE mid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -329,32 +333,16 @@ echo '<h2>', _('Edit measurement'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3">
<label for="mname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="name" name="mname" value="<?=$measurement->mname ?>">
</div>
<div class="mb-3">
<label for="note" class="form-label"><?=_('Note')?></label>
<input type="text" class="form-control" id="note" name="note" value="<?=$measurement->note ?>">
</div>
<?php <?php
form_create_text('mname', _('Name'), 80, $measurement->mname, TRUE, TRUE);
form_create_text('note', _('Note'), 80, $measurement->note);
form_create_select('nval', _('Dimensions'), $opt_dimensions, $measurement->nval); form_create_select('nval', _('Dimensions'), $opt_dimensions, $measurement->nval);
?> form_create_numeric('val2', _('Value 2'), $measurement->val1);
<div class="mb-3"> form_create_numeric('val2', _('Value 2'), $measurement->val2);
<label for="val1"><?=_('Value 1')?></label> form_create_numeric('val2', _('Value 2'), $measurement->val3);
<input type="number" min="0" class="form-control" id="val1" name="val1" value="<?=$measurement->val1 ?>">
</div>
<div class="mb-3">
<label for="val2"><?=_('Value 2')?></label>
<input type="number" min="0" class="form-control" id="val2" name="val2" value="<?=$measurement->val2 ?>">
</div>
<div class="mb-3">
<label for="val3"><?=_('Value 3')?></label>
<input type="number" min="0" class="form-control" id="val3" name="val3" value="<?=$measurement->val3 ?>">
</div>
<?php
form_create_select('unit', _('Unit'), $opt_unit, $measurement->unit); form_create_select('unit', _('Unit'), $opt_unit, $measurement->unit);
form_create_select('accuracy', _('Accuracy'), $opt_accuracy, $measurement->accuracy); form_create_select('accuracy', _('Accuracy'), $opt_accuracy, $measurement->accuracy);
form_create_select('mcat', _('Category'), $g_opt_none + $opt_category, $measurement->mcat);
form_create_select('eid', _('Equipment'), $opt_equipment, $measurement->eid); form_create_select('eid', _('Equipment'), $opt_equipment, $measurement->eid);
form_edit_buttons($g_scriptname, $id); form_edit_buttons($g_scriptname, $id);
+33 -7
View File
@@ -7,7 +7,9 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Note'); $pagetitle = _('Note');
@@ -30,6 +32,7 @@ switch ($submit = form_get_action()) {
$p[':notetype'] = gpc_get_enum($_POST, 'notetype', $opt_notetype, 'task'); $p[':notetype'] = gpc_get_enum($_POST, 'notetype', $opt_notetype, 'task');
$p[':refid'] = gpc_get_int($_POST, 'refid'); $p[':refid'] = gpc_get_int($_POST, 'refid');
$p[':annotation'] = gpc_get_string($_POST, 'annotation'); $p[':annotation'] = gpc_get_string($_POST, 'annotation');
$p[':created_by'] = $user->id;
$id = db_exec_insert('note', $p); $id = db_exec_insert('note', $p);
$caller = gpc_get_string($_POST, 'caller'); $caller = gpc_get_string($_POST, 'caller');
$callid = $p[':refid']; $callid = $p[':refid'];
@@ -83,13 +86,18 @@ if ($action == ACT_DEFAULT):
echo '<h1>', $pagetitle, "</h1>\n"; echo '<h1>', $pagetitle, "</h1>\n";
// TODO This is not so beautiful. Make it prettier
$sql = "SELECT n.noteid, n.notetype, n.refid," $sql = "SELECT n.noteid, n.notetype, n.refid,"
. " IF(CHAR_LENGTH(n.annotation) > 60, CONCAT(LEFT(n.annotation, 60), '&hellip;'), n.annotation) AS annotation " . " IF(CHAR_LENGTH(n.annotation) > 60, CONCAT(LEFT(n.annotation, 60), '&hellip;'), n.annotation) AS annotation "
. "FROM note AS n JOIN task AS t ON (n.notetype='task' AND n.refid=t.taskid AND t.vid=:vid) " . "FROM note AS n LEFT OUTER JOIN task AS t ON (n.notetype='task' AND n.refid=t.taskid AND t.vid=:vid) "
. "UNION " . "UNION "
. "SELECT n.noteid, n.notetype, n.refid," . "SELECT n.noteid, n.notetype, n.refid,"
. " IF(CHAR_LENGTH(n.annotation) > 60, CONCAT(LEFT(n.annotation, 60), '&hellip;'), n.annotation) AS annotation " . " IF(CHAR_LENGTH(n.annotation) > 60, CONCAT(LEFT(n.annotation, 60), '&hellip;'), n.annotation) AS annotation "
. "FROM note AS n JOIN maintenance AS m ON (n.notetype='maint' AND n.refid=m.maintid AND m.vid=:vid) " . "FROM note AS n LEFT OUTER JOIN maintenance AS m ON (n.notetype='maint' AND n.refid=m.maintid AND m.vid=:vid) "
. "UNION "
. "SELECT n.noteid, n.notetype, n.refid,"
. " IF(CHAR_LENGTH(n.annotation) > 60, CONCAT(LEFT(n.annotation, 60), '&hellip;'), n.annotation) AS annotation "
. "FROM note AS n LEFT OUTER JOIN equipment AS e ON (n.notetype='equip' AND n.refid=e.eid AND e.vid=:vid) "
. "ORDER BY noteid"; . "ORDER BY noteid";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([':vid' => $user->vid]); $sth->execute([':vid' => $user->vid]);
@@ -99,6 +107,7 @@ $res = $sth->fetchAll();
<table class="table table-striped"> <table class="table table-striped">
<thead> <thead>
<tr> <tr>
<th>#</th>
<th><?=_('ID')?></th> <th><?=_('ID')?></th>
<th><?=_('Reference')?></th> <th><?=_('Reference')?></th>
<th><?=_('Type')?></th> <th><?=_('Type')?></th>
@@ -107,13 +116,21 @@ $res = $sth->fetchAll();
</thead> </thead>
<?php <?php
$i = 0;
foreach ($res as $row) { foreach ($res as $row) {
$i++; // record number
echo "<tr>\n"; echo "<tr>\n";
echo '<td>', $i;
echo '<a class="text-nowrap" title="', _('View'), '" href="', $g_scriptname, '?f=view&id=', $row['noteid'], '"><i class="bi bi-eye ms-2"></i></a>', "\n";
echo "</td>\n";
echo "<td>", $row['noteid'], "</td>\n"; echo "<td>", $row['noteid'], "</td>\n";
echo "<td>", $row['refid'], "</td>\n"; echo "<td>", $row['refid'], "</td>\n";
echo "<td>", $row['notetype'], "</td>\n"; echo "<td>", $row['notetype'], "</td>\n";
echo "<td>", $row['annotation'], "</td>\n"; echo "<td>", $row['annotation'], "</td>\n";
form_action_buttons($g_scriptname, $row['noteid']); // Edit current record button
echo '<td>';
echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['noteid'], '"><i class="bi-pencil"></i></a>', "\n";
echo "</td>\n";
echo "</tr>\n"; echo "</tr>\n";
} }
@@ -130,7 +147,7 @@ echo '<h2>', _('Add Note'), "</h2>\n";
$notetype = gpc_get_enum($_REQUEST, 't', $opt_notetype); $notetype = gpc_get_enum($_REQUEST, 't', $opt_notetype);
// get task info for reference // get object info for reference
if ($notetype == 'task') { if ($notetype == 'task') {
$sql = "SELECT taskname FROM task WHERE taskid=?"; $sql = "SELECT taskname FROM task WHERE taskid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -143,6 +160,12 @@ if ($notetype == 'task') {
$sth->execute([$id]); $sth->execute([$id]);
$activities = $sth->fetchColumn(); $activities = $sth->fetchColumn();
echo '<h3>', sprintf(_('Maintenance: %s'), $activities), "</h3>\n"; echo '<h3>', sprintf(_('Maintenance: %s'), $activities), "</h3>\n";
} elseif ($notetype == 'equip') {
$sql = "SELECT ename FROM equipment WHERE eid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
$ename = $sth->fetchColumn();
echo '<h3>', sprintf(_('Equipment: %s'), $ename), "</h3>\n";
} }
?> ?>
@@ -165,7 +188,9 @@ elseif ($action == ACT_VIEW):
echo '<h2>', _('View Note'), "</h2>\n"; echo '<h2>', _('View Note'), "</h2>\n";
$sql = "SELECT refid, notetype, annotation FROM note WHERE noteid=?"; $sql = "SELECT n.refid, n.notetype, n.annotation, n.created_at, u.displayname "
. "FROM note AS n LEFT OUTER JOIN user AS u ON (n.created_by=u.userid) "
. "WHERE noteid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([$id]); $sth->execute([$id]);
$note = $sth->fetch(PDO::FETCH_OBJ); $note = $sth->fetch(PDO::FETCH_OBJ);
@@ -178,9 +203,10 @@ echo '<table class="table">', "\n";
echo '<tr><th>', _('Reference'),"</th><td>", $note->refid, "</td></tr>\n"; echo '<tr><th>', _('Reference'),"</th><td>", $note->refid, "</td></tr>\n";
echo '<tr><th>', _('Type'),"</th><td>", $note->notetype, "</td></tr>\n"; echo '<tr><th>', _('Type'),"</th><td>", $note->notetype, "</td></tr>\n";
echo '<tr><th>', _('Annotation'),"</th><td>", nl2br($note->annotation), "</td></tr>\n"; echo '<tr><th>', _('Annotation'),"</th><td>", nl2br($note->annotation), "</td></tr>\n";
echo '<tr><th>', _('Created at'),"</th><td>", format_datetime($note->created_at), "</td></tr>\n";
echo '<tr><th>', _('Created by'),"</th><td>", h($note->displayname), "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
$link = $note->notetype == 'task' ? 'task.php' : 'maintenance.php'; $link = $note->notetype == 'task' ? 'task.php' : 'maintenance.php';
// echo '<p><a href="', $link, '?f=view&id=', $note->refid, '">', _('Parent'), "</a></p>\n"; // echo '<p><a href="', $link, '?f=view&id=', $note->refid, '">', _('Parent'), "</a></p>\n";
form_view_buttons($g_scriptname, $id, $link.'?f=view&id='.$note->refid); form_view_buttons($g_scriptname, $id, $link.'?f=view&id='.$note->refid);
@@ -199,7 +225,7 @@ echo '<h2>', _('Edit Note'), "</h2>\n";
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3"> <div class="mb-3">
<label for="annotation" class="form-label"><?=_('Annotation')?></label> <label for="annotation" class="form-label"><?=_('Annotation')?></label>
<textarea class="form-control" id="annotation" name="annotation" rows="5" autofocus><?=$note->annotation;?></textarea> <textarea class="form-control" id="annotation" name="annotation" rows="5" autofocus><?=h($note->annotation);?></textarea>
</div> </div>
<?php <?php
form_edit_buttons($g_scriptname, $id); form_edit_buttons($g_scriptname, $id);
+36 -22
View File
@@ -7,18 +7,24 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Projects'); $pagetitle = _('Projects');
$id = gpc_get_int($_REQUEST, 'id', 0); $id = gpc_get_int($_REQUEST, 'id', 0);
/* OLD
$sql = "SELECT userid, displayname FROM user WHERE userid>0"; $sql = "SELECT userid, displayname FROM user WHERE userid>0";
$sth = $pdo->query($sql); $sth = $pdo->query($sql);
$opt_user = array(); $opt_user = array();
foreach ($sth->fetchAll() as $row) { foreach ($sth->fetchAll() as $row) {
$opt_user[$row['userid']] = $row['displayname']; $opt_user[$row['userid']] = $row['displayname'];
} }
*/
$opt_user = db_get_opt_user();
$opt_state = db_load_enum('project', 'projstate', true, true); $opt_state = db_load_enum('project', 'projstate', true, true);
/* Nur für choices benötigt /* Nur für choices benötigt
@@ -64,6 +70,7 @@ switch ($submit = form_get_action()) {
$p[':responsible'] = gpc_get_int($_POST, 'responsible'); $p[':responsible'] = gpc_get_int($_POST, 'responsible');
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150); $p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
$id = db_exec_insert('project', $p); $id = db_exec_insert('project', $p);
db_set_revision('table', TBL_PROJECTS);
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -147,7 +154,8 @@ $lastpage = ceil($numrows/$rows_pp);
// $grandtotal = $pdo->query("SELECT COUNT(*) FROM project WHERE " . $where)->fetchColumn(); // $grandtotal = $pdo->query("SELECT COUNT(*) FROM project WHERE " . $where)->fetchColumn();
$sql = "SELECT projid, projname, startdate, duration, projstate, remarks " $sql = "SELECT projid, projname, startdate, duration, projstate, "
. " IF(CHAR_LENGTH(remarks)>30, CONCAT(LEFT(remarks, 30), '\u{2026}'), remarks) AS remarks "
. "FROM project"; . "FROM project";
$sql .= " WHERE " . $where; $sql .= " WHERE " . $where;
$sql .= $order; $sql .= $order;
@@ -165,17 +173,11 @@ $res = $sth->fetchAll();
<div id="filter" class="card"> <div id="filter" class="card">
<div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div> <div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div>
<div class="card-body d-flex flex-wrap gap-3"> <div class="card-body d-flex flex-wrap gap-3">
<div class="d-flex flex-nowrap gap-2">
<label for="flt_name"><?=_('Name')?></label>
<input type="text" class="form-control" name="flt_name" size="15" maxlength="30" value="<?=$flt->name ?? '';?>">
</div>
<?php <?php
filter_create_text('flt_name', _('Name'), $flt->name, 15, 30);
filter_create_select('flt_state', _('State'), $g_opt_all + $opt_state, $flt->state ?? -2, FALSE); filter_create_select('flt_state', _('State'), $g_opt_all + $opt_state, $flt->state ?? -2, FALSE);
filter_create_text('flt_remarks', _('Remarks'), $flt->remarks, 15, 30);
?> ?>
<div class="d-flex flex-nowrap gap-2">
<label for="flt_remarks"><?=_('Remarks')?></label>
<input type="text" class="form-control" name="flt_remarks" size="15" maxlength="30" value="<?=$flt->remarks ?? '' ?>">
</div>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
@@ -209,13 +211,13 @@ foreach ($res as $row) {
echo '<td>', $i; echo '<td>', $i;
echo '<a class="text-nowrap" title="', _('View'), '" href="', $g_scriptname, '?f=view&id=', $row['projid'], '"><i class="bi bi-eye ms-2"></i></a>', "\n"; echo '<a class="text-nowrap" title="', _('View'), '" href="', $g_scriptname, '?f=view&id=', $row['projid'], '"><i class="bi bi-eye ms-2"></i></a>', "\n";
echo "</td>\n"; echo "</td>\n";
echo "<td>". $row['projname'] ."</td>\n"; echo '<td>', $row['projname'], "</td>\n";
echo "<td>". $row['startdate'] ."</td>\n"; echo '<td>', format_date($row['startdate']), "</td>\n";
echo "<td>". $row['duration'] ."</td>\n"; echo '<td>', $row['duration'], "</td>\n";
echo "<td>". get_enum($row['projstate']) ."</td>\n"; echo '<td>', get_enum($row['projstate']), "</td>\n";
echo "<td>". $row['remarks'] ."</td>\n"; echo '<td>', h($row['remarks']), "</td>\n";
// Edit current record button // Edit current record button
echo "<td>"; echo '<td>';
echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['projid'], '"><i class="bi-pencil"></i></a>', "\n"; echo '<a title="', _('Edit'), '" href="', $g_scriptname, '?f=edit&id=', $row['projid'], '"><i class="bi-pencil"></i></a>', "\n";
echo "</td>\n"; echo "</td>\n";
@@ -307,14 +309,29 @@ $sth->execute([$id]);
$project = $sth->fetch(PDO::FETCH_OBJ); $project = $sth->fetch(PDO::FETCH_OBJ);
echo "<h2>", $project->projname, "</h2>\n"; echo "<h2>", $project->projname, "</h2>\n";
echo '<table class="table">', "\n"; echo '<table class="table">', "\n";
echo '<tr><th scope="row" style="width:20%">', _('Name'),"</th><td>", $project->projname, "</td></tr>\n"; echo '<tr><th scope="row" style="width:20%">', _('Name'),"</th><td>", h($project->projname), "</td></tr>\n";
echo '<tr><th scope="row">', _('Responsible'),"</th><td>", $opt_user[$project->responsible], "</td></tr>\n"; echo '<tr><th scope="row">', _('Responsible'),"</th><td>", $opt_user[$project->responsible], "</td></tr>\n";
echo '<tr><th scope="row">', _('Start date'),"</th><td>", $project->startdate, "</td></tr>\n"; echo '<tr><th scope="row">', _('Start date'),"</th><td>", $project->startdate, "</td></tr>\n";
echo '<tr><th scope="row">', _('Duration'),"</th><td>", $project->duration, "</td></tr>\n"; echo '<tr><th scope="row">', _('Duration'),"</th><td>", $project->duration, "</td></tr>\n";
echo '<tr><th scope="row">', _('Costs plan'),"</th><td>", format_currency($project->costs_plan), "</td></tr>\n"; echo '<tr><th scope="row">', _('Costs plan'),"</th><td>", format_currency($project->costs_plan), "</td></tr>\n";
echo '<tr><th scope="row">', _('Costs final'),"</th><td>", format_currency($project->costs_final), "</td></tr>\n"; echo '<tr><th scope="row">', _('Costs final'),"</th><td>", format_currency($project->costs_final), "</td></tr>\n";
echo '<tr><th scope="row">', _('State'),"</th><td>", get_enum($project->projstate), "</td></tr>\n"; echo '<tr><th scope="row">', _('State'),"</th><td>", get_enum($project->projstate), "</td></tr>\n";
echo '<tr><th scope="row">', _('Remarks'),"</th><td>", nl2br($project->remarks), "</td></tr>\n"; echo '<tr><th scope="row">', _('Remarks'),"</th><td>", h($project->remarks, br:true), "</td></tr>\n";
// Custom properties go here
$sql = "SELECT keyname, valstr, valint FROM property WHERE objtype='proj' AND objid=?";
$sth = $pdo->prepare($sql);
$sth->execute([$id]);
foreach ($sth->fetchAll() as $row) {
echo "<tr><th>{$row['keyname']}</th><td>";
if (isset($row['valstr'])) {
echo $row['valstr'];
} else {
echo $row['valint'];
}
echo "</td></tr>\n";
}
echo "</table>\n"; echo "</table>\n";
form_view_buttons($g_scriptname, $id); form_view_buttons($g_scriptname, $id);
@@ -373,11 +390,8 @@ $project = $sth->fetch(PDO::FETCH_OBJ);
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3">
<label for="projname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="projname" name="projname" value="<?=$project->projname ?>">
</div>
<?php <?php
form_create_text('projname', _('Name'), 40, $project->projname, TRUE, TRUE);
form_create_select('responsible', _('Responsible'), $opt_user, $project->responsible); form_create_select('responsible', _('Responsible'), $opt_user, $project->responsible);
?> ?>
<div class="mb-3"> <div class="mb-3">
@@ -401,7 +415,7 @@ form_create_select('projstate', _('Status'), $opt_state, $project->projstate);
?> ?>
<div class="mb-3"> <div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label> <label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$project->remarks ?></textarea> <textarea class="form-control" id="remarks" name="remarks" rows="3"><?=h($project->remarks)?></textarea>
</div> </div>
<button type="submit" name="submit[update]" class="btn btn-primary"><?=_('Save')?></button> <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> <a href="<?=$g_scriptname?>?f=view&id=<?=$id?>" class="btn btn-secondary"><?=_('Back')?></a>
+19 -13
View File
@@ -7,15 +7,17 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle=_('Provisions'); $pagetitle=_('Provisions');
$id = gpc_get_int($_REQUEST, 'id', 0); $id = gpc_get_int($_REQUEST, 'id', 0);
$opt_storage = db_get_opt_storage($user->vid); $opt_storage = db_get_opt_storage($user->vid);
$opt_category = db_get_options(5); $opt_category = db_get_options(DD_PROVISION_CATEGORY);
$opt_unit = db_get_options(6); $opt_unit = db_get_options(DD_PROVISION_UNIT);
// ========== ACTIONS START =================================================== // ========== ACTIONS START ===================================================
@@ -62,8 +64,8 @@ switch ($submit = form_get_action()) {
$p[':weight_net'] = min(gpc_get_float($_POST, 'weight_net'), 999.99); $p[':weight_net'] = min(gpc_get_float($_POST, 'weight_net'), 999.99);
$p[':unit'] = gpc_get_int($_POST, 'unit'); $p[':unit'] = gpc_get_int($_POST, 'unit');
$p[':calories'] = gpc_get_uint($_POST, 'calories'); $p[':calories'] = gpc_get_uint($_POST, 'calories');
$p[':storedate'] = gpc_get_string($_POST, 'storedate'); $p[':storedate'] = gpc_get_date($_POST, 'storedate');
$p[':shelflife'] = gpc_get_string($_POST, 'shelflife'); $p[':shelflife'] = gpc_get_date($_POST, 'shelflife');
$p[':price'] = gpc_get_currency($_POST, 'price'); $p[':price'] = gpc_get_currency($_POST, 'price');
$p[':sid'] = gpc_get_int($_POST, 'sid'); $p[':sid'] = gpc_get_int($_POST, 'sid');
if ($p[':sid'] <= 0) $p[':sid'] = NULL; if ($p[':sid'] <= 0) $p[':sid'] = NULL;
@@ -101,7 +103,7 @@ if ($action == ACT_DEFAULT):
page_caption_search($pagetitle); page_caption_search($pagetitle);
// load filter from db // load filter from db
$flt = db_get_filter($user->id, 202); $flt = db_get_filter($user->id, 202, ['cat','txt']);
$w = array('(vid=:vid OR sid IS NULL)'); $w = array('(vid=:vid OR sid IS NULL)');
$p = array(':vid' => $user->vid); $p = array(':vid' => $user->vid);
@@ -159,11 +161,8 @@ $res = $sth->fetchAll();
<div class="card-body d-flex flex-wrap gap-3"> <div class="card-body d-flex flex-wrap gap-3">
<?php <?php
filter_create_select('flt_cat', _('Category'), $g_opt_all + $g_opt_none + $opt_category, $flt->cat); filter_create_select('flt_cat', _('Category'), $g_opt_all + $g_opt_none + $opt_category, $flt->cat);
filter_create_text('flt_txt', _('Text'), $flt->txt, 15, 30);
?> ?>
<div class="d-flex flex-nowrap gap-2">
<label for="flt_txt">Text</label>
<input type="text" class="form-control" name="flt_txt" maxlength="30" value="<?=$flt->txt;?>">
</div>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
@@ -288,11 +287,11 @@ echo "<tr><th>", _('Weight net'), "</th><td>", format_float($prov->weight_net, 2
echo '<tr><th>', _('Unit'),"</th><td>", $opt_unit[$prov->unit], "</td></tr>\n"; echo '<tr><th>', _('Unit'),"</th><td>", $opt_unit[$prov->unit], "</td></tr>\n";
echo "<tr><th>", _('Calories'), "</th><td>", $prov->calories, " kcal</td></tr>\n"; echo "<tr><th>", _('Calories'), "</th><td>", $prov->calories, " kcal</td></tr>\n";
echo '<tr><th>', _('Category'),"</th><td>", $opt_category[$prov->provcat] ?? 'n/a', "</td></tr>\n"; echo '<tr><th>', _('Category'),"</th><td>", $opt_category[$prov->provcat] ?? 'n/a', "</td></tr>\n";
echo '<tr><th>', _('Storedate'),"</th><td>", $prov->storedate, "</td></tr>\n"; echo '<tr><th>', _('Storedate'),"</th><td>", format_date($prov->storedate), "</td></tr>\n";
echo '<tr><th>', _('Shelflife'),"</th><td>", $prov->shelflife, "</td></tr>\n"; echo '<tr><th>', _('Shelflife'),"</th><td>", format_date($prov->shelflife), "</td></tr>\n";
echo '<tr><th>', _('Price'), "</th><td>", format_currency($prov->price), "</td></tr>\n"; echo '<tr><th>', _('Price'), "</th><td>", format_currency($prov->price), "</td></tr>\n";
echo '<tr><th>', _('Storage'),"</th><td>", ($opt_storage[$prov->sid] ?? ''), "</td></tr>\n"; echo '<tr><th>', _('Storage'),"</th><td>", ($opt_storage[$prov->sid] ?? ''), "</td></tr>\n";
echo '<tr><th>', _('Remarks'),"</th><td>", nl2br($prov->remarks), "</td></tr>\n"; echo '<tr><th>', _('Remarks'),"</th><td>", h($prov->remarks, br:true), "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
form_view_buttons($g_scriptname, $id); form_view_buttons($g_scriptname, $id);
@@ -359,7 +358,7 @@ form_create_select('sid', _('Storage'), $g_opt_none + $opt_storage, $prov->sid);
?> ?>
<div class="mb-3"> <div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label> <label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3" maxlength="150"><?=$prov->remarks ?></textarea> <textarea class="form-control" id="remarks" name="remarks" rows="3" maxlength="150"><?=h($prov->remarks)?></textarea>
</div> </div>
<?php <?php
form_edit_buttons($g_scriptname, $id); form_edit_buttons($g_scriptname, $id);
@@ -379,6 +378,13 @@ elseif ($action == ACT_VIEW_LIST):
echo '<h2>', _('Shopping list'), "</h2>\n"; echo '<h2>', _('Shopping list'), "</h2>\n";
// TODO Distinguish between provisions belonging to the boat and provisions
// that are freely available.
// - storage with vid
// - box in storage with vid
// - box without sid is free
// - prov without sid and boxid is free
$sql = "SELECT provid, provname, unit, target - number AS buy " $sql = "SELECT provid, provname, unit, target - number AS buy "
. "FROM provisions " . "FROM provisions "
. "WHERE target IS NOT NULL AND number < target " . "WHERE target IS NOT NULL AND number < target "
+2
View File
@@ -7,7 +7,9 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Search'); $pagetitle = _('Search');
+36 -15
View File
@@ -7,7 +7,9 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Settings'); $pagetitle = _('Settings');
@@ -22,6 +24,11 @@ switch ($submit = form_get_action()) {
// global settings // global settings
if ($user->role == 'captain') { if ($user->role == 'captain') {
$p[':userid'] = 0; $p[':userid'] = 0;
$p[':sno'] = 4;
$p[':valstr'] = gpc_get_string($_POST, 'currsym', 3, '€');
db_exec_update('settings', $p, $pk);
$p[':valstr'] = NULL;
// image dimensions
$p[':sno'] = 20; $p[':sno'] = 20;
$p[':valint'] = gpc_get_int($_POST, 'maximgx'); $p[':valint'] = gpc_get_int($_POST, 'maximgx');
db_exec_update('settings', $p, $pk); db_exec_update('settings', $p, $pk);
@@ -80,13 +87,17 @@ if ($res = $sth->fetch(PDO::FETCH_NUM)) {
} }
$curdate = new DateTime(); $curdate = new DateTime();
$opt_datefmt = array( $opt_datefmt = array();
foreach ($g_opt_datefmt as $format => $description) {
$opt_datefmt[$format] = $description . $curdate->format(' - ' . $format);
}
/* $opt_datefmt = array(
'Y-m-d' => _('YYYY-MM-DD'). $curdate->format(' - Y-m-d'), 'Y-m-d' => _('YYYY-MM-DD'). $curdate->format(' - Y-m-d'),
'Y/m/d' => _('YYYY/MM/DD'). $curdate->format(' - Y/m/d'), 'Y/m/d' => _('YYYY/MM/DD'). $curdate->format(' - Y/m/d'),
'd.m.Y' => _('DD.MM.YYYY'). $curdate->format(' - d.m.Y'), 'd.m.Y' => _('DD.MM.YYYY'). $curdate->format(' - d.m.Y'),
'd/m/Y' => _('DD/MM/YYYY'). $curdate->format(' - d/m/Y'), 'd/m/Y' => _('DD/MM/YYYY'). $curdate->format(' - d/m/Y'),
'm-d-Y' => _('MM/DD/YYYY'). $curdate->format(' - m-d-Y') 'm-d-Y' => _('MM-DD-YYYY'). $curdate->format(' - m-d-Y')
); ); */
$rowspp = 10; $rowspp = 10;
$sql = "SELECT valint FROM settings WHERE userid=? AND sno=10"; $sql = "SELECT valint FROM settings WHERE userid=? AND sno=10";
@@ -101,9 +112,6 @@ if ($res = $sth->fetch(PDO::FETCH_NUM)) {
$sth->execute([$user->id, $rowspp]); $sth->execute([$user->id, $rowspp]);
} }
$maximgx = $pdo->query("SELECT valint FROM settings WHERE userid=0 AND sno=20")->fetchColumn();
$maximgy = $pdo->query("SELECT valint FROM settings WHERE userid=0 AND sno=21")->fetchColumn();
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<h2><?=_('for current user')?></h2> <h2><?=_('for current user')?></h2>
@@ -121,16 +129,26 @@ for ($i = 1; $i <= 6; $i++) {
} }
form_create_select('datefmt', _('Date format'), $opt_datefmt, $datefmt); form_create_select('datefmt', _('Date format'), $opt_datefmt, $datefmt);
?> form_create_numeric('rowspp', _('Number of rows per page'), $rowspp, 5, 100, 1);
<div class="mb-3">
/* <div class="mb-3">
<label for="rowspp" class="form-label"><?=_('Number of rows per page')?></label> <label for="rowspp" class="form-label"><?=_('Number of rows per page')?></label>
<input type="text" class="form-control" id="rowspp" name="rowspp" maxlength="3" value=<?=$rowspp?>> <input type="text" class="form-control" id="rowspp" name="rowspp" maxlength="3" value=<?=$rowspp?>>
</div> </div> */
<?php
// limit global settings for captain only // limit global settings for captain only
if ($user->role == 'captain'): if ($user->role == 'captain') {
?> echo '<h2>', _('global for all users'), "</h2>\n";
<h2><?=_('global for all users')?></h2>
$currsym = $pdo->query("SELECT valstr FROM settings WHERE userid=0 AND sno=4")->fetchColumn();
$maximgx = $pdo->query("SELECT valint FROM settings WHERE userid=0 AND sno=20")->fetchColumn();
$maximgy = $pdo->query("SELECT valint FROM settings WHERE userid=0 AND sno=21")->fetchColumn();
/*
<div class="mb-3">
<label for="currsym" class="form-label"><?=_('Currency symbol')?></label>
<input type="text" class="form-control" id="currsym" name="currsym" maxlength="3" value=<?=$currsym?>>
</div>
<div class="mb-3"> <div class="mb-3">
<label for="maximgx" class="form-label"><?=_('Maximal image width')?></label> <label for="maximgx" class="form-label"><?=_('Maximal image width')?></label>
<input type="text" class="form-control" id="maximgx" name="maximgx" maxlength="4" value=<?=$maximgx?>> <input type="text" class="form-control" id="maximgx" name="maximgx" maxlength="4" value=<?=$maximgx?>>
@@ -139,8 +157,11 @@ if ($user->role == 'captain'):
<label for="maximgy" class="form-label"><?=_('Maximal image height')?></label> <label for="maximgy" class="form-label"><?=_('Maximal image height')?></label>
<input type="text" class="form-control" id="maximgy" name="maximgy" maxlength="4" value=<?=$maximgy?>> <input type="text" class="form-control" id="maximgy" name="maximgy" maxlength="4" value=<?=$maximgy?>>
</div> </div>
<?php */
endif; form_create_text('currsym', _('Currency symbol'), 3, $currsym);
form_create_numeric('maximgx', _('Maximal image width'), $maximgy, 200, 4096, 1);
form_create_numeric('maximgy', _('Maximal image height'), $maximgy, 200, 4096, 1);
}
?> ?>
<div class="container-fluid px-0 my-3"> <div class="container-fluid px-0 my-3">
<button type="submit" name="submit[update]" class="btn btn-primary"><?=_('Save')?></button> <button type="submit" name="submit[update]" class="btn btn-primary"><?=_('Save')?></button>
+63 -46
View File
@@ -7,13 +7,15 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Storage'); $pagetitle = _('Storage');
$id = gpc_get_int($_REQUEST, 'id', 0); $id = gpc_get_int($_REQUEST, 'id', 0);
$opt_stype = db_get_options(3); $opt_stype = db_get_options(DD_STORAGE_TYPE);
$opt_capaunit = $g_opt_empty + db_load_enum('storage', 'capaunit', true, true); $opt_capaunit = $g_opt_empty + db_load_enum('storage', 'capaunit', true, true);
// ========== ACTIONS START =================================================== // ========== ACTIONS START ===================================================
@@ -32,6 +34,7 @@ switch ($submit = form_get_action()) {
$p[':sname'] = gpc_get_string($_POST, 'sname'); $p[':sname'] = gpc_get_string($_POST, 'sname');
$p[':stype'] = gpc_get_int($_POST, 'stype'); $p[':stype'] = gpc_get_int($_POST, 'stype');
$id = db_exec_insert('storage', $p); $id = db_exec_insert('storage', $p);
db_set_revision('table', TBL_STORAGE);
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -39,7 +42,7 @@ switch ($submit = form_get_action()) {
$p[':sid'] = $id; $p[':sid'] = $id;
$p[':sname'] = gpc_get_string($_POST, 'sname'); $p[':sname'] = gpc_get_string($_POST, 'sname');
$p[':stype'] = gpc_get_string($_POST, 'stype'); $p[':stype'] = gpc_get_string($_POST, 'stype');
$p[':x'] = gpc_get_int($_POST, 'x'); $p[':x'] = gpc_get_uint($_POST, 'x');
$p[':y'] = gpc_get_int($_POST, 'y'); $p[':y'] = gpc_get_int($_POST, 'y');
$p[':z'] = gpc_get_int($_POST, 'z'); $p[':z'] = gpc_get_int($_POST, 'z');
$p[':wx'] = gpc_get_int($_POST, 'wx'); $p[':wx'] = gpc_get_int($_POST, 'wx');
@@ -49,6 +52,7 @@ switch ($submit = form_get_action()) {
$p[':capacity'] = gpc_get_int($_POST, 'capacity'); $p[':capacity'] = gpc_get_int($_POST, 'capacity');
if ($p[':capacity'] == 0) $p[':capacity'] = NULL; if ($p[':capacity'] == 0) $p[':capacity'] = NULL;
$p[':capaunit'] = gpc_get_string($_POST, 'capaunit'); $p[':capaunit'] = gpc_get_string($_POST, 'capaunit');
$p[':color'] = gpc_get_color($_POST, 'color');
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150); $p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
db_exec_update('storage', $p, 'sid'); db_exec_update('storage', $p, 'sid');
$action = ACT_VIEW; $action = ACT_VIEW;
@@ -106,7 +110,7 @@ page_caption_search($pagetitle);
// Storage // Storage
// stype from dropdown // stype from dropdown
$sql = "SELECT sid, sname, x, y, z, angle, remarks " $sql = "SELECT sid, sname, color, x, y, z, angle, remarks "
. "FROM storage " . "FROM storage "
. "WHERE vid=? " . "WHERE vid=? "
. "ORDER BY sid"; . "ORDER BY sid";
@@ -118,6 +122,7 @@ echo "<thead>\n";
echo "<tr>"; echo "<tr>";
echo '<th>#</th>'; echo '<th>#</th>';
echo "<th>", _('Name'), "</th>"; echo "<th>", _('Name'), "</th>";
echo "<th>", _('Color'), "</th>";
echo "<th>", _('Position'), "</th>"; echo "<th>", _('Position'), "</th>";
echo "<th>", _('Remarks'), "</th>"; echo "<th>", _('Remarks'), "</th>";
echo "<th>&nbsp;</th>"; echo "<th>&nbsp;</th>";
@@ -131,6 +136,7 @@ foreach ($res as $row) {
echo '<a class="text-nowrap" title="', _('View'), '" href="', $g_scriptname, '?f=view&id=', $row['sid'], '"><i class="bi bi-eye ms-2"></i></a>', "\n"; echo '<a class="text-nowrap" title="', _('View'), '" href="', $g_scriptname, '?f=view&id=', $row['sid'], '"><i class="bi bi-eye ms-2"></i></a>', "\n";
echo "</td>\n"; echo "</td>\n";
echo "<td>", $row['sname'], "</td>\n"; echo "<td>", $row['sname'], "</td>\n";
echo '<td>', format_color(strtoupper($row['color'])), "</td>\n";
if ($row['angle'] != 0) { if ($row['angle'] != 0) {
$angle = " (" . $row['angle'] . "°)"; $angle = " (" . $row['angle'] . "°)";
} else { } else {
@@ -145,18 +151,20 @@ foreach ($res as $row) {
echo "</tr>\n"; echo "</tr>\n";
} }
// Table summary // Table summary
$numrows = count($res); // $numrows = count($res);
table_rec_summary($i, $numrows, $numrows, 5); // table_rec_summary($i, $numrows, $numrows, 5);
echo "</table>\n"; echo "</table>\n";
form_add_button($g_scriptname); form_add_button($g_scriptname);
// Boxes // Boxes
echo "<h1>", _('Box'), "</h1>\n"; echo "<h1>", _('Box'), "</h1>\n";
$sql = "SELECT boxid, sid, label, color, content, remarks " $sql = "SELECT b.boxid, b.sid, b.label, b.color, b.content, b.remarks "
. "FROM box " . "FROM box AS b JOIN storage AS s USING (sid) "
. "ORDER BY label"; . "WHERE s.vid=? "
$sth = $pdo->query($sql); . "ORDER BY b.label";
$sth = $pdo->prepare($sql);
$sth->execute([$user->vid]);
$res = $sth->fetchAll(); $res = $sth->fetchAll();
echo '<table class="table table-striped">', "\n"; echo '<table class="table table-striped">', "\n";
echo "<thead>\n"; echo "<thead>\n";
@@ -184,8 +192,8 @@ foreach ($res as $row) {
echo "</tr>\n"; echo "</tr>\n";
} }
// Table summary // Table summary
$numrows = count($res); // $numrows = count($res);
table_rec_summary($i, $numrows, $numrows, 5); // table_rec_summary($i, $numrows, $numrows, 5);
echo "</table>\n"; echo "</table>\n";
form_add_button('box.php'); form_add_button('box.php');
@@ -196,33 +204,30 @@ elseif ($action == ACT_ADD):
echo '<h2>', _('Add Storage'), "</h2>\n"; echo '<h2>', _('Add Storage'), "</h2>\n";
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form method="post" action="<?=$g_scriptname?>">
<div class="mb-3">
<label for="sname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="sname" name="sname">
</div>
<?php <?php
form_create_text('sname', _('Name'), 40);
form_create_select('stype', _('Type'), $opt_stype); form_create_select('stype', _('Type'), $opt_stype);
?> ?>
<button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button> <div class="container-fluid px-0 my-3">
<a href="<?=$g_scriptname?>" class="btn btn-secondary"><?=_('Back')?></a> <button type="submit" name="submit[insert]" class="btn btn-primary"><?=_('Save')?></button>
<a href="<?=$g_scriptname?>" class="btn btn-secondary"><?=_('Back')?></a>
</div>
</form> </form>
<?php <?php
elseif ($action == ACT_VIEW): elseif ($action == ACT_VIEW):
// ========== VARIANT: view single record ===================================== // ========== VARIANT: view single record =====================================
$opt_unit = db_get_options(6); $opt_unit = db_get_options(DD_PROVISION_UNIT);
$sql = "SELECT sid, sname, stype, capacity, capaunit, x, y, z, wx, wy, wz, angle, color, remarks " $sql = "SELECT sid, sname, stype, capacity, capaunit, x, y, z, wx, wy, wz, angle, color, remarks "
. "FROM storage " . "FROM storage "
. "WHERE sid=?"; . "WHERE sid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
$sth->execute([$id]); $sth->execute([$id]);
$storage = $sth->fetch(PDO::FETCH_OBJ); $storage = $sth->fetch(PDO::FETCH_OBJ);
echo '<h1>', _('Storage'), ': ', $storage->sname, "</h1>\n"; echo '<h1>', sprintf(_('Storage: %s'), h($storage->sname)), "</h1>\n";
echo '<table class="table">', "\n"; echo '<table class="table">', "\n";
echo '<tr><th style="width:33%">', _('Typ'),"</th><td>", $opt_stype[$storage->stype], "</td></tr>\n"; echo '<tr><th style="width:33%">', _('Typ'),"</th><td>", $opt_stype[$storage->stype], "</td></tr>\n";
@@ -230,8 +235,8 @@ echo '<tr><th>', _('Capacity'),"</th><td>", $storage->capacity, ' ', $storage->c
echo '<tr><th>', _('Location (x, y, z)'),"</th><td>(", $storage->x, ', ', $storage->y, ', ', $storage->z, ")</td></tr>\n"; echo '<tr><th>', _('Location (x, y, z)'),"</th><td>(", $storage->x, ', ', $storage->y, ', ', $storage->z, ")</td></tr>\n";
echo '<tr><th>', _('Width (wx, wy, wz)'),"</th><td>(", $storage->wx, ', ', $storage->wy, ', ', $storage->wz, ")</td></tr>\n"; echo '<tr><th>', _('Width (wx, wy, wz)'),"</th><td>(", $storage->wx, ', ', $storage->wy, ', ', $storage->wz, ")</td></tr>\n";
echo '<tr><th>', _('Angle'),"</th><td>", $storage->angle, "°</td></tr>\n"; echo '<tr><th>', _('Angle'),"</th><td>", $storage->angle, "°</td></tr>\n";
echo '<tr><th>', _('Color'),"</th><td>", $storage->color, "</td></tr>\n"; echo '<tr><th>', _('Color'),"</th><td>", format_color($storage->color), "</td></tr>\n";
echo '<tr><th>', _('Remarks'),"</th><td>", $storage->remarks, "</td></tr>\n"; echo '<tr><th>', _('Remarks'),"</th><td>", h($storage->remarks), "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
form_view_buttons($g_scriptname, $id); form_view_buttons($g_scriptname, $id);
@@ -290,6 +295,7 @@ if (count($res) > 0) {
echo "<td>", $row['provname'], "</td>"; echo "<td>", $row['provname'], "</td>";
echo "<td>", $row['number'], ' ', $opt_unit[$row['unit']], "</td>"; echo "<td>", $row['number'], ' ', $opt_unit[$row['unit']], "</td>";
echo "<td>", $row['storedate'], ' - ', $row['shelflife'], "</td>"; echo "<td>", $row['storedate'], ' - ', $row['shelflife'], "</td>";
echo '<td><a title="', _('View'), '" href="provisions.php?f=view&id=', $row['provid'], '"><i class="bi-eye"></i></a></td>';
echo "</tr>\n"; echo "</tr>\n";
} }
echo "</table>\n"; echo "</table>\n";
@@ -302,7 +308,8 @@ elseif ($action == ACT_EDIT):
echo '<h2>', _('Edit Storage'), "</h2>\n"; echo '<h2>', _('Edit Storage'), "</h2>\n";
$sql = "SELECT sid, sname, stype, x, y, z, wx, wy, wz, angle, capacity, capaunit, remarks " $sql = "SELECT sid, sname, stype, x, y, z, wx, wy, wz, angle, capacity, "
. "color, capaunit, remarks "
. "FROM storage " . "FROM storage "
. "WHERE sid=?"; . "WHERE sid=?";
$sth = $pdo->prepare($sql); $sth = $pdo->prepare($sql);
@@ -314,22 +321,23 @@ $storage = $sth->fetch(PDO::FETCH_OBJ);
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3"> <div class="mb-3">
<label for="sname" class="form-label"><?=_('Name')?></label> <label for="sname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="sname" name="sname" value="<?=$storage->sname ?>"> <input type="text" class="form-control" id="sname" name="sname" value="<?=h($storage->sname)?>">
</div> </div>
<?php <?php
form_create_text('sname', _('Name'), $storage->name, 40);
form_create_select('stype', _('Type'), $opt_stype, $storage->stype); form_create_select('stype', _('Type'), $opt_stype, $storage->stype);
?> ?>
<div class="mb-3"> <div class="mb-3">
<label class="form-label"><?=_('Position (x, y, z) in mm')?></label> <label class="form-label"><?=_('Position (x, y, z) in mm')?></label>
<div class="row"> <div class="row">
<div class="col"> <div class="col">
<input type="number" class="form-control" id="x" name="x" min="0" value="<?=$storage->x ?>"> <input type="number" class="form-control" id="x" name="x" min="0" max="65535" value="<?=$storage->x ?>">
</div> </div>
<div class="col"> <div class="col">
<input type="number" class="form-control" id="y" name="y" value="<?=$storage->y ?>"> <input type="number" class="form-control" id="y" name="y" min="-32768" max="32767" value="<?=$storage->y ?>">
</div> </div>
<div class="col"> <div class="col">
<input type="number" class="form-control" id="z" name="z" value="<?=$storage->z ?>"> <input type="number" class="form-control" id="z" name="z" min="-32768" max="32767" value="<?=$storage->z ?>">
</div> </div>
</div> </div>
</div> </div>
@@ -337,32 +345,41 @@ form_create_select('stype', _('Type'), $opt_stype, $storage->stype);
<label class="form-label"><?=_('Width (x, y, z) in mm')?></label> <label class="form-label"><?=_('Width (x, y, z) in mm')?></label>
<div class="row"> <div class="row">
<div class="col"> <div class="col">
<input type="number" class="form-control" id="wx" name="wx" min="0" value="<?=$storage->wx ?>"> <input type="number" class="form-control" id="wx" name="wx" min="0" max="65535" value="<?=$storage->wx ?>">
</div> </div>
<div class="col"> <div class="col">
<input type="number" class="form-control" id="wy" name="wy" min="0" value="<?=$storage->wy ?>"> <input type="number" class="form-control" id="wy" name="wy" min="0" max="65535" value="<?=$storage->wy ?>">
</div> </div>
<div class="col"> <div class="col">
<input type="number" class="form-control" id="wz" name="wz" min="0" value="<?=$storage->wz ?>"> <input type="number" class="form-control" id="wz" name="wz" min="0" max="65535" value="<?=$storage->wz ?>">
</div> </div>
</div> </div>
</div> </div>
<div class="mb-3"> <?php
<label for="angle" class="form-label"><?=_('Angle, deg.')?></label> form_create_numeric('angle', _('Anglem deg.'), $storage->angle, 0, 359, 1);
<input type="number" class="form-control" id="angle" name="angle" value="<?=$storage->angle ?>"> form_create_numeric('capacity', _('Capacity'), $storage->capacity, 0, 32767);
</div> form_create_select('capaunit', _('Capacity Unit'), $opt_capaunit, $storage->capaunit);
<div class="mb-3"> form_create_color('color', _('Color'), $storage->color);
<label for="capacity" class="form-label"><?=_('Capacity')?></label> form_create_textarea('remarks', _('Remarks'), 3, 150, $storage->remarks);
<input type="number" class="form-control" id="capacity" name="capacity" value="<?=$storage->capacity ?>"> ?>
</div>
<?php form_create_select('capaunit', _('Capacity Unit'), $opt_capaunit, $storage->capaunit); ?>
<div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=$storage->remarks ?></textarea>
</div>
<button type="submit" name="submit[update]" class="btn btn-primary"><?=_('Save')?></button> <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> <a href="<?=$g_scriptname?>?f=view&id=<?=$id?>" class="btn btn-secondary"><?=_('Back')?></a>
</form> </form>
<script>
document.getElementById('capaunit').addEventListener('change', function () {
const capacity = document.getElementById('capacity');
if (this.value === 'pcs') {
capacity.step = 1;
decpl = 0;
} else {
capacity.step = 0.01;
decpl = 2;
}
if (capacity.value !== '' && Number.isFinite(Number(capacity.value))) {
capacity.value = Number(capacity.value).toFixed(decpl);
}
});
</script>
<?php <?php
elseif ($action == ACT_DELETE): elseif ($action == ACT_DELETE):
@@ -377,8 +394,8 @@ $storage = $sth->fetch(PDO::FETCH_OBJ);
echo '<h2>', _('Delete Storage'), "</h2>\n"; echo '<h2>', _('Delete Storage'), "</h2>\n";
echo '<p>', sprintf(_('Record no. %d'), $id), "</p>\n"; echo '<p>', sprintf(_('Record no. %d'), $id), "</p>\n";
echo '<p>Name: ', $storage->sname, "</p>"; echo '<p>Name: ', h($storage->sname), "</p>";
echo '<p>Remarks: ', $storage->remarks, "</p>"; echo '<p>Remarks: ', h($storage->remarks, br:true), "</p>";
echo '<p>', _('Deleting a storage is final. There is no way back. Only delete if you are absolute sure.'), "</p>\n"; echo '<p>', _('Deleting a storage is final. There is no way back. Only delete if you are absolute sure.'), "</p>\n";
+9 -6
View File
@@ -7,7 +7,9 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Tags'); $pagetitle = _('Tags');
@@ -39,6 +41,7 @@ switch ($submit = form_get_action()) {
case 'insert': case 'insert':
$p[':tagname'] = gpc_get_string($_POST, 'tagname');; $p[':tagname'] = gpc_get_string($_POST, 'tagname');;
$id = db_exec_insert('tag', $p); $id = db_exec_insert('tag', $p);
db_set_revision('table', TBL_TAGS);
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -88,14 +91,13 @@ echo "<h1>$pagetitle</h1>\n";
// Filter // Filter
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form id="filterform" method="post" action="<?=$g_scriptname?>">
<div id="filter" class="card"> <div id="filter" class="card">
<div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div> <div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div>
<div class="card-body d-flex flex-wrap gap-3"> <div class="card-body d-flex flex-wrap gap-3">
<div class="d-flex flex-nowrap gap-2"> <?php
<label for="flt_txt">Text</label> filter_create_text('flt_txt', _('Text'), $flt->txt, 30, 45);
<input type="text" class="form-control" name="flt_txt" size="15" maxlength="30" value="<?=$flt->txt ?? ''?>"> ?>
</div>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button> <button name="submit[filter]" class="btn btn-sm btn-primary" title="<?=_('Apply')?>"><?=_('Go')?></button>
@@ -140,7 +142,8 @@ foreach ($res as $row) {
echo "</tr>\n"; echo "</tr>\n";
} }
// Table summary // Table summary
table_rec_summary($i0, $i, $numrows, 6); $numrows = count($res);
table_rec_summary(1, $i, $numrows, 6);
echo "</table>\n"; echo "</table>\n";
form_add_button($g_scriptname); form_add_button($g_scriptname);
+17 -14
View File
@@ -7,7 +7,9 @@
******************************************************************************/ ******************************************************************************/
require 'globals.inc'; require 'globals.inc';
require 'lib/db.inc';
require 'lib/gpc.inc'; require 'lib/gpc.inc';
require 'lib/form.inc';
$pagetitle = _('Task'); $pagetitle = _('Task');
@@ -73,6 +75,7 @@ switch ($submit = form_get_action()) {
$p[':finished'] = gpc_get_datetime($_POST, 'finished'); $p[':finished'] = gpc_get_datetime($_POST, 'finished');
$p[':taskstate'] = gpc_get_enum($_POST, 'taskstate', array_keys($opt_state)); $p[':taskstate'] = gpc_get_enum($_POST, 'taskstate', array_keys($opt_state));
$p[':responsible'] = gpc_get_int($_POST, 'responsible'); $p[':responsible'] = gpc_get_int($_POST, 'responsible');
$p[':remarks'] = gpc_get_string($_POST, 'remarks', 150);
db_exec_update('task', $p, 'taskid'); db_exec_update('task', $p, 'taskid');
$action = ACT_VIEW; $action = ACT_VIEW;
break; break;
@@ -127,7 +130,6 @@ page_caption_search($pagetitle);
// load filter from db // load filter from db
$flt = db_get_filter($user->id, 206, ['txt', 'prio', 'stat', 'proj']); $flt = db_get_filter($user->id, 206, ['txt', 'prio', 'stat', 'proj']);
$w = array('(t.vid=:vid OR t.vid IS NULL)'); $w = array('(t.vid=:vid OR t.vid IS NULL)');
$p = array(':vid' => $user->vid); $p = array(':vid' => $user->vid);
if (strlen($flt->txt) > 1) { if (strlen($flt->txt) > 1) {
@@ -176,7 +178,7 @@ try {
} }
$numrows = $sth->fetchColumn(); $numrows = $sth->fetchColumn();
$page = gpc_get_int($_REQUEST, 'p', 1); $page = gpc_get_int($_REQUEST, 'p', 1);
$rows_pp = gpc_get_int($_REQUEST, 'n', $g_rows_pp); $rows_pp = gpc_get_int($_REQUEST, 'n', $user->rows_pp);
$lastpage = ceil($numrows/$rows_pp); $lastpage = ceil($numrows/$rows_pp);
$sql = "SELECT t.taskid, t.vid, t.projid, t.taskname, t.priority, t.taskstate," $sql = "SELECT t.taskid, t.vid, t.projid, t.taskname, t.priority, t.taskstate,"
@@ -200,7 +202,7 @@ try {
$res = $sth->fetchAll(); $res = $sth->fetchAll();
?> ?>
<form method="post" action="<?=$g_scriptname?>"> <form id="filterform" method="post" action="<?=$g_scriptname?>">
<div id="filter" class="card"> <div id="filter" class="card">
<div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div> <div class="card-header"><i class="bi bi-funnel me-2"></i>Filter</div>
<div class="card-body d-flex flex-wrap gap-3"> <div class="card-body d-flex flex-wrap gap-3">
@@ -208,14 +210,9 @@ $res = $sth->fetchAll();
$opt_proj_filter = db_get_opt_proj($user->vid, ['finished']); $opt_proj_filter = db_get_opt_proj($user->vid, ['finished']);
filter_create_select('flt_proj', _('Project'), $g_opt_all + $g_opt_none + $opt_proj_filter, $flt->proj); filter_create_select('flt_proj', _('Project'), $g_opt_all + $g_opt_none + $opt_proj_filter, $flt->proj);
filter_create_select('flt_prio', _('Priority'), $g_opt_all + $g_opt_none + $opt_priority, $flt->prio); filter_create_select('flt_prio', _('Priority'), $g_opt_all + $g_opt_none + $opt_priority, $flt->prio);
?> filter_create_text('flt_txt', _('Text'), $flt->txt, 15, 30);
<div class="d-flex flex-nowrap gap-2">
<label for="flt_txt">Text</label>
<input type="text" class="form-control" name="flt_txt" size="15" maxlength="30" value="<?=$flt->txt ?>">
</div>
<?php
$opt_status = db_load_enum('task', 'taskstate', true, true, false); $opt_status = db_load_enum('task', 'taskstate', true, true, false);
filter_create_checks('flt_stat', _('Status'), $opt_status, $flt->stat); filter_create_checks('flt_stat', _('Status'), $opt_status, $flt->stat ?? []);
?> ?>
</div> </div>
<div class="card-footer"> <div class="card-footer">
@@ -298,7 +295,7 @@ elseif ($action == ACT_VIEW):
$sql = "SELECT t.taskname, t.priority, t.plandate, t.duedate," $sql = "SELECT t.taskname, t.priority, t.plandate, t.duedate,"
. " t.started, t.finished, t.taskstate, t.responsible," . " t.started, t.finished, t.taskstate, t.responsible,"
. " u.displayname, p.projname " . " t.remarks, u.displayname, p.projname "
. "FROM task AS t LEFT JOIN project AS p USING (projid) " . "FROM task AS t LEFT JOIN project AS p USING (projid) "
. " LEFT JOIN user AS u ON (t.responsible=u.userid) " . " LEFT JOIN user AS u ON (t.responsible=u.userid) "
. "WHERE taskid=?"; . "WHERE taskid=?";
@@ -317,6 +314,7 @@ echo '<tr><th>', _('Started at'),"</th><td>", $task->started, "</td></tr>\n";
echo '<tr><th>', _('Finished at'),"</th><td>", $task->finished, "</td></tr>\n"; echo '<tr><th>', _('Finished at'),"</th><td>", $task->finished, "</td></tr>\n";
echo '<tr><th>', _('Status'),"</th><td>", $opt_state[$task->taskstate], "</td></tr>\n"; echo '<tr><th>', _('Status'),"</th><td>", $opt_state[$task->taskstate], "</td></tr>\n";
echo '<tr><th>', _('Responsible'),"</th><td>", $task->displayname, "</td></tr>\n"; echo '<tr><th>', _('Responsible'),"</th><td>", $task->displayname, "</td></tr>\n";
echo '<tr><th>', _('Remarks'),"</th><td>", h($task->remarks, br:true), "</td></tr>\n";
echo "</table>\n"; echo "</table>\n";
form_view_buttons($g_scriptname, $id); form_view_buttons($g_scriptname, $id);
@@ -350,7 +348,7 @@ echo '<p>', _('Not yet implemented'), "</p>";
elseif ($action == ACT_EDIT): elseif ($action == ACT_EDIT):
// ========== VARIANT: edit single record ===================================== // ========== VARIANT: edit single record =====================================
$opt_user = db_get_opt_user($user->id); // only used here $opt_user = db_get_opt_user(); // only used here
$sql = "SELECT taskname, projid, priority, plandate, duedate, started, finished," $sql = "SELECT taskname, projid, priority, plandate, duedate, started, finished,"
. " taskstate " . " taskstate "
@@ -367,7 +365,7 @@ echo '<h2>', _('Edit Task'), "</h2>\n";
<input type="hidden" name="id" value="<?=$id?>"> <input type="hidden" name="id" value="<?=$id?>">
<div class="mb-3"> <div class="mb-3">
<label for="taskname" class="form-label"><?=_('Name')?></label> <label for="taskname" class="form-label"><?=_('Name')?></label>
<input type="text" class="form-control" id="taskname" name="taskname" value="<?=$task->taskname ?>"> <input type="text" class="form-control" id="taskname" name="taskname" value="<?=h($task->taskname)?>">
</div> </div>
<?php <?php
$opt_none = [-1 => '&horbar; none &horbar;']; $opt_none = [-1 => '&horbar; none &horbar;'];
@@ -393,7 +391,12 @@ form_create_select('priority', _('Priority'), $opt_none + $opt_priority, $task->
<?php <?php
form_create_select('taskstate', _('Status'), $opt_state, $task->taskstate); form_create_select('taskstate', _('Status'), $opt_state, $task->taskstate);
form_create_select('responsible', _('Responsible'), $opt_user, $user->id); form_create_select('responsible', _('Responsible'), $opt_user, $user->id);
?>
<div class="mb-3">
<label for="remarks" class="form-label"><?=_('Remarks')?></label>
<textarea class="form-control" id="remarks" name="remarks" rows="3"><?=h($task->remarks)?></textarea>
</div>
<?php
form_edit_buttons($g_scriptname, $id); form_edit_buttons($g_scriptname, $id);
echo "</form>\n"; echo "</form>\n";
+103
View File
@@ -0,0 +1,103 @@
.TH YMS 1 "November 2026" "YMS 0.3" "User Commands"
.SH NAME
yms - Yacht Management Software
.SH SYNOPSIS
.B yms
.SH DESCRIPTION
.B YMS
(Yacht Management Software) is free and open-source software for
managing yachts, sailboats and their equipment.
YMS is designed for managing yachts and sailboats, including
equipment, inventory, storage locations, documents, maintenance,
tasks, projects, provisions and technical data.
The application uses MariaDB for structured application data.
User-managed photos and documents are stored in the local filesystem.
.SH FEATURES
YMS provides the following functionality:
.TP
.B Equipment and inventory management
Manage equipment and inventory belonging to the yacht.
.TP
.B Storage locations
Organize equipment and inventory by physical storage location.
.TP
.B Documents and manuals
Manage documents and manuals associated with the yacht and its
equipment.
.TP
.B Maintenance and service history
Record maintenance activities and service history.
.TP
.B Tasks and projects
Manage tasks and projects related to the yacht.
.TP
.B Provisions and consumables
Manage provisions, supplies and consumable items.
.TP
.B Technical data and measurements
Store technical information, measurements and other data associated
with the yacht.
.SH DATABASE
YMS uses MariaDB to store its structured application data.
The MariaDB server must be available to the YMS application when
the application is running.
.SH FILES
.TP
.I ~/.config/ymsgui.conf
Per-user configuration file for the YMS graphical user interface.
.TP
.I /var/local/lib/yms/
Persistent storage for files managed by YMS.
The directory contains photos, documents and other media associated
with the managed yacht. Supported file formats include JPEG, PNG,
SVG and PDF.
.SH BACKUP
YMS stores application data in two separate locations.
The directory
.I /var/local/lib/yms/
contains user-managed photos and documents and should be included
in regular backups.
The structured application data is stored in MariaDB and must be
backed up using an appropriate MariaDB backup procedure.
.SH REQUIREMENTS
YMS requires a graphical desktop environment with GTK3 support.
The application requires Python and the GTK3 Python bindings.
A MariaDB server is required for database access.
.SH OPEN SOURCE
YMS is free and open-source software.
The source code is available from the YMS Git repository:
.UR https://git.hoogi.de/thooge/YMS
.UE
.SH VERSION
This manual describes YMS version 0.3.
.SH PROJECT
The YMS project homepage is available at:
.UR https://yms.hoogi.de/
.UE
A live demonstration is available at:
.UR https://www.hoogi.de/ymsdemo
.UE
German-language documentation is available at:
.UR https://computerclub.hoogi.de/yms
.UE
.SH BUGS
Please report bugs and contribute improvements through thread in Segeln-Forum or
by submitting a mail
.SH AUTHOR
YMS is developed by Thomas Hooge / thomas@hoogi.de.
.SH COPYRIGHT
YMS is free and open-source software. See the project repository for
license and copyright information.
+1 -1
View File
@@ -5,7 +5,7 @@ GenericName=Yacht Management
GenericName[de]=Yacht-Verwaltungssoftware GenericName[de]=Yacht-Verwaltungssoftware
Comment=Yacht Management Software Comment=Yacht Management Software
Comment[de]=Verwaltung von Yachten, Dokumenten und technischen Daten Comment[de]=Verwaltung von Yachten, Dokumenten und technischen Daten
Exec=/usr/local/bin/yms Exec=@PREFIX@/bin/yms
Icon=yms Icon=yms
StartupNotify=true StartupNotify=true
Terminal=false Terminal=false
+9
View File
@@ -0,0 +1,9 @@
table Icon
Caption: Yacht Management
Command: @PREFIX@/bin/yms
Icon: @PREFIX@/share/icons/hicolor/48x48/apps/yms.png
Width: 48
Height: 48
X: 168
Y: 16
end
+4 -2
View File
@@ -1,3 +1,5 @@
# SPDX-License-Identifier: WTFPL
from gi.repository import Gtk from gi.repository import Gtk
def load_from_dict(combobox, dictionary, selected=None, sort=False): def load_from_dict(combobox, dictionary, selected=None, sort=False):
@@ -33,7 +35,7 @@ def refresh_dict(combobox, dictionary, keep_selection=True):
model = combobox.get_model() model = combobox.get_model()
selected = get_value(combobox) selected = get_value(combobox)
model.clear() model.clear()
for item in dictionary.iteritems(): for item in dictionary.items():
model.append(item) model.append(item)
if keep_selection: if keep_selection:
activate_row(combobox, selected) activate_row(combobox, selected)
@@ -70,7 +72,7 @@ def get_value(combobox, decode=False):
if active < 0: if active < 0:
return None return None
else: else:
if type(model) == gtk.TreeStore: if type(model) == Gtk.TreeStore:
it = combobox.get_active_iter() it = combobox.get_active_iter()
val = model.get_value(it, 0) val = model.get_value(it, 0)
if decode: if decode:
+153 -6
View File
@@ -1,6 +1,10 @@
import MySQLdb # SPDX-License-Identifier: WTFPL
class Database(): import MySQLdb
import secrets
from gettext import pgettext
class Database:
def __init__(self, hostname, dbname): def __init__(self, hostname, dbname):
self.hostname = hostname self.hostname = hostname
@@ -20,6 +24,7 @@ class Database():
except MySQLdb.Error as e: except MySQLdb.Error as e:
self.error = e self.error = e
return False return False
self.conn.autocommit(False)
self.cur = self.conn.cursor() self.cur = self.conn.cursor()
self.dcur = self.conn.cursor(MySQLdb.cursors.DictCursor) self.dcur = self.conn.cursor(MySQLdb.cursors.DictCursor)
return True return True
@@ -47,10 +52,152 @@ class Database():
def is_connected(self): def is_connected(self):
return self.conn.open return self.conn.open
def is_encrypted(self):
self.cur.execute("SHOW SESSION STATUS LIKE 'Ssl_cipher'")
row = self.cur.fetchone()
return (row and row[1])
def get_timestamp(self):
self.cur.execute("SELECT CURRENT_TIMESTAMP")
return self.cur.fetchone()[0]
def last_error(self): def last_error(self):
if not self.error: if not self.error:
return(0, '') return('UnknownType', 0, '')
code = self.error.args[0]
text = self.error.args[1] etype = type(self.error).__name__
ecode = 0
etext = str(self.error)
if len(self.error.args) >= 2 and isinstance(self.error.args[0], int):
ecode = self.error.args[0]
etext = str(self.error.args[1])
self.error = None self.error = None
return(code, text) return(etype, ecode, etext)
def load_enum(self, table, column):
"""
Load an enum or set directly from a database table and provide it as a
dictionary for use in, for example, selection lists.
"""
sql = (
"SELECT TRIM(TRAILING ')' FROM SUBSTRING(column_type,6)) "
"FROM information_schema.columns "
"WHERE table_schema=DATABASE() AND table_name=%s AND column_name=%s AND data_type IN ('enum','set')"
)
self.cur.execute(sql, (table, column))
row = self.cur.fetchone()
if not row:
return {}
enumvals = row[0].replace("'", "").split(",")
return {
value: pgettext(f"{table}.{column}", value)
for value in enumvals
}
def lock_acquire(self, table, key, userid):
token = secrets.token_hex(8)
# first try new lock
sql = (
"INSERT INTO recordlock (lock_table, lock_key, token, userid)"
"VALUES (%s, %s, %s, %s)"
)
try:
self.cur.execute(sql, (table, key, token, userid))
self.conn.commit()
return token
except self.conn.IntegrityError as e:
self.conn.rollback()
if e.args[0] != 1062:
raise
# lazy locking: lock exists but is old, so we use it
sql = (
"UPDATE recordlock "
"SET token=%s, userid=%s,"
" created_at=CURRENT_TIMESTAMP, last_seen=CURRENT_TIMESTAMP "
"WHERE lock_table=%s AND lock_key=%s AND last_seen<CURRENT_TIMESTAMP-INTERVAL 5 MINUTE"
)
self.cur.execute(sql, (token, userid, table, key))
self.conn.commit()
if self.cur.rowcount == 1:
return token
return None
def lock_refresh(self, token):
sql = (
"UPDATE recordlock "
"SET last_seen=CURRENT_TIMESTAMP "
"WHERE token=%s"
)
self.cur.execute(sql, (token,))
self.conn.commit()
return self.cur.rowcount == 1
def lock_release(self, token):
sql = "DELETE FROM recordlock WHERE token=%s"
self.cur.execute(sql, (token,))
self.conn.commit()
return self.cur.rowcount == 1
def load_setting(self, sno, autocreate=True):
sql = "SELECT valstr, valint FROM settings WHERE userid=0 AND sno=%s"
self.cur.execute(sql, (sno,))
row = self.cur.fetchone()
if not row:
if autocreate:
sql = "INSERT INTO settings (userid, sno) VALUES (0, %s)"
self.cur.execute(sql, (sno,))
self.conn.commit()
return (None, None)
return row
def save_setting(self, sno, valstr, valint):
sql = "UPDATE settings SET valstr=%s, valint=%s WHERE userid=0 AND sno=%s"
values = (valstr, valint, sno)
return self.execute_write(sql, values, 1)
def get_free_number(self, table, column):
"""
Get first free number from column, so gaps are filled
"""
sql = (
"SELECT MIN(n.{col}) AS nextval "
"FROM ("
"SELECT 1 AS {col} "
"UNION ALL "
"SELECT DISTINCT {col} + 1 "
"FROM {tbl} "
"WHERE {col} > 0"
") AS n "
"LEFT JOIN {tbl} AS m ON m.{col}=n.{col} "
"WHERE m.{col} IS NULL"
).format(tbl=table, col=column)
self.cur.execute(sql)
return self.cur.fetchone()[0] or 1
def execute_write(self, sql, values=(), expected_rows=None):
"""
Execute an INSERT, UPDATE, or DELETE statement.
expected_rows:
None = do not check the number of affected rows
1 = expect exactly one affected row
0 = expect no affected rows / no data changed
"""
try:
self.cur.execute(sql, values)
except MySQLdb.Error as e:
self.conn.rollback()
self.error = e
return False
if (expected_rows is not None and self.cur.rowcount != expected_rows):
self.conn.rollback()
self.error = RuntimeError(
"Expected {} affected rows, got {}".format(
expected_rows,
self.cur.rowcount
)
)
return False
self.error = None
return True
-33
View File
@@ -1,33 +0,0 @@
# -*- coding: utf-8 -*-
import MySQLdb.cursors
class Equipment():
fields = ('vid' 'ename', 'shortname', 'model', 'ecat', 'serial', 'supplier',
'manufacturer', 'purchdate', 'price', 'weight', 'remarks', 'flags')
def __init__(self, dbconn, eid=None):
self.conn = dbconn
self.dcur = dbconn.cursor(MySQLdb.cursors.DictCursor)
self.remarks = None
self.data = {} # for old/new checks
def load(self):
sql = (
"SELECT {}".format(', '.join(self.fields))
"FROM equipment "
"WHERE eid=%s"
)
self.dcur.execute(sql, (self.eid,))
self.data = self.dcur.fetchone()
if self.data:
for field in self.fields:
setattr(self, field, self.data.get(field))
else:
for field in self.fields:
setattr(self, field, None)
def save(self):
pass
+58 -3
View File
@@ -1,3 +1,5 @@
# SPDX-License-Identifier: WTFPL
from gi.repository import Gtk from gi.repository import Gtk
def init_named_controls(window, builder): def init_named_controls(window, builder):
@@ -50,9 +52,7 @@ def messagebox(messagetext, symbol=None, title=None, parent=None):
def questionbox(messagetext, symbol=None, title=None, parent=None): def questionbox(messagetext, symbol=None, title=None, parent=None):
""" """
Ja/Nein-Nachfrage bei wirklich wichtigen Entscheidungen The decision is returned as a value: True if agreed to, False if rejected
Die Entscheidung wird als Rückgabewert geliefert: True falls
zugestimmt wurde, False bei Ablehnung
""" """
if not symbol: if not symbol:
symbol = Gtk.MessageType.QUESTION symbol = Gtk.MessageType.QUESTION
@@ -69,3 +69,58 @@ def questionbox(messagetext, symbol=None, title=None, parent=None):
response = md.run() response = md.run()
md.destroy() md.destroy()
return response == Gtk.ResponseType.YES return response == Gtk.ResponseType.YES
def get_text_contents(textview):
"""
Convenience function to get all contents from GtkTextView
"""
buf = textview.get_buffer()
contents = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), True).strip()
return contents or None
class TouchPopup():
"""
A pop-up window that can be closed again with another click.
The pop-up features a title in bold, as well as a list of labels and values.
"""
#TODO finish converting to GTK3
def __init__(self, parent, title, data, width=None):
self.window = win = gtk.Window(Gtk.WindowType.POPUP)
win.set_position(Gtk.WindowPosition.MOUSE)
win.set_transient_for(parent)
win.set_modal(True)
if width:
win.set_size_request(width, -1)
#win.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#feffd0"))
win.override_background_color(
Gtk.StateFlags.NORMAL,
Gdk.RGBA(1.0, 1.0, 0.816, 1.0) # #feffd0
)
frame = Gtk.Frame()
frame.set_shadow_type(Gtk.ShadowType.ETCHED_OUT)
frame.set_border_width(2)
win.add(frame)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
frame.add(vbox)
# Title
label = Gtk.Label("<b>" + title + "</b>")
label.set_use_markup(True)
label.set_alignment(0.0, 0.5)
vbox.pack_start(label)
# Data
sg = Gtk.SizeGroup(Gtk.SizeGroupMode.HORIZONTAL)
for d in data:
hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
vbox.pack_start(hbox)
label = Gtk.Label(d[0])
label.set_alignment(0.0, 0.5)
hbox.pack_start(label, False, False, 4)
sg.add_widget(label)
label = Gtk.Label(d[1])
label.set_alignment(0.0, 0.5)
hbox.pack_start(label)
win.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
win.connect('button-press-event', self.callback)
win.show_all()
def callback(self, window, event):
window.destroy()
+362
View File
@@ -0,0 +1,362 @@
# SPDX-License-Identifier: WTFPL
from enum import IntEnum
"""
Dropdowns, Database enums and Table numbers
dropdowns contents can change
enums are static
TBD
- language
- dateformat
- dimensions (measurement)
"""
class Dropdown(IntEnum):
VESSEL_TYPE = 1
COMPANY_TYPE = 2
STORAGE_TYPE = 3
EQUIPMENT_CATEGORY = 4
PROVISION_CATEGORY = 5
PROVISION_UNIT = 6
FUSE_TYPE = 7
UNIT = 8
BOX_TYPE = 9
FUSE_BLOCK = 10
CABLE_TYPE = 11
CABLE_TECHNAME = 12
INVENTORY_CATEGORY = 13
BBN_VESSELDATA = 14
MEASUREMENT_CATEGORY = 15
DDNAME = {
Dropdown.VESSEL_TYPE: "vtype",
Dropdown.COMPANY_TYPE: "comptype",
Dropdown.STORAGE_TYPE: "stype",
Dropdown.EQUIPMENT_CATEGORY: "ecat",
Dropdown.PROVISION_CATEGORY: "provcat",
Dropdown.PROVISION_UNIT: "provunit",
Dropdown.FUSE_TYPE: "ftype",
Dropdown.UNIT: "unit",
Dropdown.BOX_TYPE: "boxtype",
Dropdown.FUSE_BLOCK: "location",
Dropdown.CABLE_TYPE: "cabletype",
Dropdown.CABLE_TECHNAME: "techname",
Dropdown.INVENTORY_CATEGORY: "invcat",
Dropdown.BBN_VESSELDATA: "bbndata",
Dropdown.MEASUREMENT_CATEGORY: "mcat"
}
DropdownDeps = {
Dropdown.VESSEL_TYPE: (
('vessel', 'vtype')
),
Dropdown.COMPANY_TYPE: (
('company', 'comptype'),
('company', 'comptype2')
),
Dropdown.STORAGE_TYPE: (
('storage', 'stype')
),
Dropdown.EQUIPMENT_CATEGORY: (
('equipment', 'ecat')
),
Dropdown.PROVISION_CATEGORY: (
('provisions', 'provcat')
),
Dropdown.PROVISION_UNIT: (
('provisions', 'unit')
),
Dropdown.FUSE_TYPE: (
('fuse', 'ftype')
),
Dropdown.UNIT: (
('measurement', 'unit')
),
Dropdown.BOX_TYPE: (
('box', 'boxtype')
),
Dropdown.FUSE_BLOCK: (
('fuse', 'location')
),
Dropdown.CABLE_TYPE: (
('cable', 'cabletype')
),
Dropdown.CABLE_TECHNAME: (
('cable', 'techname')
),
Dropdown.INVENTORY_CATEGORY: (
('inventory', 'invcat')
),
Dropdown.BBN_VESSELDATA: (
#unused
),
Dropdown.MEASUREMENT_CATEGORY: (
('measurement', 'mcat')
)
}
class Table(IntEnum):
VESSEL = (1, "base")
USERS = (2, "base")
COMPANIES = (3, "companies")
STORAGE = (4, "storage")
BOXES = (5, "boxes")
EQUIPMENT = (6, "equipment")
INVENTORY = (7, "inventory")
PROJECTS = (8, "projects")
CABLES = (9, "cables")
FUSES = (10, "fuses")
TAGS = (11, "tags")
def __new__(cls, value, module):
obj = int.__new__(cls, value)
obj._value_ = value
obj.module = module
return obj
class Lookup:
def __init__(self, db):
self.db = db
self._enums = {}
self._dropdowns = {}
self._revision_ts = {} # tracking list revisions
def load(self):
self._load_enums()
self._load_dropdowns()
def _load_enums(self):
"""
enums and sets
translation via gettext from db schema
"""
db_enums = {
'cable.cablecond': ('cable', 'cablecond'),
'checkitem.checkresult': ('checkitem', 'checkresult'),
'checklist.clstate': ('checklist', 'clstate'),
'company.flags': ('company', 'flags'),
'docref.reftype': ('docref', 'reftype'),
'document.doctype': ('document', 'doctype'),
'document.roleaccess': ('document', 'roleaccess'),
'dropdown.flags': ('dropdown', 'flags'),
'equipment.econd': ('equipment', 'econd'),
'equipment.flags': ('equipment', 'flags'),
'inventory.conttype': ('inventory', 'conttype'),
'inventory.invcond': ('inventory', 'invcond'),
'inventory.flags': ('inventory', 'flags'),
'maintenance.maintstate': ('maintenance', 'maintstate'),
'maintenance.plan_precision': ('maintenance', 'plan_precision'),
'measurement.accuracy': ('measurement', 'accuracy'),
'note.notetype': ('note', 'notetype'),
'project.projstate': ('project', 'projstate'),
'signalk.datatype': ('signalk', 'datatype'),
'signalk.objtype': ('signalk', 'objtype'),
'storage.capaunit': ('storage', 'capaunit'),
'tagref.objtype': ('tagref', 'objtype'),
'task.priority': ('task', 'priority'),
'task.taskstate': ('task', 'taskstate'),
'user.role': ('user', 'role'),
'vessel.htype': ('vessel', 'htype')
}
for key, (table, column) in db_enums.items():
self._enums[key] = self.db.load_enum(table, column)
def _load_dropdowns(self):
self._dropdowns.clear()
sql = "SELECT ddval FROM dropdown WHERE ddid=0 AND ddval>0"
# Step 1: init all lists as empty
self.db.cur.execute(sql)
for ddval in self.db.cur.fetchall():
self._dropdowns[ddval[0]] = {}
# Step 2: fill values where defined
sql = (
"SELECT ddid, ddval, ddtext "
"FROM dropdown "
"WHERE ddid>0 "
"ORDER BY ddid, sort, ddval"
)
self.db.cur.execute(sql)
for ddid, ddval, ddtext in self.db.cur.fetchall():
if ddid not in self._dropdowns:
# should really not happen!
print("unknown dropdown list id found!")
self._dropdowns[ddid] = {}
self._dropdowns[ddid][ddval] = ddtext
def reload_dropdown(self, ddid):
self._dropdowns[ddid] = {}
sql = (
"SELECT ddval, ddtext "
"FROM dropdown "
"WHERE ddid=%s "
"ORDER BY sort, ddval"
)
self.db.cur.execute(sql)
for ddval, ddtext in self.db.cur.fetchall():
self._dropdowns[ddid][ddval] = ddtext
def enum(self, name):
return self._enums[name]
def dropdown(self, ddid):
return self._dropdowns[ddid]
def iter_dropdowns(self):
yield from self._dropdowns.keys()
def user(self):
self.db.cur.execute("SELECT userid, displayname FROM user ORDER BY displayname")
return dict(self.db.cur.fetchall())
def vessel(self):
vessellist = {}
self.db.dcur.execute("SELECT vid, vesselname, model FROM vessel ORDER BY vid")
for row in self.db.dcur.fetchall():
vessellist[row['vid']] = (
row['vesselname'] + " - " + row['model'] if row['model']
else row['vesselname']
)
return vessellist
def company(self, comptype):
sql = (
"SELECT compid, compname "
"FROM company "
"WHERE comptype=%(type)s OR comptype2=%(type)s "
"ORDER BY compname"
)
self.db.cur.execute(sql, {"type": comptype})
return dict(self.db.cur.fetchall())
def storage(self, vid):
storagelist = {}
sql = (
"SELECT sid, sname, CONCAT(x, ',', y, ',', z) AS position, remarks "
"FROM storage "
"WHERE vid=%s "
"ORDER BY sname"
)
self.db.cur.execute(sql, (vid,))
for row in self.db.cur.fetchall():
if row[3]:
storagelist[row[0]] = "{} ({}) - {}".format(row[1], row[2], row[3])
else:
storagelist[row[0]] = "{} ({})".format(row[1], row[2])
return storagelist
def box(self, vid):
boxlist = {}
sql = (
"SELECT b.boxid, b.label, b.content "
"FROM box AS b LEFT JOIN storage AS s USING (sid) "
"WHERE s.vid=%s OR s.vid IS NULL "
"ORDER BY b.label"
)
self.db.cur.execute(sql, (vid,))
for row in self.db.cur.fetchall():
if row[2]:
boxlist[row[0]] = "{} - {}".format(row[1], row[2])
else:
boxlist[row[0]] = row[1]
return boxlist
def equipment(self, vid):
sql = (
"SELECT eid, ename "
"FROM equipment "
"WHERE vid=%s "
"ORDER BY ename"
)
self.db.cur.execute(sql, (vid,))
return dict(self.db.cur.fetchall())
def inventory(self, vid):
sql = (
"SELECT invid, invname "
"FROM inventory "
"WHERE vid=%s "
"ORDER BY invname"
)
self.db.cur.execute(sql, (vid,))
return dict(self.db.cur.fetchall())
def cable(self, vid):
sql = (
"SELECT cableid, cablename "
"FROM cable "
"WHERE vid=%s "
"ORDER BY cablename"
)
self.db.cur.execute(sql, (vid,))
return dict(self.db.cur.fetchall())
def fuse(self, vid):
sql = (
"SELECT fuseid, CONCAT('F', fnumber, ' - ', description) "
"FROM fuse "
"WHERE vid=%s "
"ORDER BY fnumber"
)
self.db.cur.execute(sql, (vid,))
return dict(self.db.cur.fetchall())
def project(self, vid):
sql = (
"SELECT projid, projname "
"FROM project "
"WHERE vid=%s "
"ORDER BY projname"
)
self.db.cur.execute(sql, (vid,))
return dict(self.db.cur.fetchall())
def refresh(self):
# TODO ugly hack please improve
self._load_dropdowns()
class ListDefinition:
pass
"""
EQUIPMENT_LIST = ListDefinition(
name="equipment",
query=
"SELECT
e.eid,
e.ename,
c.name AS manufacturer,
e.model,
e.ecat,
e.weight
FROM equipment e
LEFT JOIN company c
ON c.cid = e.manufacturer"
,
columns=[
Column("ename", _("Name")),
Column("manufacturer", _("Manufacturer")),
Column(
"model",
_("Model")
),
Column(
"ecat",
_("Category"),
formatter=dropdown(Dropdown.EQUIPMENT_CATEGORY)
),
Column(
"weight",
_("Weight"),
formatter=weight()
),
]
)
"""
View File
Whitespace-only changes.
+27
View File
@@ -0,0 +1,27 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
from yms.lookup import Table
class Box(DbRecord):
table = "box"
pk_field = "boxid"
pk_is_auto = True
fields = ('boxid', 'sid', 'boxtype', 'parent', 'label', 'color',
'content', 'wx', 'wy', 'wz', 'weight', 'weight_net', 'price',
'remarks')
def __init__(self, db, boxid=None):
super().__init__(db, boxid)
self.title = _("Box({})")
def save(self, commit=True):
if not super().save(Table.BOXES):
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+27
View File
@@ -0,0 +1,27 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
from yms.lookup import Table
class Cable(DbRecord):
table = "cable"
pk_field = "cableid"
pk_is_auto = True
fields = ('cableid', 'vid', 'cablename', 'cabletype', 'techname',
'length', 'conductors', 'diameter', 'xsection', 'weight', 'color',
'supplier', 'manufacturer', 'cablecond', 'remarks')
def __init__(self, db, cableid=None):
super().__init__(db, cableid)
self.title = _("Cable({})")
def save(self, commit=True):
if not super().save(Table.CABLES):
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+33
View File
@@ -0,0 +1,33 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
from yms.lookup import Table
# names for fixed dropdown values
SUPPLIER = 1
MANUFACTURER = 2
SHIPYARD = 3
MISC = 9
class Company(DbRecord):
table = "company"
pk_field = "compid"
pk_is_auto = True
fields = ('compid', 'compname', 'comptype', 'comptype2',
'shortname', 'street', 'zip', 'city', 'country', 'contact', 'phone',
'email', 'web', 'customerno', 'contractno', 'remarks', 'flags')
def __init__(self, db, compid=None):
super().__init__(db, compid)
self.title = _("Company({})")
def save(self, commit=True):
if not super().save(Table.COMPANIES):
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+182
View File
@@ -0,0 +1,182 @@
# SPDX-License-Identifier: WTFPL
"""
No commits here: Has to be done elsewhere to support transactions!
Fields has to be a tuple to have fixed order which simplifies debugging
TODO primary keys can be multiple fields, stored as tuple
do not include pk auto fields in inserts and updates!
"""
from datetime import datetime
class DbRecord:
REQUIRED = ('table', 'pk_field', 'pk_is_auto', 'fields')
def __init_subclass__(cls, **kwargs):
for variable in DbRecord.REQUIRED:
if variable not in cls.__dict__:
raise TypeError(f"{cls.__name__} subclass must define '{variable}'")
def __init__(self, db, record_id=None):
self.db = db
self.cur = db.cur
self.dcur = db.dcur
self.conn = db.conn
self.last_update = None
self._title = _("DbRecord({})") # for pretty print
self.pk_value = None
if record_id is not None:
self.pk_value = int(record_id)
self.load()
else:
self.clear()
def clear(self):
self.pk_value = None
self.data = {} # for old/new checks
for field in self.fields:
setattr(self, field, None)
self.data[field] = None
def load(self, record_id=None):
if record_id is not None:
self.pk_value = int(record_id)
if self.pk_value is None:
self.clear()
return
sql = ("SELECT {} FROM {} WHERE {}=%s").format(', '.join(self.fields), self.table, self.pk_field)
try:
self.dcur.execute(sql, (self.pk_value,))
self.data = self.dcur.fetchone()
except Exception as e:
print(e)
print(sql)
self.db.error = e
self.clear()
return False
if self.data:
for field, value in self.data.items():
setattr(self, field, value)
return True
else:
self.clear()
return False
def save(self, rev_id=None):
self.last_update = datetime.now()
if self.pk_value is not None:
ret = self._update()
else:
ret = self._insert()
if ret == True and rev_id is not None:
# set list change marker
sql = (
"INSERT INTO revision (revtype, revid, changed) "
"VALUES ('table', %s, NOW()) "
"ON DUPLICATE KEY UPDATE changed = NOW()"
)
self.cur.execute(sql, (rev_id,))
return ret
def _update(self):
sqlfield = []
values = []
if self.pk_is_auto:
if type(self.pk_field) == tuple:
flist = set(self.fields) - set(self.pk_field)
else:
flist = set(self.fields) - {self.pk_field}
else:
flist = self.fields
for field in flist:
newdata = getattr(self, field)
if self.data[field] != newdata:
sqlfield.append("{}=%s".format(field))
values.append(newdata)
if values:
# only save if there are changes
sql = (
f"UPDATE {self.table} SET " + ",".join(sqlfield) +
f" WHERE {self.pk_field}=%s"
)
values.append(self.pk_value)
try:
self.cur.execute(sql, values)
except Exception as e:
print(e)
print(sql)
print(values)
self.db.error = e
return False
for field in self.fields:
self.data[field] = getattr(self, field)
return True
def _insert(self):
if self.pk_is_auto:
if type(self.pk_field) == tuple:
flist = set(self.fields) - set(self.pk_field)
else:
flist = set(self.fields) - {self.pk_field}
else:
flist = self.fields
sql = (
"INSERT INTO {} ({}) "
"VALUES ({})"
).format(
self.table,
','.join(flist),
','.join(["%s"] * len(flist))
)
values = []
for field in flist:
newdata = getattr(self, field)
values.append(newdata)
self.data[field] = newdata
try:
self.cur.execute(sql, values)
except Exception as e:
print(e)
print(sql)
print(values)
self.db.error = e
return False
self.pk_value = self.cur.lastrowid
setattr(self, self.pk_field, self.pk_value)
return True
def delete(self, record_id=None):
if record_id is None:
if self.pk_value is None:
return False
record_id = self.pk_value
sql = "DELETE FROM {} WHERE {}=%s".format(self.table, self.pk_field)
try:
self.dcur.execute(sql, (record_id,))
except Exception as e:
print(e)
print(sql)
self.db.error = e
return False
if self.dcur.rowcount != 1:
return False
if self.pk_value == record_id:
self.pk_value = None
self.clear()
return True
def __str__(self):
out = [self._title.format(self.pk_value)]
for field in self.fields:
value = getattr(self, field, None)
oldvalue = self.data[field]
if value != oldvalue:
out.append(" {:15}: {} ({})".format(field, value, oldvalue))
else:
out.append(" {:15}: {}".format(field, value))
return "\n".join(out)
+26
View File
@@ -0,0 +1,26 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
class Document(DbRecord):
table = "document"
pk_field = "docid"
pk_is_auto = True
fields = ('docid', 'doctype', 'mimetype', 'filename', 'extension',
'hash', 'docsize', 'doctime', 'docdate', 'title', 'pages', 'remarks',
'roleaccess')
def __init__(self, db, docid=None):
super().__init__(db, docid)
self.title = _("Document({})")
def save(self, commit=True):
if not super().save():
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+27
View File
@@ -0,0 +1,27 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
from yms.lookup import Table
class Equipment(DbRecord):
table = "equipment"
pk_field = "eid"
pk_is_auto = True
fields = ('eid', 'vid', 'ename', 'shortname', 'model', 'ecat',
'serial', 'supplier', 'manufacturer', 'purchdate', 'price', 'weight',
'remarks', 'econd', 'flags')
def __init__(self, db, eid=None):
super().__init__(db, eid)
self.title = _("Equipment({})")
def save(self, commit=True):
if not super().save(Table.EQUIPMENT):
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+26
View File
@@ -0,0 +1,26 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
from yms.lookup import Table
class Fuse(DbRecord):
table = "fuse"
pk_field = "fuseid"
pk_is_auto = True
fields = ('fuseid', 'vid', 'fnumber', 'ftype', 'current',
'cableid', 'eid', 'location', 'description', 'color', 'remarks')
def __init__(self, db, fuseid=None):
super().__init__(db, fuseid)
self.title = _("Fuse({})")
def save(self, commit=True):
if not super().save(Table.FUSES):
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+27
View File
@@ -0,0 +1,27 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
from yms.lookup import Table
class Inventory(DbRecord):
table = "inventory"
pk_field = "invid"
pk_is_auto = True
fields = ('invid', 'invname', 'icat', 'conttype', 'sid', 'boxid',
'eid', 'number', 'weight', 'price', 'purchdate', 'invcond', 'remarks',
'flags')
def __init__(self, db, invid=None):
super().__init__(db, invid)
self.title = _("Inventory({})")
def save(self, commit=True):
if not super().save():
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+26
View File
@@ -0,0 +1,26 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
class Maintenance(DbRecord):
table = "maintenance"
pk_field = "maintid"
pk_is_auto = True
fields = ('maintid', 'vid', 'eid', 'series', 'activities',
'plan_date', 'plan_precision', 'completion_date', 'interval_hours',
'last_hours', 'remarks', 'maintstate')
def __init__(self, db, maintid=None):
super().__init__(db, maintid)
self.title = _("Maintenance({})")
def save(self, commit=True):
if not super().save():
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+25
View File
@@ -0,0 +1,25 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
class Measurement(DbRecord):
table = "measurement"
pk_field = "mid"
pk_is_auto = True
fields = ('mid', 'mname', 'vid', 'eid', 'nval', 'val1', 'val2',
'val3', 'unit', 'accuracy', 'mdate', 'mcat', 'note')
def __init__(self, db, mid=None):
super().__init__(db, mid)
self.title = _("Measurement({})")
def save(self, commit=True):
if not super().save():
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+26
View File
@@ -0,0 +1,26 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
from yms.lookup import Table
class Project(DbRecord):
table = "project"
pk_field = "projid"
pk_is_auto = True
fields = ('projid', 'projname', 'vid', 'responsible', 'startdate',
'duration', 'costs_plan', 'costs_final', 'remarks', 'projstate')
def __init__(self, db, projid=None):
super().__init__(db, projid)
self.title = _("Project({})")
def save(self, commit=True):
if not super().save(Table.PROJECTS):
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+26
View File
@@ -0,0 +1,26 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
class Provision(DbRecord):
table = "provisions"
pk_field = "provid"
pk_is_auto = True
fields = ('provid', 'provname', 'provcat', 'sid', 'boxid',
'number','target', 'weight', 'weight_net', 'unit', 'calories',
'storedate', 'shelflife', 'price', 'remarks')
def __init__(self, db, provid=None):
super().__init__(db, provid)
self.title = _("Provision({})")
def save(self, commit=True):
if not super().save():
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+35
View File
@@ -0,0 +1,35 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
from yms.lookup import Table
# names for fixed dropdown values
GENERIC = 0
TANK = 1
EXT = 2
class Storage(DbRecord):
table = "storage"
pk_field = "sid"
pk_is_auto = True
fields = ('sid', 'vid', 'sname', 'stype', 'capacity', 'capaunit',
'x', 'y', 'z', 'wx', 'wy', 'wz', 'angle', 'color', 'remarks')
def __init__(self, db, sid=None):
super().__init__(db, sid)
self.title = _("Storage({})")
def save(self, commit=True):
if not super().save(Table.STORAGE):
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
def delete(self):
# there must be no associated data!
pass
+26
View File
@@ -0,0 +1,26 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
class Task(DbRecord):
table = "task"
pk_field = "taskid"
pk_is_auto = True
fields = ('taskid', 'vid', 'projid', 'taskname', 'priority',
'taskstate', 'state_ts', 'plandate', 'duedate', 'started', 'finished',
'responsible', 'remarks')
def __init__(self, db, taskid=None):
super().__init__(db, taskid)
self.title = _("Task({})")
def save(self, commit=True):
if not super().save():
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
+19 -5
View File
@@ -1,4 +1,4 @@
# -*- coding: utf-8 -*- # SPDX-License-Identifier: WTFPL
import MySQLdb.cursors import MySQLdb.cursors
import bcrypt import bcrypt
@@ -11,9 +11,9 @@ class User(object):
def genpass(cls, length=12): def genpass(cls, length=12):
return ''.join(random.choices(string.ascii_letters + string.digits, k=length)) return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
def __init__(self, dbconn, user_id=None): def __init__(self, db, user_id=None):
self.conn = dbconn self.conn = db.conn
self.cur = dbconn.cursor(MySQLdb.cursors.DictCursor) self.cur = db.conn.cursor(MySQLdb.cursors.DictCursor)
if user_id is not None: if user_id is not None:
self.user_id = int(user_id) self.user_id = int(user_id)
self.load() self.load()
@@ -104,6 +104,13 @@ class User(object):
# create mandatory settings # create mandatory settings
sql = "INSERT INTO settings (userid, sno, valint) VALUES (%s, 1, 0)" sql = "INSERT INTO settings (userid, sno, valint) VALUES (%s, 1, 0)"
self.cur.execute(sql, (newid,)) self.cur.execute(sql, (newid,))
# set list change marker
sql = (
"INSERT INTO revision (revtype, revid, changed) "
"VALUES ('table', 2, NOW()) "
"ON DUPLICATE KEY UPDATE changed = NOW()"
)
self.db.cur.execute()
self.conn.commit() self.conn.commit()
return newid return newid
@@ -112,6 +119,13 @@ class User(object):
self.cur.execute(sql, (self.user_id,)) self.cur.execute(sql, (self.user_id,))
sql = "DELETE FROM user WHERE userid=%s" sql = "DELETE FROM user WHERE userid=%s"
self.cur.execute(sql, (self.user_id,)) self.cur.execute(sql, (self.user_id,))
# set list change marker
sql = (
"INSERT INTO revision (revtype, revid, changed) "
"VALUES ('table', 2, NOW()) "
"ON DUPLICATE KEY UPDATE changed = NOW()"
)
self.db.cur.execute()
self.conn.commit() self.conn.commit()
def setpass(self, newpass): def setpass(self, newpass):
@@ -123,7 +137,7 @@ class User(object):
def __repr__(self): def __repr__(self):
# Unique description # Unique description
out = "User(%d)" % self.user_id out = "User({})".format(self.user_id)
return out return out
def __str__(self): def __str__(self):
+66
View File
@@ -0,0 +1,66 @@
# SPDX-License-Identifier: WTFPL
from .dbrecord import DbRecord
class Vessel(DbRecord):
table = "vessel"
pk_field = "vid"
pk_is_auto = True
fields = ('vid', 'vtype', 'htype', 'vesselname', 'model',
'shipyard', 'hull_number', 'loa', 'lwl', 'beam', 'draught',
'draught_min', 'displacement', 'ballast', 'beltpos_aft', 'beltpos_bow',
'shapefile', 'sid_default', 'year_built', 'remarks')
def __init__(self, db, vid=None):
super().__init__(db, vid)
self.title = _("Vessel({})")
def create(self):
self.clear()
sql = (
"SELECT IFNULL(MIN(v1.vid+1), 1) AS newid "
"FROM vessel AS v1 LEFT JOIN vessel AS v2 ON v2.vid=v1.vid+1 "
"WHERE v1.vid>=0 AND v2.vid IS NULL"
)
self.dcur.execute(sql)
row = self.dcur.fetchone()
if row is None:
# vessel table empty: create first vessel
self.pk_value = 1
else:
# create additional vessel
self.pk_value = row['newid']
self.vid = self.pk_value
self.vesselname = "Vessel #{}".format(self.pk_value)
self.htype = 'mono'
self._insert()
# set list change marker
sql = (
"INSERT INTO revision (revtype, revid, changed) "
"VALUES ('table', 1, NOW()) "
"ON DUPLICATE KEY UPDATE changed = NOW()"
)
self.db.cur.execute(sql)
self.conn.commit()
def save(self, commit=True):
if not super().save():
return False
if commit:
try:
self.conn.commit()
except mariadb.Error as e:
return False
return True
def delete(self):
# there must be no assiciated data!
pass
# set list change marker
sql = (
"INSERT INTO revision (revtype, revid, changed) "
"VALUES ('table', 1, NOW()) "
"ON DUPLICATE KEY UPDATE changed = NOW()"
)
self.db.cur.execute()
+10
View File
@@ -0,0 +1,10 @@
.field-name {
color: #3D3846;
}
.field-value {
color: black;
}
.invalid {
color: #cc0000;
background-color: #ffdddd;
}
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more