Merge pull request #142 from ZeusWPI/fix-pylint-formatting
Fix pylint formatting for Haldis
This commit is contained in:
commit
112cafecbb
37 changed files with 776 additions and 129 deletions
492
.pylintrc
Normal file
492
.pylintrc
Normal file
|
@ -0,0 +1,492 @@
|
||||||
|
[MASTER]
|
||||||
|
|
||||||
|
# A comma-separated list of package or module names from where C extensions may
|
||||||
|
# be loaded. Extensions are loading into the active Python interpreter and may
|
||||||
|
# run arbitrary code.
|
||||||
|
extension-pkg-whitelist=
|
||||||
|
|
||||||
|
# Add files or directories to the blacklist. They should be base names, not
|
||||||
|
# paths.
|
||||||
|
ignore=CVS
|
||||||
|
|
||||||
|
# Add files or directories matching the regex patterns to the blacklist. The
|
||||||
|
# regex matches against base names, not paths.
|
||||||
|
ignore-patterns=.*.db
|
||||||
|
|
||||||
|
# Python code to execute, usually for sys.path manipulation such as
|
||||||
|
# pygtk.require().
|
||||||
|
#init-hook=
|
||||||
|
|
||||||
|
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
|
||||||
|
# number of processors available to use.
|
||||||
|
jobs=0
|
||||||
|
|
||||||
|
# Control the amount of potential inferred values when inferring a single
|
||||||
|
# object. This can help the performance when dealing with large functions or
|
||||||
|
# complex, nested conditions.
|
||||||
|
limit-inference-results=100
|
||||||
|
|
||||||
|
# List of plugins (as comma separated values of python modules names) to load,
|
||||||
|
# usually to register additional checkers.
|
||||||
|
load-plugins=
|
||||||
|
|
||||||
|
# Pickle collected data for later comparisons.
|
||||||
|
persistent=yes
|
||||||
|
|
||||||
|
# Specify a configuration file.
|
||||||
|
#rcfile=
|
||||||
|
|
||||||
|
# When enabled, pylint would attempt to guess common misconfiguration and emit
|
||||||
|
# user-friendly hints instead of false-positive error messages.
|
||||||
|
suggestion-mode=yes
|
||||||
|
|
||||||
|
# Allow loading of arbitrary C extensions. Extensions are imported into the
|
||||||
|
# active Python interpreter and may run arbitrary code.
|
||||||
|
unsafe-load-any-extension=no
|
||||||
|
|
||||||
|
|
||||||
|
[MESSAGES CONTROL]
|
||||||
|
|
||||||
|
# Only show warnings with the listed confidence levels. Leave empty to show
|
||||||
|
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
|
||||||
|
confidence=
|
||||||
|
|
||||||
|
# Disable the message, report, category or checker with the given id(s). You
|
||||||
|
# can either give multiple identifiers separated by comma (,) or put this
|
||||||
|
# option multiple times (only on the command line, not in the configuration
|
||||||
|
# file where it should appear only once). You can also use "--disable=all" to
|
||||||
|
# disable everything first and then reenable specific checks. For example, if
|
||||||
|
# you want to run only the similarities checker, you can use "--disable=all
|
||||||
|
# --enable=similarities". If you want to run only the classes checker, but have
|
||||||
|
# no Warning level messages displayed, use "--disable=all --enable=classes
|
||||||
|
# --disable=W".
|
||||||
|
disable=E0401,E0611,C0103,W0511,W0611
|
||||||
|
|
||||||
|
# Enable the message, report, category or checker with the given id(s). You can
|
||||||
|
# either give multiple identifier separated by comma (,) or put this option
|
||||||
|
# multiple time (only on the command line, not in the configuration file where
|
||||||
|
# it should appear only once). See also the "--disable" option for examples.
|
||||||
|
enable=c-extension-no-member
|
||||||
|
|
||||||
|
|
||||||
|
[REPORTS]
|
||||||
|
|
||||||
|
# Python expression which should return a note less than 10 (10 is the highest
|
||||||
|
# note). You have access to the variables errors warning, statement which
|
||||||
|
# respectively contain the number of errors / warnings messages and the total
|
||||||
|
# number of statements analyzed. This is used by the global evaluation report
|
||||||
|
# (RP0004).
|
||||||
|
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
|
||||||
|
|
||||||
|
# Template used to display messages. This is a python new-style format string
|
||||||
|
# used to format the message information. See doc for all details.
|
||||||
|
#msg-template=
|
||||||
|
|
||||||
|
# Set the output format. Available formats are text, parseable, colorized, json
|
||||||
|
# and msvs (visual studio). You can also give a reporter class, e.g.
|
||||||
|
# mypackage.mymodule.MyReporterClass.
|
||||||
|
output-format=text
|
||||||
|
|
||||||
|
# Tells whether to display a full report or only the messages.
|
||||||
|
reports=no
|
||||||
|
|
||||||
|
# Activate the evaluation score.
|
||||||
|
score=yes
|
||||||
|
|
||||||
|
|
||||||
|
[REFACTORING]
|
||||||
|
|
||||||
|
# Maximum number of nested blocks for function / method body
|
||||||
|
max-nested-blocks=5
|
||||||
|
|
||||||
|
# Complete name of functions that never returns. When checking for
|
||||||
|
# inconsistent-return-statements if a never returning function is called then
|
||||||
|
# it will be considered as an explicit return statement and no message will be
|
||||||
|
# printed.
|
||||||
|
never-returning-functions=sys.exit
|
||||||
|
|
||||||
|
|
||||||
|
[SIMILARITIES]
|
||||||
|
|
||||||
|
# Ignore comments when computing similarities.
|
||||||
|
ignore-comments=yes
|
||||||
|
|
||||||
|
# Ignore docstrings when computing similarities.
|
||||||
|
ignore-docstrings=yes
|
||||||
|
|
||||||
|
# Ignore imports when computing similarities.
|
||||||
|
ignore-imports=no
|
||||||
|
|
||||||
|
# Minimum lines number of a similarity.
|
||||||
|
min-similarity-lines=4
|
||||||
|
|
||||||
|
|
||||||
|
[TYPECHECK]
|
||||||
|
|
||||||
|
# List of decorators that produce context managers, such as
|
||||||
|
# contextlib.contextmanager. Add to this list to register other decorators that
|
||||||
|
# produce valid context managers.
|
||||||
|
contextmanager-decorators=contextlib.contextmanager
|
||||||
|
|
||||||
|
# List of members which are set dynamically and missed by pylint inference
|
||||||
|
# system, and so shouldn't trigger E1101 when accessed. Python regular
|
||||||
|
# expressions are accepted.
|
||||||
|
generated-members=
|
||||||
|
|
||||||
|
# Tells whether missing members accessed in mixin class should be ignored. A
|
||||||
|
# mixin class is detected if its name ends with "mixin" (case insensitive).
|
||||||
|
ignore-mixin-members=yes
|
||||||
|
|
||||||
|
# Tells whether to warn about missing members when the owner of the attribute
|
||||||
|
# is inferred to be None.
|
||||||
|
ignore-none=yes
|
||||||
|
|
||||||
|
# This flag controls whether pylint should warn about no-member and similar
|
||||||
|
# checks whenever an opaque object is returned when inferring. The inference
|
||||||
|
# can return multiple potential results while evaluating a Python object, but
|
||||||
|
# some branches might not be evaluated, which results in partial inference. In
|
||||||
|
# that case, it might be useful to still emit no-member and other checks for
|
||||||
|
# the rest of the inferred objects.
|
||||||
|
ignore-on-opaque-inference=yes
|
||||||
|
|
||||||
|
# List of class names for which member attributes should not be checked (useful
|
||||||
|
# for classes with dynamically set attributes). This supports the use of
|
||||||
|
# qualified names.
|
||||||
|
ignored-classes=optparse.Values,thread._local,_thread._local
|
||||||
|
|
||||||
|
# List of module names for which member attributes should not be checked
|
||||||
|
# (useful for modules/projects where namespaces are manipulated during runtime
|
||||||
|
# and thus existing member attributes cannot be deduced by static analysis. It
|
||||||
|
# supports qualified module names, as well as Unix pattern matching.
|
||||||
|
ignored-modules=
|
||||||
|
|
||||||
|
# Show a hint with possible names when a member name was not found. The aspect
|
||||||
|
# of finding the hint is based on edit distance.
|
||||||
|
missing-member-hint=yes
|
||||||
|
|
||||||
|
# The minimum edit distance a name should have in order to be considered a
|
||||||
|
# similar match for a missing member name.
|
||||||
|
missing-member-hint-distance=1
|
||||||
|
|
||||||
|
# The total number of similar names that should be taken in consideration when
|
||||||
|
# showing a hint for a missing member.
|
||||||
|
missing-member-max-choices=1
|
||||||
|
|
||||||
|
|
||||||
|
[LOGGING]
|
||||||
|
|
||||||
|
# Format style used to check logging format string. `old` means using %
|
||||||
|
# formatting, while `new` is for `{}` formatting.
|
||||||
|
logging-format-style=old
|
||||||
|
|
||||||
|
# Logging modules to check that the string format arguments are in logging
|
||||||
|
# function parameter format.
|
||||||
|
logging-modules=logging
|
||||||
|
|
||||||
|
|
||||||
|
[VARIABLES]
|
||||||
|
|
||||||
|
# List of additional names supposed to be defined in builtins. Remember that
|
||||||
|
# you should avoid defining new builtins when possible.
|
||||||
|
additional-builtins=
|
||||||
|
|
||||||
|
# Tells whether unused global variables should be treated as a violation.
|
||||||
|
allow-global-unused-variables=yes
|
||||||
|
|
||||||
|
# List of strings which can identify a callback function by name. A callback
|
||||||
|
# name must start or end with one of those strings.
|
||||||
|
callbacks=cb_,
|
||||||
|
_cb
|
||||||
|
|
||||||
|
# A regular expression matching the name of dummy variables (i.e. expected to
|
||||||
|
# not be used).
|
||||||
|
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
|
||||||
|
|
||||||
|
# Argument names that match this expression will be ignored. Default to name
|
||||||
|
# with leading underscore.
|
||||||
|
ignored-argument-names=_.*|^ignored_|^unused_
|
||||||
|
|
||||||
|
# Tells whether we should check for unused import in __init__ files.
|
||||||
|
init-import=no
|
||||||
|
|
||||||
|
# List of qualified module names which can have objects that can redefine
|
||||||
|
# builtins.
|
||||||
|
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
|
||||||
|
|
||||||
|
|
||||||
|
[SPELLING]
|
||||||
|
|
||||||
|
# Limits count of emitted suggestions for spelling mistakes.
|
||||||
|
max-spelling-suggestions=4
|
||||||
|
|
||||||
|
# Spelling dictionary name. Available dictionaries: none. To make it working
|
||||||
|
# install python-enchant package..
|
||||||
|
spelling-dict=
|
||||||
|
|
||||||
|
# List of comma separated words that should not be checked.
|
||||||
|
spelling-ignore-words=
|
||||||
|
|
||||||
|
# A path to a file that contains private dictionary; one word per line.
|
||||||
|
spelling-private-dict-file=
|
||||||
|
|
||||||
|
# Tells whether to store unknown words to indicated private dictionary in
|
||||||
|
# --spelling-private-dict-file option instead of raising a message.
|
||||||
|
spelling-store-unknown-words=no
|
||||||
|
|
||||||
|
|
||||||
|
[MISCELLANEOUS]
|
||||||
|
|
||||||
|
# List of note tags to take in consideration, separated by a comma.
|
||||||
|
notes=FIXME,
|
||||||
|
XXX,
|
||||||
|
TODO
|
||||||
|
|
||||||
|
|
||||||
|
[BASIC]
|
||||||
|
|
||||||
|
# Naming style matching correct argument names.
|
||||||
|
argument-naming-style=snake_case
|
||||||
|
|
||||||
|
# Regular expression matching correct argument names. Overrides argument-
|
||||||
|
# naming-style.
|
||||||
|
#argument-rgx=
|
||||||
|
|
||||||
|
# Naming style matching correct attribute names.
|
||||||
|
attr-naming-style=snake_case
|
||||||
|
|
||||||
|
# Regular expression matching correct attribute names. Overrides attr-naming-
|
||||||
|
# style.
|
||||||
|
#attr-rgx=
|
||||||
|
|
||||||
|
# Bad variable names which should always be refused, separated by a comma.
|
||||||
|
bad-names=foo,
|
||||||
|
bar,
|
||||||
|
baz,
|
||||||
|
toto,
|
||||||
|
tutu,
|
||||||
|
tata
|
||||||
|
|
||||||
|
# Naming style matching correct class attribute names.
|
||||||
|
class-attribute-naming-style=any
|
||||||
|
|
||||||
|
# Regular expression matching correct class attribute names. Overrides class-
|
||||||
|
# attribute-naming-style.
|
||||||
|
#class-attribute-rgx=
|
||||||
|
|
||||||
|
# Naming style matching correct class names.
|
||||||
|
class-naming-style=PascalCase
|
||||||
|
|
||||||
|
# Regular expression matching correct class names. Overrides class-naming-
|
||||||
|
# style.
|
||||||
|
#class-rgx=
|
||||||
|
|
||||||
|
# Naming style matching correct constant names.
|
||||||
|
const-naming-style=UPPER_CASE
|
||||||
|
|
||||||
|
# Regular expression matching correct constant names. Overrides const-naming-
|
||||||
|
# style.
|
||||||
|
#const-rgx=
|
||||||
|
|
||||||
|
# Minimum line length for functions/classes that require docstrings, shorter
|
||||||
|
# ones are exempt.
|
||||||
|
docstring-min-length=-1
|
||||||
|
|
||||||
|
# Naming style matching correct function names.
|
||||||
|
function-naming-style=snake_case
|
||||||
|
|
||||||
|
# Regular expression matching correct function names. Overrides function-
|
||||||
|
# naming-style.
|
||||||
|
#function-rgx=
|
||||||
|
|
||||||
|
# Good variable names which should always be accepted, separated by a comma.
|
||||||
|
good-names=i,
|
||||||
|
j,
|
||||||
|
k,
|
||||||
|
ex,
|
||||||
|
Run,
|
||||||
|
_
|
||||||
|
|
||||||
|
# Include a hint for the correct naming format with invalid-name.
|
||||||
|
include-naming-hint=no
|
||||||
|
|
||||||
|
# Naming style matching correct inline iteration names.
|
||||||
|
inlinevar-naming-style=any
|
||||||
|
|
||||||
|
# Regular expression matching correct inline iteration names. Overrides
|
||||||
|
# inlinevar-naming-style.
|
||||||
|
#inlinevar-rgx=
|
||||||
|
|
||||||
|
# Naming style matching correct method names.
|
||||||
|
method-naming-style=snake_case
|
||||||
|
|
||||||
|
# Regular expression matching correct method names. Overrides method-naming-
|
||||||
|
# style.
|
||||||
|
#method-rgx=
|
||||||
|
|
||||||
|
# Naming style matching correct module names.
|
||||||
|
module-naming-style=snake_case
|
||||||
|
|
||||||
|
# Regular expression matching correct module names. Overrides module-naming-
|
||||||
|
# style.
|
||||||
|
#module-rgx=
|
||||||
|
|
||||||
|
# Colon-delimited sets of names that determine each other's naming style when
|
||||||
|
# the name regexes allow several styles.
|
||||||
|
name-group=
|
||||||
|
|
||||||
|
# Regular expression which should only match function or class names that do
|
||||||
|
# not require a docstring.
|
||||||
|
no-docstring-rgx=^_
|
||||||
|
|
||||||
|
# List of decorators that produce properties, such as abc.abstractproperty. Add
|
||||||
|
# to this list to register other decorators that produce valid properties.
|
||||||
|
# These decorators are taken in consideration only for invalid-name.
|
||||||
|
property-classes=abc.abstractproperty
|
||||||
|
|
||||||
|
# Naming style matching correct variable names.
|
||||||
|
variable-naming-style=snake_case
|
||||||
|
|
||||||
|
# Regular expression matching correct variable names. Overrides variable-
|
||||||
|
# naming-style.
|
||||||
|
#variable-rgx=
|
||||||
|
|
||||||
|
|
||||||
|
[STRING]
|
||||||
|
|
||||||
|
# This flag controls whether the implicit-str-concat-in-sequence should
|
||||||
|
# generate a warning on implicit string concatenation in sequences defined over
|
||||||
|
# several lines.
|
||||||
|
check-str-concat-over-line-jumps=no
|
||||||
|
|
||||||
|
|
||||||
|
[FORMAT]
|
||||||
|
|
||||||
|
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
|
||||||
|
expected-line-ending-format=LF
|
||||||
|
|
||||||
|
# Regexp for a line that is allowed to be longer than the limit.
|
||||||
|
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
|
||||||
|
|
||||||
|
# Number of spaces of indent required inside a hanging or continued line.
|
||||||
|
indent-after-paren=4
|
||||||
|
|
||||||
|
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
|
||||||
|
# tab).
|
||||||
|
indent-string=' '
|
||||||
|
|
||||||
|
# Maximum number of characters on a single line.
|
||||||
|
max-line-length=100
|
||||||
|
|
||||||
|
# Maximum number of lines in a module.
|
||||||
|
max-module-lines=1000
|
||||||
|
|
||||||
|
# List of optional constructs for which whitespace checking is disabled. `dict-
|
||||||
|
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
|
||||||
|
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
|
||||||
|
# `empty-line` allows space-only lines.
|
||||||
|
no-space-check=trailing-comma,
|
||||||
|
dict-separator
|
||||||
|
|
||||||
|
# Allow the body of a class to be on the same line as the declaration if body
|
||||||
|
# contains single statement.
|
||||||
|
single-line-class-stmt=no
|
||||||
|
|
||||||
|
# Allow the body of an if to be on the same line as the test if there is no
|
||||||
|
# else.
|
||||||
|
single-line-if-stmt=no
|
||||||
|
|
||||||
|
|
||||||
|
[DESIGN]
|
||||||
|
|
||||||
|
# Maximum number of arguments for function / method.
|
||||||
|
max-args=5
|
||||||
|
|
||||||
|
# Maximum number of attributes for a class (see R0902).
|
||||||
|
max-attributes=7
|
||||||
|
|
||||||
|
# Maximum number of boolean expressions in an if statement.
|
||||||
|
max-bool-expr=5
|
||||||
|
|
||||||
|
# Maximum number of branch for function / method body.
|
||||||
|
max-branches=12
|
||||||
|
|
||||||
|
# Maximum number of locals for function / method body.
|
||||||
|
max-locals=15
|
||||||
|
|
||||||
|
# Maximum number of parents for a class (see R0901).
|
||||||
|
max-parents=7
|
||||||
|
|
||||||
|
# Maximum number of public methods for a class (see R0904).
|
||||||
|
max-public-methods=20
|
||||||
|
|
||||||
|
# Maximum number of return / yield for function / method body.
|
||||||
|
max-returns=6
|
||||||
|
|
||||||
|
# Maximum number of statements in function / method body.
|
||||||
|
max-statements=50
|
||||||
|
|
||||||
|
# Minimum number of public methods for a class (see R0903).
|
||||||
|
min-public-methods=2
|
||||||
|
|
||||||
|
|
||||||
|
[CLASSES]
|
||||||
|
|
||||||
|
# List of method names used to declare (i.e. assign) instance attributes.
|
||||||
|
defining-attr-methods=__init__,
|
||||||
|
__new__,
|
||||||
|
setUp
|
||||||
|
|
||||||
|
# List of member names, which should be excluded from the protected access
|
||||||
|
# warning.
|
||||||
|
exclude-protected=_asdict,
|
||||||
|
_fields,
|
||||||
|
_replace,
|
||||||
|
_source,
|
||||||
|
_make
|
||||||
|
|
||||||
|
# List of valid names for the first argument in a class method.
|
||||||
|
valid-classmethod-first-arg=cls
|
||||||
|
|
||||||
|
# List of valid names for the first argument in a metaclass class method.
|
||||||
|
valid-metaclass-classmethod-first-arg=cls
|
||||||
|
|
||||||
|
|
||||||
|
[IMPORTS]
|
||||||
|
|
||||||
|
# Allow wildcard imports from modules that define __all__.
|
||||||
|
allow-wildcard-with-all=no
|
||||||
|
|
||||||
|
# Analyse import fallback blocks. This can be used to support both Python 2 and
|
||||||
|
# 3 compatible code, which means that the block might have code that exists
|
||||||
|
# only in one or another interpreter, leading to false positives when analysed.
|
||||||
|
analyse-fallback-blocks=no
|
||||||
|
|
||||||
|
# Deprecated modules which should not be used, separated by a comma.
|
||||||
|
deprecated-modules=optparse,tkinter.tix
|
||||||
|
|
||||||
|
# Create a graph of external dependencies in the given file (report RP0402 must
|
||||||
|
# not be disabled).
|
||||||
|
ext-import-graph=
|
||||||
|
|
||||||
|
# Create a graph of every (i.e. internal and external) dependencies in the
|
||||||
|
# given file (report RP0402 must not be disabled).
|
||||||
|
import-graph=
|
||||||
|
|
||||||
|
# Create a graph of internal dependencies in the given file (report RP0402 must
|
||||||
|
# not be disabled).
|
||||||
|
int-import-graph=
|
||||||
|
|
||||||
|
# Force import order to recognize a module as part of the standard
|
||||||
|
# compatibility libraries.
|
||||||
|
known-standard-library=
|
||||||
|
|
||||||
|
# Force import order to recognize a module as part of a third party library.
|
||||||
|
known-third-party=enchant
|
||||||
|
|
||||||
|
|
||||||
|
[EXCEPTIONS]
|
||||||
|
|
||||||
|
# Exceptions that will emit a warning when being caught. Defaults to
|
||||||
|
# "BaseException, Exception".
|
||||||
|
overgeneral-exceptions=BaseException,
|
||||||
|
Exception
|
25
app/admin.py
25
app/admin.py
|
@ -1,3 +1,5 @@
|
||||||
|
"Haldis admin related views and models"
|
||||||
|
|
||||||
import flask_login as login
|
import flask_login as login
|
||||||
from flask import Flask
|
from flask import Flask
|
||||||
from flask_admin import Admin
|
from flask_admin import Admin
|
||||||
|
@ -8,34 +10,43 @@ from models import Location, Order, OrderItem, Product, User
|
||||||
|
|
||||||
|
|
||||||
class ModelBaseView(ModelView):
|
class ModelBaseView(ModelView):
|
||||||
|
"Base model for admin related things"
|
||||||
|
# pylint: disable=R0201, R0903
|
||||||
def is_accessible(self) -> bool:
|
def is_accessible(self) -> bool:
|
||||||
|
"Check if the user has admin permission"
|
||||||
if login.current_user.is_anonymous():
|
if login.current_user.is_anonymous():
|
||||||
return False
|
return False
|
||||||
|
|
||||||
return login.current_user.is_admin()
|
return login.current_user.is_admin()
|
||||||
|
|
||||||
|
|
||||||
class UserAdminModel(ModelBaseView):
|
class UserAdminModel(ModelBaseView):
|
||||||
|
"Model for user admin"
|
||||||
|
# pylint: disable=R0903
|
||||||
column_searchable_list = ("username",)
|
column_searchable_list = ("username",)
|
||||||
inline_models = None
|
inline_models = None
|
||||||
|
|
||||||
|
|
||||||
class ProductAdminModel(ModelBaseView):
|
class ProductAdminModel(ModelBaseView):
|
||||||
|
"Model for product admin"
|
||||||
|
# pylint: disable=R0903
|
||||||
column_searchable_list = ("name",)
|
column_searchable_list = ("name",)
|
||||||
inline_models = None
|
inline_models = None
|
||||||
|
|
||||||
|
|
||||||
class LocationAdminModel(ModelBaseView):
|
class LocationAdminModel(ModelBaseView):
|
||||||
|
"Model for location admin"
|
||||||
|
# pylint: disable=R0903
|
||||||
column_searchable_list = ("name", "address", "website")
|
column_searchable_list = ("name", "address", "website")
|
||||||
inline_models = None
|
inline_models = None
|
||||||
form_columns = ("name", "address", "website", "telephone")
|
form_columns = ("name", "address", "website", "telephone")
|
||||||
|
|
||||||
|
|
||||||
def init_admin(app: Flask, db: SQLAlchemy) -> None:
|
def init_admin(app: Flask, database: SQLAlchemy) -> None:
|
||||||
|
"Initialize the admin related things in the app."
|
||||||
admin = Admin(app, name="Haldis", url="/admin", template_mode="bootstrap3")
|
admin = Admin(app, name="Haldis", url="/admin", template_mode="bootstrap3")
|
||||||
|
|
||||||
admin.add_view(UserAdminModel(User, db.session))
|
admin.add_view(UserAdminModel(User, database.session))
|
||||||
admin.add_view(LocationAdminModel(Location, db.session))
|
admin.add_view(LocationAdminModel(Location, database.session))
|
||||||
admin.add_view(ProductAdminModel(Product, db.session))
|
admin.add_view(ProductAdminModel(Product, database.session))
|
||||||
admin.add_view(ModelBaseView(Order, db.session))
|
admin.add_view(ModelBaseView(Order, database.session))
|
||||||
admin.add_view(ModelBaseView(OrderItem, db.session))
|
admin.add_view(ModelBaseView(OrderItem, database.session))
|
||||||
|
|
40
app/app.py
40
app/app.py
|
@ -1,7 +1,8 @@
|
||||||
|
"Main Haldis script"
|
||||||
import logging
|
import logging
|
||||||
|
from logging.handlers import TimedRotatingFileHandler
|
||||||
import typing
|
import typing
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from logging.handlers import TimedRotatingFileHandler
|
|
||||||
|
|
||||||
from airbrake import Airbrake, AirbrakeHandler
|
from airbrake import Airbrake, AirbrakeHandler
|
||||||
from flask import Flask, render_template
|
from flask import Flask, render_template
|
||||||
|
@ -21,21 +22,24 @@ from zeus import init_oauth
|
||||||
|
|
||||||
|
|
||||||
def create_app() -> Manager:
|
def create_app() -> Manager:
|
||||||
|
"Create the Haldis application"
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
|
||||||
# Load the config file
|
# Load the config file
|
||||||
app.config.from_object("config.Configuration")
|
app.config.from_object("config.Configuration")
|
||||||
|
|
||||||
manager = register_plugins(app, debug=app.debug)
|
app_manager = register_plugins(app)
|
||||||
add_handlers(app)
|
add_handlers(app)
|
||||||
add_routes(app)
|
add_routes(app)
|
||||||
add_template_filters(app)
|
add_template_filters(app)
|
||||||
|
|
||||||
# TODO do we need to return and then run the manager?
|
# TODO do we need to return and then run the manager?
|
||||||
return manager
|
return app_manager
|
||||||
|
|
||||||
|
|
||||||
def register_plugins(app: Flask, debug: bool) -> Manager:
|
def register_plugins(app: Flask) -> Manager:
|
||||||
|
"Register all the plugins to Haldis"
|
||||||
|
# pylint: disable=W0612
|
||||||
# Register Airbrake and enable the logrotation
|
# Register Airbrake and enable the logrotation
|
||||||
if not app.debug:
|
if not app.debug:
|
||||||
timedFileHandler = TimedRotatingFileHandler(
|
timedFileHandler = TimedRotatingFileHandler(
|
||||||
|
@ -51,11 +55,10 @@ def register_plugins(app: Flask, debug: bool) -> Manager:
|
||||||
airbrakelogger = logging.getLogger("airbrake")
|
airbrakelogger = logging.getLogger("airbrake")
|
||||||
|
|
||||||
# Airbrake
|
# Airbrake
|
||||||
airbrake = Airbrake(
|
airbrake = Airbrake(project_id=app.config["AIRBRAKE_ID"],
|
||||||
project_id=app.config["AIRBRAKE_ID"], api_key=app.config["AIRBRAKE_KEY"]
|
api_key=app.config["AIRBRAKE_KEY"])
|
||||||
)
|
|
||||||
# ugly hack to make this work for out errbit
|
# ugly hack to make this work for out errbit
|
||||||
airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format(
|
airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format( # pylint: disable=W0212
|
||||||
airbrake.project_id
|
airbrake.project_id
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -67,9 +70,9 @@ def register_plugins(app: Flask, debug: bool) -> Manager:
|
||||||
|
|
||||||
# Initialize Flask-Migrate
|
# Initialize Flask-Migrate
|
||||||
migrate = Migrate(app, db)
|
migrate = Migrate(app, db)
|
||||||
manager = Manager(app)
|
app_manager = Manager(app)
|
||||||
manager.add_command("db", MigrateCommand)
|
app_manager.add_command("db", MigrateCommand)
|
||||||
manager.add_command("runserver", Server(port=8000))
|
app_manager.add_command("runserver", Server(port=8000))
|
||||||
|
|
||||||
# Add admin interface
|
# Add admin interface
|
||||||
init_admin(app, db)
|
init_admin(app, db)
|
||||||
|
@ -103,10 +106,12 @@ def register_plugins(app: Flask, debug: bool) -> Manager:
|
||||||
if not app.debug:
|
if not app.debug:
|
||||||
app.config.update(SESSION_COOKIE_SECURE=True)
|
app.config.update(SESSION_COOKIE_SECURE=True)
|
||||||
|
|
||||||
return manager
|
return app_manager
|
||||||
|
|
||||||
|
|
||||||
def add_handlers(app: Flask) -> None:
|
def add_handlers(app: Flask) -> None:
|
||||||
|
"Add handlers for 4xx error codes"
|
||||||
|
# pylint: disable=W0612,W0613
|
||||||
@app.errorhandler(404)
|
@app.errorhandler(404)
|
||||||
def handle404(e) -> typing.Tuple[str, int]:
|
def handle404(e) -> typing.Tuple[str, int]:
|
||||||
return render_template("errors/404.html"), 404
|
return render_template("errors/404.html"), 404
|
||||||
|
@ -117,6 +122,7 @@ def add_handlers(app: Flask) -> None:
|
||||||
|
|
||||||
|
|
||||||
def add_routes(application: Flask) -> None:
|
def add_routes(application: Flask) -> None:
|
||||||
|
"Add all routes to Haldis"
|
||||||
# import views # TODO convert to blueprint
|
# import views # TODO convert to blueprint
|
||||||
# import views.stats # TODO convert to blueprint
|
# import views.stats # TODO convert to blueprint
|
||||||
|
|
||||||
|
@ -138,8 +144,12 @@ def add_routes(application: Flask) -> None:
|
||||||
|
|
||||||
|
|
||||||
def add_template_filters(app: Flask) -> None:
|
def add_template_filters(app: Flask) -> None:
|
||||||
|
"Add functions which can be used in the templates"
|
||||||
|
# pylint: disable=W0612
|
||||||
@app.template_filter("countdown")
|
@app.template_filter("countdown")
|
||||||
def countdown(value, only_positive: bool = True, show_text: bool = True) -> str:
|
def countdown(value, only_positive: bool = True,
|
||||||
|
show_text: bool = True) -> str:
|
||||||
|
"A function which returns time until the order is done"
|
||||||
delta = value - datetime.now()
|
delta = value - datetime.now()
|
||||||
if delta.total_seconds() < 0 and only_positive:
|
if delta.total_seconds() < 0 and only_positive:
|
||||||
return "closed"
|
return "closed"
|
||||||
|
@ -151,11 +161,13 @@ def add_template_filters(app: Flask) -> None:
|
||||||
return time
|
return time
|
||||||
|
|
||||||
@app.template_filter("year")
|
@app.template_filter("year")
|
||||||
def current_year(value: typing.Any) -> str:
|
def current_year(value: typing.Any) -> str: # pylint: disable=W0613
|
||||||
|
"A function which returns the current year"
|
||||||
return str(datetime.now().year)
|
return str(datetime.now().year)
|
||||||
|
|
||||||
@app.template_filter("euro")
|
@app.template_filter("euro")
|
||||||
def euro(value: int) -> str:
|
def euro(value: int) -> str:
|
||||||
|
"A function which converts a value to its euro_string"
|
||||||
return euro_string(value)
|
return euro_string(value)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,10 @@
|
||||||
|
"An example for a Haldis config"
|
||||||
# config
|
# config
|
||||||
|
|
||||||
|
|
||||||
class Configuration(object):
|
class Configuration():
|
||||||
|
"Haldis configuration object"
|
||||||
|
# pylint: disable=R0903
|
||||||
SQLALCHEMY_DATABASE_URI = "sqlite:///haldis.db"
|
SQLALCHEMY_DATABASE_URI = "sqlite:///haldis.db"
|
||||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||||
DEBUG = True
|
DEBUG = True
|
||||||
|
|
|
@ -1,8 +1,10 @@
|
||||||
|
"Script for adding users as admin to Haldis."
|
||||||
from app import db
|
from app import db
|
||||||
from models import User
|
from models import User
|
||||||
|
|
||||||
|
|
||||||
def add() -> None:
|
def add() -> None:
|
||||||
|
"Add users as admin."
|
||||||
feli = User()
|
feli = User()
|
||||||
feli.configure("feliciaan", True, 0)
|
feli.configure("feliciaan", True, 0)
|
||||||
db.session.add(feli)
|
db.session.add(feli)
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script to add Fitchen to Haldis"
|
||||||
from app import db
|
from app import db
|
||||||
from models import Location, Product
|
from models import Location, Product
|
||||||
|
|
||||||
|
@ -23,14 +24,15 @@ pricedict = {"Small": 799, "Medium": 999, "Large": 1199}
|
||||||
|
|
||||||
|
|
||||||
def add() -> None:
|
def add() -> None:
|
||||||
simpizza = Location()
|
"Add Fitchen to the database"
|
||||||
simpizza.configure("Fitchen", "?", "?", "https://www.fitchen.be/")
|
fitchen = Location()
|
||||||
db.session.add(simpizza)
|
fitchen.configure("Fitchen", "?", "?", "https://www.fitchen.be/")
|
||||||
|
db.session.add(fitchen)
|
||||||
|
|
||||||
for menuitem in menuitems:
|
for menuitem in menuitems:
|
||||||
for size, price in pricedict.items():
|
for size, price in pricedict.items():
|
||||||
for container in ["bowl", "wrap"]:
|
for container in ["bowl", "wrap"]:
|
||||||
name = "%s %s in %s" % (size, menuitem, container)
|
name = "%s %s in %s" % (size, menuitem, container)
|
||||||
entry = Product()
|
entry = Product()
|
||||||
entry.configure(simpizza, name, price)
|
entry.configure(fitchen, name, price)
|
||||||
db.session.add(entry)
|
db.session.add(entry)
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script to add Ocean Garden to Haldis"
|
||||||
from itertools import product
|
from itertools import product
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
|
@ -30,6 +31,7 @@ specials = [
|
||||||
|
|
||||||
|
|
||||||
def add() -> None:
|
def add() -> None:
|
||||||
|
"Add Ocean Garden to the database"
|
||||||
chinees = Location()
|
chinees = Location()
|
||||||
chinees.configure(
|
chinees.configure(
|
||||||
"Oceans's Garden",
|
"Oceans's Garden",
|
||||||
|
|
|
@ -1,8 +1,10 @@
|
||||||
|
"Script to add Primadonna to Haldis"
|
||||||
from app import db
|
from app import db
|
||||||
from models import Location, Product
|
from models import Location, Product
|
||||||
|
|
||||||
|
|
||||||
def add():
|
def add():
|
||||||
|
"Add Primadonna to the database"
|
||||||
addTA()
|
addTA()
|
||||||
addAfhalen()
|
addAfhalen()
|
||||||
|
|
||||||
|
@ -47,6 +49,7 @@ pizzasTA = {
|
||||||
|
|
||||||
|
|
||||||
def addTA() -> None:
|
def addTA() -> None:
|
||||||
|
"Add Primadonna on takeaway.com to the database"
|
||||||
primadonna_takeaway = Location()
|
primadonna_takeaway = Location()
|
||||||
primadonna_takeaway.configure(
|
primadonna_takeaway.configure(
|
||||||
"Primadonna (takeaway laten bezorgen)",
|
"Primadonna (takeaway laten bezorgen)",
|
||||||
|
@ -102,6 +105,7 @@ pizzasAfhalen = {
|
||||||
|
|
||||||
|
|
||||||
def addAfhalen() -> None:
|
def addAfhalen() -> None:
|
||||||
|
"Add Primadonna to takeaway to the database"
|
||||||
primadonna_afhalen = Location()
|
primadonna_afhalen = Location()
|
||||||
primadonna_afhalen.configure(
|
primadonna_afhalen.configure(
|
||||||
"Primadonna (bellen en afhalen)",
|
"Primadonna (bellen en afhalen)",
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script to add SimPizza to Haldis"
|
||||||
from app import db
|
from app import db
|
||||||
from models import Location, Product
|
from models import Location, Product
|
||||||
|
|
||||||
|
@ -19,7 +20,8 @@ pizzas = [
|
||||||
"Chicken bbq",
|
"Chicken bbq",
|
||||||
"Funky chicken",
|
"Funky chicken",
|
||||||
"Veggie",
|
"Veggie",
|
||||||
"Meat lovers" "Scampi mampi",
|
"Meat lovers",
|
||||||
|
"Scampi mampi",
|
||||||
"Tabasco",
|
"Tabasco",
|
||||||
"Chicken time",
|
"Chicken time",
|
||||||
"Meatballs",
|
"Meatballs",
|
||||||
|
@ -33,6 +35,7 @@ pizzas = [
|
||||||
|
|
||||||
|
|
||||||
def add() -> None:
|
def add() -> None:
|
||||||
|
"Add Simpizza to the database"
|
||||||
simpizza = Location()
|
simpizza = Location()
|
||||||
simpizza.configure(
|
simpizza.configure(
|
||||||
"Sim-pizza",
|
"Sim-pizza",
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script to add Stefanos to Haldis"
|
||||||
from app import db
|
from app import db
|
||||||
from models import Location, Product
|
from models import Location, Product
|
||||||
|
|
||||||
|
@ -101,12 +102,13 @@ data = [special_bickies, specials, vlezekes, friet]
|
||||||
|
|
||||||
|
|
||||||
def add() -> None:
|
def add() -> None:
|
||||||
|
"Add Stefanos to the database"
|
||||||
stefanos = Location()
|
stefanos = Location()
|
||||||
stefanos.configure(
|
stefanos.configure(
|
||||||
"Stefano's Place",
|
"Stefano's Place",
|
||||||
"Overpoortstraat 12 9000 Gent",
|
"Overpoortstraat 12 9000 Gent",
|
||||||
"tel: geen",
|
"tel: geen",
|
||||||
"https://www.facebook.com/pages/category/Fast-Food-Restaurant/Stefanos-Place-370774480004139/",
|
"https://www.facebook.com/pages/category/Fast-Food-Restaurant/Stefanos-Place-370774480004139/", # pylint: disable=C0301
|
||||||
)
|
)
|
||||||
db.session.add(stefanos)
|
db.session.add(stefanos)
|
||||||
|
|
||||||
|
@ -120,8 +122,8 @@ def add() -> None:
|
||||||
bicky_cheese.configure(stefanos, name + " cheese", price + 30)
|
bicky_cheese.configure(stefanos, name + " cheese", price + 30)
|
||||||
db.session.add(bicky_cheese)
|
db.session.add(bicky_cheese)
|
||||||
|
|
||||||
for dict in data:
|
for dictionary in data:
|
||||||
for name, price in dict.items():
|
for name, price in dictionary.items():
|
||||||
item = Product()
|
item = Product()
|
||||||
item.configure(stefanos, name, price)
|
item.configure(stefanos, name, price)
|
||||||
db.session.add(item)
|
db.session.add(item)
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script for interaction and changes to the database"
|
||||||
import add_admins
|
import add_admins
|
||||||
import add_fitchen
|
import add_fitchen
|
||||||
import add_oceans_garden
|
import add_oceans_garden
|
||||||
|
@ -19,24 +20,27 @@ yes = ["yes", "y"]
|
||||||
no = ["no", "n"]
|
no = ["no", "n"]
|
||||||
|
|
||||||
|
|
||||||
# Commit all the things
|
|
||||||
def commit() -> None:
|
def commit() -> None:
|
||||||
|
"Commit all the things to the database"
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
print("Committing successful")
|
print("Committing successful")
|
||||||
|
|
||||||
|
|
||||||
def check_if_overwrite() -> bool:
|
def check_if_overwrite() -> bool:
|
||||||
|
"Check if the user wants to overwrite the previous database"
|
||||||
answer = input("Do you want to overwrite the previous database? (y/N) ")
|
answer = input("Do you want to overwrite the previous database? (y/N) ")
|
||||||
return answer.lower() in yes
|
return answer.lower() in yes
|
||||||
|
|
||||||
|
|
||||||
def add_all() -> None:
|
def add_all() -> None:
|
||||||
for entry_set in entry_sets.keys():
|
"Add all possible entries in the entry_sets to the database"
|
||||||
|
for entry_set, function in entry_sets.items():
|
||||||
print("Adding {}.".format(entry_set))
|
print("Adding {}.".format(entry_set))
|
||||||
entry_sets[entry_set]()
|
function()
|
||||||
|
|
||||||
|
|
||||||
def recreate_from_scratch() -> None:
|
def recreate_from_scratch() -> None:
|
||||||
|
"Recreate a completely new database"
|
||||||
confirmation = "Are you very very sure? (Will delete previous entries!) (y/N) "
|
confirmation = "Are you very very sure? (Will delete previous entries!) (y/N) "
|
||||||
if input(confirmation) in yes:
|
if input(confirmation) in yes:
|
||||||
print("Resetting the database!")
|
print("Resetting the database!")
|
||||||
|
@ -48,6 +52,7 @@ def recreate_from_scratch() -> None:
|
||||||
|
|
||||||
|
|
||||||
def add_to_current() -> None:
|
def add_to_current() -> None:
|
||||||
|
"Add things to the current database"
|
||||||
available = [entry_set for entry_set in entry_sets]
|
available = [entry_set for entry_set in entry_sets]
|
||||||
|
|
||||||
def add_numbers() -> str:
|
def add_numbers() -> str:
|
||||||
|
@ -77,7 +82,8 @@ def add_to_current() -> None:
|
||||||
manager = create_app()
|
manager = create_app()
|
||||||
|
|
||||||
@manager.command
|
@manager.command
|
||||||
def setup_database():
|
def setup_database(): #type: None
|
||||||
|
"Start the database interaction script"
|
||||||
print("Database modification script!")
|
print("Database modification script!")
|
||||||
print("=============================\n\n")
|
print("=============================\n\n")
|
||||||
if check_if_overwrite():
|
if check_if_overwrite():
|
||||||
|
|
|
@ -28,9 +28,9 @@ class FatOrder(Order, FatModel):
|
||||||
@classmethod
|
@classmethod
|
||||||
def items_per_order(cls):
|
def items_per_order(cls):
|
||||||
return (
|
return (
|
||||||
Order.query.join(OrderItem)
|
Order.query.join(OrderItem).group_by(Order.id)
|
||||||
.group_by(Order.id)
|
.with_entities(Order.id,
|
||||||
.with_entities(Order.id, func.count(OrderItem.user_id).label("total"))
|
func.count(OrderItem.user_id).label("total"))
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@ -50,7 +50,8 @@ class FatProduct(Product, FatModel):
|
||||||
.join(Location)
|
.join(Location)
|
||||||
.group_by(Product.id)
|
.group_by(Product.id)
|
||||||
.with_entities(
|
.with_entities(
|
||||||
Product.name, Location.name, func.count(Product.id).label("count")
|
Product.name, Location.name, func.count(
|
||||||
|
Product.id).label("count")
|
||||||
)
|
)
|
||||||
.order_by(desc("count"))
|
.order_by(desc("count"))
|
||||||
.limit(4)
|
.limit(4)
|
||||||
|
|
19
app/forms.py
19
app/forms.py
|
@ -1,3 +1,4 @@
|
||||||
|
"Script for everything form related in Haldis"
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
from flask import session
|
from flask import session
|
||||||
|
@ -11,6 +12,8 @@ from utils import euro_string
|
||||||
|
|
||||||
|
|
||||||
class OrderForm(Form):
|
class OrderForm(Form):
|
||||||
|
"Class which defines the form for a new Order"
|
||||||
|
# pylint: disable=R0903
|
||||||
courrier_id = SelectField("Courrier", coerce=int)
|
courrier_id = SelectField("Courrier", coerce=int)
|
||||||
location_id = SelectField(
|
location_id = SelectField(
|
||||||
"Location", coerce=int, validators=[validators.required()]
|
"Location", coerce=int, validators=[validators.required()]
|
||||||
|
@ -22,6 +25,7 @@ class OrderForm(Form):
|
||||||
submit_button = SubmitField("Submit")
|
submit_button = SubmitField("Submit")
|
||||||
|
|
||||||
def populate(self) -> None:
|
def populate(self) -> None:
|
||||||
|
"Fill in the options for courrier for an Order"
|
||||||
if current_user.is_admin():
|
if current_user.is_admin():
|
||||||
self.courrier_id.choices = [(0, None)] + [
|
self.courrier_id.choices = [(0, None)] + [
|
||||||
(u.id, u.username) for u in User.query.order_by("username")
|
(u.id, u.username) for u in User.query.order_by("username")
|
||||||
|
@ -39,25 +43,38 @@ class OrderForm(Form):
|
||||||
|
|
||||||
|
|
||||||
class OrderItemForm(Form):
|
class OrderItemForm(Form):
|
||||||
|
"Class which defines the form for a new Item in an Order"
|
||||||
|
# pylint: disable=R0903
|
||||||
product_id = SelectField("Item", coerce=int)
|
product_id = SelectField("Item", coerce=int)
|
||||||
extra = StringField("Extra")
|
extra = StringField("Extra")
|
||||||
submit_button = SubmitField("Submit")
|
submit_button = SubmitField("Submit")
|
||||||
|
|
||||||
def populate(self, location: Location) -> None:
|
def populate(self, location: Location) -> None:
|
||||||
|
"Fill in all the product options from the location"
|
||||||
self.product_id.choices = [
|
self.product_id.choices = [
|
||||||
(i.id, (i.name + ": " + euro_string(i.price))) for i in location.products
|
(i.id, (i.name + ": " + euro_string(i.price)))
|
||||||
|
for i in location.products
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class AnonOrderItemForm(OrderItemForm):
|
class AnonOrderItemForm(OrderItemForm):
|
||||||
|
"""
|
||||||
|
Class which defines the form for a new Item in an Order
|
||||||
|
For Users who aren't logged in
|
||||||
|
"""
|
||||||
name = StringField("Name", validators=[validators.required()])
|
name = StringField("Name", validators=[validators.required()])
|
||||||
|
|
||||||
def populate(self, location: Location) -> None:
|
def populate(self, location: Location) -> None:
|
||||||
|
"""
|
||||||
|
Fill in all the product options from the location and
|
||||||
|
the name of the anon user
|
||||||
|
"""
|
||||||
OrderItemForm.populate(self, location)
|
OrderItemForm.populate(self, location)
|
||||||
if self.name.data is None:
|
if self.name.data is None:
|
||||||
self.name.data = session.get("anon_name", None)
|
self.name.data = session.get("anon_name", None)
|
||||||
|
|
||||||
def validate(self) -> bool:
|
def validate(self) -> bool:
|
||||||
|
"Check if the provided anon_name is not already taken"
|
||||||
rv = OrderForm.validate(self)
|
rv = OrderForm.validate(self)
|
||||||
if not rv:
|
if not rv:
|
||||||
return False
|
return False
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script for everything related to logging in and out"
|
||||||
from flask import Blueprint, abort, redirect, session, url_for
|
from flask import Blueprint, abort, redirect, session, url_for
|
||||||
from flask_login import current_user, logout_user
|
from flask_login import current_user, logout_user
|
||||||
from werkzeug.wrappers import Response
|
from werkzeug.wrappers import Response
|
||||||
|
@ -9,18 +10,23 @@ auth_bp = Blueprint("auth_bp", __name__)
|
||||||
|
|
||||||
|
|
||||||
def init_login(app) -> None:
|
def init_login(app) -> None:
|
||||||
|
"Initialize the login"
|
||||||
|
# pylint: disable=W0612
|
||||||
@app.login_manager.user_loader
|
@app.login_manager.user_loader
|
||||||
def load_user(userid) -> User:
|
def load_user(userid) -> User:
|
||||||
|
"Load the user"
|
||||||
return User.query.filter_by(id=userid).first()
|
return User.query.filter_by(id=userid).first()
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.route("/login")
|
@auth_bp.route("/login")
|
||||||
def login():
|
def login():
|
||||||
|
"Function to handle a user trying to log in"
|
||||||
return zeus_login()
|
return zeus_login()
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.route("/logout")
|
@auth_bp.route("/logout")
|
||||||
def logout() -> Response:
|
def logout() -> Response:
|
||||||
|
"Function to handle a user trying to log out"
|
||||||
if "zeus_token" in session:
|
if "zeus_token" in session:
|
||||||
session.pop("zeus_token", None)
|
session.pop("zeus_token", None)
|
||||||
logout_user()
|
logout_user()
|
||||||
|
@ -28,5 +34,6 @@ def logout() -> Response:
|
||||||
|
|
||||||
|
|
||||||
def before_request() -> None:
|
def before_request() -> None:
|
||||||
|
"Function for what has to be done before a request"
|
||||||
if current_user.is_anonymous() or not current_user.is_allowed():
|
if current_user.is_anonymous() or not current_user.is_allowed():
|
||||||
abort(401)
|
abort(401)
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script that runs migrations online or offline"
|
||||||
from __future__ import with_statement
|
from __future__ import with_statement
|
||||||
|
|
||||||
from logging.config import fileConfig
|
from logging.config import fileConfig
|
||||||
|
|
|
@ -1,5 +1,7 @@
|
||||||
# This file will expose what we want from the models module
|
"The base file for everything related to the models"
|
||||||
# This will probably be everything. But putting the imports here makes it possible to import all models in one line like this:
|
# This file will expose what we want from the models module.
|
||||||
|
# This will probably be everything. But putting the imports here makes it possible to import all
|
||||||
|
# models in one line like this:
|
||||||
#
|
#
|
||||||
# from models import User, Item, ...
|
# from models import User, Item, ...
|
||||||
#
|
#
|
||||||
|
|
|
@ -1,3 +1,7 @@
|
||||||
|
"AnonymouseUser for people who are not logged in the normal way"
|
||||||
|
# pylint: disable=R0201,C0111
|
||||||
|
|
||||||
|
|
||||||
class AnonymouseUser:
|
class AnonymouseUser:
|
||||||
id = None
|
id = None
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
# pylint: disable=C0111
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
|
||||||
db = SQLAlchemy()
|
db = SQLAlchemy()
|
||||||
|
|
|
@ -1,9 +1,11 @@
|
||||||
|
"Script for everything Location related in the database"
|
||||||
import typing
|
import typing
|
||||||
|
|
||||||
from models import db
|
from models import db
|
||||||
|
|
||||||
|
|
||||||
class Location(db.Model):
|
class Location(db.Model):
|
||||||
|
"Class used for configuring the Location model in the database"
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
name = db.Column(db.String(120), nullable=False)
|
name = db.Column(db.String(120), nullable=False)
|
||||||
address = db.Column(db.String(254))
|
address = db.Column(db.String(254))
|
||||||
|
@ -12,9 +14,9 @@ class Location(db.Model):
|
||||||
products = db.relationship("Product", backref="location", lazy="dynamic")
|
products = db.relationship("Product", backref="location", lazy="dynamic")
|
||||||
orders = db.relationship("Order", backref="location", lazy="dynamic")
|
orders = db.relationship("Order", backref="location", lazy="dynamic")
|
||||||
|
|
||||||
def configure(
|
def configure(self, name: str, address: str,
|
||||||
self, name: str, address: str, telephone: typing.Optional[str], website: str
|
telephone: typing.Optional[str], website: str) -> None:
|
||||||
) -> None:
|
"Configure the Location"
|
||||||
self.name = name
|
self.name = name
|
||||||
self.address = address
|
self.address = address
|
||||||
self.website = website
|
self.website = website
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script for everything Order related in the database"
|
||||||
import typing
|
import typing
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
@ -7,6 +8,7 @@ from .user import User
|
||||||
|
|
||||||
|
|
||||||
class Order(db.Model):
|
class Order(db.Model):
|
||||||
|
"Class used for configuring the Order model in the database"
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
courrier_id = db.Column(db.Integer, nullable=True)
|
courrier_id = db.Column(db.Integer, nullable=True)
|
||||||
location_id = db.Column(db.Integer, db.ForeignKey("location.id"))
|
location_id = db.Column(db.Integer, db.ForeignKey("location.id"))
|
||||||
|
@ -15,31 +17,31 @@ class Order(db.Model):
|
||||||
public = db.Column(db.Boolean, default=True)
|
public = db.Column(db.Boolean, default=True)
|
||||||
items = db.relationship("OrderItem", backref="order", lazy="dynamic")
|
items = db.relationship("OrderItem", backref="order", lazy="dynamic")
|
||||||
|
|
||||||
def configure(
|
def configure(self, courrier: User, location: Location,
|
||||||
self,
|
starttime: db.DateTime, stoptime: db.DateTime,) -> None:
|
||||||
courrier: User,
|
"Configure the Order"
|
||||||
location: Location,
|
# pylint: disable=W0201
|
||||||
starttime: db.DateTime,
|
|
||||||
stoptime: db.DateTime,
|
|
||||||
) -> None:
|
|
||||||
self.courrier = courrier
|
self.courrier = courrier
|
||||||
self.location = location
|
self.location = location
|
||||||
self.starttime = starttime
|
self.starttime = starttime
|
||||||
self.stoptime = stoptime
|
self.stoptime = stoptime
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
|
# pylint: disable=R1705
|
||||||
if self.location:
|
if self.location:
|
||||||
return "Order %d @ %s" % (self.id, self.location.name or "None")
|
return "Order %d @ %s" % (self.id, self.location.name or "None")
|
||||||
else:
|
else:
|
||||||
return "Order %d" % (self.id)
|
return "Order %d" % (self.id)
|
||||||
|
|
||||||
def group_by_user(self) -> typing.Dict[str, typing.Any]:
|
def group_by_user(self) -> typing.Dict[str, typing.Any]:
|
||||||
|
"Group items of an Order by user"
|
||||||
group: typing.Dict[str, typing.Any] = dict()
|
group: typing.Dict[str, typing.Any] = dict()
|
||||||
for item in self.items:
|
for item in self.items:
|
||||||
user = group.get(item.get_name(), dict())
|
user = group.get(item.get_name(), dict())
|
||||||
user["total"] = user.get("total", 0) + item.product.price
|
user["total"] = user.get("total", 0) + item.product.price
|
||||||
user["to_pay"] = (
|
user["to_pay"] = (
|
||||||
user.get("to_pay", 0) + item.product.price if not item.paid else 0
|
user.get("to_pay", 0) +
|
||||||
|
item.product.price if not item.paid else 0
|
||||||
)
|
)
|
||||||
user["paid"] = user.get("paid", True) and item.paid
|
user["paid"] = user.get("paid", True) and item.paid
|
||||||
user["products"] = user.get("products", []) + [item.product]
|
user["products"] = user.get("products", []) + [item.product]
|
||||||
|
@ -48,6 +50,7 @@ class Order(db.Model):
|
||||||
return group
|
return group
|
||||||
|
|
||||||
def group_by_product(self) -> typing.Dict[str, typing.Any]:
|
def group_by_product(self) -> typing.Dict[str, typing.Any]:
|
||||||
|
"Group items of an Order by product"
|
||||||
group: typing.Dict[str, typing.Any] = dict()
|
group: typing.Dict[str, typing.Any] = dict()
|
||||||
for item in self.items:
|
for item in self.items:
|
||||||
product = group.get(item.product.name, dict())
|
product = group.get(item.product.name, dict())
|
||||||
|
@ -59,6 +62,7 @@ class Order(db.Model):
|
||||||
return group
|
return group
|
||||||
|
|
||||||
def can_close(self, user_id: int) -> bool:
|
def can_close(self, user_id: int) -> bool:
|
||||||
|
"Check if a user can close the Order"
|
||||||
if self.stoptime and self.stoptime < datetime.now():
|
if self.stoptime and self.stoptime < datetime.now():
|
||||||
return False
|
return False
|
||||||
user = None
|
user = None
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script for everything OrderItem related in the database"
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from .database import db
|
from .database import db
|
||||||
|
@ -7,6 +8,7 @@ from .user import User
|
||||||
|
|
||||||
|
|
||||||
class OrderItem(db.Model):
|
class OrderItem(db.Model):
|
||||||
|
"Class used for configuring the OrderItem model in the database"
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
|
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
|
||||||
order_id = db.Column(db.Integer, db.ForeignKey("order.id"), nullable=False)
|
order_id = db.Column(db.Integer, db.ForeignKey("order.id"), nullable=False)
|
||||||
|
@ -20,11 +22,14 @@ class OrderItem(db.Model):
|
||||||
name = db.Column(db.String(120))
|
name = db.Column(db.String(120))
|
||||||
|
|
||||||
def configure(self, user: User, order: Order, product: Product) -> None:
|
def configure(self, user: User, order: Order, product: Product) -> None:
|
||||||
|
"Configure the OrderItem"
|
||||||
|
# pylint: disable=W0201
|
||||||
self.user = user
|
self.user = user
|
||||||
self.order = order
|
self.order = order
|
||||||
self.product = product
|
self.product = product
|
||||||
|
|
||||||
def get_name(self) -> str:
|
def get_name(self) -> str:
|
||||||
|
"Get the name of the user which 'owns' the item"
|
||||||
if self.user_id is not None and self.user_id > 0:
|
if self.user_id is not None and self.user_id > 0:
|
||||||
return self.user.username
|
return self.user.username
|
||||||
return self.name
|
return self.name
|
||||||
|
@ -39,7 +44,9 @@ class OrderItem(db.Model):
|
||||||
product_name or "None",
|
product_name or "None",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# pylint: disable=W0613
|
||||||
def can_delete(self, order_id: int, user_id: int, name: str) -> bool:
|
def can_delete(self, order_id: int, user_id: int, name: str) -> bool:
|
||||||
|
"Check if a user can delete an item"
|
||||||
if int(self.order_id) != int(order_id):
|
if int(self.order_id) != int(order_id):
|
||||||
return False
|
return False
|
||||||
if self.order.stoptime and self.order.stoptime < datetime.now():
|
if self.order.stoptime and self.order.stoptime < datetime.now():
|
||||||
|
|
|
@ -1,23 +1,25 @@
|
||||||
|
"Script for everything Product related in the database"
|
||||||
from models import db
|
from models import db
|
||||||
|
|
||||||
from .location import Location
|
from .location import Location
|
||||||
|
|
||||||
|
|
||||||
class Product(db.Model):
|
class Product(db.Model):
|
||||||
|
"Class used for configuring the Product model in the database"
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
location_id = db.Column(db.Integer, db.ForeignKey("location.id"))
|
location_id = db.Column(db.Integer, db.ForeignKey("location.id"))
|
||||||
name = db.Column(db.String(120), nullable=False)
|
name = db.Column(db.String(120), nullable=False)
|
||||||
price = db.Column(db.Integer, nullable=False)
|
price = db.Column(db.Integer, nullable=False)
|
||||||
orderItems = db.relationship("OrderItem", backref="product", lazy="dynamic")
|
orderItems = db.relationship("OrderItem",
|
||||||
|
backref="product", lazy="dynamic")
|
||||||
|
|
||||||
def configure(self, location: Location, name: str, price: int) -> None:
|
def configure(self, location: Location, name: str, price: int) -> None:
|
||||||
|
"Configure the Product"
|
||||||
|
# pylint: disable=W0201
|
||||||
self.location = location
|
self.location = location
|
||||||
self.name = name
|
self.name = name
|
||||||
self.price = price
|
self.price = price
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
return "%s (€%d)from %s" % (
|
return "%s (€%d)from %s" % (self.name, self.price / 100,
|
||||||
self.name,
|
self.location or "None",)
|
||||||
self.price / 100,
|
|
||||||
self.location or "None",
|
|
||||||
)
|
|
||||||
|
|
|
@ -1,7 +1,9 @@
|
||||||
|
"Script for everything User related in the database"
|
||||||
from models import db
|
from models import db
|
||||||
|
|
||||||
|
|
||||||
class User(db.Model):
|
class User(db.Model):
|
||||||
|
"Class used for configuring the User model in the database"
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
username = db.Column(db.String(80), unique=True, nullable=False)
|
username = db.Column(db.String(80), unique=True, nullable=False)
|
||||||
admin = db.Column(db.Boolean)
|
admin = db.Column(db.Boolean)
|
||||||
|
@ -15,10 +17,12 @@ class User(db.Model):
|
||||||
orderItems = db.relationship("OrderItem", backref="user", lazy="dynamic")
|
orderItems = db.relationship("OrderItem", backref="user", lazy="dynamic")
|
||||||
|
|
||||||
def configure(self, username: str, admin: bool, bias: int) -> None:
|
def configure(self, username: str, admin: bool, bias: int) -> None:
|
||||||
|
"Configure the User"
|
||||||
self.username = username
|
self.username = username
|
||||||
self.admin = admin
|
self.admin = admin
|
||||||
self.bias = bias
|
self.bias = bias
|
||||||
|
|
||||||
|
# pylint: disable=C0111, R0201
|
||||||
def is_authenticated(self) -> bool:
|
def is_authenticated(self) -> bool:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script that handles Haldis notifications on chat platforms"
|
||||||
import json
|
import json
|
||||||
import typing
|
import typing
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
@ -10,10 +11,12 @@ from models.order import Order
|
||||||
|
|
||||||
|
|
||||||
def webhook_text(order_item: Order) -> typing.Optional[str]:
|
def webhook_text(order_item: Order) -> typing.Optional[str]:
|
||||||
|
"Function that makes the text for the notification"
|
||||||
if "Testlocation" in order_item.location.name:
|
if "Testlocation" in order_item.location.name:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
if order_item.courrier is not None:
|
if order_item.courrier is not None:
|
||||||
|
# pylint: disable=C0301
|
||||||
return "<!channel|@channel> {3} is going to {1}, order <{0}|here>! Deadline in {2} minutes!".format(
|
return "<!channel|@channel> {3} is going to {1}, order <{0}|here>! Deadline in {2} minutes!".format(
|
||||||
url_for("order_bp.order", id=order_item.id, _external=True),
|
url_for("order_bp.order", id=order_item.id, _external=True),
|
||||||
order_item.location.name,
|
order_item.location.name,
|
||||||
|
@ -29,13 +32,17 @@ def webhook_text(order_item: Order) -> typing.Optional[str]:
|
||||||
|
|
||||||
|
|
||||||
def post_order_to_webhook(order_item: Order) -> None:
|
def post_order_to_webhook(order_item: Order) -> None:
|
||||||
|
"Function that sends the notification for the order"
|
||||||
message = webhook_text(order_item)
|
message = webhook_text(order_item)
|
||||||
if message:
|
if message:
|
||||||
webhookthread = WebhookSenderThread(message, app.config["SLACK_WEBHOOK"])
|
webhookthread = WebhookSenderThread(
|
||||||
|
message, app.config["SLACK_WEBHOOK"])
|
||||||
webhookthread.start()
|
webhookthread.start()
|
||||||
|
|
||||||
|
|
||||||
class WebhookSenderThread(Thread):
|
class WebhookSenderThread(Thread):
|
||||||
|
"Extension of the Thread class, which sends a webhook for the notification"
|
||||||
|
|
||||||
def __init__(self, message: str, url: str) -> None:
|
def __init__(self, message: str, url: str) -> None:
|
||||||
super(WebhookSenderThread, self).__init__()
|
super(WebhookSenderThread, self).__init__()
|
||||||
self.message = message
|
self.message = message
|
||||||
|
@ -45,6 +52,7 @@ class WebhookSenderThread(Thread):
|
||||||
self.slack_webhook()
|
self.slack_webhook()
|
||||||
|
|
||||||
def slack_webhook(self) -> None:
|
def slack_webhook(self) -> None:
|
||||||
|
"The webhook for the specified chat platform"
|
||||||
if self.url:
|
if self.url:
|
||||||
requests.post(self.url, json={"text": self.message})
|
requests.post(self.url, json={"text": self.message})
|
||||||
else:
|
else:
|
||||||
|
@ -52,6 +60,7 @@ class WebhookSenderThread(Thread):
|
||||||
|
|
||||||
|
|
||||||
def remaining_minutes(value) -> str:
|
def remaining_minutes(value) -> str:
|
||||||
|
"Return the remaining minutes until the deadline of and order"
|
||||||
delta = value - datetime.now()
|
delta = value - datetime.now()
|
||||||
if delta.total_seconds() < 0:
|
if delta.total_seconds() < 0:
|
||||||
return "0"
|
return "0"
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
"Script to run Haldis on a server"
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
|
@ -5,7 +5,7 @@
|
||||||
('general_bp.home', 'Home'),
|
('general_bp.home', 'Home'),
|
||||||
('order_bp.orders', 'Orders'),
|
('order_bp.orders', 'Orders'),
|
||||||
('general_bp.locations', 'Locations'),
|
('general_bp.locations', 'Locations'),
|
||||||
('general_bp.map', 'Map'),
|
('general_bp.map_view', 'Map'),
|
||||||
('general_bp.about', 'About'),
|
('general_bp.about', 'About'),
|
||||||
('stats_blueprint.stats', 'Stats'),
|
('stats_blueprint.stats', 'Stats'),
|
||||||
] -%}
|
] -%}
|
||||||
|
|
|
@ -14,7 +14,7 @@
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for loc in locations -%}
|
{% for loc in locations -%}
|
||||||
<tr>
|
<tr>
|
||||||
<td><a href="{{ url_for('general_bp.location', id=loc.id) }}">{{ loc.name }}</a></td>
|
<td><a href="{{ url_for('general_bp.location', location_id=loc.id) }}">{{ loc.name }}</a></td>
|
||||||
<td>{{ loc.address }}<td>
|
<td>{{ loc.address }}<td>
|
||||||
<td><a href="{{ loc.website}}"><span class="glyphicon glyphicon-link"></span></a></td>
|
<td><a href="{{ loc.website}}"><span class="glyphicon glyphicon-link"></span></a></td>
|
||||||
<td>
|
<td>
|
||||||
|
|
|
@ -28,7 +28,7 @@
|
||||||
loc = {
|
loc = {
|
||||||
"address": "{{loc.address}}",
|
"address": "{{loc.address}}",
|
||||||
"name": "{{loc.name}}",
|
"name": "{{loc.name}}",
|
||||||
"url": "{{ url_for('general_bp.location', id=loc.id) }}"
|
"url": "{{ url_for('general_bp.location', location_id=loc.id) }}"
|
||||||
};
|
};
|
||||||
locations.push(loc);
|
locations.push(loc);
|
||||||
|
|
||||||
|
|
|
@ -11,16 +11,16 @@
|
||||||
<h3 id="order-title">Order {{ order.id }}
|
<h3 id="order-title">Order {{ order.id }}
|
||||||
<div class="pull-right">
|
<div class="pull-right">
|
||||||
{% if order.can_close(current_user.id) -%}
|
{% if order.can_close(current_user.id) -%}
|
||||||
<form action="{{ url_for('order_bp.close_order', id=order.id) }}" method="post" style="display:inline">
|
<form action="{{ url_for('order_bp.close_order', order_id=order.id) }}" method="post" style="display:inline">
|
||||||
<input type="submit" class="btn btn-danger" value="Close"></input>
|
<input type="submit" class="btn btn-danger" value="Close"></input>
|
||||||
</form>
|
</form>
|
||||||
{% endif %}{% if courier_or_admin %}
|
{% endif %}{% if courier_or_admin %}
|
||||||
<a class="btn btn-warning" href="{{ url_for('order_bp.order_edit', id=order.id) }}">Edit</a>
|
<a class="btn btn-warning" href="{{ url_for('order_bp.order_edit', order_id=order.id) }}">Edit</a>
|
||||||
{%- endif %}
|
{%- endif %}
|
||||||
</div></h3>
|
</div></h3>
|
||||||
courier: {{ order.courrier.username }}
|
courier: {{ order.courrier.username }}
|
||||||
{% if order.courrier == None and not current_user.is_anonymous() %}
|
{% if order.courrier == None and not current_user.is_anonymous() %}
|
||||||
<form action="{{ url_for('order_bp.volunteer', id=order.id) }}" method="post" style="display:inline">
|
<form action="{{ url_for('order_bp.volunteer', order_id=order.id) }}" method="post" style="display:inline">
|
||||||
<input type="submit" class="btn btn-primary btn-sm" value="Volunteer"></input>
|
<input type="submit" class="btn btn-primary btn-sm" value="Volunteer"></input>
|
||||||
</form>
|
</form>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
@ -38,7 +38,7 @@
|
||||||
{% if form -%}
|
{% if form -%}
|
||||||
<div class="col-md-push-1 col-md-10 darker" id="form">
|
<div class="col-md-push-1 col-md-10 darker" id="form">
|
||||||
<h4>Order:</h4>
|
<h4>Order:</h4>
|
||||||
<form method="post" action="{{ url_for('order_bp.order_item_create', id=order.id) }}">
|
<form method="post" action="{{ url_for('order_bp.order_item_create', order_id=order.id) }}">
|
||||||
<span class="pull-right">
|
<span class="pull-right">
|
||||||
<a class="btn btn-primary" onclick="chooseRandom()">Choose for me</a>
|
<a class="btn btn-primary" onclick="chooseRandom()">Choose for me</a>
|
||||||
</span>
|
</span>
|
||||||
|
@ -99,7 +99,7 @@
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-push-2 col-md-4 darker box" id="items-ordered">
|
<div class="col-md-push-2 col-md-4 darker box" id="items-ordered">
|
||||||
<h3>Ordered products: {{ order.items.count() }}</h3>
|
<h3>Ordered products: {{ order.items.count() }}</h3>
|
||||||
<a class="divLink" href="{{ url_for('order_bp.items_showcase', id=order.id) }}"></a>
|
<a class="divLink" href="{{ url_for('order_bp.items_showcase', order_id=order.id) }}"></a>
|
||||||
{% for key, value in order.group_by_product().items() -%}
|
{% for key, value in order.group_by_product().items() -%}
|
||||||
<div class="product">
|
<div class="product">
|
||||||
{{ key }}: {{ value["count"] }}
|
{{ key }}: {{ value["count"] }}
|
||||||
|
|
|
@ -11,7 +11,7 @@
|
||||||
<h3>Edit order:</h3>
|
<h3>Edit order:</h3>
|
||||||
<div class="row darker">
|
<div class="row darker">
|
||||||
<div class="col-sm-12">
|
<div class="col-sm-12">
|
||||||
<form method="post" action="{{ url_for('.order_edit', id=order_id) }}">
|
<form method="post" action="{{ url_for('.order_edit', order_id=order_id) }}">
|
||||||
{{ form.csrf_token }}
|
{{ form.csrf_token }}
|
||||||
<div class="form-group select2 {{ 'has-errors' if form.courrier_id.errors else ''}}">
|
<div class="form-group select2 {{ 'has-errors' if form.courrier_id.errors else ''}}">
|
||||||
{{ form.courrier_id.label(class='control-label') }}<br>
|
{{ form.courrier_id.label(class='control-label') }}<br>
|
||||||
|
|
|
@ -9,7 +9,7 @@
|
||||||
<b>Orders:</b> {{ order.items.count() }}</p>
|
<b>Orders:</b> {{ order.items.count() }}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-4 col-lg-3">
|
<div class="col-md-4 col-lg-3">
|
||||||
<a class="btn btn-primary btn-block align-bottom" href="{{ url_for('order_bp.order', id=order.id) }}">Expand</a>
|
<a class="btn btn-primary btn-block align-bottom" href="{{ url_for('order_bp.order', order_id=order.id) }}">Expand</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{%- endmacro %}
|
{%- endmacro %}
|
||||||
|
|
|
@ -1,3 +1,6 @@
|
||||||
|
"Script which contains several utils for Haldis"
|
||||||
|
|
||||||
|
|
||||||
def euro_string(value: int) -> str:
|
def euro_string(value: int) -> str:
|
||||||
"""
|
"""
|
||||||
Convert cents to string formatted euro
|
Convert cents to string formatted euro
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"View used for debugging Haldis"
|
||||||
from flask import Blueprint
|
from flask import Blueprint
|
||||||
from flask import current_app as app
|
from flask import current_app as app
|
||||||
from flask import url_for
|
from flask import url_for
|
||||||
|
@ -9,6 +10,7 @@ debug_bp = Blueprint("debug_bp", __name__)
|
||||||
@debug_bp.route("/routes")
|
@debug_bp.route("/routes")
|
||||||
@login_required
|
@login_required
|
||||||
def list_routes() -> str:
|
def list_routes() -> str:
|
||||||
|
"List all routes of the application"
|
||||||
import urllib
|
import urllib
|
||||||
|
|
||||||
output = []
|
output = []
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script to generate the general views of Haldis"
|
||||||
import os
|
import os
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
@ -15,6 +16,7 @@ general_bp = Blueprint("general_bp", __name__)
|
||||||
|
|
||||||
@general_bp.route("/")
|
@general_bp.route("/")
|
||||||
def home() -> str:
|
def home() -> str:
|
||||||
|
"Generate the home view"
|
||||||
prev_day = datetime.now() - timedelta(days=1)
|
prev_day = datetime.now() - timedelta(days=1)
|
||||||
recently_closed = get_orders(
|
recently_closed = get_orders(
|
||||||
((Order.stoptime > prev_day) & (Order.stoptime < datetime.now()))
|
((Order.stoptime > prev_day) & (Order.stoptime < datetime.now()))
|
||||||
|
@ -24,22 +26,24 @@ def home() -> str:
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@general_bp.route("/map", defaults={"id": None})
|
@general_bp.route("/map")
|
||||||
@general_bp.route("/map/<int:id>")
|
def map_view() -> str:
|
||||||
def map(id) -> str:
|
"Generate the map view"
|
||||||
locs = Location.query.order_by("name")
|
locs = Location.query.order_by("name")
|
||||||
return render_template("maps.html", locations=locs)
|
return render_template("maps.html", locations=locs)
|
||||||
|
|
||||||
|
|
||||||
@general_bp.route("/location")
|
@general_bp.route("/location")
|
||||||
def locations() -> str:
|
def locations() -> str:
|
||||||
|
"Generate the location view"
|
||||||
locs = Location.query.order_by("name")
|
locs = Location.query.order_by("name")
|
||||||
return render_template("locations.html", locations=locs)
|
return render_template("locations.html", locations=locs)
|
||||||
|
|
||||||
|
|
||||||
@general_bp.route("/location/<int:id>")
|
@general_bp.route("/location/<int:location_id>")
|
||||||
def location(id) -> str:
|
def location(location_id) -> str:
|
||||||
loc = Location.query.filter(Location.id == id).first()
|
"Generate the location view given an id"
|
||||||
|
loc = Location.query.filter(Location.id == location_id).first()
|
||||||
if loc is None:
|
if loc is None:
|
||||||
abort(404)
|
abort(404)
|
||||||
return render_template("location.html", location=loc, title=loc.name)
|
return render_template("location.html", location=loc, title=loc.name)
|
||||||
|
@ -47,18 +51,22 @@ def location(id) -> str:
|
||||||
|
|
||||||
@general_bp.route("/about/")
|
@general_bp.route("/about/")
|
||||||
def about() -> str:
|
def about() -> str:
|
||||||
|
"Generate the about view"
|
||||||
return render_template("about.html")
|
return render_template("about.html")
|
||||||
|
|
||||||
|
|
||||||
@general_bp.route("/profile/")
|
@general_bp.route("/profile/")
|
||||||
@login_required
|
@login_required
|
||||||
def profile() -> str:
|
def profile() -> str:
|
||||||
|
"Generate the profile view"
|
||||||
return render_template("profile.html")
|
return render_template("profile.html")
|
||||||
|
|
||||||
|
|
||||||
@general_bp.route("/favicon.ico")
|
@general_bp.route("/favicon.ico")
|
||||||
def favicon() -> str:
|
def favicon() -> str:
|
||||||
if len(get_orders((Order.stoptime > datetime.now()))) == 0:
|
"Generate the favicon"
|
||||||
|
# pylint: disable=R1705
|
||||||
|
if not get_orders((Order.stoptime > datetime.now())):
|
||||||
return send_from_directory(
|
return send_from_directory(
|
||||||
os.path.join(str(app.root_path), "static"),
|
os.path.join(str(app.root_path), "static"),
|
||||||
"favicon.ico",
|
"favicon.ico",
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
|
"Script to generate the order related views of Haldis"
|
||||||
import random
|
import random
|
||||||
import typing
|
import typing
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
import werkzeug
|
from werkzeug.wrappers import Response
|
||||||
# from flask import current_app as app
|
# from flask import current_app as app
|
||||||
from flask import (Blueprint, abort, flash, redirect, render_template, request,
|
from flask import (Blueprint, abort, flash, redirect, render_template, request,
|
||||||
session, url_for, wrappers)
|
session, url_for, wrappers)
|
||||||
from flask_login import current_user, login_required
|
from flask_login import current_user, login_required
|
||||||
from werkzeug.wrappers import Response
|
|
||||||
|
|
||||||
from forms import AnonOrderItemForm, OrderForm, OrderItemForm
|
from forms import AnonOrderItemForm, OrderForm, OrderItemForm
|
||||||
from models import Order, OrderItem, User, db
|
from models import Order, OrderItem, User, db
|
||||||
|
@ -18,6 +18,7 @@ order_bp = Blueprint("order_bp", "order")
|
||||||
|
|
||||||
@order_bp.route("/")
|
@order_bp.route("/")
|
||||||
def orders(form: OrderForm = None) -> str:
|
def orders(form: OrderForm = None) -> str:
|
||||||
|
"Generate general order view"
|
||||||
if form is None and not current_user.is_anonymous():
|
if form is None and not current_user.is_anonymous():
|
||||||
form = OrderForm()
|
form = OrderForm()
|
||||||
location_id = request.args.get("location_id")
|
location_id = request.args.get("location_id")
|
||||||
|
@ -30,6 +31,7 @@ def orders(form: OrderForm = None) -> str:
|
||||||
@order_bp.route("/create", methods=["POST"])
|
@order_bp.route("/create", methods=["POST"])
|
||||||
@login_required
|
@login_required
|
||||||
def order_create() -> typing.Union[str, Response]:
|
def order_create() -> typing.Union[str, Response]:
|
||||||
|
"Generate order create view"
|
||||||
orderForm = OrderForm()
|
orderForm = OrderForm()
|
||||||
orderForm.populate()
|
orderForm.populate()
|
||||||
if orderForm.validate_on_submit():
|
if orderForm.validate_on_submit():
|
||||||
|
@ -38,33 +40,35 @@ def order_create() -> typing.Union[str, Response]:
|
||||||
db.session.add(order)
|
db.session.add(order)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
post_order_to_webhook(order)
|
post_order_to_webhook(order)
|
||||||
return redirect(url_for("order_bp.order", id=order.id))
|
return redirect(url_for("order_bp.order_from_id", order_id=order.id))
|
||||||
return orders(form=orderForm)
|
return orders(form=orderForm)
|
||||||
|
|
||||||
|
|
||||||
@order_bp.route("/<id>")
|
@order_bp.route("/<order_id>")
|
||||||
def order(id: int, form: OrderForm = None) -> str:
|
def order_from_id(order_id: int, form: OrderForm = None) -> str:
|
||||||
order = Order.query.filter(Order.id == id).first()
|
"Generate order view from id"
|
||||||
|
order = Order.query.filter(Order.id == order_id).first()
|
||||||
if order is None:
|
if order is None:
|
||||||
abort(404)
|
abort(404)
|
||||||
if current_user.is_anonymous() and not order.public:
|
if current_user.is_anonymous() and not order.public:
|
||||||
flash("Please login to see this order.", "info")
|
flash("Please login to see this order.", "info")
|
||||||
abort(401)
|
abort(401)
|
||||||
if form is None:
|
if form is None:
|
||||||
form = AnonOrderItemForm() if current_user.is_anonymous() else OrderItemForm()
|
form = AnonOrderItemForm() if current_user.is_anonymous() \
|
||||||
|
else OrderItemForm()
|
||||||
form.populate(order.location)
|
form.populate(order.location)
|
||||||
if order.stoptime and order.stoptime < datetime.now():
|
if order.stoptime and order.stoptime < datetime.now():
|
||||||
form = None
|
form = None
|
||||||
total_price = sum([o.product.price for o in order.items])
|
total_price = sum([o.product.price for o in order.items])
|
||||||
debts = sum([o.product.price for o in order.items if not o.paid])
|
debts = sum([o.product.price for o in order.items if not o.paid])
|
||||||
return render_template(
|
return render_template("order.html", order=order, form=form,
|
||||||
"order.html", order=order, form=form, total_price=total_price, debts=debts
|
total_price=total_price, debts=debts)
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@order_bp.route("/<id>/items")
|
@order_bp.route("/<order_id>/items")
|
||||||
def items_showcase(id: int, form: OrderForm = None) -> str:
|
def items_showcase(order_id: int) -> str:
|
||||||
order = Order.query.filter(Order.id == id).first()
|
"Generate order items view from id"
|
||||||
|
order = Order.query.filter(Order.id == order_id).first()
|
||||||
if order is None:
|
if order is None:
|
||||||
abort(404)
|
abort(404)
|
||||||
if current_user.is_anonymous() and not order.public:
|
if current_user.is_anonymous() and not order.public:
|
||||||
|
@ -73,11 +77,13 @@ def items_showcase(id: int, form: OrderForm = None) -> str:
|
||||||
return render_template("order_items.html", order=order)
|
return render_template("order_items.html", order=order)
|
||||||
|
|
||||||
|
|
||||||
@order_bp.route("/<id>/edit", methods=["GET", "POST"])
|
@order_bp.route("/<order_id>/edit", methods=["GET", "POST"])
|
||||||
@login_required
|
@login_required
|
||||||
def order_edit(id: int) -> typing.Union[str, Response]:
|
def order_edit(order_id: int) -> typing.Union[str, Response]:
|
||||||
order = Order.query.filter(Order.id == id).first()
|
"Generate order edit view from id"
|
||||||
if current_user.id is not order.courrier_id and not current_user.is_admin():
|
order = Order.query.filter(Order.id == order_id).first()
|
||||||
|
if current_user.id is not order.courrier_id and \
|
||||||
|
not current_user.is_admin():
|
||||||
abort(401)
|
abort(401)
|
||||||
if order is None:
|
if order is None:
|
||||||
abort(404)
|
abort(404)
|
||||||
|
@ -86,15 +92,17 @@ def order_edit(id: int) -> typing.Union[str, Response]:
|
||||||
if orderForm.validate_on_submit():
|
if orderForm.validate_on_submit():
|
||||||
orderForm.populate_obj(order)
|
orderForm.populate_obj(order)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return redirect(url_for("order_bp.order", id=order.id))
|
return redirect(url_for("order_bp.order_from_id", order_id=order.id))
|
||||||
return render_template("order_edit.html", form=orderForm, order_id=id)
|
return render_template("order_edit.html", form=orderForm,
|
||||||
|
order_id=order_id)
|
||||||
|
|
||||||
|
|
||||||
@order_bp.route("/<id>/create", methods=["POST"])
|
@order_bp.route("/<order_id>/create", methods=["POST"])
|
||||||
def order_item_create(id: int) -> typing.Any:
|
def order_item_create(order_id: int) -> typing.Any:
|
||||||
# type is 'typing.Union[str, Response]', but this errors due to
|
# type is 'typing.Union[str, Response]', but this errors due to
|
||||||
# https://github.com/python/mypy/issues/7187
|
# https://github.com/python/mypy/issues/7187
|
||||||
current_order = Order.query.filter(Order.id == id).first()
|
"Add item to order from id"
|
||||||
|
current_order = Order.query.filter(Order.id == order_id).first()
|
||||||
if current_order is None:
|
if current_order is None:
|
||||||
abort(404)
|
abort(404)
|
||||||
if current_order.stoptime and current_order.stoptime < datetime.now():
|
if current_order.stoptime and current_order.stoptime < datetime.now():
|
||||||
|
@ -102,12 +110,13 @@ def order_item_create(id: int) -> typing.Any:
|
||||||
if current_user.is_anonymous() and not current_order.public:
|
if current_user.is_anonymous() and not current_order.public:
|
||||||
flash("Please login to see this order.", "info")
|
flash("Please login to see this order.", "info")
|
||||||
abort(401)
|
abort(401)
|
||||||
form = AnonOrderItemForm() if current_user.is_anonymous() else OrderItemForm()
|
form = AnonOrderItemForm() if current_user.is_anonymous() \
|
||||||
|
else OrderItemForm()
|
||||||
form.populate(current_order.location)
|
form.populate(current_order.location)
|
||||||
if form.validate_on_submit():
|
if form.validate_on_submit():
|
||||||
item = OrderItem()
|
item = OrderItem()
|
||||||
form.populate_obj(item)
|
form.populate_obj(item)
|
||||||
item.order_id = id
|
item.order_id = order_id
|
||||||
if not current_user.is_anonymous():
|
if not current_user.is_anonymous():
|
||||||
item.user_id = current_user.id
|
item.user_id = current_user.id
|
||||||
else:
|
else:
|
||||||
|
@ -115,26 +124,31 @@ def order_item_create(id: int) -> typing.Any:
|
||||||
db.session.add(item)
|
db.session.add(item)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
flash("Ordered %s" % (item.product.name), "success")
|
flash("Ordered %s" % (item.product.name), "success")
|
||||||
return redirect(url_for("order_bp.order", id=id))
|
return redirect(url_for("order_bp.order_from_id", order_id=order_id))
|
||||||
return order(id, form=form)
|
return order_from_id(order_id, form=form)
|
||||||
|
|
||||||
|
|
||||||
@order_bp.route("/<order_id>/<item_id>/paid", methods=["POST"])
|
@order_bp.route("/<order_id>/<item_id>/paid", methods=["POST"])
|
||||||
@login_required
|
@login_required
|
||||||
|
# pylint: disable=R1710
|
||||||
def item_paid(order_id: int, item_id: int) -> typing.Optional[Response]:
|
def item_paid(order_id: int, item_id: int) -> typing.Optional[Response]:
|
||||||
|
"Indicate payment status for an item in an order"
|
||||||
item = OrderItem.query.filter(OrderItem.id == item_id).first()
|
item = OrderItem.query.filter(OrderItem.id == item_id).first()
|
||||||
id = current_user.id
|
user_id = current_user.id
|
||||||
if item.order.courrier_id == id or current_user.admin:
|
if item.order.courrier_id == user_id or current_user.admin:
|
||||||
item.paid = True
|
item.paid = True
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
flash("Paid %s by %s" % (item.product.name, item.get_name()), "success")
|
flash("Paid %s by %s" % (item.product.name, item.get_name()),
|
||||||
return redirect(url_for("order_bp.order", id=order_id))
|
"success")
|
||||||
|
return redirect(url_for("order_bp.order_from_id", order_id=order_id))
|
||||||
abort(404)
|
abort(404)
|
||||||
|
|
||||||
|
|
||||||
@order_bp.route("/<order_id>/<user_name>/user_paid", methods=["POST"])
|
@order_bp.route("/<order_id>/<user_name>/user_paid", methods=["POST"])
|
||||||
@login_required
|
@login_required
|
||||||
|
# pylint: disable=R1710
|
||||||
def items_user_paid(order_id: int, user_name: str) -> typing.Optional[Response]:
|
def items_user_paid(order_id: int, user_name: str) -> typing.Optional[Response]:
|
||||||
|
"Indicate payment status for a user in an order"
|
||||||
user = User.query.filter(User.username == user_name).first()
|
user = User.query.filter(User.username == user_name).first()
|
||||||
items: typing.List[OrderItem] = []
|
items: typing.List[OrderItem] = []
|
||||||
if user:
|
if user:
|
||||||
|
@ -152,33 +166,37 @@ def items_user_paid(order_id: int, user_name: str) -> typing.Optional[Response]:
|
||||||
for item in items:
|
for item in items:
|
||||||
item.paid = True
|
item.paid = True
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
flash("Paid %d items for %s" % (len(items), item.get_name()), "success")
|
flash("Paid %d items for %s" %
|
||||||
return redirect(url_for("order_bp.order", id=order_id))
|
(len(items), item.get_name()), "success")
|
||||||
|
return redirect(url_for("order_bp.order_from_id", order_id=order_id))
|
||||||
abort(404)
|
abort(404)
|
||||||
|
|
||||||
|
|
||||||
@order_bp.route("/<order_id>/<item_id>/delete", methods=["POST"])
|
@order_bp.route("/<order_id>/<item_id>/delete", methods=["POST"])
|
||||||
|
# pylint: disable=R1710
|
||||||
def delete_item(order_id: int, item_id: int) -> typing.Any:
|
def delete_item(order_id: int, item_id: int) -> typing.Any:
|
||||||
# type is 'typing.Optional[Response]', but this errors due to
|
# type is 'typing.Optional[Response]', but this errors due to
|
||||||
# https://github.com/python/mypy/issues/7187
|
# https://github.com/python/mypy/issues/7187
|
||||||
|
"Delete an item from an order"
|
||||||
item = OrderItem.query.filter(OrderItem.id == item_id).first()
|
item = OrderItem.query.filter(OrderItem.id == item_id).first()
|
||||||
id = None
|
user_id = None
|
||||||
if not current_user.is_anonymous():
|
if not current_user.is_anonymous():
|
||||||
print("%s tries to delete orders" % (current_user.username))
|
print("%s tries to delete orders" % (current_user.username))
|
||||||
id = current_user.id
|
user_id = current_user.id
|
||||||
if item.can_delete(order_id, id, session.get("anon_name", "")):
|
if item.can_delete(order_id, user_id, session.get("anon_name", "")):
|
||||||
product_name = item.product.name
|
product_name = item.product.name
|
||||||
db.session.delete(item)
|
db.session.delete(item)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
flash("Deleted %s" % (product_name), "success")
|
flash("Deleted %s" % (product_name), "success")
|
||||||
return redirect(url_for("order_bp.order", id=order_id))
|
return redirect(url_for("order_bp.order_from_id", order_id=order_id))
|
||||||
abort(404)
|
abort(404)
|
||||||
|
|
||||||
|
|
||||||
@order_bp.route("/<id>/volunteer", methods=["POST"])
|
@order_bp.route("/<order_id>/volunteer", methods=["POST"])
|
||||||
@login_required
|
@login_required
|
||||||
def volunteer(id: int) -> Response:
|
def volunteer(order_id: int) -> Response:
|
||||||
order = Order.query.filter(Order.id == id).first()
|
"Add a volunteer to an order"
|
||||||
|
order = Order.query.filter(Order.id == order_id).first()
|
||||||
if order is None:
|
if order is None:
|
||||||
abort(404)
|
abort(404)
|
||||||
if order.courrier_id is None or order.courrier_id == 0:
|
if order.courrier_id is None or order.courrier_id == 0:
|
||||||
|
@ -187,18 +205,18 @@ def volunteer(id: int) -> Response:
|
||||||
flash("Thank you for volunteering!")
|
flash("Thank you for volunteering!")
|
||||||
else:
|
else:
|
||||||
flash("Volunteering not possible!")
|
flash("Volunteering not possible!")
|
||||||
return redirect(url_for("order_bp.order", id=id))
|
return redirect(url_for("order_bp.order_from_id", order_id=order_id))
|
||||||
|
|
||||||
|
|
||||||
@order_bp.route("/<id>/close", methods=["POST"])
|
@order_bp.route("/<order_id>/close", methods=["POST"])
|
||||||
@login_required
|
@login_required
|
||||||
def close_order(id: int) -> typing.Optional[Response]:
|
def close_order(order_id: int) -> typing.Optional[Response]:
|
||||||
order = Order.query.filter(Order.id == id).first()
|
"Close an order"
|
||||||
|
order = Order.query.filter(Order.id == order_id).first()
|
||||||
if order is None:
|
if order is None:
|
||||||
abort(404)
|
abort(404)
|
||||||
if (current_user.id == order.courrier_id or current_user.is_admin()) and (
|
if (current_user.id == order.courrier_id or current_user.is_admin()) and (
|
||||||
order.stoptime is None or (order.stoptime > datetime.now())
|
order.stoptime is None or (order.stoptime > datetime.now())):
|
||||||
):
|
|
||||||
order.stoptime = datetime.now()
|
order.stoptime = datetime.now()
|
||||||
if order.courrier_id == 0 or order.courrier_id is None:
|
if order.courrier_id == 0 or order.courrier_id is None:
|
||||||
courrier = select_user(order.items)
|
courrier = select_user(order.items)
|
||||||
|
@ -206,7 +224,7 @@ def close_order(id: int) -> typing.Optional[Response]:
|
||||||
if courrier is not None:
|
if courrier is not None:
|
||||||
order.courrier_id = courrier.id
|
order.courrier_id = courrier.id
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return redirect(url_for("order_bp.order", id=id))
|
return redirect(url_for("order_bp.order_from_id", order_id=order_id))
|
||||||
# The line below is to make sure mypy doesn't say
|
# The line below is to make sure mypy doesn't say
|
||||||
# "Missing return statement"
|
# "Missing return statement"
|
||||||
# https://github.com/python/mypy/issues/4223
|
# https://github.com/python/mypy/issues/4223
|
||||||
|
@ -214,11 +232,12 @@ def close_order(id: int) -> typing.Optional[Response]:
|
||||||
|
|
||||||
|
|
||||||
def select_user(items) -> typing.Optional[User]:
|
def select_user(items) -> typing.Optional[User]:
|
||||||
|
"Select a random user from those who are signed up for the order"
|
||||||
user = None
|
user = None
|
||||||
# remove non users
|
# remove non users
|
||||||
items = [i for i in items if i.user_id]
|
items = [i for i in items if i.user_id]
|
||||||
|
|
||||||
if len(items) <= 0:
|
if not items:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
while user is None:
|
while user is None:
|
||||||
|
@ -232,13 +251,17 @@ def select_user(items) -> typing.Optional[User]:
|
||||||
|
|
||||||
|
|
||||||
def get_orders(expression=None) -> typing.List[Order]:
|
def get_orders(expression=None) -> typing.List[Order]:
|
||||||
orders: typing.List[OrderForm] = []
|
"Give the list of all currently open and public Orders"
|
||||||
|
order_list: typing.List[OrderForm] = []
|
||||||
if expression is None:
|
if expression is None:
|
||||||
expression = (datetime.now() > Order.starttime) & (
|
expression = (datetime.now() > Order.starttime) & (
|
||||||
Order.stoptime > datetime.now()
|
Order.stoptime > datetime.now()
|
||||||
|
# pylint: disable=C0121
|
||||||
) | (Order.stoptime == None)
|
) | (Order.stoptime == None)
|
||||||
if not current_user.is_anonymous():
|
if not current_user.is_anonymous():
|
||||||
orders = Order.query.filter(expression).all()
|
order_list = Order.query.filter(expression).all()
|
||||||
else:
|
else:
|
||||||
orders = Order.query.filter((expression & (Order.public == True))).all()
|
order_list = Order.query.filter(
|
||||||
return orders
|
# pylint: disable=C0121
|
||||||
|
(expression & (Order.public == True))).all()
|
||||||
|
return order_list
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
"Script to generate the stats related views of Haldis"
|
||||||
from flask import Blueprint
|
from flask import Blueprint
|
||||||
from flask import current_app as app
|
from flask import current_app as app
|
||||||
from flask import render_template
|
from flask import render_template
|
||||||
|
@ -9,6 +10,7 @@ stats_blueprint = Blueprint("stats_blueprint", __name__)
|
||||||
|
|
||||||
@stats_blueprint.route("/")
|
@stats_blueprint.route("/")
|
||||||
def stats() -> str:
|
def stats() -> str:
|
||||||
|
"Generate Haldis data in a pretty format"
|
||||||
data = {
|
data = {
|
||||||
"amount": {
|
"amount": {
|
||||||
"orders": FatOrder.amount(),
|
"orders": FatOrder.amount(),
|
||||||
|
|
12
app/zeus.py
12
app/zeus.py
|
@ -1,3 +1,4 @@
|
||||||
|
"Script containing everything specific to ZeusWPI"
|
||||||
import typing
|
import typing
|
||||||
|
|
||||||
from flask import (Blueprint, current_app, flash, redirect, request, session,
|
from flask import (Blueprint, current_app, flash, redirect, request, session,
|
||||||
|
@ -12,6 +13,7 @@ oauth_bp = Blueprint("oauth_bp", __name__)
|
||||||
|
|
||||||
|
|
||||||
def zeus_login():
|
def zeus_login():
|
||||||
|
"Log in using ZeusWPI"
|
||||||
return current_app.zeus.authorize(
|
return current_app.zeus.authorize(
|
||||||
callback=url_for("oauth_bp.authorized", _external=True)
|
callback=url_for("oauth_bp.authorized", _external=True)
|
||||||
)
|
)
|
||||||
|
@ -21,6 +23,7 @@ def zeus_login():
|
||||||
def authorized() -> typing.Any:
|
def authorized() -> typing.Any:
|
||||||
# type is 'typing.Union[str, Response]', but this errors due to
|
# type is 'typing.Union[str, Response]', but this errors due to
|
||||||
# https://github.com/python/mypy/issues/7187
|
# https://github.com/python/mypy/issues/7187
|
||||||
|
"Check authorized status"
|
||||||
resp = current_app.zeus.authorized_response()
|
resp = current_app.zeus.authorized_response()
|
||||||
if resp is None:
|
if resp is None:
|
||||||
return "Access denied: reason=%s error=%s" % (
|
return "Access denied: reason=%s error=%s" % (
|
||||||
|
@ -35,9 +38,10 @@ def authorized() -> typing.Any:
|
||||||
username = me.data.get("username", "").lower()
|
username = me.data.get("username", "").lower()
|
||||||
|
|
||||||
user = User.query.filter_by(username=username).first()
|
user = User.query.filter_by(username=username).first()
|
||||||
if len(username) > 0 and user:
|
# pylint: disable=R1705
|
||||||
|
if username and user:
|
||||||
return login_and_redirect_user(user)
|
return login_and_redirect_user(user)
|
||||||
elif len(username) > 0:
|
elif username > 0:
|
||||||
user = create_user(username)
|
user = create_user(username)
|
||||||
return login_and_redirect_user(user)
|
return login_and_redirect_user(user)
|
||||||
|
|
||||||
|
@ -46,6 +50,7 @@ def authorized() -> typing.Any:
|
||||||
|
|
||||||
|
|
||||||
def init_oauth(app):
|
def init_oauth(app):
|
||||||
|
"Initialize the OAuth for ZeusWPI"
|
||||||
oauth = OAuth(app)
|
oauth = OAuth(app)
|
||||||
|
|
||||||
zeus = oauth.remote_app(
|
zeus = oauth.remote_app(
|
||||||
|
@ -59,6 +64,7 @@ def init_oauth(app):
|
||||||
authorize_url="https://adams.ugent.be/oauth/oauth2/authorize/",
|
authorize_url="https://adams.ugent.be/oauth/oauth2/authorize/",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# pylint: disable=W0612
|
||||||
@zeus.tokengetter
|
@zeus.tokengetter
|
||||||
def get_zeus_oauth_token():
|
def get_zeus_oauth_token():
|
||||||
return session.get("zeus_token")
|
return session.get("zeus_token")
|
||||||
|
@ -67,11 +73,13 @@ def init_oauth(app):
|
||||||
|
|
||||||
|
|
||||||
def login_and_redirect_user(user) -> Response:
|
def login_and_redirect_user(user) -> Response:
|
||||||
|
"Log in the user and then redirect them"
|
||||||
login_user(user)
|
login_user(user)
|
||||||
return redirect(url_for("general_bp.home"))
|
return redirect(url_for("general_bp.home"))
|
||||||
|
|
||||||
|
|
||||||
def create_user(username) -> User:
|
def create_user(username) -> User:
|
||||||
|
"Create a temporary user if it is needed"
|
||||||
user = User()
|
user = User()
|
||||||
user.configure(username, False, 1)
|
user.configure(username, False, 1)
|
||||||
db.session.add(user)
|
db.session.add(user)
|
||||||
|
|
Loading…
Reference in a new issue