Skip to content

Commit

Permalink
Merge branch 'INRIM:2.1' into 2.1
Browse files Browse the repository at this point in the history
  • Loading branch information
simoneanam authored Oct 8, 2024
2 parents 54ba662 + 795da71 commit 54c7e5f
Show file tree
Hide file tree
Showing 163 changed files with 2,378 additions and 36,942 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Service App is a project and framework designed to
- available plugin class system to build your own backend and/or frontend custom service
- documentation for plugin development is in WIP

Read the complete [Documentations ](docs/index.md)

### TODO

- i18n
Expand Down
2 changes: 1 addition & 1 deletion backend/ozon/core/ModelData.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,7 +662,7 @@ async def clean_expired_to_delete_record(self):
if data_model:
if name == "session":
res = await clean_session(datetime.now().isoformat())
logger.info(f" clean to delete {name} {res}")
logger.info(f" clean to delete {res} useless session")
else:
res = await erese_all_to_delete_record(data_model)
logger.info(f" clean to delete {name} {res}")
Expand Down
15 changes: 7 additions & 8 deletions backend/ozon/core/OzonRawMiddleware.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
# Copyright INRIM (https://www.inrim.eu)
# See LICENSE file for full licensing details.

from typing import Optional, Sequence, Union, Any
from fastapi.responses import RedirectResponse, JSONResponse
from typing import Optional, Union, Any

from starlette.requests import HTTPConnection, Request
from starlette.types import Message, Receive, Scope, Send
from fastapi import FastAPI
from .Ozon import Ozon
from .SessionMain import SessionMain, SessionBase
import logging
import bson

logger = logging.getLogger(__name__)



