Compare commits

...

9 Commits

13 changed files with 371 additions and 200 deletions

5
.gitignore vendored

@ -1,2 +1,7 @@
__pycache__/
ENV
# generated files
create.sql
methods.py
openapi.yaml

@ -18,7 +18,8 @@ RUN \
pip3 install uwsgi && \
pip3 install flask-cors && \
pip3 install python-jose[cryptography] && \
pip3 install loguru
pip3 install loguru && \
pip3 install Cheetah3
@ -28,13 +29,19 @@ RUN \
useradd -d ${APP_DIR} -u 1000 user
COPY *.py ${APP_DIR}/
COPY openapi.yaml ${APP_DIR}/
COPY openapi.yaml.tmpl ${APP_DIR}/
COPY methods.py.tmpl ${APP_DIR}/
COPY schema.json ${APP_DIR}/
COPY server.ini ${CONF_DIR}/
USER 1000:1000
WORKDIR ${APP_DIR}
VOLUME ${CONF_DIR}
RUN \
python3 generate.py
USER 1000:1000
EXPOSE 5000
EXPOSE 9191

@ -1,8 +0,0 @@
from db import dbGetMany, dbGetOne
def getAccounts(user, token_info):
return dbGetMany(user, token_info, {"statement": "SELECT id, description FROM account_t", "params": ()})
def getAccount(user, token_info, accountId=None):
return dbGetOne(user, token_info, {"statement": "select id, description from account_t where id = %s", "params": (accountId, )})

29
create.sql.tmpl Normal file

@ -0,0 +1,29 @@
#for $table in $tables
CREATE TABLE ${table.name}_t (
id serial not null primary key
#for $column in $table.columns
,$column.name $column.sqltype #slurp
#if (('notnull' in $column) and $column.notnull)
not null #slurp
#end if
#if (('primarykey' in $column) and $column.primarykey)
primary key #slurp
#end if
#if (('foreignkey' in $column) and $column.foreignkey)
references ${column.name}_t (id) #slurp
#end if
#if ('default' in $column)
default $column.default #slurp
#end if
#end for
#if ('tableConstraints' in $table)
#for $tableConstraint in $table.tableConstraints
,$tableConstraint
#end for
#end if
);
#end for

49
generate.py Normal file

@ -0,0 +1,49 @@
import json
from Cheetah.Template import Template
import glob
import argparse
parser = argparse.ArgumentParser(description="generate.py")
parser.add_argument('--schema', '-s',
help='Schema file. Default: schema.json in the current folder.',
required=False,
default='./schema.json')
parser.add_argument('--template', '-t',
help="""Template file, templates files must be named as the final output file
with an additional .tmpl extension. Default: all template files in the current folder.""",
required=False,
default="*.tmpl")
args = parser.parse_args()
with open(args.schema) as schemaFile:
schema = json.load(schemaFile)
for table in schema["tables"]:
for column in table["columns"]:
if column["sqltype"] == 'serial':
column["apitype"] = 'integer'
column["jstype"] = 'number'
elif column["sqltype"] == 'integer':
column["apitype"] = 'integer'
column["jstype"] = 'number'
elif column["sqltype"] == 'date':
column["apitype"] = 'string'
column["jstype"] = 'string'
elif column["sqltype"] == 'timestamp':
column["apitype"] = 'string'
column["jstype"] = 'string'
elif column["sqltype"].startswith('varchar'):
column["apitype"] = 'string'
column["jstype"] = 'string'
elif column["sqltype"].startswith('numeric'):
column["apitype"] = 'number'
column["jstype"] = 'number'
for f in glob.glob(args.template):
print(f"process {f}")
tmpl = Template(file=f, searchList=[schema])
with open(f[:-5], 'w') as outFile:
outFile.write(str(tmpl))

3
generateHelper.py Normal file

@ -0,0 +1,3 @@
def JsNameConverter(tmplName):
return ''.join([x.capitalize() for x in tmplName.split('_')])

32
methods.py.tmpl Normal file

