Compare commits
35
Commits
a4c5659701
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6471070a6 | ||
|
|
c6544f29c8 | ||
|
|
bd3ca2f413 | ||
|
|
87366336c5 | ||
|
|
140b272f6c | ||
|
|
a7461f6e2c | ||
|
|
3c07be0160 | ||
|
|
61cf7696a5 | ||
|
|
3d9ad49020 | ||
|
|
1b6d0c40f3 | ||
|
|
235ef32efd | ||
|
|
85598adaab | ||
|
|
70934a2f85 | ||
|
|
5cec28cad1 | ||
|
|
d57e66c033 | ||
|
|
d9114d21c7 | ||
|
|
2108ef2418 | ||
|
|
a2d1d42362 | ||
|
|
32bcb1b18a | ||
|
|
1e4aadee06 | ||
|
|
a82e75999b | ||
|
|
7b95b69c7b | ||
|
|
e0aef726bd | ||
|
|
7707a9da6d | ||
|
|
ca2e2e2e4a | ||
|
|
208cc54e53 | ||
|
|
f7dd572fe1 | ||
|
|
69dba202d0 | ||
|
|
3d6bd7bac5 | ||
|
|
0f9be13e31 | ||
|
|
be86248cce | ||
|
|
01d060cf5f | ||
|
|
8c5b34073d | ||
|
|
fe81014794 | ||
|
|
f308bca1fb |
@@ -5,3 +5,4 @@ jon/config.json
|
||||
elm-stuff/
|
||||
venv/
|
||||
.venv/
|
||||
jon/static/*.js
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
FROM debian:latest as builder
|
||||
|
||||
RUN apt-get update
|
||||
RUN apt-get upgrade -y
|
||||
RUN apt-get install -y elm-compiler make ca-certificates
|
||||
|
||||
COPY . /app
|
||||
WORKDIR /app
|
||||
RUN rm -rf .venv venv
|
||||
|
||||
RUN make frontend
|
||||
|
||||
|
||||
FROM python:3.11-alpine as runner
|
||||
COPY --from=builder /app /app
|
||||
|
||||
WORKDIR /app
|
||||
RUN pip install -r requirements.txt
|
||||
RUN pip install gunicorn
|
||||
|
||||
EXPOSE 5000
|
||||
ENV JON_DB_CONNECTION_STRING="host=fsmi-db.fsmi.org dbname=garfield"
|
||||
ENV JON_SECRET_KEY="changeme"
|
||||
|
||||
CMD ["sh", "-c", "gunicorn -b '0.0.0.0:5000' --chdir /app 'jon:create_app()'"]
|
||||
@@ -0,0 +1,6 @@
|
||||
.PHONY: frontend
|
||||
|
||||
frontend: jon/static/entry.js
|
||||
|
||||
jon/static/entry.js: $(shell find frontend -name '*.elm')
|
||||
elm make --optimize frontend/Entry.elm --output $@
|
||||
@@ -4,6 +4,11 @@
|
||||
|
||||
## Setup
|
||||
|
||||
`jon` is a Python WSGI application written using Flask.
|
||||
This means you'll have to install a bunch of Python packages to get up and running.
|
||||
|
||||
### Dependencies
|
||||
|
||||
```
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
@@ -11,6 +16,27 @@ pip install -r requirements.txt
|
||||
You should probably use a virtualenv for that.
|
||||
I develop `jon` using Python 3.10 but it should work with older versions as well.
|
||||
|
||||
#### Arch Linux
|
||||
|
||||
If you're on Arch, these packages are required for running the server:
|
||||
|
||||
```
|
||||
python python-flask python-flask-login python-psycopg2
|
||||
```
|
||||
|
||||
### Building Frontend JS
|
||||
|
||||
Most of jon works without JS but there are some features that require it.
|
||||
The frontend code lives in `./frontend` and is written using Elm, a functional language that compiles to JS.
|
||||
To compile the Elm code to `.js` files, first make sure that the Elm compiler is installed:
|
||||
|
||||
```
|
||||
elm --version
|
||||
# 0.19.1
|
||||
```
|
||||
|
||||
Then run `make frontend`.
|
||||
|
||||
## Running
|
||||
|
||||
```
|
||||
@@ -19,6 +45,20 @@ flask --app jon run --debug
|
||||
|
||||
`--debug` restarts the server when a source file changes.
|
||||
|
||||
## Running with docker
|
||||
When you prefer running the application using docker you can just use
|
||||
```
|
||||
docker compose up
|
||||
```
|
||||
|
||||
In case your local username does not line up with your FSMI-username, you need to specify your FSMI-username
|
||||
using `USER=<username>`, e.g.:
|
||||
```
|
||||
USER=shirkanesi docker compose up
|
||||
```
|
||||
|
||||
This can also be persisted by following the instructions in the docker-compose.yml
|
||||
|
||||
## fsmi-db forward
|
||||
|
||||
```
|
||||
@@ -27,13 +67,19 @@ ssh -nNTvL 5432:fsmi-db.fsmi.org:5432 fsmi-login.fsmi.uni-karlsruhe.de
|
||||
|
||||
## TODO
|
||||
|
||||
- [ ] Implement item and snack entry as Elm application
|
||||
- [ ] Needs good documentation for maintainability
|
||||
- [ ] Implement and document report generation
|
||||
- [ ] How many days will the item last?
|
||||
- [ ] How many do we need to last X months?
|
||||
- [ ] etc.
|
||||
- [ ] Make it print nicely
|
||||
- [ ] Make it possible to edit entries
|
||||
- [ ] Fix unsafe client-side sessions, either:
|
||||
- [ ] Use `flask-session` for file-backed sessions
|
||||
- [ ] Use `flask-login` with a single user stored in memory
|
||||
- [ ] Improve project structure
|
||||
- [ ] Figure out/Add documentation about building `entry.js`
|
||||
- [ ] Use `flask.flash` for error messages
|
||||
- [x] Implement item and snack entry as Elm application
|
||||
- [x] Figure out/Add documentation about building `entry.js`
|
||||
- [ ] Clean up the code a little and add some comments
|
||||
- [ ] Needs good documentation for maintainability
|
||||
- [ ] Use cool new function for deactivating items
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
version: '3.7'
|
||||
|
||||
services:
|
||||
jon:
|
||||
container_name: jon
|
||||
build: .
|
||||
ports:
|
||||
- "5000:5000"
|
||||
volumes:
|
||||
- ~/.pgpass:/root/.pgpass:ro
|
||||
dns:
|
||||
- 1.1.1.1
|
||||
- 8.8.8.8
|
||||
network_mode: bridge
|
||||
environment:
|
||||
# If your local user is different from your fsmi user, change $USER here!
|
||||
- JON_DB_CONNECTION_STRING="host=fsmi-db.fsmi.org dbname=garfield user=$USER"
|
||||
- JON_SECRET_KEY="changemetosomethingsuperrandomandsecure"
|
||||
+49
-24
@@ -9,7 +9,15 @@ import Select
|
||||
|
||||
type Tax = Net | Gross
|
||||
|
||||
ctShow ct = case ct of
|
||||
-- Duplicated from Entry.elm but too lazy to sandwich this out
|
||||
type alias TaxGroup =
|
||||
{ id : Int
|
||||
, description : String
|
||||
, percentage : Float
|
||||
}
|
||||
|
||||
showTax : Tax -> String
|
||||
showTax tax = case tax of
|
||||
Gross -> "Brutto"
|
||||
Net -> "Netto"
|
||||
|
||||
@@ -19,11 +27,13 @@ type alias Model =
|
||||
, bundleSize : NumberInput.Model Int
|
||||
}
|
||||
|
||||
init : Float -> Model
|
||||
init bundlePrice = Model
|
||||
(Select.init ctShow ctShow Net [Net, Gross])
|
||||
(Select.init showTax showTax Net [Net, Gross])
|
||||
(NumberInput.fromFloat bundlePrice)
|
||||
(NumberInput.fromInt 1)
|
||||
|
||||
getResult : Model -> TaxGroup -> Maybe Float
|
||||
getResult model taxGroup =
|
||||
case (NumberInput.get model.bundlePrice, NumberInput.get model.bundleSize) of
|
||||
(Just bundlePrice, Just bundleSize) ->
|
||||
@@ -41,6 +51,7 @@ type Msg
|
||||
| SetBundlePrice String
|
||||
| SetBundleSize String
|
||||
|
||||
update : Msg -> Model -> Model
|
||||
update msg model = case msg of
|
||||
SetTax key ->
|
||||
{ model | tax = Select.update key model.tax }
|
||||
@@ -49,42 +60,55 @@ update msg model = case msg of
|
||||
SetBundleSize str ->
|
||||
{ model | bundleSize = NumberInput.update str model.bundleSize }
|
||||
|
||||
view : Model -> TaxGroup -> Html Msg
|
||||
view model taxGroup =
|
||||
let
|
||||
mainPart =
|
||||
[ text "("
|
||||
, input
|
||||
[ class "formula-input", placeholder "Gebindepreis"
|
||||
, value <| NumberInput.show model.bundlePrice
|
||||
, onInput SetBundlePrice
|
||||
, div [ class "form-input --inline" ]
|
||||
[ label [ for "bundle-price" ] [ text "Gebindepreis" ]
|
||||
, input
|
||||
[ placeholder "Gebindepreis"
|
||||
, value <| NumberInput.show model.bundlePrice
|
||||
, onInput SetBundlePrice
|
||||
, id "bundle-price"
|
||||
, type_ "number"
|
||||
, step "0.01"
|
||||
]
|
||||
[]
|
||||
]
|
||||
[]
|
||||
, text " ÷ "
|
||||
, input
|
||||
[ class "formula-input", placeholder "Gebindegröße"
|
||||
, value <| NumberInput.show model.bundleSize
|
||||
, onInput SetBundleSize
|
||||
, div [ class "form-input --inline" ]
|
||||
[ label [ for "bundle-size" ] [ text "Gebindegröße" ]
|
||||
, input
|
||||
[ placeholder "Gebindegröße"
|
||||
, value <| NumberInput.show model.bundleSize
|
||||
, onInput SetBundleSize
|
||||
, id "bundle-size"
|
||||
, type_ "number"
|
||||
, step "1"
|
||||
]
|
||||
[]
|
||||
]
|
||||
[]
|
||||
, text ") "
|
||||
]
|
||||
taxPart =
|
||||
[ text " ÷ "
|
||||
, input
|
||||
[ class "formula-input"
|
||||
, disabled True
|
||||
, value <| String.fromFloat <| 1 + taxGroup.percentage
|
||||
, div [ class "form-input --inline" ]
|
||||
[ label [ for "tax" ] [ text "Steuer" ]
|
||||
, input
|
||||
[ value <| String.fromFloat <| 1 + taxGroup.percentage
|
||||
, id "tax"
|
||||
, type_ "number"
|
||||
, step "0.01"
|
||||
, disabled True
|
||||
]
|
||||
[]
|
||||
]
|
||||
[]
|
||||
]
|
||||
resultPart =
|
||||
[ text " = "
|
||||
, input
|
||||
[ class "formula-input"
|
||||
, disabled True
|
||||
, value <| Maybe.withDefault "?" <| Maybe.map String.fromFloat <| getResult model taxGroup
|
||||
]
|
||||
[]
|
||||
, text <| Maybe.withDefault "?" <| Maybe.map String.fromFloat <| getResult model taxGroup
|
||||
]
|
||||
in
|
||||
fieldset []
|
||||
@@ -100,4 +124,5 @@ view model taxGroup =
|
||||
]
|
||||
]
|
||||
|
||||
roundTo places x = toFloat (round <| x * 10 ^ places) / 10 ^ places
|
||||
roundTo : Int -> Float -> Float
|
||||
roundTo places x = toFloat (round <| x * 10 ^ toFloat places) / 10 ^ toFloat places
|
||||
|
||||
+75
-9
@@ -14,6 +14,50 @@ import Calculator
|
||||
import NumberInput
|
||||
import Select
|
||||
|
||||
{-
|
||||
Elm forces us to use the Elm architecture:
|
||||
|
||||
┌──────┐
|
||||
┌─────Model──► view ├──Html───────┐
|
||||
│ └──────┘ │
|
||||
│ │
|
||||
┌┴─────────────────────────────────▼┐
|
||||
│ Elm runtime │
|
||||
└▲─────────────────────────────────┬┘
|
||||
│ │
|
||||
│ ┌──────┐ │
|
||||
└─Model+Cmd──┤update◄──Msg+Model──┘
|
||||
└──────┘
|
||||
|
||||
This architecture is similar to what React does but its implementation
|
||||
in Elm is a bit special since it's purely functional and side effects
|
||||
are isolated into the runtime system.
|
||||
|
||||
An Elm component is usually centered around two types, Model and Msg.
|
||||
Model contains all data the application is concerned with, including the state
|
||||
of UI elements. Msg encodes all updates to Model that the application supports.
|
||||
|
||||
In addition to Msg and Model, we have to provide two functions, view and update.
|
||||
|
||||
view : Model -> Html Msg
|
||||
update : Msg -> Model -> (Model, Cmd Msg)
|
||||
|
||||
view maps a Model to a DOM tree. Events in this DOM tree create Msg values.
|
||||
update maps a Msg and a Model to a new Model. In addition, update can create
|
||||
a command. Commands are used to make the runtime do side effects, which in
|
||||
turn create new Msg values.
|
||||
|
||||
For example, we have a SetSearchTerm message which simply updates the searchTerm
|
||||
property in the model. This message is triggered every time the search box input
|
||||
is changed. Submitting the search box form triggers a SubmitSearch event.
|
||||
This event leaves the model unchanged but issues a command that sends the search
|
||||
term to a JSON endpoint. When the request successfully resolves, the runtime
|
||||
triggers a ReceiveSearchResults messages which updates the list of search results
|
||||
in the model.
|
||||
|
||||
See Calculator.elm for a simpler example of this architecture.
|
||||
-}
|
||||
|
||||
main = Browser.element
|
||||
{ init = \globals ->
|
||||
( Context globals <| ItemSearch { searchTerm = "", searchResults = [] }
|
||||
@@ -38,6 +82,7 @@ type alias SearchResult =
|
||||
, groupName : String
|
||||
, groupId : Int
|
||||
, taxGroupId : Int
|
||||
, unitsLeft : Int
|
||||
}
|
||||
|
||||
searchResultDecoder =
|
||||
@@ -53,6 +98,7 @@ searchResultDecoder =
|
||||
|> P.required "group_name" D.string
|
||||
|> P.required "group_id" D.int
|
||||
|> P.required "tax_group_id" D.int
|
||||
|> P.required "units_left" D.int
|
||||
|
||||
type alias Location =
|
||||
{ id : Int
|
||||
@@ -200,7 +246,7 @@ suggestedGrossPrice netPrice percentage =
|
||||
view { globals, state } = case state of
|
||||
ItemSearch model ->
|
||||
fieldset []
|
||||
[ legend [] [ text "Vorlage für neuen Inventareintrag" ]
|
||||
[ legend [] [ text "Vorlage für Auftrag wählen" ]
|
||||
, Html.form [ onSubmit SubmitSearch ]
|
||||
[ div [ class "form-input" ]
|
||||
[ label [ for "search-term", title "Barcode oder Name" ] [ text "Suchbegriff" ]
|
||||
@@ -210,32 +256,50 @@ view { globals, state } = case state of
|
||||
]
|
||||
]
|
||||
ItemEditor model ->
|
||||
Html.form [ method "POST", action "/entry/add-to-cart" ]
|
||||
Html.form [ method "POST" ]
|
||||
[ fieldset []
|
||||
[ legend [] [ text "Neuer Inventareintrag" ]
|
||||
, div [ class "form-input" ]
|
||||
[ label [ for "barcode" ] [ text "Barcode" ]
|
||||
, input [ onInput SetBarcode, value model.barcode, disabled True, name "barcode", id "barcode" ] []
|
||||
, input [ onInput SetBarcode, value model.barcode, name "barcode", id "barcode" ] []
|
||||
]
|
||||
, div [ class "form-input" ]
|
||||
[ label [ for "name" ] [ text "Name" ]
|
||||
, input [ onInput SetName, value model.name, name "name", id "name" ] []
|
||||
]
|
||||
, div [ class "form-input" ]
|
||||
[ label [ for "sales-units" ] [ text "Stückzahl" ]
|
||||
[ label [ for "sales-units" ] [ text "Eingekauft" ]
|
||||
, input [ onInput SetSalesUnits, value <| NumberInput.show model.salesUnits, name "sales-units", id "sales-units", type_ "number" ] []
|
||||
]
|
||||
, div [ class "form-input" ]
|
||||
[ label [ for "group" ] [ text "Gruppe" ]
|
||||
, Select.view [ name "group", id "group" ] SetGroup model.group
|
||||
, Select.view [ name "group-id", id "group" ] SetGroup model.group
|
||||
, input
|
||||
[ type_ "hidden"
|
||||
, name "group-name"
|
||||
, value <| (Select.get model.group).name
|
||||
]
|
||||
[]
|
||||
]
|
||||
, div [ class "form-input" ]
|
||||
[ label [ for "location" ] [ text "Raum" ]
|
||||
, Select.view [ name "location", id "location" ] SetLocation model.location
|
||||
, Select.view [ name "location-id", id "location" ] SetLocation model.location
|
||||
, input
|
||||
[ type_ "hidden"
|
||||
, name "location-name"
|
||||
, value <| (Select.get model.location).name
|
||||
]
|
||||
[]
|
||||
]
|
||||
, div [ class "form-input" ]
|
||||
[ label [ for "tax-group" ] [ text "Steuergruppe" ]
|
||||
, Select.view [ name "tax-group", id "tax-group" ] SetTaxGroup model.taxGroup
|
||||
, Select.view [ name "tax-group-id", id "tax-group" ] SetTaxGroup model.taxGroup
|
||||
, input
|
||||
[ type_ "hidden"
|
||||
, name "tax-group-description"
|
||||
, value <| (Select.get model.taxGroup).description
|
||||
]
|
||||
[]
|
||||
]
|
||||
, Html.map CalculatorMsg <| Calculator.view model.calculator (Select.get model.taxGroup)
|
||||
, div [ class "form-input" ]
|
||||
@@ -264,7 +328,7 @@ view { globals, state } = case state of
|
||||
[]
|
||||
, viewSetSuggestedPriceButton model
|
||||
]
|
||||
, button [] [ text "In den Warenkorb" ]
|
||||
, button [] [ text "Auftrag anlegen" ]
|
||||
]
|
||||
]
|
||||
|
||||
@@ -321,7 +385,9 @@ viewSearchResult model =
|
||||
, td [] [ text model.locationName ]
|
||||
, td [] [ text <| showBool model.available ]
|
||||
, td []
|
||||
[ button [ onClick <| GotoItemEditor model ] [ text "Als Vorlage verwenden" ]
|
||||
[ Html.form [ onSubmit <| GotoItemEditor model ]
|
||||
[ button [] [ text "Als Vorlage verwenden" ]
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
+4
-6
@@ -20,14 +20,10 @@ def create_app():
|
||||
# You don't need a config.json. If you don't provide one, default-config.json
|
||||
# is used.
|
||||
app.config.from_file("config.json", load=json.load, silent=True)
|
||||
app.config.from_prefixed_env(prefix="JON")
|
||||
|
||||
db.init_app(app)
|
||||
|
||||
# This function denies every request until `auth.ACCESS_TOKEN`
|
||||
# is passed using `?token=` to authenticate the session.
|
||||
@app.before_request
|
||||
def before_req_fun():
|
||||
return auth.before_request()
|
||||
auth.init_app(app)
|
||||
|
||||
@app.context_processor
|
||||
def utility_processor():
|
||||
@@ -43,5 +39,7 @@ def create_app():
|
||||
return render_template("index.html")
|
||||
|
||||
print(f"Jon started. Token: {auth.ACCESS_TOKEN}", file=sys.stderr)
|
||||
# TODO: Get host and port from config
|
||||
print(f"http://localhost:5000/?token={auth.ACCESS_TOKEN}", file=sys.stderr)
|
||||
|
||||
return app
|
||||
|
||||
+63
-20
@@ -1,12 +1,15 @@
|
||||
import random
|
||||
import secrets
|
||||
import string
|
||||
|
||||
from flask import Blueprint, request, redirect, render_template, session
|
||||
from flask import Blueprint, request, redirect, render_template
|
||||
from flask_login import current_user, login_user, logout_user, LoginManager
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
bp = Blueprint("auth", __name__, url_prefix="/auth")
|
||||
|
||||
|
||||
ACCESS_TOKEN = "".join(random.choice(string.ascii_lowercase) for i in range(64))
|
||||
ACCESS_TOKEN = "".join(secrets.choice(string.ascii_lowercase) for i in range(64))
|
||||
|
||||
|
||||
ALLOWED_PATHS = [
|
||||
@@ -15,27 +18,67 @@ ALLOWED_PATHS = [
|
||||
]
|
||||
|
||||
|
||||
def before_request():
|
||||
"""
|
||||
If the correct token query parameter is passed along with any request,
|
||||
we mark this session authenticated by setting `session["authenticated"]`.
|
||||
Unless the session is authenticated, all requests result in a 403 FORBIDDEN.
|
||||
"""
|
||||
if "token" in request.args:
|
||||
if request.args["token"] == ACCESS_TOKEN:
|
||||
session["authenticated"] = ()
|
||||
# Reload the page without query parameters
|
||||
return redirect(request.path)
|
||||
# A poor man's replacement for memory-backed session solution.
|
||||
# We keep exactly one User (and the corresponding UserData) in
|
||||
# memory and use that to store session data.
|
||||
class UserData:
|
||||
location: Optional[Dict[str, Any]]
|
||||
orders: List[Dict[str, Any]]
|
||||
|
||||
# Don't deny any paths in `ALLOWED_PATHS`
|
||||
if request.path in ALLOWED_PATHS:
|
||||
return
|
||||
def __init__(self):
|
||||
self.location = None
|
||||
self.orders = []
|
||||
|
||||
if not "authenticated" in session:
|
||||
return render_template("auth/denied.html"), 403
|
||||
|
||||
class User:
|
||||
is_authenticated: bool
|
||||
is_active: bool
|
||||
is_anonymous: bool
|
||||
|
||||
data: UserData
|
||||
|
||||
def __init__(self):
|
||||
self.is_authenticated = True
|
||||
self.is_active = True
|
||||
self.is_anonymous = False
|
||||
|
||||
self.data = UserData()
|
||||
|
||||
def get_id(self) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def init_app(app):
|
||||
login_manager = LoginManager(app)
|
||||
the_one_and_only_user = User()
|
||||
|
||||
@login_manager.user_loader
|
||||
def load_user(user_id: str) -> User:
|
||||
assert user_id == ""
|
||||
return the_one_and_only_user
|
||||
|
||||
# This function denies every request until `auth.ACCESS_TOKEN`
|
||||
# is passed using `?token=` to authenticate the user.
|
||||
# We use this instead of @login_required because otherwise we'd have
|
||||
# to add that annotation to all routes.
|
||||
# See also: https://flask-login.readthedocs.io/en/latest/#flask_login.login_required
|
||||
@app.before_request
|
||||
def before_request():
|
||||
if "token" in request.args:
|
||||
if request.args["token"] == ACCESS_TOKEN:
|
||||
login_user(the_one_and_only_user)
|
||||
# Reload the page without query parameters
|
||||
return redirect(request.path)
|
||||
|
||||
# Never deny any paths in `ALLOWED_PATHS`
|
||||
if request.path in ALLOWED_PATHS:
|
||||
return
|
||||
|
||||
if not current_user.is_authenticated:
|
||||
return render_template("auth/denied.html"), 403
|
||||
|
||||
|
||||
@bp.get("/logout")
|
||||
def logout():
|
||||
session.pop("authenticated", None)
|
||||
logout_user()
|
||||
return redirect("/")
|
||||
|
||||
@@ -7,8 +7,6 @@ from psycopg2.extras import RealDictCursor
|
||||
|
||||
def get_db():
|
||||
if "db" not in g:
|
||||
# TODO: Make this configurable and use a default that works
|
||||
# on the pool computers.
|
||||
g.db = psycopg2.connect(current_app.config["DB_CONNECTION_STRING"])
|
||||
run_query_on(g.db, "add_views.sql", None)
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ SELECT
|
||||
inventory_items.available,
|
||||
inventory_items.item_group,
|
||||
inventory_items.location,
|
||||
inventory_items.tax_group,
|
||||
inventory_item_groups.group_name,
|
||||
COALESCE(b.sales::numeric, 0::numeric) - COALESCE(cancel.count::numeric, 0::numeric) AS sales,
|
||||
inventory_items.sales_units::numeric - COALESCE(b.sales, 0::bigint)::numeric + COALESCE(c.delta, 0::numeric) + COALESCE(cancel.count::numeric, 0::numeric) AS units_left,
|
||||
@@ -57,3 +58,56 @@ FROM garfield.inventory_items
|
||||
) m USING (item_id)
|
||||
ORDER BY inventory_items.name;
|
||||
|
||||
-- How many *other* active inventory lines exist with the same barcode in the same location that are newer?
|
||||
CREATE TEMPORARY VIEW more_recent_inventory_lines_with_same_barcode AS
|
||||
SELECT
|
||||
a.item_id,
|
||||
-- It's important not to count(*) here because item_id is NULL
|
||||
-- when no other inventory lines exist.
|
||||
count(b.item_id) AS other_lines_count
|
||||
FROM garfield.inventory_items AS a
|
||||
LEFT JOIN garfield.inventory_items AS b
|
||||
ON a.item_barcode = b.item_barcode
|
||||
AND a.item_id != b.item_id
|
||||
AND a.location = b.location
|
||||
AND b.available
|
||||
AND b.bought > a.bought
|
||||
GROUP BY a.item_id;
|
||||
|
||||
-- We need to create this table so that we can put an index on it
|
||||
-- Otherwise the join in the consumption graph query becomes much slower
|
||||
-- Perhaps it would be nicer to use a materialized view instead
|
||||
DROP TABLE IF EXISTS last_n_days;
|
||||
CREATE TEMPORARY TABLE last_n_days AS (
|
||||
SELECT
|
||||
generate_series(now() - interval '14 days', now(), interval '1 day')::date AS sale_date
|
||||
);
|
||||
CREATE UNIQUE INDEX last_n_days_sale_date ON last_n_days (sale_date);
|
||||
|
||||
-- Get an array of how often items were sold over the last 14 days
|
||||
CREATE TEMPORARY VIEW inventory_last_n_days_sales AS
|
||||
WITH
|
||||
sales_by_date AS (
|
||||
SELECT
|
||||
inventory_line AS item_id,
|
||||
date_trunc('day', snack_sales_log_timestamp AT TIME ZONE 'UTC+1') AS sale_date,
|
||||
count(*)::int AS sales
|
||||
FROM garfield.snack_sales_log
|
||||
GROUP BY item_id, sale_date
|
||||
),
|
||||
beeg AS (
|
||||
SELECT item_id, sale_date, count(snack_sales_log_timestamp)::int AS sales
|
||||
FROM garfield.inventory_items
|
||||
CROSS JOIN last_n_days
|
||||
LEFT JOIN garfield.snack_sales_log
|
||||
ON inventory_line = item_id
|
||||
-- snack_sales_log has an index on snack_sales_log_timestamp to speed up this query
|
||||
-- If that index doesn't exist the query takes much longer.
|
||||
AND sale_date = date_trunc('day', snack_sales_log_timestamp AT TIME ZONE 'UTC+1')
|
||||
WHERE available
|
||||
GROUP BY item_id, sale_date
|
||||
ORDER BY item_id, sale_date
|
||||
)
|
||||
SELECT item_id, array_agg(sales) AS last_n_days_sales
|
||||
FROM beeg
|
||||
GROUP BY item_id
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
DO $$
|
||||
DECLARE new_item_id integer;
|
||||
DECLARE new_snack_id integer;
|
||||
BEGIN
|
||||
|
||||
-- Create a new inventory line
|
||||
INSERT INTO garfield.inventory_items
|
||||
(item_barcode, name, item_group, location, tax_group, sales_units, unit_price)
|
||||
VALUES
|
||||
(%(barcode)s, %(name)s, %(group_id)s, %(location_id)s, %(tax_group_id)s, %(sales_units)s, %(net_unit_price)s)
|
||||
RETURNING item_id INTO new_item_id;
|
||||
|
||||
-- Delete (i.e. mark as inactive) any old snacks with the same barcode in the given location
|
||||
PERFORM garfield.snack_delete(snack_id)
|
||||
FROM garfield.snacks
|
||||
WHERE snack_barcode = %(barcode)s
|
||||
AND location_id = %(location_id)s;
|
||||
|
||||
-- Create a new snack entry...
|
||||
SELECT garfield.snack_create(%(name)s, %(barcode)s, %(gross_unit_price)s, %(tax_group_id)s, %(location_id)s)
|
||||
INTO new_snack_id;
|
||||
|
||||
-- ... and map it to the new inventory line
|
||||
PERFORM garfield.inventory_map_snack(new_snack_id, new_item_id);
|
||||
|
||||
END$$
|
||||
@@ -1,6 +1,8 @@
|
||||
SELECT
|
||||
*
|
||||
FROM all_inventory_item_overview
|
||||
LEFT JOIN more_recent_inventory_lines_with_same_barcode USING (item_id)
|
||||
LEFT JOIN inventory_last_n_days_sales USING (item_id)
|
||||
WHERE (%(location_id)s IS NULL OR location = %(location_id)s)
|
||||
AND available
|
||||
ORDER BY
|
||||
|
||||
@@ -6,13 +6,12 @@ SELECT
|
||||
sales_units,
|
||||
available,
|
||||
location_name,
|
||||
location_id,
|
||||
location as location_id,
|
||||
group_name,
|
||||
item_group AS group_id,
|
||||
tax_group AS tax_group_id
|
||||
FROM garfield.inventory_items
|
||||
LEFT JOIN garfield.locations ON location = location_id
|
||||
LEFT JOIN garfield.inventory_item_groups ON item_group = group_id
|
||||
tax_group AS tax_group_id,
|
||||
units_left :: integer
|
||||
FROM all_inventory_item_overview
|
||||
WHERE (%(location_id)s IS NULL OR location = %(location_id)s)
|
||||
AND (name ILIKE CONCAT('%%', %(search_term)s, '%%') OR item_barcode = %(search_term)s)
|
||||
ORDER BY bought DESC
|
||||
|
||||
+92
-11
@@ -1,5 +1,5 @@
|
||||
from flask import Blueprint, redirect, render_template, request, session
|
||||
|
||||
from flask import Blueprint, flash, redirect, render_template, request
|
||||
from flask_login import current_user
|
||||
|
||||
from . import db
|
||||
|
||||
@@ -7,8 +7,84 @@ from . import db
|
||||
bp = Blueprint("entry", __name__, url_prefix="/entry")
|
||||
|
||||
|
||||
@bp.get("/")
|
||||
@bp.route("/", methods=["GET", "POST"])
|
||||
def index():
|
||||
return render_template(
|
||||
"entry/index.html"
|
||||
)
|
||||
|
||||
|
||||
@bp.post("/add-new-items")
|
||||
def add_new_entries():
|
||||
i_know_what_im_doing = "i-know-what-im-doing" in request.form
|
||||
if not i_know_what_im_doing:
|
||||
return "Du weißt nicht was du tust", 400
|
||||
|
||||
orders = current_user.data.orders
|
||||
if not orders:
|
||||
return "Keine Aufträge", 404
|
||||
|
||||
# I'm aware of execute_many and extras.execute_values but we don't need to
|
||||
# optimize here (yet?). This way it's a bit easier to use anyways.
|
||||
for order in orders:
|
||||
with db.run_query("entry/add_item_and_snack_entry.sql", order) as cursor:
|
||||
pass
|
||||
db.get_db().commit()
|
||||
|
||||
# Reset the cart
|
||||
current_user.data.orders = []
|
||||
|
||||
return redirect(request.referrer)
|
||||
|
||||
|
||||
@bp.post("/delete-order")
|
||||
def delete_order():
|
||||
try:
|
||||
order_index = int(request.form["order-index"])
|
||||
except:
|
||||
return "Incomplete or mistyped form", 400
|
||||
|
||||
del current_user.data.orders[order_index]
|
||||
|
||||
return redirect(request.referrer)
|
||||
|
||||
|
||||
@bp.route("/new-order", methods=["GET", "POST"])
|
||||
def new_order():
|
||||
if request.method == "POST":
|
||||
try:
|
||||
barcode = request.form["barcode"]
|
||||
name = request.form["name"]
|
||||
sales_units = int(request.form["sales-units"])
|
||||
group_id = int(request.form["group-id"])
|
||||
# group_name, location_name and tax_group_description are not
|
||||
# necessarily needed here but storing them makes it easier to
|
||||
# render the list of orders.
|
||||
group_name = request.form["group-name"]
|
||||
location_id = int(request.form["location-id"])
|
||||
location_name = request.form["location-name"]
|
||||
tax_group_id = int(request.form["tax-group-id"])
|
||||
tax_group_description = request.form["tax-group-description"]
|
||||
net_unit_price = float(request.form["net-unit-price"])
|
||||
gross_unit_price = float(request.form["gross-unit-price"])
|
||||
except:
|
||||
return f"Incomplete or mistyped form", 400
|
||||
|
||||
current_user.data.orders.append({
|
||||
"barcode": barcode,
|
||||
"name": name,
|
||||
"sales_units": sales_units,
|
||||
"group_id": group_id,
|
||||
"group_name": group_name,
|
||||
"location_id": location_id,
|
||||
"location_name": location_name,
|
||||
"tax_group_id": tax_group_id,
|
||||
"tax_group_description": tax_group_description,
|
||||
"net_unit_price": net_unit_price,
|
||||
"gross_unit_price": gross_unit_price
|
||||
})
|
||||
return redirect("/entry")
|
||||
|
||||
with db.run_query("entry/get_groups.sql") as cursor:
|
||||
groups = cursor.fetchall()
|
||||
|
||||
@@ -18,11 +94,17 @@ def index():
|
||||
with db.run_query("entry/get_tax_groups.sql") as cursor:
|
||||
tax_groups = cursor.fetchall()
|
||||
|
||||
return render_template("entry/index.html", **{
|
||||
"locations": locations,
|
||||
"groups": groups,
|
||||
"tax_groups": tax_groups
|
||||
})
|
||||
return render_template(
|
||||
"entry/new-order.html",
|
||||
groups=groups,
|
||||
locations=locations,
|
||||
tax_groups=tax_groups
|
||||
)
|
||||
|
||||
|
||||
|
||||
# API routes for interactive JS stuff
|
||||
|
||||
|
||||
@bp.get("/api/search-items")
|
||||
def api_search_items():
|
||||
@@ -31,10 +113,9 @@ def api_search_items():
|
||||
except:
|
||||
return {"error": "Missing query parameter `search-term`"}, 400
|
||||
|
||||
location = session.get("location", None)
|
||||
|
||||
location = current_user.data.location
|
||||
with db.run_query("search_items.sql", {
|
||||
"location_id": None if location is None else location["location_id"],
|
||||
"location_id": location["location_id"] if location else None,
|
||||
"search_term": search_term
|
||||
}) as cursor:
|
||||
items = cursor.fetchall()
|
||||
|
||||
+4
-3
@@ -1,4 +1,5 @@
|
||||
from flask import Blueprint, redirect, render_template, request, session
|
||||
from flask import Blueprint, redirect, render_template, request
|
||||
from flask_login import current_user
|
||||
|
||||
from . import db
|
||||
|
||||
@@ -8,7 +9,7 @@ bp = Blueprint("inventory", __name__, url_prefix="/inventory")
|
||||
|
||||
@bp.get("/")
|
||||
def index():
|
||||
location = session.get("location", None)
|
||||
location = current_user.data.location
|
||||
items = db.run_query("get_inventory_overview.sql", {
|
||||
"location_id": None if location is None else location["location_id"]
|
||||
}).fetchall()
|
||||
@@ -20,7 +21,7 @@ def index():
|
||||
|
||||
@bp.get("/report")
|
||||
def read_report():
|
||||
location = session.get("location", None)
|
||||
location = current_user.data.location
|
||||
items = db.run_query("get_inventory_report.sql", {
|
||||
"location_id": None if location is None else location["location_id"]
|
||||
}).fetchall()
|
||||
|
||||
+6
-6
@@ -1,4 +1,5 @@
|
||||
from flask import Blueprint, render_template, request, session
|
||||
from flask import Blueprint, render_template, request
|
||||
from flask_login import current_user
|
||||
|
||||
from . import db
|
||||
|
||||
@@ -11,13 +12,12 @@ def index():
|
||||
if request.method == "POST":
|
||||
location_id = request.form.get("location_id", "")
|
||||
if location_id == "":
|
||||
session.pop("location", None)
|
||||
current_user.data.location = None
|
||||
else:
|
||||
location = db.run_query("get_location_by_id.sql", {
|
||||
"location_id": location_id}
|
||||
).fetchone()
|
||||
session["location"] = location
|
||||
|
||||
"location_id": location_id
|
||||
}).fetchone()
|
||||
current_user.data.location = location
|
||||
|
||||
locations = db.run_query("get_locations.sql").fetchall()
|
||||
|
||||
|
||||
-12371
File diff suppressed because it is too large
Load Diff
+14
-2
@@ -63,6 +63,18 @@ th {
|
||||
.form-input > select {
|
||||
display: block;
|
||||
}
|
||||
.formula-input {
|
||||
width: 10em;
|
||||
.form-input.--inline {
|
||||
display: inline-block;
|
||||
}
|
||||
.form-input.--inline > input:not([type=radio]),
|
||||
.form-input.--inline > select {
|
||||
display: block;
|
||||
width: 8em;
|
||||
}
|
||||
details {
|
||||
font-size: 0.8em;
|
||||
}
|
||||
.consumption-graph {
|
||||
display: block;
|
||||
height: 1em;
|
||||
}
|
||||
|
||||
+12
-2
@@ -15,10 +15,10 @@
|
||||
<li{{ " class=current-page" if request.path.startswith("/entry") else "" }}><a href="/entry">Eintragen</a></li>
|
||||
<li{{ " class=current-page" if request.path.startswith("/location") else "" }}>
|
||||
<a href="/location">
|
||||
{% if "location" not in session %}
|
||||
{% if not current_user.data.location %}
|
||||
Raum wählen
|
||||
{% else %}
|
||||
Raum: {{ session.location.location_name }}
|
||||
Raum: {{ current_user.data.location.location_name }}
|
||||
{% endif %}
|
||||
</a>
|
||||
</li>
|
||||
@@ -30,6 +30,16 @@
|
||||
<details>
|
||||
<summary><code>config</code></summary>
|
||||
<pre>{% for key, value in config.items() %}{{ key }} = {{ value }}
|
||||
{% endfor %}</pre>
|
||||
</details>
|
||||
<details>
|
||||
<summary><code>session</code></summary>
|
||||
<pre>{% for key, value in session.items() %}{{ key }} = {{ value }}
|
||||
{% endfor %}</pre>
|
||||
</details>
|
||||
<details>
|
||||
<summary><code>current_user.data</code></summary>
|
||||
<pre>{% for key, value in current_user.data.__dict__.items() %}{{ key }} = {{ value }}
|
||||
{% endfor %}</pre>
|
||||
</details>
|
||||
{% endif %}
|
||||
|
||||
@@ -1,16 +1,42 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<div class="entry-app"></div>
|
||||
<script src="{{ url_for('static', filename='entry.js') }}"></script>
|
||||
<script>
|
||||
Elm.Entry.init({
|
||||
node: document.querySelector('.entry-app'),
|
||||
flags: {
|
||||
locations: {{ to_json(locations) | safe }},
|
||||
groups: {{ to_json(groups) | safe }},
|
||||
taxGroups: {{ to_json(tax_groups) | safe }}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<a href="/entry/new-order">Neuer Auftrag</a>
|
||||
<h2>Aufträge</h2>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Barcode</th>
|
||||
<th>Name</th>
|
||||
<th>Eingekauft</th>
|
||||
<th>Gruppe</th>
|
||||
<th>Raum</th>
|
||||
<th>Steuergruppe</th>
|
||||
<th>EK-Preis (Netto)</th>
|
||||
<th>VK-Preis (Brutto)</th>
|
||||
<th>Aktionen</th>
|
||||
</tr>
|
||||
{% for cart_item in current_user.data.orders %}
|
||||
<tr>
|
||||
<td><code>{{ cart_item.barcode }}</code></td>
|
||||
<td>{{ cart_item.name }}</td>
|
||||
<td class="--align-right">{{ cart_item.sales_units }}</td>
|
||||
<td class="--align-right">{{ cart_item.group_name }} ({{ cart_item.group_id }})</td>
|
||||
<td class="--align-right">{{ cart_item.location_name }} ({{ cart_item.location_id }})</td>
|
||||
<td class="--align-right">{{ cart_item.tax_group_description }} ({{ cart_item.tax_group_id }})</td>
|
||||
<td class="--align-right">{{ format_currency(cart_item.net_unit_price) }}</td>
|
||||
<td class="--align-right">{{ format_currency(cart_item.gross_unit_price) }}</td>
|
||||
<td>
|
||||
<form method="POST" action="/entry/delete-order">
|
||||
<input type="hidden" name="order-index" value="{{ loop.index0 }}">
|
||||
<button>Löschen</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
<form method="POST" action="/entry/add-new-items">
|
||||
<input type="checkbox" name="i-know-what-im-doing" id="i-know-what-im-doing">
|
||||
<label for="i-know-what-im-doing">I weiß, was ich tue</label>
|
||||
<button>Neue Einträge anlegen</button>
|
||||
</form>
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<div class="entry-app"></div>
|
||||
<script src="{{ url_for('static', filename='entry.js') }}"></script>
|
||||
<script>
|
||||
Elm.Entry.init({
|
||||
node: document.querySelector('.entry-app'),
|
||||
flags: {
|
||||
locations: {{ to_json(locations) | safe }},
|
||||
groups: {{ to_json(groups) | safe }},
|
||||
taxGroups: {{ to_json(tax_groups) | safe }}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,9 +1,34 @@
|
||||
{% macro consumption_graph_svg(values) -%}
|
||||
{% set stroke_width = 8 %}
|
||||
{% set width = 300 %}
|
||||
{% set height = 100 %}
|
||||
{% set padding = 4 %}
|
||||
{% set dx = (width - 2 * padding) / ((values | length) + 1) %}
|
||||
{% set dy = (height - 2 * padding) / ((values + [1]) | max) %}
|
||||
<svg viewBox="0 0 {{ width }} {{ height }}" role="img" class="consumption-graph">
|
||||
<polyline
|
||||
points="
|
||||
{% for value in values %}
|
||||
{{ padding + loop.index * dx }}, {{ height - padding - value * dy }}
|
||||
{% endfor %}
|
||||
"
|
||||
stroke="green"
|
||||
stroke-width="{{ stroke_width }}"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
fill="none"
|
||||
>
|
||||
</svg>
|
||||
{% endmacro -%}
|
||||
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<table>
|
||||
<tr>
|
||||
<th>Stat</th>
|
||||
<th>ID</th>
|
||||
<th>Graph</th>
|
||||
<th>Barcode</th>
|
||||
<th>Name</th>
|
||||
<th>Preis (Netto)</th>
|
||||
@@ -17,7 +42,12 @@
|
||||
</tr>
|
||||
{% for item in items %}
|
||||
<tr>
|
||||
<td>
|
||||
{% if item.units_left == 0 %}<span title="Leerer aktiver Inventareintrag">🅾️</span>{% endif %}
|
||||
{% if item.other_lines_count != 0 %}<span title="{% if item.other_lines_count == 1 %}Neuerer Eintrag mit demselben Barcode ist aktiv{% else %}{{ item.other_lines_count }} Einträge mit demselben Barcode sind aktiv{% endif %}">🔄</span>{% endif %}
|
||||
</td>
|
||||
<td><a href="/inventory/item/{{ item.item_id }}">{{ item.item_id }}</a></td>
|
||||
<td>{{ consumption_graph_svg(item.last_n_days_sales) }}</td>
|
||||
<td><code>{{ item.item_barcode }}</code></td>
|
||||
<td>{{ item.name }}</td>
|
||||
<td class="--align-right">{{ format_currency(item.unit_price) }}</td>
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
{% block content %}
|
||||
<form method="POST">
|
||||
<select name="location_id">
|
||||
<option value="" {{ "selected" if "location" not in session else ""}}>-</option>
|
||||
<option value="" {{ "selected" if not current_user.data.location else ""}}>-</option>
|
||||
{% for location in locations %}
|
||||
<option value="{{ location.location_id }}" {{ "selected" if "location" in session and session.location.location_id == location.location_id else "" }}>{{ location.location_name }}</option>
|
||||
<option value="{{ location.location_id }}" {{ "selected" if current_user.data.location.location_id == location.location_id else "" }}>{{ location.location_name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
blinker==1.6.2
|
||||
click==8.1.3
|
||||
Flask==2.3.2
|
||||
Flask-Login==0.6.2
|
||||
itsdangerous==2.1.2
|
||||
Jinja2==3.1.2
|
||||
MarkupSafe==2.1.2
|
||||
|
||||
Reference in New Issue
Block a user