class OzonRawMiddleware:
def __init__(
self, app: FastAPI, settings, pwd_context: Optional[Any] = None
self, app: FastAPI, settings, pwd_context: Optional[Any] = None
) -> None:
self.app = app
self.pwd_context = pwd_context
Expand All @@ -26,7 +25,7 @@ def __init__(

@staticmethod
def get_request_object(
scope, receive, send
scope, receive, send
) -> Union[Request, HTTPConnection]:
# here we instantiate HTTPConnection instead of a Request object
# because only headers are needed so that's sufficient.
Expand All @@ -35,7 +34,7 @@ def get_request_object(
return Request(scope, receive, send)

async def __call__(
self, scope: Scope, receive: Receive, send: Send
self, scope: Scope, receive: Receive, send: Send
) -> None:
if scope["type"] not in ("http", "websocket"): # pragma: no cover
await self.app(scope, receive, send)
Expand All @@ -62,8 +61,8 @@ async def send_wrapper(message: Message) -> None:
f"object: {request.scope['ozon']} , params: {request.query_params}, headers{request.headers}"
)
# self.session = await self.init_request(request)

if not session or session is None:
logger.info(f'Is public {request.scope["ozon"].auth_service.is_public_endpoint()}')
if not session or session is None and not request.scope["ozon"].auth_service.is_public_endpoint():
response = request.scope["ozon"].auth_service.login_page()
await response(scope, receive, send)
else:
Expand Down
57 changes: 23 additions & 34 deletions backend/ozon/core/ServiceAuth.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,17 @@
# Copyright INRIM (https://www.inrim.eu)
# See LICENSE file for full licensing details.
import sys
import os
from os import listdir
from os.path import isfile, join
from fastapi.responses import RedirectResponse, JSONResponse
import ujson
import uuid

# from ozon.settings import get_settings
from .database.mongo_core import *
from collections import OrderedDict
from pathlib import Path
from fastapi import Request
from .SessionMain import SessionMain
from fastapi.responses import JSONResponse

from .BaseClass import PluginBase
from .ModelData import ModelData
from .BaseClass import BaseClass, PluginBase
from pydantic import ValidationError
from .SessionMain import SessionMain
# from ozon.settings import get_settings
from .database.mongo_core import *

import logging
import pymongo
import requests
import httpx
import uuid
from cryptography.fernet import Fernet

logger = logging.getLogger(__name__)

Expand All @@ -37,13 +26,13 @@ def __init_subclass__(cls, **kwargs):
class ServiceAuthBase(ServiceAuth):
@classmethod
def create(
cls,
settings=None,
public_endpoint="",
parent=None,
request=None,
pwd_context=None,
req_id="",
cls,
settings=None,
public_endpoint="",
parent=None,
request=None,
pwd_context=None,
req_id="",
):
self = ServiceAuthBase()
self.init(
Expand All @@ -52,13 +41,13 @@ def create(
return self

def init(
self,
settings=None,
public_endpoint="",
parent=None,
request=None,
pwd_context=None,
req_id="",
self,
settings=None,
public_endpoint="",
parent=None,
request=None,
pwd_context=None,
req_id="",
):
self.session = None
self.app_code = parent.app_code
Expand Down Expand Up @@ -155,7 +144,7 @@ async def check_default_token_header(self):
logger.debug(f"ws_request {apitoken}")
self.ws_request = True
self.token = apitoken
logger.info(f" Is WS {self.ws_request} with token {self.token}")
logger.debug(f" Is WS {self.ws_request} with token {self.token}")

async def check_session(self):
logger.info("check_session")
Expand Down Expand Up @@ -190,7 +179,7 @@ async def init_session(self):
self.session = await self.session_service.find_session_by_token()
if not self.session and self.is_public_endpoint:
self.session = await self.create_session_public_user()
if self.session.expire_datetime < datetime.now():
if self.session and self.session.expire_datetime < datetime.now():
self.session.active = False
await self.mdata.save_record(self.session)
self.session = None
Expand Down
33 changes: 12 additions & 21 deletions backend/ozon/core/database/mongodb/mongo_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,7 @@ async def set_to_delete_records(model: Type[ModelType], query={}):
days=settings.delete_record_after_days
)
rec.deleted = delete_at_datetime.timestamp()
rec.active = False
await engine.save(rec)
return True

Expand All @@ -498,6 +499,7 @@ async def set_to_delete_record(schema: Type[ModelType], rec):
days=settings.delete_record_after_days
)
rec.deleted = delete_at_datetime.timestamp()
rec.active = False
return await save_record(rec, remove_meta=False)


Expand All @@ -506,35 +508,24 @@ async def retrieve_all_to_delete(model: Type[ModelType]):
q = {
"$and": [{"deleted": {"$gt": 0}}, {"deleted": {"$lt": curr_timestamp}}]
}
res = await search_by_filter(model, q)
return res
# res = await search_by_filter(model, q)
return q


async def erese_all_to_delete_record(model: Type[ModelType]):
res = await retrieve_all_to_delete(model)
query = await retrieve_all_to_delete(model)
coll = db.engine.get_collection(model.str_name())
for rec in res:
if isinstance(rec, dict):
name = rec["rec_name"]
else:
name = rec.rec_name
await coll.delete_one({"rec_name": name})
return f"removed {len(res)} records"
res = await coll.delete_many(query)
return f"removed {res.deleted_count} records"


async def clean_session(date_expire):
res_to_expire = await search_by_filter(
Session, {"expire_datetime": {"$lt": date_expire}}
)
coll = db.engine.get_collection("session")
for item in res_to_expire:
await coll.delete_one({"_id": item["_id"]})
res = await search_by_filter(
Session, {"$or": [{"active": False}, {"is_public": True}]}
)
for rec in res:
await coll.delete_one({"_id": rec["_id"]})
return f"removed {len(res) + len(res_to_expire)} records"
res = await coll.delete_many({"expire_datetime": {"$lt": date_expire}})
res2 = await coll.delete_many(
{"$or": [{"active": False}, {"is_public": True}]})

return f"removed {res.deleted_count + res2.deleted_count} records"


## TODO handle archiviations
Expand Down
4 changes: 2 additions & 2 deletions build_and_run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ source ${PWD}/.env
CURRPATH=${PWD}
#./init.sh
echo "Update"
docker-compose -f docker-compose.yml -p ${APP_CODE} --profile core-only stop
docker-compose -f docker-compose.yml --env-file .env -p ${APP_CODE} --profile core-only --compatibility up -d
docker compose -f docker-compose.yml -p ${APP_CODE} --profile core-only stop
docker compose -f docker-compose.yml --env-file .env -p ${APP_CODE} --profile core-only --compatibility up -d
10 changes: 5 additions & 5 deletions deploy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ echo "setup coplete"
cd $CURRPATH
if [ -e "$PWD/docker-compose-custom.yml" ]; then
echo "setup compose custom"
docker-compose -f docker-compose-custom.yml -p ${STACK} --profile all stop
docker-compose -f docker-compose-custom.yml -p ${STACK} --env-file .env build --no-cache --rm=false .
docker-compose -f docker-compose-custom.yml -p ${STACK} --profile all --compatibility up --force-recreate --always-recreate-deps --detach --build
docker compose -f docker-compose-custom.yml -p ${STACK} --profile all stop
docker compose -f docker-compose-custom.yml -p ${STACK} --env-file .env build --no-cache --rm=false .
docker compose -f docker-compose-custom.yml -p ${STACK} --profile all --compatibility up --force-recreate --always-recreate-deps --detach --build
else
echo "setup compose ${APP_NAME}"
docker-compose -f docker-compose.yml --env-file .env -p ${STACK} --profile all stop
docker-compose -f docker-compose.yml --env-file .env -p ${STACK} --profile all --compatibility up --force-recreate --always-recreate-deps --detach --build
docker compose -f docker-compose.yml --env-file .env -p ${STACK} --profile all stop
docker compose -f docker-compose.yml --env-file .env -p ${STACK} --profile all --compatibility up --force-recreate --always-recreate-deps --detach --build
fi

sh update.sh automation
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ services:
restart: always

automation:
profiles: [ "all" ]
profiles: [ "all", "automation" ]
stdin_open: true # -i
tty: true
build:
Expand Down
Binary file added docs/en/.base.md.swp
Binary file not shown.
52 changes: 52 additions & 0 deletions docs/en/base.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Form Builder Components

All components in the builder are or are derived from the default components of [Formio.js](https://formio.github.io/formio.js/app/builder)
The system integrates this tool for creating Drag&Drop forms and makes them available to the user in the form of an App with [graphics adhering to AGID guidelines](https://italia.github.io/bootstrap-italia/docs/come-iniziare/introduzione/)
Not all the features of Formio.js have been managed but only those useful for the purpose of the project.
As regards the basic functionality of the project, see [general documentation of the application](index.md#L60)

## **Metadata**
Metadata is data present in each model (form) and is automatically enhanced when creating/modifying a form record.
The list of metadata is as follows:
**id, rec_name, owner_uid, owner_name, owner_sector, owner_sector_id, owner_function, update_datetime,create_datetime,owner_function_type, sys, demo, deleted, list_order, owner_personal_type, owner_job_title**

# Basic functionality of all components:
### The following properties are managed in the components:
**Display:**
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**Custom CSS Class →** classes can be used [Bootstrap 4](https://italia.github.io/bootstrap-italia/1.x/docs/utilities/colori/)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**Hidden →** set the field hidden or not
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**Disabled →** disables the field and makes it read-only and does not save the data.
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**Table View →** displays the field in the list view or not
**Validation:**
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**Required →** makes the field mandatory in the form
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**Unique →** checks that the field value is unique in the db, renders the field mandatory in the form
**Api:**
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Property Name → is the name of the field in the database
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**Custom Properties →** this configuration depends on the type of functionality adds the field; Yessee the specific documentation of the components
**Conditional:**
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Advanced Conditions [Json-logic](logic.md#Guide)
**Logic:**
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[Json-logic](logic.md#Guide)
### <font color="#FA8072">In the components the following properties are **<font color = "#ff6063">not</font>** managed:</font>

**Display:**
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Label Position
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Initial Focus
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hide Label

**Validation:**
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Validate On
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Error Label
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Custom Error Message
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Custom Validation
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;JSONLogic-Validation

**API:**
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Field Tags
**Conditional:**
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Simple

### Icons
Regarding the icons and images available in the interfaces, refer to [official AGID guide](https://italia.github.io/bootstrap-italia/docs/utilities/icone/).

[Return home](index.md)
41 changes: 41 additions & 0 deletions docs/en/components/advanced/datetime.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
### Datetime
Implement the [standard configurations](../../base.md#the-following-properties-are-managed-in-the-components).
With the datetime field you can manage fields **data** or **date and time**
In the current version the field formatFormat it is not managed in the configurator.

It is possible, by acting on the flag:**Enable Time Input** true/false, enable or disable the time in the form field. It is possible to activate the set date or today's date/time **Default Date a Today**

<font color=" #e74c3c">**Do not use the field to manage a specific year. If so, use a select resource.**</font>

![datetime](../../../img/componenti/advanced/datetime_img1.png "datetime")

#### Datetime calendar range
![datetime](../../../img/componenti/advanced/datetime_img2.png "datetime")

To manage a calendar **start date ~ end date** dynamic it is necessary to insert the two date fields, set **date** or **datetime** is:
- dateStart
- dateEnd

Then into the field **dateEnd** add the following Json logic:
```
[
{
"name": "check start",
"trigger": {
"type": "json",
"json": {
"var": "form.dateStart"
}
},
"actions": [
{
"name": "update min",
"type": "value",
"value": "min={\"var\":\"form.dateStart\"}"
}
]
}
]
```

[Return home](../../index.md)
5 changes: 5 additions & 0 deletions docs/en/components/advanced/editor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Editor
It does not require additional configurations; launches a WYSIWYG editor on the form
and save the HTML content.

[Return home](../../index.md)
4 changes: 4 additions & 0 deletions docs/en/components/advanced/email.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Email
Implement the [standard configurations](../../base.md#the-following-properties-are-managed-in-the-components).

[Return home](../../index.md)
4 changes: 4 additions & 0 deletions docs/en/components/advanced/jsoneditor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Jsoneditor
This is a textArea component with specific edit properties in json format.

[Return home](../../index.md)
5 changes: 5 additions & 0 deletions docs/en/components/advanced/model_list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Model List
List of models (forms) created in the system, useful for forms that provide activities for application administrators only.
Implement the [standard configurations](../../base.md#the-following-properties-are-managed-in-the-components).

[Return home](../../index.md)
4 changes: 4 additions & 0 deletions docs/en/components/advanced/phone_number.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Phone number
Implement thestandard configurations

[Return home](../../index.md)
4 changes: 4 additions & 0 deletions docs/en/components/advanced/print_button.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Print button
It does not require additional configurations; if necessary use the [standard configurations](../../base.md#the-following-properties-are-managed-in-the-components).

[Return home](../../index.md)
Loading

0 comments on commit 54c7e5f

Please sign in to comment.