@ -0,0 +1,32 @@
from db import dbGetMany, dbGetOne
#for $table in $tables
def get_${table.name}s(user, token_info):
return dbGetMany(user, token_info, {
"statement": """
SELECT
id
#for $column in $table.columns
,$column.name
#end for
FROM ${table.name}_t
""",
"params": ()
}
)
def get_${table.name}(user, token_info, ${table.name}Id=None):
return dbGetOne(user, token_info, {
"statement": """
SELECT
id
#for $column in $table.columns
,$column.name
#end for
FROM ${table.name}_t
WHERE id = %s
""",
"params": (${table.name}Id, )
}
)
#end for

@ -1,159 +0,0 @@
openapi: 3.0.0
info:
title: hv2-api
version: "1"
description: "REST-API for the Nober Grundbesitz GbR Hausverwaltungs-Software"
termsOfService: "https://home.hottis.de/dokuwiki/doku.php?id=hv2pub:termsofuse"
contact:
name: "Wolfgang Hottgenroth"
email: "wolfgang.hottgenroth@icloud.com"
externalDocs:
description: "Find more details here"
url: "https://home.hottis.de/dokuwiki/doku.php?id=hv2pub:externaldocs"
paths:
/v1/test:
get:
tags: [ "Test" ]
summary: Return secret string
operationId: auth.testToken
responses:
'200':
description: secret response
content:
'application/json':
schema:
$ref: '#/components/schemas/TestOutput'
security:
- jwt: ['secret']
/v1/accounts:
get:
tags: [ "Account" ]
summary: Return all normalized accounts
operationId: account.getAccounts
responses:
'200':
description: accounts response
content:
'application/json':
schema:
type: array
items:
$ref: '#/components/schemas/Account'
security:
- jwt: ['secret']
/v1/accounts/{accountId}:
get:
tags: [ "Account" ]
summary: Return the normalized account with given id
operationId: account.getAccount
parameters:
- name: accountId
in: path
required: true
schema:
type: integer
responses:
'200':
description: accounts response
content:
'application/json':
schema:
type: array
items:
$ref: '#/components/schemas/Account'
security:
- jwt: ['secret']
/v1/tenants:
get:
tags: [ "Tenant" ]
summary: Return all normalized tenants
operationId: tenant.getTenants
responses:
'200':
description: tenant response
content:
'application/json':
schema:
type: array
items:
$ref: '#/components/schemas/Tenant'
security:
- jwt: ['secret']
/v1/tenants/{tenantId}:
get:
tags: [ "Tenant" ]
summary: Return the normalized tenant with given id
operationId: tenant.getTenant
parameters:
- name: tenantId
in: path
required: true
schema:
type: integer
responses:
'200':
description: tenants response
content:
'application/json':
schema:
type: array
items:
$ref: '#/components/schemas/Tenant'
security:
- jwt: ['secret']
components:
securitySchemes:
jwt:
type: http
scheme: bearer
bearerFormat: JWT
x-bearerInfoFunc: auth.decodeToken
schemas:
TestOutput:
description: Test Output
type: object
properties:
message:
type: string
details:
type: string
Account:
description: Account
type: object
properties:
id:
type: integer
description:
type: string
Tenant:
description: Tenant
type: object
properties:
id:
type: integer
salutation:
type: string
firstname:
type: string
lastname:
type: string
address1:
type: string
address2:
type: string
address3:
type: string
zip:
type: string
city:
type: string
phone1:
type: string
phone2:
type: string
iban:
type: string
account:
type: integer

75
openapi.yaml.tmpl Normal file

