diff --git a/backend/workspaces/Invoices/actions/README.md b/backend/workspaces/Invoices/actions/README.md new file mode 100644 index 0000000..e69de29 diff --git a/backend/workspaces/Invoices/actions/createConsumptionLog.py b/backend/workspaces/Invoices/actions/createConsumptionLog.py new file mode 100644 index 0000000..f758bd5 --- /dev/null +++ b/backend/workspaces/Invoices/actions/createConsumptionLog.py @@ -0,0 +1,53 @@ +""" +The roseguarden project + +Copyright (C) 2018-2020 Marcus Drobisch, + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation, either version 3 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +You should have received a copy of the GNU General Public License along with +this program. If not, see . +""" + +__authors__ = ["Marcus Drobisch"] +__contact__ = "roseguarden@fabba.space" +__credits__ = [] +__license__ = "GPLv3" + +from core.actions.action import Action +from core.logs import logManager +from core.actions import webclientActions +from core.users import userManager +from core.messages import send_mail, send_message +from core.actions import generateActionLink + +from workspaces.Invoices.models import ConsumptionLog + + +class CreateConsumptionLog(Action): + def __init__(self, app): + # logManager.info("Register of type Action created") + super().__init__(app, uri="createConsumptionLog") + + def handle(self, action, user, workspace, actionManager): + replyActions = [] + + consumption_log = ConsumptionLog() + consumption_log.consumed_as_guest = action.get("consumedAsGuest", True) + consumption_log.guest_email = action.get("guestEmail", "") + consumption_log.guest_is_member = action.get("guestIsMember", False) + consumption_log.service_area = action.get("serviceAreas", "") + consumption_log.service_name = action.get("serviceName", "") + consumption_log.service_quantity = action.get("serviceQuantity", 0.0) + consumption_log.service_unit = action.get("serviceUnit", "") + + workspace.db.session.add(consumption_log) + + replyActions.append(webclientActions.NotificationAction.generate("Consumption log created", "success")) + return "success", replyActions, {"custom": "customResponse"} diff --git a/backend/workspaces/Invoices/jobs/README.md b/backend/workspaces/Invoices/jobs/README.md new file mode 100644 index 0000000..e69de29 diff --git a/backend/workspaces/Invoices/models/README.md b/backend/workspaces/Invoices/models/README.md new file mode 100644 index 0000000..652063f --- /dev/null +++ b/backend/workspaces/Invoices/models/README.md @@ -0,0 +1,25 @@ +# General + +Place your models in this folder. + +The core loads all models imported in `__init__.py`. + +# Migrations + +You might use the alembic command lines to setup migration here. + +Run the command in the specific `models` folder + +## Create a new revision in `versions`: + +`alembic revision -m "name" --autogenerate --rev-id REV_ID` + +Please use the actual naming convention. E.g. `-m "name" --autogenerate --rev-id 000001`. + +## Upgrade to a new revision: + +`alembic upgrade REV_ID` + +## Stamp to an actual version (may be needed before upgrade or create a new revision): + +`alembic stamp --purge REV_ID` \ No newline at end of file diff --git a/backend/workspaces/Invoices/models/__init__.py b/backend/workspaces/Invoices/models/__init__.py new file mode 100644 index 0000000..6acd968 --- /dev/null +++ b/backend/workspaces/Invoices/models/__init__.py @@ -0,0 +1 @@ +from .consumption_log import * # noqa: F401, F403 diff --git a/backend/workspaces/Invoices/models/alembic.ini b/backend/workspaces/Invoices/models/alembic.ini new file mode 100644 index 0000000..6be3947 --- /dev/null +++ b/backend/workspaces/Invoices/models/alembic.ini @@ -0,0 +1,83 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = migrations + +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# timezone to use when rendering the date +# within the migration file as well as the filename. +# string value is passed to dateutil.tz.gettz() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; this defaults +# to migrations/versions. When using multiple version +# directories, initial revisions must be specified with --version-path +# version_locations = %(here)s/bar %(here)s/bat migrations/versions + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks=black +# black.type=console_scripts +# black.entrypoint=black +# black.options=-l 79 + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/backend/workspaces/Invoices/models/consumption_log.py b/backend/workspaces/Invoices/models/consumption_log.py new file mode 100644 index 0000000..354e5ef --- /dev/null +++ b/backend/workspaces/Invoices/models/consumption_log.py @@ -0,0 +1,49 @@ +""" +The roseguarden project + +Copyright (C) 2018-2020 Marcus Drobisch, + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation, either version 3 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +You should have received a copy of the GNU General Public License along with +this program. If not, see . +""" + +__authors__ = ["Marcus Drobisch"] +__contact__ = "roseguarden@fabba.space" +__credits__ = [] +__license__ = "GPLv3" + +from sqlalchemy_utils import ArrowType +import arrow + +from core import db +from core.users.models import User + + +class ConsumptionLog(db.Model): + __tablename__ = "invoice_consumption_log" + id = db.Column(db.Integer, primary_key=True, index=True, autoincrement=True, unique=True) + consumed_as_guest = db.Column(db.Boolean, default=None) + linked_user_id = db.Column(db.Integer, db.ForeignKey(User.id, ondelete="SET NULL")) + linked_user = db.relationship("User", backref="consumptions", foreign_keys=linked_user_id) + guest_is_member = db.Column(db.Boolean, default=None) + guest_email = db.Column(db.String(128), default=None) + + consumed_at = db.Column(ArrowType, default=arrow.utcnow) + created_at = db.Column(ArrowType, default=arrow.utcnow) + + service_area = db.Column(db.String(128), default=None) + service_name = db.Column(db.String(128), default=None) + service_quantity = db.Column(db.Float, default=None) + service_unit = db.Column(db.String(128), default=None) + + project_name = db.Column(db.String(128), default=None) + project_purpose = db.Column(db.String(128), default=None) + project_details = db.Column(db.String(128), default=None) diff --git a/backend/workspaces/Invoices/models/migrations/README.md b/backend/workspaces/Invoices/models/migrations/README.md new file mode 100644 index 0000000..e69de29 diff --git a/backend/workspaces/Invoices/models/migrations/env.py b/backend/workspaces/Invoices/models/migrations/env.py new file mode 100644 index 0000000..112c31f --- /dev/null +++ b/backend/workspaces/Invoices/models/migrations/env.py @@ -0,0 +1,156 @@ +from logging.config import fileConfig +import logging +from sqlalchemy import engine_from_config +from sqlalchemy import pool +import sqlalchemy_utils # noqa: F401 + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger("alembic.env") + +al_logger = logging.getLogger("alembic.runtime.migration") +al_logger.setLevel(logging.ERROR) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +import os +import sys +from pathlib import Path + + +file = Path(__file__).resolve() +parent, top, root = file.parent, file.parents[4], file.parents[5] + +sys.path.append(str(top)) +sys.path.append(str(file.parents[2])) + +logger.info(f"cwd {os.getcwd()} {top} {root} {file.parents[2]}") + +# fixme: set this per workspace +alembic_datatable_name = "migration_version_" + (str(file.parents[2].name)).lower() +print(alembic_datatable_name) +from core import db +import models +from config import configure_app, load_config + +target_metadata = db.Model.metadata + +# fixme: this is probably fine for our use case, but in configure_app() +# we also allow setting from os.environ.get('DATABASE_URL') +app_config = load_config("config.ini") +database_path = app_config["SYSTEM"].get("database_path", None) +basedir = file.parents[4] + +config.set_main_option( + "sqlalchemy.url", database_path or os.environ.get("DATABASE_URL") or "sqlite:///" + os.path.join(basedir, "app.db") +) + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def include_object(obj, name, type_, reflected, compare_to): + """ + Should you include this table or not? + """ + if reflected is False: + if type(obj) == type(compare_to): + logger.info(f"No changes on {name}") + else: + logger.info(f"Changes found for {name}") + return True + return False + + +def render_item(type_, obj, autogen_context): + # custom render for sqalchemy_utils ChoiceType column and params + # May be better to use: https://stackoverflow.com/questions/30132370/trouble-when-using-alembic-with-sqlalchemy-utils + print(type(obj)) + if type_ == "type" and type(obj).__name__ == "IntEnum": + col_type = "sa.Integer(), default=0" + return col_type + if type_ == "type" and type(obj).__name__ == "IntFlag": + col_type = "sa.Integer(), default=0" + return col_type + + # default rendering for other objects + return False + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, "autogenerate", False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info("No changes in schema detected.") + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + render_item=render_item, + include_object=include_object, + version_table=alembic_datatable_name, + process_revision_directives=process_revision_directives, + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/backend/workspaces/Invoices/models/migrations/script.py.mako b/backend/workspaces/Invoices/models/migrations/script.py.mako new file mode 100644 index 0000000..ee5cea7 --- /dev/null +++ b/backend/workspaces/Invoices/models/migrations/script.py.mako @@ -0,0 +1,25 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +import sqlalchemy_utils +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/backend/workspaces/Invoices/models/migrations/versions/000001_base.py b/backend/workspaces/Invoices/models/migrations/versions/000001_base.py new file mode 100644 index 0000000..9413f06 --- /dev/null +++ b/backend/workspaces/Invoices/models/migrations/versions/000001_base.py @@ -0,0 +1,49 @@ +"""base + +Revision ID: 000001 +Revises: +Create Date: 2023-02-19 15:10:22.868852 + +""" +from alembic import op +import sqlalchemy as sa +import sqlalchemy_utils + + +# revision identifiers, used by Alembic. +revision = "000001" +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + "invoice_consumption_log", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("consumed_as_guest", sa.Boolean(), nullable=True), + sa.Column("linked_user_id", sa.Integer(), nullable=True), + sa.Column("guest_is_member", sa.Boolean(), nullable=True), + sa.Column("guest_email", sa.String(length=128), nullable=True), + sa.Column("consumed_at", sqlalchemy_utils.types.arrow.ArrowType(), nullable=True), + sa.Column("created_at", sqlalchemy_utils.types.arrow.ArrowType(), nullable=True), + sa.Column("service_area", sa.String(length=128), nullable=True), + sa.Column("service_name", sa.String(length=128), nullable=True), + sa.Column("service_quantity", sa.Float(), nullable=True), + sa.Column("service_unit", sa.String(length=128), nullable=True), + sa.Column("project_name", sa.String(length=128), nullable=True), + sa.Column("project_purpose", sa.String(length=128), nullable=True), + sa.Column("project_details", sa.String(length=128), nullable=True), + sa.ForeignKeyConstraint(["linked_user_id"], ["users.id"], ondelete="SET NULL"), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index(op.f("ix_invoice_consumption_log_id"), "invoice_consumption_log", ["id"], unique=True) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f("ix_invoice_consumption_log_id"), table_name="invoice_consumption_log") + op.drop_table("invoice_consumption_log") + # ### end Alembic commands ### diff --git a/backend/workspaces/Invoices/pages/README.md b/backend/workspaces/Invoices/pages/README.md new file mode 100644 index 0000000..e69de29 diff --git a/backend/workspaces/Invoices/pages/consumptions.py b/backend/workspaces/Invoices/pages/consumptions.py new file mode 100644 index 0000000..65dfce8 --- /dev/null +++ b/backend/workspaces/Invoices/pages/consumptions.py @@ -0,0 +1,37 @@ +""" +The roseguarden project + +Copyright (C) 2018-2020 Marcus Drobisch, + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation, either version 3 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +You should have received a copy of the GNU General Public License along with +this program. If not, see . +""" + +__authors__ = ["Marcus Drobisch"] +__contact__ = "roseguarden@fabba.space" +__credits__ = [] +__license__ = "GPLv3" + +from core.workspaces.page import Page + +""" The consumption overview page +""" + + +class Consumptions(Page): + title = "Consumptions" # Shown label of the page in the menu + group = "Admin" # groupname multiple pages + icon = "mdi-food-apple" # icon (in typeset of material design icons) + route = "/invoices/consumptions" # routing + builder = "frontend" # page get build by the client (frontend) + rank = 1.6 # ranks (double) the page higher values are at the top of the menu + # groups will be ranked by the sum of the rank-values of their entries + requireLogin = True # login is required to view the page diff --git a/backend/workspaces/Invoices/permissions.py b/backend/workspaces/Invoices/permissions.py new file mode 100644 index 0000000..b2fbc2e --- /dev/null +++ b/backend/workspaces/Invoices/permissions.py @@ -0,0 +1,25 @@ +""" +The roseguarden project + +Copyright (C) 2018-2020 Marcus Drobisch, + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation, either version 3 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +You should have received a copy of the GNU General Public License along with +this program. If not, see . +""" + +__authors__ = ["Marcus Drobisch"] +__contact__ = "roseguarden@fabba.space" +__credits__ = [] +__license__ = "GPLv3" + +from core.workspaces.permission import Permission + +# Define your Permissions here diff --git a/backend/workspaces/Invoices/templates/README.md b/backend/workspaces/Invoices/templates/README.md new file mode 100644 index 0000000..e69de29 diff --git a/backend/workspaces/Invoices/views/README.md b/backend/workspaces/Invoices/views/README.md new file mode 100644 index 0000000..e69de29 diff --git a/backend/workspaces/Invoices/views/consumed.py b/backend/workspaces/Invoices/views/consumed.py new file mode 100644 index 0000000..92dc00d --- /dev/null +++ b/backend/workspaces/Invoices/views/consumed.py @@ -0,0 +1,81 @@ +""" +The roseguarden project + +Copyright (C) 2018-2020 Marcus Drobisch, + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation, either version 3 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +You should have received a copy of the GNU General Public License along with +this program. If not, see . +""" + +__authors__ = ["Marcus Drobisch"] +__contact__ = "roseguarden@fabba.space" +__credits__ = [] +__license__ = "GPLv3" + +from core.workspaces.workspace import Workspace +from core.workspaces.dataView import DataView + +from core.common.deface import deface_string_end, deface_string_middle + +from core.users.models import User + +from workspaces.Invoices.models import ConsumptionLog + +""" A view contaning a list of all consumed logs +""" + + +class ConsumedList(DataView): + uri = "consumedList" + requireLogin = True + + def defineProperties(self): + self.addIntegerProperty(name="id", label="Id", isKey=True, hide=True) + self.addDatetimeProperty(name="consumed_at", label="Date") + self.addStringProperty(name="consumed_by", label="User") + self.addStringProperty(name="service", label="Service") + self.addStringProperty(name="amount", label="Amount") + self.addStringProperty(name="details", label="Details") + + def getViewHandler(self, user: User, workspace: Workspace, query=None): + print("getDataViewHandler for AuthenticatorRequestList") + + entrylist = [] + all_consume_logs = ConsumptionLog.query.all() + cl: ConsumptionLog + for cl in all_consume_logs: + # get new empty entry + entry = self.createEntry() + + # fill entry + entry.id = cl.id + entry.consumed_at = cl.consumed_at.format("YYYY-MM-DD HH:mm") + entry.service = f"[{cl.service_area}] {cl.service_name}" + entry.amount = f"{cl.service_quantity} {cl.service_unit}" + if cl.linked_user is None or cl.consumed_as_guest: + entry.consumed_by = "(Guest) " + str(cl.guest_email) + else: + entry.consumed_by = f"{cl.linked_user.firstname} {cl.linked_user.lastname} ({cl.linked_user.email})" + entry.details = f"{cl.project_purpose}" + + entrylist.append(entry.extract()) + return entrylist + + def __repr__(self): + return "<{} with {} properties>".format(self.name, len(self.properties)) + + # Handler for a request to create a new view entry + def createViewEntryHandler(self, user, workspace, entry): + print("Handle createViewEntry request for " + self.uri) + + # Handler for a request to update a single view entry + def updateViewEntryHandler(self, user, workspace, key, entry): + print("Handle updateViewEntryHandler request for " + self.uri) diff --git a/backend/workspaces/Invoices/workspace.py b/backend/workspaces/Invoices/workspace.py new file mode 100644 index 0000000..e3bedaa --- /dev/null +++ b/backend/workspaces/Invoices/workspace.py @@ -0,0 +1,31 @@ +""" +The roseguarden project + +Copyright (C) 2018-2020 Marcus Drobisch, + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation, either version 3 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +You should have received a copy of the GNU General Public License along with +this program. If not, see . +""" + +__authors__ = ["Marcus Drobisch"] +__contact__ = "roseguarden@fabba.space" +__credits__ = [] +__license__ = "GPLv3" + +from core.workspaces.workspace import Workspace + +"""This plugin (workspace) is for the administration of the invoices +""" + + +class Invoices(Workspace): + uri = "invoices" + description = "Invoices and consumptions" diff --git a/frontend/pages/invoices/consumptions.vue b/frontend/pages/invoices/consumptions.vue new file mode 100644 index 0000000..db9a868 --- /dev/null +++ b/frontend/pages/invoices/consumptions.vue @@ -0,0 +1,107 @@ + + + + +