@ -0,0 +1,75 @@
openapi: 3.0.0
info:
title: hv2-api
version: "1"
description: "REST-API for the Nober Grundbesitz GbR Hausverwaltungs-Software"
termsOfService: "https://home.hottis.de/dokuwiki/doku.php?id=hv2pub:termsofuse"
contact:
name: "Wolfgang Hottgenroth"
email: "wolfgang.hottgenroth@icloud.com"
externalDocs:
description: "Find more details here"
url: "https://home.hottis.de/dokuwiki/doku.php?id=hv2pub:externaldocs"
paths:
#for $table in $tables
/v1/${table.name}s:
get:
tags: [ "$table.name" ]
summary: Return all normalized ${table.name}s
operationId: methods.get_${table.name}s
responses:
'200':
description: ${table.name}s response
content:
'application/json':
schema:
type: array
items:
\$ref: '#/components/schemas/$table.name'
security:
- jwt: ['secret']
/v1/${table.name}s/{${table.name}Id}:
get:
tags: [ "$table.name" ]
summary: Return the normalized $table.name with given id
operationId: methods.get_$table.name
parameters:
- name: ${table.name}Id
in: path
required: true
schema:
type: integer
responses:
'200':
description: $table.name response
content:
'application/json':
schema:
type: array
items:
\$ref: '#/components/schemas/$table.name'
security:
- jwt: ['secret']
#end for
components:
securitySchemes:
jwt:
type: http
scheme: bearer
bearerFormat: JWT
x-bearerInfoFunc: auth.decodeToken
schemas:
#for $table in $tables
$table.name:
description: $table.name
type: object
properties:
id:
type: integer
#for $column in $table.columns
$column.name:
type: $column.apitype
#end for
#end for

119
schema.json Normal file

@ -0,0 +1,119 @@
{
"tables": [
{
"name": "account",
"columns": [
{ "name": "description", "sqltype": "varchar(128)", "notnull": true }
]
},
{
"name": "tenant",
"columns": [
{ "name": "salutation", "sqltype": "varchar(128)" },
{ "name": "firstname", "sqltype": "varchar(128)" },
{ "name": "lastname", "sqltype": "varchar(128)" },
{ "name": "address1", "sqltype": "varchar(128)" },
{ "name": "address2", "sqltype": "varchar(128)" },
{ "name": "address3", "sqltype": "varchar(128)" },
{ "name": "zip", "sqltype": "varchar(10)" },
{ "name": "city", "sqltype": "varchar(128)" },
{ "name": "phone1", "sqltype": "varchar(64)" },
{ "name": "phone2", "sqltype": "varchar(64)" },
{ "name": "iban", "sqltype": "varchar(64)" },
{ "name": "account", "sqltype": "integer", "notnull": true, "foreignkey": true }
]
},
{
"name": "premise",
"columns": [
{ "name": "description", "sqltype": "varchar(128)" },
{ "name": "street", "sqltype": "varchar(128)", "notnull": true },
{ "name": "zip", "sqltype": "varchar(10)", "notnull": true },
{ "name": "city", "sqltype": "varchar(128)", "notnull": true }
]
},
{
"name": "flat",
"columns": [
{ "name": "description", "sqltype": "varchar(128)" },
{ "name": "premise", "sqltype": "integer", "foreignkey": true },
{ "name": "area", "sqltype": "numeric(10,2)", "notnull": true },
{ "name": "flat_no", "sqltype": "integer" }
]
},
{
"name": "overhead_advance",
"columns": [
{ "name": "description", "sqltype": "varchar(128)" },
{ "name": "amount", "sqltype": "numeric(10,4)", "notnull": true },
{ "name": "startdate", "sqltype": "date" },
{ "name": "enddate", "sqltype": "date" }
]
},
{
"name": "overhead_advance_flat_mapping",
"columns": [
{ "name": "overhead_advance", "sqltype": "integer", "notnull": true, "foreignkey": true },
{ "name": "flat", "sqltype": "integer", "notnull": true, "foreignkey": true }
]
},
{
"name": "parking",
"columns": [
{ "name": "description", "sqltype": "varchar(128)" },
{ "name": "premise", "sqltype": "integer", "foreignkey": true }
]
},
{
"name": "commercial_premise",
"columns": [
{ "name": "description", "sqltype": "varchar(128)" },
{ "name": "premise", "sqltype": "integer", "foreignkey": true }
]
},
{
"name": "tenancy",
"columns": [
{ "name": "description", "sqltype": "varchar(128)" },
{ "name": "tenant", "sqltype": "integer", "notnull": true, "foreignkey": true },
{ "name": "flat", "sqltype": "integer", "notnull": false, "foreignkey": true },
{ "name": "parking", "sqltype": "integer", "notnull": false, "foreignkey": true },
{ "name": "commercial_premise", "sqltype": "integer", "notnull": false, "foreignkey": true },
{ "name": "startdate", "sqltype": "date", "notnull": true },
{ "name": "enddate", "sqltype": "date", "notnull": false }
],
"tableConstraints": [
"constraint tenancy_only_one_object check ((flat is not null and parking is null and commercial_premise is null) or (flat is null and parking is not null and commercial_premise is null) or (flat is null and parking is null and commercial_premise is not null))"
]
},
{
"name": "fee",
"columns": [
{ "name": "description", "sqltype": "varchar(128)" },
{ "name": "amount", "sqltype": "numeric(10,2)", "notnull": true },
{ "name": "fee_type", "sqltype": "varchar(10)", "notnull": true },
{ "name": "startdate", "sqltype": "date" },
{ "name": "enddate", "sqltype": "date" }
],
"tableConstraints": [
"constraint fee_fee_type check (fee_type = 'per_area' or fee_type = 'total')"
]
},
{
"name": "tenancy_fee_mapping",
"columns": [
{ "name": "tenancy", "sqltype": "integer", "notnull": true, "foreignkey": true },
{ "name": "fee", "sqltype": "integer", "notnull": true, "foreignkey": true }
]
},
{
"name": "account_entry",
"columns": [
{ "name": "description", "sqltype": "varchar(128)", "notnull": true },
{ "name": "account", "sqltype": "integer", "notnull": true, "foreignkey": true },
{ "name": "created_at", "sqltype": "timestamp", "notnull": true, "default": "now()" },
{ "name": "amount", "sqltype": "numeric(10,2)", "notnull": true }
]
}
]
}

@ -1,29 +0,0 @@
from db import dbGetMany, dbGetOne
def getTenants(user, token_info):
return dbGetMany(user, token_info,
{
"statement": """
SELECT id, salutation, firstname, lastname,
address1, address2, address3, zip, city,
phone1, phone2, iban, account
FROM tenant_t
""",
"params": ()
}
)
def getTenant(user, token_info, tenantId=None):
return dbGetOne(user, token_info,
{
"statement": """
SELECT id, salutation, firstname, lastname,
address1, address2, address3, zip, city,
phone1, phone2, iban, account
FROM tenant_t
WHERE id = %s
""",
"params": (tenantId, )
}
)

48
testdata/testdata.sql vendored Normal file

@ -0,0 +1,48 @@
insert into account_t (description) values ('account testtenant1');
insert into tenant_t (lastname, account) values (
'testtenant1',
(select id from account_t where description = 'account testtenant1')
);
insert into premise_t (street, zip, city) values ('Hemsingskotten 38', '45259', 'Essen');
insert into parking_t (description, premise) values ('Garage 1', (select id from premise_t where street = 'Hemsingskotten 38'));
insert into flat_t (description, premise, area, flat_no) values('EG links', (select id from premise_t where street = 'Hemsingskotten 38'), 59.0, 1);
insert into fee_t (description, amount, fee_type, startdate) values ('Altenwohnung Hemsingskotten', 5.23, 'per_area', '2021-01-01');
insert into fee_t (description, amount, fee_type, startdate) values ('Garage intern', 30.0, 'total', '2021-01-01');
insert into tenancy_t (tenant, flat, description, startdate) values (
(select id from tenant_t where lastname = 'testtenant1'),
(select id from flat_t where flat_no = 1),
'flat testtenant1',
'2021-06-01'
);
insert into tenancy_t (tenant, parking, description, startdate) values (
(select id from tenant_t where lastname = 'testtenant1'),
(select id from parking_t where description = 'Garage 1'),
'parking testtenant1',
'2021-06-01'
);
insert into overhead_advance_t (description, amount, startdate) values ('BKV Altenwohnung Hemsingskotten', 0.34, '2021-01-01');
insert into overhead_advance_flat_mapping_t (overhead_advance, flat) values (
(select id from overhead_advance_t where description = 'BKV Altenwohnung Hemsingskotten'),
(select id from flat_t where flat_no = 1)
);
insert into tenancy_fee_mapping_t (tenancy, fee) values (
(select id from tenancy_t where description = 'flat testtenant1'),
(select id from fee_t where description = 'Altenwohnung Hemsingskotten')
);
insert into tenancy_fee_mapping_t (tenancy, fee) values (
(select id from tenancy_t where description = 'parking testtenant1'),
(select id from fee_t where description = 'Garage intern')
);