82 Commits
0.0.3 ... 0.1.4

Author SHA1 Message Date
9a1e3231d6 remove broken sorting code 2022-04-01 15:42:37 +02:00
0075416fc3 forgotten change 2022-04-01 15:26:32 +02:00
47e96c10b1 forgotten config fix 2022-04-01 15:08:32 +02:00
3e32613a78 better handling of presets 2022-04-01 15:05:06 +02:00
74d0a6084b sorting not yet working 2022-04-01 14:25:58 +02:00
ac1636c162 sorting 2022-04-01 13:59:31 +02:00
d0771be1d1 Abrechnungsskript 2022-04-01 12:04:33 +02:00
452b4f69bd output dir 2022-04-01 10:59:52 +02:00
4553272c42 format of output 2022-03-31 22:30:09 +02:00
0d4e33505e account statement stuff 2022-03-31 21:40:49 +02:00
2be6a6e140 some forgotten details 2022-03-31 16:19:36 +02:00
4391cc1d8b account entry reference stuff 2022-03-31 16:07:00 +02:00
b346cc07d0 merged 2022-03-31 15:31:53 +02:00
169795c16e account entry reference stuff 2022-03-31 15:30:22 +02:00
25f6de1c11 Kontoauszug 2022-02-13 12:30:10 +01:00
1c6fe0dd16 account statement view 2022-02-11 20:33:25 +01:00
2a0bda012b year is number 2022-02-05 18:05:50 +01:00
5ca2f16757 Merge branch 'master' of ssh://repo.hottis.de:2922/hv2/hv2-all-in-one 2022-02-05 17:56:49 +01:00
292886f834 fiscalyear is number 2022-02-05 17:56:29 +01:00
3debcf6c2d fix formcontrol handling 2022-01-31 17:24:56 +01:00
af7b388118 fix 2022-01-29 19:37:09 +01:00
b561ec8a48 small fix 2022-01-29 19:18:50 +01:00
9cb599e2a6 ready so far 2022-01-29 18:35:58 +01:00
d7c713404d overview tmpl 2022-01-29 15:43:50 +01:00
7d8755aab9 overview calculated 2022-01-29 14:40:14 +01:00
f2f2100b8c tenant letter nearly done 2022-01-29 13:42:58 +01:00
b3a49b0fb6 minus_area in premise, calculation of areas and factors 2022-01-24 18:06:10 +01:00
e1ebfe254a consider year in creating fee and overhead requests 2022-01-24 16:36:28 +01:00
b748ba7a77 fiscal year 2022-01-24 16:11:02 +01:00
ab365c65a1 add fiscal_year, drop due_to 2022-01-21 20:46:28 +01:00
0e4fd12238 commercial unit area and overhead stuff 2022-01-06 23:16:34 +01:00
cb632e9e8e due at fix 2 2022-01-06 21:52:17 +01:00
2fc7922707 due_at fix 2022-01-06 21:06:16 +01:00
422a8d37ab get flat tenants 2021-12-19 14:44:27 +01:00
006b488c63 start overhead accounts 2021-12-19 14:17:44 +01:00
1d36d99462 option to select config file 2021-12-19 12:51:35 +01:00
05fb3c1677 disable description at payment entry form 2021-12-12 14:07:25 +01:00
cbc96036d9 adjusted gitignore file 2021-11-09 10:39:37 +01:00
44202ef9ed Merge branch 'overhead_account' of ssh://repo.hottis.de:2922/hv2/hv2-all-in-one into overhead_account 2021-11-09 10:22:12 +01:00
34f8e8ecd4 note on betriebskosten at ledger page 2021-11-09 10:21:47 +01:00
6f3248f03c more fix premise account stuff 2021-11-09 10:14:16 +01:00
3c97fb3582 fix premise account stuff 2021-11-09 10:02:53 +01:00
3ad019b374 schema changes 2021-11-08 21:05:24 +01:00
28e505f570 overhead account stuff 2021-11-08 21:04:21 +01:00
ba63874a18 change order 2021-11-02 13:11:02 +01:00
0e1e03f1a9 error dialog introduced 2021-11-02 13:06:34 +01:00
272500df8c one-way-binding in account entry form works now 2021-11-02 12:36:35 +01:00
0ab106d021 switch to one-way-binding in form 2021-11-01 21:17:20 +01:00
125af5a206 viewchild, das hat es noch nicht gebracht 2021-11-01 09:40:19 +01:00
419997cea5 not yet working correctly 2021-10-31 23:06:02 +01:00
797151d547 more ledger stuff 2021-10-31 22:27:00 +01:00
2b883aee02 ledger 2021-10-31 21:47:53 +01:00
8c4dbe7d71 add ledger, Buchfuehrung 2021-10-31 16:06:18 +01:00
d297eb60b3 option to disable colors in output 2021-09-15 17:36:57 +02:00
5744e84842 Merge branch 'master' of https://home.hottis.de/gitlab/hv2/hv2-all-in-one 2021-09-15 17:32:16 +02:00
b8083ec41e outer join for tenant-saldo-query 2021-09-15 17:31:55 +02:00
f559aba317 default today to monthly payment 2021-09-14 22:36:25 +02:00
97dfcbe2fb optimize tenant with saldo query, fix 2021-09-14 14:31:42 +02:00
76255efbe9 optimize tenant with saldo query 2021-09-14 14:14:56 +02:00
797cbb4b65 monthly payment 2021-09-14 13:38:27 +02:00
4a54190b00 fix 2021-09-14 10:34:33 +02:00
3977685915 consistency check 2021-09-14 10:33:08 +02:00
66283bb533 fix 2021-09-13 19:28:18 +02:00
966ad7aee8 begin cli work 2021-09-13 19:27:32 +02:00
2ec6311ca9 home component 2021-09-13 17:11:17 +02:00
db089a9f2a Mietzahlung eintragen 2021-09-13 16:47:56 +02:00
a8296ee210 logout out automatically when session expires 2021-09-12 13:26:08 +02:00
e3236b671d fix menu 2021-09-12 10:35:11 +02:00
457ba1bee5 disable messages when not logged in 2021-09-11 23:58:25 +02:00
22db10a31e disable menu when not logged in 2021-09-11 23:54:18 +02:00
4f88ac5d0e disable menu when not logged in 2021-09-11 23:50:59 +02:00
3ae92c020c disable menu when not logged in 2021-09-11 23:34:29 +02:00
d098317331 disable ui 2021-09-11 19:19:16 +02:00
641565d8ff config 2021-09-11 19:02:00 +02:00
25d016c154 cors 2021-09-11 18:50:54 +02:00
39703dca22 cors 2021-09-11 18:44:43 +02:00
c06184d1b1 fix in ci 2021-09-11 18:13:02 +02:00
1450c8fdd7 fix in ci 2021-09-11 18:12:09 +02:00
72a3241286 fix in ci 2021-09-11 18:09:10 +02:00
d2cf532a0e fix in ci 2021-09-11 17:52:38 +02:00
dbb9686312 changes in ci 2021-09-11 17:46:29 +02:00
05823a1829 nullable api params and tenancy mapping 2021-09-11 17:07:39 +02:00
76 changed files with 2550 additions and 348 deletions

10
.gitignore vendored
View File

@ -2,4 +2,12 @@ __pycache__/
ENV
api/config/dbconfig.ini
api/config/authservice.pub
cli/config/dbconfig.ini
cli/output/
*~
.*~
.vscode/
cli/*.tex
cli/*.log
cli/*.pdf
cli/*.aux

View File

@ -2,6 +2,7 @@ stages:
- check
- build
- dockerize
- deploy
check:
@ -55,6 +56,7 @@ build-ui:
- cd ui/hv2-ui
- if [ "$CI_COMMIT_TAG" != "" ]; then
sed -i -e 's/GITTAGVERSION/'"$CI_COMMIT_TAG"':'"$CI_COMMIT_SHORT_SHA"'/' ./src/app/navigation/navigation.component.html;
sed -i -e 's,http://localhost:8080,https://api.hv.nober.de,' ./src/app/config.ts;
fi
- npm install
- ./node_modules/.bin/ng build --prod
@ -80,4 +82,40 @@ dockerize-ui:
docker push $IMAGE_NAME:${CI_COMMIT_TAG};
fi
.deploy:
image: registry.hottis.de/dockerized/docker-bash:latest
stage: deploy
tags:
- hottis
- linux
- docker
only:
- tags
variables:
GIT_STRATEGY: none
script:
- docker stop $CONTAINER_NAME || echo "container not running, never mind"
- docker rm $CONTAINER_NAME || echo "container not existing, never mind"
- docker run -d --network docker-server
--ip $CONTAINER_IP
$VOLUMEOPT
--name $CONTAINER_NAME
--restart always
$IMAGE_NAME:$CI_COMMIT_TAG
deploy-api:
extends:
- .deploy
variables:
IMAGE_NAME: ${CI_REGISTRY}/${CI_PROJECT_PATH}/api
CONTAINER_NAME: hv2-api
CONTAINER_IP: 172.16.10.38
VOLUMEOPT: -v hv2-api-conf:/opt/app/config
deploy-ui:
extends:
- .deploy
variables:
IMAGE_NAME: ${CI_REGISTRY}/${CI_PROJECT_PATH}/ui
CONTAINER_NAME: hv2-ui
CONTAINER_IP: 172.16.10.39

View File

@ -0,0 +1,30 @@
# -------------------------------------------------------------------
# ATTENTION: This file will not be parsed by Cheetah
# Use plain openapi/yaml syntax, no Cheetah
# escaping
# -------------------------------------------------------------------
tenant_with_saldo:
description: tenant with saldo
type: object
properties:
id:
type: integer
salutation:
type: string
nullable: true
firstname:
type: string
nullable: true
lastname:
type: string
nullable: true
address1:
type: string
nullable: true
saldo:
type: number
nullable: true

View File

@ -72,4 +72,59 @@
type: number
security:
- jwt: ['secret']
/v1/tenants/saldo:
get:
tags: [ "tenant", "account" ]
summary: Return tenant with saldo of the account
operationId: additional_methods.get_tenant_with_saldo
responses:
'200':
description: get_tenant_with_saldo
content:
'application/json':
schema:
type: array
items:
$ref: '#/components/schemas/tenant_with_saldo'
security:
- jwt: ['secret']
/v1/accounts/bydescription/{description}:
get:
tags: [ "account" ]
summary: Return the normalized account with given description
operationId: additional_methods.get_account_by_description
parameters:
- name: description
in: path
required: true
schema:
type: string
responses:
'200':
description: account response
content:
'application/json':
schema:
type: array
items:
$ref: '#/components/schemas/account'
security:
- jwt: ['secret']
/v1/uniquenumber:
get:
tags: [ "uniquenumber" ]
summary: Returns a unique number
operationId: additional_methods.get_unique_number
responses:
'200':
description: get_unique_number
content:
'application/json':
schema:
type: object
properties:
number:
type: number
security:
- jwt: ['secret']

View File

@ -31,4 +31,33 @@ def get_account_saldo(user, token_info, accountId=None):
"statement": "SELECT sum(amount) as saldo FROM account_entry_t WHERE account=%s",
"params": (accountId, )
}
)
)
def get_tenant_with_saldo(user, token_info):
return dbGetMany(user, token_info, {
"statement": """
SELECT t.id, t.firstname, t.lastname, t.address1, sum(a.amount) AS saldo
FROM tenant_t t LEFT OUTER JOIN account_entry_t a ON a.account = t.account
GROUP BY t.id, t.firstname, t.lastname, t.address1
""",
"params": ()
}
)
def get_account_by_description(user, token_info, description=None):
return dbGetOne(user, token_info, {
"statement": """
SELECT a.id ,a.description
FROM account_t a
WHERE a.description = %s""",
"params": (description, )
}
)
def get_unique_number(user, token_info):
return dbGetOne(user, token_info, {
"statement": """
SELECT nextval('unique_number_s') AS "number"
""",
"params": ()
})

View File

@ -269,6 +269,9 @@ SELECT
,account
FROM tenant_t
WHERE account = %s
ORDER BY
lastname
,firstname
""",
"params": (accountId, )
}
@ -283,6 +286,8 @@ SELECT
,street
,zip
,city
,minus_area
,account
FROM premise_t
ORDER BY
description
@ -298,6 +303,8 @@ def insert_premise(user, token_info, **args):
v_street = body["street"]
v_zip = body["zip"]
v_city = body["city"]
v_minus_area = body["minus_area"]
v_account = body["account"]
return dbInsert(user, token_info, {
"statement": """
INSERT INTO premise_t
@ -306,11 +313,15 @@ INSERT INTO premise_t
,street
,zip
,city
,minus_area
,account
) VALUES (
%s
,%s
,%s
,%s
,%s
,%s
)
RETURNING *
""",
@ -319,6 +330,8 @@ INSERT INTO premise_t
,v_street
,v_zip
,v_city
,v_minus_area
,v_account
]
})
except KeyError as e:
@ -335,6 +348,8 @@ SELECT
,street
,zip
,city
,minus_area
,account
FROM premise_t
WHERE id = %s
""",
@ -349,6 +364,7 @@ def update_premise(user, token_info, premiseId=None, **args):
v_street = body["street"]
v_zip = body["zip"]
v_city = body["city"]
v_minus_area = body["minus_area"]
return dbUpdate(user, token_info, {
"statement": """
UPDATE premise_t
@ -357,6 +373,7 @@ UPDATE premise_t
,street = %s
,zip = %s
,city = %s
,minus_area = %s
WHERE id = %s
RETURNING *
""",
@ -365,6 +382,7 @@ UPDATE premise_t
v_street,
v_zip,
v_city,
v_minus_area,
premiseId
]
})
@ -373,6 +391,26 @@ UPDATE premise_t
raise werkzeug.exceptions.UnprocessableEntity("parameter missing: {}".format(e))
def get_premise_by_account(user, token_info, accountId=None):
return dbGetMany(user, token_info, {
"statement": """
SELECT
id
,description
,street
,zip
,city
,minus_area
,account
FROM premise_t
WHERE account = %s
ORDER BY
description
""",
"params": (accountId, )
}
)
def get_flats(user, token_info):
return dbGetMany(user, token_info, {
"statement": """
@ -484,6 +522,9 @@ SELECT
,flat_no
FROM flat_t
WHERE premise = %s
ORDER BY
premise
,description
""",
"params": (premiseId, )
}
@ -651,6 +692,9 @@ SELECT
,flat
FROM overhead_advance_flat_mapping_t
WHERE overhead_advance = %s
ORDER BY
overhead_advance
,flat
""",
"params": (overhead_advanceId, )
}
@ -665,6 +709,9 @@ SELECT
,flat
FROM overhead_advance_flat_mapping_t
WHERE flat = %s
ORDER BY
overhead_advance
,flat
""",
"params": (flatId, )
}
@ -761,6 +808,9 @@ SELECT
,premise
FROM parking_t
WHERE premise = %s
ORDER BY
premise
,description
""",
"params": (premiseId, )
}
@ -773,6 +823,7 @@ SELECT
id
,description
,premise
,area
FROM commercial_premise_t
ORDER BY
premise
@ -787,21 +838,25 @@ def insert_commercial_premise(user, token_info, **args):
body = args["body"]
v_description = body["description"]
v_premise = body["premise"]
v_area = body["area"]
return dbInsert(user, token_info, {
"statement": """
INSERT INTO commercial_premise_t
(
description
,premise
,area
) VALUES (
%s
,%s
,%s
)
RETURNING *
""",
"params": [
v_description
,v_premise
,v_area
]
})
except KeyError as e:
@ -816,6 +871,7 @@ SELECT
id
,description
,premise
,area
FROM commercial_premise_t
WHERE id = %s
""",
@ -828,18 +884,21 @@ def update_commercial_premise(user, token_info, commercial_premiseId=None, **arg
body = args["body"]
v_description = body["description"]
v_premise = body["premise"]
v_area = body["area"]
return dbUpdate(user, token_info, {
"statement": """
UPDATE commercial_premise_t
SET
description = %s
,premise = %s
,area = %s
WHERE id = %s
RETURNING *
""",
"params": [
v_description,
v_premise,
v_area,
commercial_premiseId
]
})
@ -855,8 +914,12 @@ SELECT
id
,description
,premise
,area
FROM commercial_premise_t
WHERE premise = %s
ORDER BY
premise
,description
""",
"params": (premiseId, )
}
@ -988,6 +1051,9 @@ SELECT
,enddate
FROM tenancy_t
WHERE tenant = %s
ORDER BY
description
,startdate
""",
"params": (tenantId, )
}
@ -1007,6 +1073,9 @@ SELECT
,enddate
FROM tenancy_t
WHERE flat = %s
ORDER BY
description
,startdate
""",
"params": (flatId, )
}
@ -1026,6 +1095,9 @@ SELECT
,enddate
FROM tenancy_t
WHERE parking = %s
ORDER BY
description
,startdate
""",
"params": (parkingId, )
}
@ -1045,6 +1117,9 @@ SELECT
,enddate
FROM tenancy_t
WHERE commercial_premise = %s
ORDER BY
description
,startdate
""",
"params": (commercial_premiseId, )
}
@ -1240,6 +1315,7 @@ def get_account_entry_categorys(user, token_info):
SELECT
id
,description
,considerMinusArea
,overhead_relevant
FROM account_entry_category_t
ORDER BY
@ -1253,21 +1329,25 @@ def insert_account_entry_category(user, token_info, **args):
try:
body = args["body"]
v_description = body["description"]
v_considerMinusArea = body["considerMinusArea"]
v_overhead_relevant = body["overhead_relevant"]
return dbInsert(user, token_info, {
"statement": """
INSERT INTO account_entry_category_t
(
description
,considerMinusArea
,overhead_relevant
) VALUES (
%s
,%s
,%s
)
RETURNING *
""",
"params": [
v_description
,v_considerMinusArea
,v_overhead_relevant
]
})
@ -1282,6 +1362,7 @@ def get_account_entry_category(user, token_info, account_entry_categoryId=None):
SELECT
id
,description
,considerMinusArea
,overhead_relevant
FROM account_entry_category_t
WHERE id = %s
@ -1300,11 +1381,13 @@ SELECT
,description
,account
,created_at
,fiscal_year
,amount
,document_no
,account_entry_category
FROM account_entry_t
ORDER BY
amount
created_at
""",
"params": ()
}
@ -1316,7 +1399,9 @@ def insert_account_entry(user, token_info, **args):
v_description = body["description"]
v_account = body["account"]
v_created_at = body["created_at"]
v_fiscal_year = body["fiscal_year"]
v_amount = body["amount"]
v_document_no = body["document_no"]
v_account_entry_category = body["account_entry_category"]
return dbInsert(user, token_info, {
"statement": """
@ -1325,7 +1410,9 @@ INSERT INTO account_entry_t
description
,account
,created_at
,fiscal_year
,amount
,document_no
,account_entry_category
) VALUES (
%s
@ -1333,6 +1420,8 @@ INSERT INTO account_entry_t
,%s
,%s
,%s
,%s
,%s
)
RETURNING *
""",
@ -1340,7 +1429,9 @@ INSERT INTO account_entry_t
v_description
,v_account
,v_created_at
,v_fiscal_year
,v_amount
,v_document_no
,v_account_entry_category
]
})
@ -1357,7 +1448,9 @@ SELECT
,description
,account
,created_at
,fiscal_year
,amount
,document_no
,account_entry_category
FROM account_entry_t
WHERE id = %s
@ -1376,10 +1469,14 @@ SELECT
,description
,account
,created_at
,fiscal_year
,amount
,document_no
,account_entry_category
FROM account_entry_t
WHERE account = %s
ORDER BY
created_at
""",
"params": (accountId, )
}
@ -1393,10 +1490,14 @@ SELECT
,description
,account
,created_at
,fiscal_year
,amount
,document_no
,account_entry_category
FROM account_entry_t
WHERE account_entry_category = %s
ORDER BY
created_at
""",
"params": (account_entry_categoryId, )
}
@ -1411,6 +1512,8 @@ SELECT
,tenant
,note
FROM note_t
ORDER BY
created_at
""",
"params": ()
}
@ -1474,6 +1577,8 @@ SELECT
,note
FROM note_t
WHERE tenant = %s
ORDER BY
created_at
""",
"params": (tenantId, )
}

View File

@ -129,6 +129,14 @@ SELECT
#end for
FROM ${table.name}_t
WHERE ${column.name} = %s
#if $table.selectors
ORDER BY
#set $sep = ""
#for $selector in $table.selectors
$sep$selector
#set $sep = ","
#end for
#end if
""",
"params": (${column.name}Id, )
}

View File

@ -299,6 +299,28 @@ paths:
$ref: '#/components/schemas/premise'
security:
- jwt: ['secret']
/v1/premises/account/{accountId}:
get:
tags: [ "premise", "account" ]
summary: Return premise by $account
operationId: methods.get_premise_by_account
parameters:
- name: accountId
in: path
required: true
schema:
type: integer
responses:
'200':
description: premise response
content:
'application/json':
schema:
type: array
items:
$ref: '#/components/schemas/premise'
security:
- jwt: ['secret']
/v1/flats:
get:
tags: [ "flat" ]
@ -1493,6 +1515,61 @@ paths:
type: number
security:
- jwt: ['secret']
/v1/tenants/saldo:
get:
tags: [ "tenant", "account" ]
summary: Return tenant with saldo of the account
operationId: additional_methods.get_tenant_with_saldo
responses:
'200':
description: get_tenant_with_saldo
content:
'application/json':
schema:
type: array
items:
$ref: '#/components/schemas/tenant_with_saldo'
security:
- jwt: ['secret']
/v1/accounts/bydescription/{description}:
get:
tags: [ "account" ]
summary: Return the normalized account with given description
operationId: additional_methods.get_account_by_description
parameters:
- name: description
in: path
required: true
schema:
type: string
responses:
'200':
description: account response
content:
'application/json':
schema:
type: array
items:
$ref: '#/components/schemas/account'
security:
- jwt: ['secret']
/v1/uniquenumber:
get:
tags: [ "uniquenumber" ]
summary: Returns a unique number
operationId: additional_methods.get_unique_number
responses:
'200':
description: get_unique_number
content:
'application/json':
schema:
type: object
properties:
number:
type: number
security:
- jwt: ['secret']
components:
@ -1519,26 +1596,37 @@ components:
type: integer
salutation:
type: string
nullable: true
firstname:
type: string
nullable: true
lastname:
type: string
nullable: true
address1:
type: string
nullable: true
address2:
type: string
nullable: true
address3:
type: string
nullable: true
zip:
type: string
nullable: true
city:
type: string
nullable: true
phone1:
type: string
nullable: true
phone2:
type: string
nullable: true
iban:
type: string
nullable: true
account:
type: integer
premise:
@ -1549,12 +1637,17 @@ components:
type: integer
description:
type: string
nullable: true
street:
type: string
zip:
type: string
city:
type: string
minus_area:
type: number
account:
type: integer
flat:
description: flat
type: object
@ -1563,12 +1656,15 @@ components:
type: integer
description:
type: string
nullable: true
premise:
type: integer
nullable: true
area:
type: number
flat_no:
type: integer
nullable: true
overhead_advance:
description: overhead_advance
type: object
@ -1577,12 +1673,15 @@ components:
type: integer
description:
type: string
nullable: true
amount:
type: number
startdate:
type: string
nullable: true
enddate:
type: string
nullable: true
overhead_advance_flat_mapping:
description: overhead_advance_flat_mapping
type: object
@ -1601,8 +1700,10 @@ components:
type: integer
description:
type: string
nullable: true
premise:
type: integer
nullable: true
commercial_premise:
description: commercial_premise
type: object
@ -1611,8 +1712,13 @@ components:
type: integer
description:
type: string
nullable: true
premise:
type: integer
nullable: true
area:
type: number
nullable: true
tenancy:
description: tenancy
type: object
@ -1621,18 +1727,23 @@ components:
type: integer
description:
type: string
nullable: true
tenant:
type: integer
flat:
type: integer
nullable: true
parking:
type: integer
nullable: true
commercial_premise:
type: integer
nullable: true
startdate:
type: string
enddate:
type: string
nullable: true
fee:
description: fee
type: object
@ -1641,14 +1752,17 @@ components:
type: integer
description:
type: string
nullable: true
amount:
type: number
fee_type:
type: string
startdate:
type: string
nullable: true
enddate:
type: string
nullable: true
tenancy_fee_mapping:
description: tenancy_fee_mapping
type: object
@ -1667,6 +1781,8 @@ components:
type: integer
description:
type: string
considerMinusArea:
type: boolean
overhead_relevant:
type: boolean
account_entry:
@ -1681,8 +1797,13 @@ components:
type: integer
created_at:
type: string
fiscal_year:
type: integer
amount:
type: number
document_no:
type: integer
nullable: true
account_entry_category:
type: integer
note:
@ -1697,3 +1818,34 @@ components:
type: integer
note:
type: string
# -------------------------------------------------------------------
# ATTENTION: This file will not be parsed by Cheetah
# Use plain openapi/yaml syntax, no Cheetah
# escaping
# -------------------------------------------------------------------
tenant_with_saldo:
description: tenant with saldo
type: object
properties:
id:
type: integer
salutation:
type: string
nullable: true
firstname:
type: string
nullable: true
lastname:
type: string
nullable: true
address1:
type: string
nullable: true
saldo:
type: number
nullable: true

View File

@ -151,5 +151,10 @@ components:
#for $column in $table.columns
$column.name:
type: $column.apitype
#if (('notnull' not in $column) or (not $column.notnull))
nullable: true
#end if
#end for
#end for
#include raw "./api/additional_components.yaml"

View File

@ -3,10 +3,16 @@ from flask_cors import CORS
# instantiate the webservice
app = connexion.App(__name__)
app.add_api('openapi.yaml')
app.add_api('openapi.yaml', options = {"swagger_ui": False})
# CORSify it - otherwise Angular won't accept it
CORS(app.app)
CORS(app.app,
origins=[
"http://localhost:4200",
"https://base.hv.nober.de"
],
supports_credentials=True
)
# provide the webservice application to uwsgi
application = app.app

View File

@ -5,6 +5,6 @@ from flask_cors import CORS
logging.basicConfig(level=logging.DEBUG)
app = connexion.App('hv2-api')
app.add_api('./openapi.yaml')
app.add_api('./openapi.yaml', options = {"swagger_ui": True})
CORS(app.app)
app.run(port=8080)

View File

@ -1,61 +0,0 @@
stages:
- check
- build
- deploy
variables:
IMAGE_NAME: $CI_REGISTRY/$CI_PROJECT_PATH
check:
image: registry.hottis.de/dockerized/base-build-env:latest
stage: check
tags:
- hottis
- linux
- docker
rules:
- if: $CI_COMMIT_TAG
script:
- checksemver.py -v
--versionToValidate "${CI_COMMIT_TAG}"
--validateMessage
--messageToValidate "${CI_COMMIT_MESSAGE}"
build:
image: registry.hottis.de/dockerized/docker-bash:latest
stage: build
tags:
- hottis
- linux
- docker
script:
- docker build --tag $IMAGE_NAME:latest .
- if [ "$CI_COMMIT_TAG" != "" ]; then
docker tag $IMAGE_NAME:latest $IMAGE_NAME:${CI_COMMIT_TAG};
docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY;
docker push $IMAGE_NAME:latest;
docker push $IMAGE_NAME:${CI_COMMIT_TAG};
fi
deploy:
stage: deploy
image: registry.hottis.de/dockerized/docker-bash:latest
only:
- tags
tags:
- hottis
- linux
- docker
variables:
GIT_STRATEGY: none
script:
- CONTAINER_NAME=$CI_PROJECT_NAME
- SERVICE_VOLUME=$CI_PROJECT_NAME"-conf"
- SERVICE_PORT=5000
- docker volume inspect $SERVICE_VOLUME || docker volume create $SERVICE_VOLUME
- docker stop $CONTAINER_NAME || echo "$CONTAINER_NAME not running, anyway okay"
- docker rm $CONTAINER_NAME || echo "$CONTAINER_NAME not exsting, anyway okay"
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY;
- docker pull $IMAGE_NAME:${CI_COMMIT_TAG}
- docker run -d --restart always --name $CONTAINER_NAME --network docker-server --ip 172.16.10.38 -v $SERVICE_VOLUME:/opt/app/config $IMAGE_NAME:${CI_COMMIT_TAG}

View File

@ -1,88 +0,0 @@
stages:
- check
- build
- dockerize
- deploy
variables:
IMAGE_NAME: $CI_REGISTRY/$CI_PROJECT_PATH
check:
image: registry.hottis.de/dockerized/base-build-env:latest
stage: check
tags:
- hottis
- linux
- docker
rules:
- if: $CI_COMMIT_TAG
script:
- checksemver.py -v
--versionToValidate "$CI_COMMIT_TAG"
--validateMessage
--messageToValidate "$CI_COMMIT_MESSAGE"
build:
image: registry.hottis.de/hv2/hv2-node-build-env:1.0.0
stage: build
variables:
GIT_SUBMODULE_STRATEGY: recursive
tags:
- hottis
- linux
- docker
artifacts:
paths:
- dist.tgz
expire_in: 1 day
script:
- cd hv2-ui
- if [ "$CI_COMMIT_TAG" != "" ]; then
sed -i -e 's/GITTAGVERSION/'"$CI_COMMIT_TAG"':'"$CI_COMMIT_SHORT_SHA"'/' ./src/app/navigation/navigation.component.html;
fi
- npm install
- for F in ./src/app/*.tmpl; do
python ../helpers/hv2-api/generate.py -s ../helpers/hv2-api/schema.json -t $F;
done
- ./node_modules/.bin/ng build --prod
- tar -czf ../dist.tgz dist
dockerize:
image: registry.hottis.de/dockerized/docker-bash:latest
stage: dockerize
tags:
- hottis
- linux
- docker
rules:
- if: $CI_COMMIT_TAG
script:
- tar -xzf dist.tgz
- docker build --tag $IMAGE_NAME:latest --tag $IMAGE_NAME:$CI_COMMIT_TAG .
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
- docker push $IMAGE_NAME:latest
- docker push $IMAGE_NAME:$CI_COMMIT_TAG
deploy:
stage: deploy
image: registry.hottis.de/dockerized/docker-bash:latest
only:
- tags
tags:
- hottis
- linux
- docker
variables:
GIT_STRATEGY: none
script:
- CONTAINER_NAME=$CI_PROJECT_NAME
- docker stop $CONTAINER_NAME || echo "$CONTAINER_NAME not running, anyway okay"
- docker rm $CONTAINER_NAME || echo "$CONTAINER_NAME not exsting, anyway okay"
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY;
- docker pull $IMAGE_NAME:${CI_COMMIT_TAG}
- docker run -d --restart always --name $CONTAINER_NAME --network docker-server --ip 172.16.10.39 $IMAGE_NAME:${CI_COMMIT_TAG}

54
cli/AccountStatement.py Normal file
View File

@ -0,0 +1,54 @@
from db import dbGetMany, dbGetOne
from loguru import logger
import datetime
import iso8601
from utils import getParam
from Cheetah.Template import Template
def perform(dbh, params):
year = getParam(params, 'year', datetime.datetime.today().year)
accountEntries = dbGetMany(
dbh,
{
"statement": "SELECT * FROM account_statement_v WHERE fiscal_year = %(year)s",
"params": {
'year': year
}
}
)
overview = dbGetMany(
dbh,
{
"statement": "select sum(amount), category from account_statement_v where fiscal_year = %(year)s group by category",
"params": {
'year': year
}
}
)
sum_related = dbGetOne(
dbh,
{
"statement": "select coalesce(sum(amount), 0::numeric(10,2)) as sum from account_statement_v where fiscal_year = %(year)s and category != 'nicht abrechenbare Positionen'",
"params": {
'year': year
}
}
)
sum_unrelated = dbGetOne(
dbh,
{
"statement": "select coalesce(sum(amount), 0::numeric(10,2)) as sum from account_statement_v where fiscal_year = %(year)s and category = 'nicht abrechenbare Positionen'",
"params": {
'year': year
}
}
)
template = getParam(params, 'template', 'accountStatement.tmpl')
input = { 'year': year, 'entries': accountEntries, 'overview': overview, 'related': sum_related, 'unrelated': sum_unrelated }
tmpl = Template(file=template, searchList=[ input ])
print(tmpl)

51
cli/AccountStatement.sh Executable file
View File

@ -0,0 +1,51 @@
#!/bin/bash
SHOW="0"
PRINT="0"
while getopts "y:sphP:" flag
do
case "${flag}" in
h)
echo "y ... year for statement";
echo "s ... show output using evince";
echo "p ... print output";
echo "P ... printer name";
exit 1;
;;
y)
YEAR=${OPTARG}
;;
s)
SHOW="1"
;;
p)
PRINT="1"
;;
P)
PRINTER="-P ${OPTARG}"
;;
esac
done
if [ "$YEAR" = "" ]; then
echo "give year for statement as argument"
exit 1
fi
python3.10 hv2cli.py -o AccountStatement -p '{"year":'$YEAR'}' > ./output/$YEAR.tex
pushd ./output
pdflatex $YEAR.tex
pdflatex $YEAR.tex
pdflatex $YEAR.tex
if [ "$SHOW" = "1" ]; then
evince $YEAR.pdf
fi
if [ "$PRINT" = "1" ]; then
lpr $PRINTER $YEAR.pdf
fi
popd

126
cli/ConsistencyCheck.py Normal file
View File

@ -0,0 +1,126 @@
from db import dbGetMany
from loguru import logger
errorCnt = 0
def perform(dbh, params):
global errorCnt
checkTenant(dbh, params)
checkFlats(dbh, params)
checkParkings(dbh, params)
checkCommercialPremise(dbh, params)
if (errorCnt > 0):
logger.error(f"Total error count: {errorCnt}")
def checkTenant(dbh, params):
global errorCnt
tenants = dbGetMany(dbh, { "statement": "SELECT * FROM tenant_t", "params": () })
for tenant in tenants:
outPre = f"Tenant: {tenant['firstname']} {tenant['lastname']}"
logger.info(outPre)
# check tenancies
tenancyCnt = 0
flatTenancyCnt = 0
tenancies = dbGetMany(dbh, {
"statement": "SELECT * FROM tenancy_t WHERE tenant = %s AND startdate < now() AND (enddate > now() or enddate is null)",
"params": (tenant['id'], )
}
)
for tenancy in tenancies:
tenancyCnt += 1
if (tenancy['flat']):
flatTenancyCnt += 1
logger.info(f"{outPre}: Flat tenancy: {tenancy['id']}, start: {tenancy['startdate']}, end: {tenancy['enddate']}")
if (tenancy['parking']):
logger.info(f"{outPre}: Garage tenancy: {tenancy['id']}, start: {tenancy['startdate']}, end: {tenancy['enddate']}")
if (tenancy['commercial_premise']):
logger.info(f"{outPre}: Commercial premise tenancy: {tenancy['id']}, start: {tenancy['startdate']}, end: {tenancy['enddate']}")
if (flatTenancyCnt == 0):
logger.warning(f"{outPre}: no flat tenancy")
if (flatTenancyCnt > 1):
logger.warning(f"{outPre}: more than one flat tenancy ({flatTenancyCnt})")
if (tenancyCnt == 0):
logger.error(f"{outPre}: no tenancy at all")
errorCnt += 1
noCurrentTenancies = dbGetMany(dbh, {
"statement": "SELECT * FROM tenancy_t WHERE tenant = %s",
"params": (tenant['id'], )
}
)
for noCurrentTenancy in noCurrentTenancies:
logger.error(f"{outPre}: but: flat {noCurrentTenancy['flat']}, parking: {noCurrentTenancy['parking']}, commercial premise: {noCurrentTenancy['commercial_premise']}, start: {noCurrentTenancy['startdate']}, end: {noCurrentTenancy['enddate']}")
def _checkRentals(dbh, params, rentalType):
global errorCnt
table = f"{rentalType}_t"
rentals = dbGetMany(dbh, {
"statement": f"SELECT * FROM {table}",
"params": ()
}
)
for rental in rentals:
outPre = f"{rentalType}: {rental['description']}, premise: {rental['premise']}"
logger.info(outPre)
if (rentalType == 'flat'):
overheadMappingCnt = 0
overheadMappings = dbGetMany(dbh, {
"statement": "SELECT * FROM overhead_advance_flat_mapping_t WHERE flat = %s",
"params": (rental['id'], )
}
)
for overheadMapping in overheadMappings:
overheadMappingCnt += 1
logger.info(f"{outPre}: overhead mapping: {overheadMapping['id']}")
if (overheadMappingCnt == 0):
errorCnt += 1
logger.error(f"{outPre}: no overhead mapping available")
if (overheadMappingCnt > 1):
errorCnt += 1
logger.error(f"{outPre}: more than one overhead mapping available")
tenancyCnt = 0
tenancies = dbGetMany(dbh, {
"statement": f"SELECT * FROM tenancy_t WHERE {rentalType} = %s AND startdate < now() AND (enddate > now() or enddate is null)",
"params": (rental['id'], )
}
)
for tenancy in tenancies:
tenancyCnt += 1
logger.info(f"{outPre}: tenant: {tenancy['tenant']}, start: {tenancy['startdate']}, end: {tenancy['enddate']}")
feeMappingCnt = 0
feeMappings = dbGetMany(dbh, {
"statement": "SELECT * FROM tenancy_fee_mapping_t where tenancy = %s",
"params": (tenancy['id'], )
}
)
for feeMapping in feeMappings:
feeMappingCnt += 1
logger.info(f"{outPre}: fee mapping: {feeMapping['id']}")
if (feeMappingCnt == 0):
errorCnt += 1
logger.error(f"{outPre}: no fee mapping available")
if (feeMappingCnt > 1):
errorCnt += 1
logger.error(f"{outPre}: more than one fee mapping available")
if (tenancyCnt == 0):
errorCnt += 1
logger.error(f"{outPre}: vacant")
if (tenancyCnt > 1):
errorCnt += 1
logger.error(f"{outPre}: overbooked")
def checkFlats(dbh, params):
_checkRentals(dbh, params, "flat")
def checkParkings(dbh, params):
_checkRentals(dbh, params, "parking")
def checkCommercialPremise(dbh, params):
_checkRentals(dbh, params, "commercial_premise")

View File

@ -0,0 +1,117 @@
from db import dbGetMany, dbGetOne
from loguru import logger
from decimal import Decimal
import datetime
import iso8601
def perform(dbh, params):
try:
createdAt = iso8601.parse_date(params['created_at'])
except iso8601.iso8601.ParseError:
msg = f"Can not parse given date {params['created_at']}"
logger.error(msg)
raise Exception(msg)
except KeyError:
createdAt = datetime.datetime.today()
year = createdAt.year
createdAt = createdAt.strftime("%Y-%m-%d")
tenants = dbGetMany(dbh, { "statement": "SELECT * FROM tenant_t", "params": () })
for tenant in tenants:
logger.info(f"Tenant: {tenant['firstname']} {tenant['lastname']}")
# check tenancies
tenancies = dbGetMany(dbh, {
"statement": "SELECT * FROM tenancy_t WHERE tenant = %s AND startdate < now() AND (enddate > now() or enddate is null)",
"params": (tenant['id'], )
}
)
requests = []
for tenancy in tenancies:
fee = dbGetOne(dbh, {
"statement": """
SELECT f.amount, f.fee_type
FROM fee_t f, tenancy_fee_mapping_t t
WHERE t.tenancy = %s AND
f.id = t.fee AND
f.startdate < now() AND
(f.enddate > now() OR f.enddate is null)
""",
"params": (tenancy['id'], )
}
)
if (tenancy['flat']):
logger.debug(f" Flat tenancy: {tenancy['id']}, Fee: {fee['amount']}, Fee_Type: {fee['fee_type']}")
flat = dbGetOne(dbh, { "statement": "SELECT area FROM flat_t WHERE id = %s", "params": (tenancy['flat'], ) })
logger.debug(f" Area: {flat['area']}")
if (fee['fee_type'] == 'per_area'):
feeRequest = flat['area'] * fee['amount']
else:
feeRequest = fee['amount']
feeRequest = feeRequest.quantize(Decimal('1.00'))
requests.append({
'description': f"Miete {tenancy['description']}",
'account': tenant['account'],
'created_at': createdAt,
'amount': feeRequest,
'category': 'Mietforderung'
})
overheadAdvance = dbGetOne(dbh, {
"statement": """
SELECT o.amount
FROM overhead_advance_t o, overhead_advance_flat_mapping_t m
WHERE m.flat = %s AND
o.id = m.overhead_advance AND
o.startdate < now() AND
(o.enddate > now() OR o.enddate is null)
""",
"params": (tenancy['flat'], )
}
)
overheadAdvanceRequest = flat['area'] * overheadAdvance['amount']
overheadAdvanceRequest = overheadAdvanceRequest.quantize(Decimal('1.00'))
requests.append({
'description': f"Betriebskosten {tenancy['description']}",
'account': tenant['account'],
'created_at': createdAt,
'amount': overheadAdvanceRequest,
'category': 'Betriebskostenforderung'
})
if (tenancy['parking']):
logger.debug(f" Garage tenancy: {tenancy['id']}, Fee: {fee['amount']}, Fee_Type: {fee['fee_type']}")
feeRequest = fee['amount']
feeRequest = feeRequest.quantize(Decimal('1.00'))
requests.append({
'description': f"Miete {tenancy['description']}",
'account': tenant['account'],
'created_at': createdAt,
'amount': feeRequest,
'category': 'Mietforderung'
})
if (tenancy['commercial_premise']):
logger.debug(f" Commercial premise tenancy: {tenancy['id']}, Fee: {fee['amount']}, Fee_Type: {fee['fee_type']}")
feeRequest = fee['amount']
feeRequest = feeRequest.quantize(Decimal('1.00'))
requests.append({
'description': f"Miete {tenancy['description']}",
'account': tenant['account'],
'created_at': createdAt,
'amount': feeRequest,
'category': 'Mietforderung'
})
for request in requests:
request['amount'] = Decimal('-1.0') * request['amount']
logger.info(f" {request['description']}, {request['account']}, {request['created_at']}, {request['amount']}, {request['category']}")
accountEntry = dbGetOne(dbh, {
"statement": """
INSERT INTO account_entry_t
(description, account, created_at, fiscal_year, amount, account_entry_category)
VALUES (%s, %s, %s, %s, %s, (SELECT id FROM account_entry_category_t WHERE description = %s))
RETURNING id
""",
"params": (request['description'], request['account'], request['created_at'], year, request['amount'], request['category'])
}
)
logger.info(f" account entry entered with id {accountEntry['id']}")

314
cli/OverheadAccounts.py Normal file
View File

@ -0,0 +1,314 @@
from db import dbGetMany, dbGetOne
import datetime
from loguru import logger
from decimal import *
from utils import getParam
from Cheetah.Template import Template
EPSILON = Decimal('0.000000001')
def perform(dbh, params):
year = getParam(params, 'year', datetime.datetime.today().year)
startDate = datetime.datetime(year, 1, 1, 0, 0, 0)
endDate = datetime.datetime(year, 12, 31, 23, 59, 59)
premises = (1, 2)
houses = {}
for premise in premises:
# get overhead sums by object, category and timespan
overheadItems = dbGetMany(
dbh,
{
"statement":
"""
select (coalesce(sum(ae.amount), 0::numeric(10,2)) * -1) as sum,
aec.description as category,
aec.considerminusarea as considerminusarea
from account_t a,
premise_t p,
account_entry_t ae,
account_entry_category_t aec
where p.account = a.id and
ae.account = a.id and
aec.overhead_relevant = 't' and
ae.account_entry_category = aec.id and
ae.fiscal_year = %(year)s and
p.id = %(premise)s
group by category, considerminusarea
union
select 0 as sum,
aec.description as category,
aec.considerminusarea as considerminusarea
from account_t a,
premise_t p,
account_entry_t ae,
account_entry_category_t aec
where p.account = a.id and
ae.account = a.id and
aec.overhead_relevant = 't' and
aec.id not in (select distinct account_entry_category from account_entry_t where fiscal_year = %(year)s) and
ae.fiscal_year = %(year)s and
p.id = %(premise)s
group by category, considerminusarea
union
select 120 as sum,
'16. Waschmaschine' as category,
false as considerminusarea
from premise_t
where id = %(premise)s
order by category
""",
"params": {
"year": year,
"premise": premise
}
}
)
# get areas and factors
totalArea = {}
flatArea = dbGetOne(
dbh,
{
"statement":
"""
select
sum(f.area) as flat_area
from
premise_t p,
flat_t f
where
f.premise = p.id and
p.id = %(premise)s
""",
"params": {
"premise": premise
}
}
)
totalArea['flat_area'] = flatArea['flat_area']
commercialArea = dbGetOne(
dbh,
{
"statement":
"""
select
coalesce(sum(c.area), 0) as commercial_area
from
premise_t p full outer join commercial_premise_t c on c.premise = p.id
where
p.id = %(premise)s
""",
"params": {
"premise": premise
}
}
)
totalArea['commercial_area'] = commercialArea['commercial_area']
minusAreaAndDetails = dbGetOne(
dbh,
{
"statement":
"""
select
p.minus_area as minus_area,
p.id as house_id,
p.description as house
from
premise_t p
where
p.id = %(premise)s
""",
"params": {
"premise": premise
}
}
)
totalArea['minus_area'] = minusAreaAndDetails['minus_area']
details = { 'id': minusAreaAndDetails['house_id'], 'description': minusAreaAndDetails['house'] }
totalArea['other_area'] = totalArea['commercial_area'] + totalArea['minus_area']
totalArea['total_area'] = totalArea['flat_area'] + totalArea['other_area']
totalArea['flat_factor'] = totalArea['flat_area'] / totalArea['total_area']
totalArea['other_factor'] = totalArea['other_area'] / totalArea['total_area']
totalArea['factor_check'] = totalArea['flat_factor'] + totalArea['other_factor']
totalSum = Decimal('0')
flatSum = Decimal('0')
otherSum = Decimal('0')
for overheadItem in overheadItems:
totalSum += overheadItem['sum']
overheadItem['flat_part'] = overheadItem['sum'] * totalArea['flat_factor'] if overheadItem['considerminusarea'] else overheadItem['sum']
flatSum += overheadItem['flat_part']
overheadItem['other_part'] = overheadItem['sum'] * totalArea['other_factor'] if overheadItem['considerminusarea'] else Decimal('0')
otherSum += overheadItem['other_part']
verifyDifference = totalSum - flatSum - otherSum
logger.debug(f"{totalSum=}, {verifyDifference=}")
if abs(verifyDifference) > EPSILON:
raise Exception(f"Verify Difference is too large: {premise=}, {verifyDifference=}")
umlageAusfallWagnis = flatSum * Decimal('0.02')
flatSum2 = flatSum + umlageAusfallWagnis
partByMonthArea = flatSum2 / Decimal('12') / totalArea['flat_area']
houses[details['id']] = {
'details': details,
'areas': totalArea,
'overhead_items': overheadItems,
'flat_sum': flatSum,
'flat_sum_2': flatSum2,
'other_sum': otherSum,
'total_sum': totalSum,
'umlage_ausfall_wagnis': umlageAusfallWagnis,
'part_by_montharea': partByMonthArea,
'year': year }
logger.info(f"{houses=}")
printOverviews = getParam(params, 'printOverviews', True)
if printOverviews:
overviewTemplate = getParam(params, 'overviewTemplate', 'betriebskostenuebersicht.tmpl')
overviewPrefix = getParam(params, 'overviewPrefix', 'overview')
overviewSuffix = getParam(params, 'overviewSuffix', 'tex')
for house in houses.values():
logger.debug(f"Processing item: {house}")
outputFile = f"./output/{overviewPrefix}-{house['details']['id']}.{overviewSuffix}"
tmpl = Template(file=overviewTemplate, searchList=[ house ])
logger.debug(tmpl)
with open(outputFile, 'w') as f:
f.write(str(tmpl))
# get flat tenants by object and timespan with paid overhead and due overhead
tenants = dbGetMany(
dbh,
{
"statement":
"""
select t.id as tenant_id,
t.salutation as tenant_salutation,
t.firstname as tenant_firstname,
t.lastname as tenant_lastname,
t.address1 as tenant_address1,
t.address2 as tenant_address2,
t.address3 as tenant_address3,
t.zip as tenant_zip,
t.city as tenant_city,
f.id as flat_id,
f.description as flat,
f.area as flat_area,
p.id as house_id,
p.description as house,
ty.startdate as startdate,
ty.enddate as enddate,
t.account as tenant_account
from tenant_t t,
premise_t p,
flat_t f,
tenancy_t ty
where ty.tenant = t.id and
ty.flat = f.id and
ty.startdate <= %(startDate)s and
(ty.enddate >= %(endDate)s or ty.enddate is null) and
f.premise = p.id and
p.id in %(premises)s
order by house_id, tenant_id
""",
"params": {
"startDate": startDate,
"endDate": endDate,
"premises": premises
}
}
)
letters = []
for tenant in tenants:
letter = {}
paidTotal = dbGetOne(
dbh,
{
"statement":
"""
SELECT sum(amount) AS sum,
count(id) AS cnt
FROM account_entry_t
WHERE account = %(account)s AND
account_entry_category = 2 AND
fiscal_year = %(year)s
""",
"params": {
"account": tenant['tenant_account'],
"year": year
}
}
)
tenant['paid_total'] = paidTotal['sum']
receivableFee = dbGetOne(
dbh,
{
"statement":
"""
SELECT sum(amount) * -1 AS sum ,
count(id) AS cnt
FROM account_entry_t
WHERE account = %(account)s AND
account_entry_category = 3 AND
fiscal_year = %(year)s
""",
"params": {
"account": tenant['tenant_account'],
"year": year
}
}
)
tenant['receivable_fee'] = receivableFee['sum']
tenant['rent_time'] = receivableFee['cnt']
tenant['paid_overhead'] = paidTotal['sum'] - receivableFee['sum']
letter['tenant'] = tenant
letter['year'] = year
letter['flat_area'] = houses[tenant['house_id']]['areas']['flat_area']
letter['receivable_overhead'] = tenant['flat_area'] * houses[tenant['house_id']]['part_by_montharea'] * tenant['rent_time']
letter['unbalanced_overhead'] = tenant['paid_overhead'] - letter['receivable_overhead']
letter['unbalanced_overhead_unsigned'] = abs(letter['unbalanced_overhead'])
letter['total_overhead'] = houses[tenant['house_id']]['flat_sum_2']
letters.append(letter)
logger.info(f"{letter=}")
printLetters = getParam(params, 'printLetters', True)
if printLetters:
letterTemplate = getParam(params, 'letterTemplate', 'jahresabrechnung.tmpl')
letterPrefix = getParam(params, 'letterPrefix', 'letter')
letterSuffix = getParam(params, 'letterSuffix', 'tex')
for letter in letters:
logger.debug(f"Processing item: {letter}")
outputFile = f"./output/{letterPrefix}-{letter['tenant']['tenant_id']}.{letterSuffix}"
tmpl = Template(file=letterTemplate, searchList=[ letter ])
logger.debug(tmpl)
with open(outputFile, 'w') as f:
f.write(str(tmpl))

55
cli/OverheadAccounts.sh Executable file
View File

@ -0,0 +1,55 @@
#!/bin/bash
PRINT="0"
while getopts "y:phP:" flag
do
case "${flag}" in
h)
echo "y ... year for statement";
echo "p ... print output";
echo "P ... printer name";
exit 1;
;;
y)
YEAR=${OPTARG}
;;
p)
PRINT="1"
;;
P)
PRINTER="-P ${OPTARG}"
;;
esac
done
if [ "$YEAR" = "" ]; then
echo "give year for statement as argument"
exit 1
fi
python3.10 hv2cli.py -o OverheadAccounts -p '{"year":'$YEAR'}'
pushd ./output
for I in letter-*.tex; do
pdflatex $I
pdflatex $I
pdflatex $I
done
for I in overview-*.tex; do
pdflatex $I
pdflatex $I
pdflatex $I
done
if [ "$PRINT" = "1" ]; then
for I in letter-*.pdf; do
lpr $PRINTER $I
done
for I in overview-*.pdf; do
lpr $PRINTER $I
done
fi
popd

59
cli/accountStatement.tmpl Normal file
View File

@ -0,0 +1,59 @@
\documentclass[10pt]{article}
\usepackage{german}
\usepackage{eurosym}
\usepackage[a4paper, landscape=true, left=2cm, right=2cm, top=2cm]{geometry}
\usepackage{icomma}
\usepackage{longtable}
\usepackage{color}
\setlength{\parindent}{0pt}
\begin{document}
\subsection*{Account Statement $year}
\begin{longtable}{|r|r|p{6cm}|r|r|r|p{3cm}|r|p{5cm}|}
\hline \textcolor{blue}{\bf{ID}} & \textcolor{blue}{\bf{Date}} & \textcolor{blue}{\bf{Description}} & \textcolor{blue}{\bf{Amount}} & \textcolor{blue}{\bf{DocNo}} & \textcolor{blue}{\bf{Year}} & \textcolor{blue}{\bf{Category}} & \textcolor{blue}{\bf{IsRef}} & \textcolor{blue}{\bf{BaseAccount}} \\ \hline \hline
\endfirsthead
\hline \textcolor{blue}{\bf{ID}} & \textcolor{blue}{\bf{Date}} & \textcolor{blue}{\bf{Description}} & \textcolor{blue}{\bf{Amount}} & \textcolor{blue}{\bf{DocNo}} & \textcolor{blue}{\bf{Year}} & \textcolor{blue}{\bf{Category}} & \textcolor{blue}{\bf{IsRef}} & \textcolor{blue}{\bf{BaseAccount}} \\ \hline \hline
\endhead
\multicolumn{9}{r}{\em{to be continued}}
\endfoot
\endlastfoot
#for $entry in $entries
\tt{$entry['id']} & \tt{$entry['created_at']} & \tt{$entry['description']} & #slurp
#if $entry['amount'] <= 0
\textcolor{red}{#slurp
#end if
\tt{$entry['amount']} \,\euro{}#slurp
#if $entry['amount'] <= 0
}#slurp
#end if
& \tt{$entry['document_no']} & \tt{$entry['fiscal_year']} & \tt{$entry['category']} & \tt{$entry['is_reference']} & \tt{{$entry['base_account'].replace('_', ' ') }} \\ \hline
#end for
\end{longtable}
\pagebreak
\subsection*{Overviews}
\begin{tabular}{|l|r|} \hline
\hline \textcolor{blue}{\bf{category}} & \textcolor{blue}{\bf{sum}} \\
#for $entry in $overview
\hline \tt{$entry['category']} & #slurp
#if $entry['sum'] <= 0
\textcolor{red}{#slurp
#end if
\tt{$entry['sum']} \,\euro{}#slurp
#if $entry['sum'] <= 0
}#slurp
#end if
\\
#end for
\hline \hline related & \tt{$related['sum']} \,\euro{} \\
\hline unrelated & \tt{$unrelated['sum']} \,\euro{} \\
\hline \hline
\end{tabular}
\end{document}

View File

@ -0,0 +1,47 @@
\documentclass[12pt]{article}
\renewcommand{\familydefault}{\sfdefault}
\usepackage{german}
\usepackage{eurosym}
\usepackage[a4paper, left=2cm, right=2cm, top=2cm]{geometry}
\usepackage{icomma}
\setlength{\parindent}{0pt}
\begin{document}
\subsection*{Aufstellung}
über die Ermittlung der Betriebskosten gemäß §27 II. BV
\vspace{15mm}
\begin{tabular}{ll}
Objekt & $details['description'] \\
Jahr & $year \\
Eigent"umer & Nober Grundbesitz GmbH \\
\end{tabular}
\addvspace{1cm}
\begin{tabular}{|p{7cm}|r|r|r|}
\hline Art & Wohnungen & andere Fl"achen & Gesamtfl"ache \\
\hline
\hline Fl"ache & \tt{$areas['flat_area']\,m\textsuperscript{2}} & \tt{$areas['other_area']\,m\textsuperscript{2}} & \tt{$areas['total_area']\,m\textsuperscript{2}} \\
\hline Faktor & \tt{#echo '%.10f' % $areas['flat_factor'] #} & \tt{#echo '%.10f' % $areas['other_factor'] #} & \\
\hline \hline
#for $item in $overhead_items
\hline $item['category'] & \tt{#echo '%.2f' % $item['flat_part'] #\,\euro{}} & \tt{#echo '%.2f' % $item['other_part'] #\,\euro{}} & \tt{#echo '%.2f' % $item['sum'] #\,\euro{}} \\
#end for
\hline
% \hline \multicolumn{4}{c}{ } \\
\hline Zwischensumme & \tt{#echo '%.2f' % $flat_sum #\,\euro{}} & \tt{#echo '%.2f' % $other_sum #\,\euro{}} & \tt{#echo '%.2f' % $total_sum #\,\euro{}} \\
\hline Umlageausfallwagnis & \tt{#echo '%.2f' % $umlage_ausfall_wagnis #\,\euro{}} & & \\
\hline Summe & \tt{#echo '%.2f' % $flat_sum_2 #\,\euro{}} & & \\
\hline
% \hline \multicolumn{4}{c}{ } \\
\hline Anteil pro Monat und m\textsuperscript{2} & \tt{#echo '%.10f' % $part_by_montharea #\,\euro{}} & & \\
\hline
\end{tabular}
\end{document}

47
cli/db.py Normal file
View File

@ -0,0 +1,47 @@
import psycopg2
import psycopg2.extras
from loguru import logger
class NoDataFoundException(Exception): pass
class TooMuchDataFoundException(Exception): pass
def execDatabaseOperation(dbh, func, params):
cur = None
try:
with dbh.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
# params["params"] = [ v if not v=='' else None for v in params["params"] ]
logger.debug("edo: {}".format(str(params)))
return func(cur, params)
except psycopg2.Error as err:
raise Exception("Error when working on cursor: {}".format(err))
def _opGetMany(cursor, params):
#logger.warning(f"{params=}")
items = []
cursor.execute(params["statement"], params["params"])
for itemObj in cursor:
logger.debug("item received {}".format(str(itemObj)))
items.append(itemObj)
return items
def dbGetMany(dbh, params):
return execDatabaseOperation(dbh, _opGetMany, params)
def _opGetOne(cursor, params):
cursor.execute(params["statement"], params["params"])
itemObj = cursor.fetchone()
logger.debug(f"item received: {itemObj}")
if not itemObj:
raise NoDataFoundException
dummyObj = cursor.fetchone()
if dummyObj:
raise TooMuchDataFoundException
return itemObj
def dbGetOne(dbh, params):
return execDatabaseOperation(dbh, _opGetOne, params)

38
cli/fixDueDate.py Normal file
View File

@ -0,0 +1,38 @@
from loguru import logger
from db import dbGetMany, dbGetOne
def perform(dbh, params):
accountEntries = dbGetMany(
dbh,
{
"statement":
"""
select id, due_at from account_entry_t where due_at is not null
""",
"params": {}
}
)
for accountEntry in accountEntries:
id = accountEntry['id']
oldDueAt = accountEntry['due_at']
newDueAt = oldDueAt.replace(day=1)
logger.info(f"id: {id}, due_at: {oldDueAt} -> {newDueAt}")
fixedEntry = dbGetOne(
dbh,
{
"statement":
"""
UPDATE account_entry_t
SET due_at = %(dueAt)s
WHERE id = %(id)s
RETURNING *
""",
"params": {
"id": id,
"dueAt": newDueAt
}
}
)
logger.info("fixed")

82
cli/hv2cli.py Normal file
View File

@ -0,0 +1,82 @@
import psycopg2
import psycopg2.extras
from loguru import logger
import os
import configparser
import json
import argparse
import importlib
import sys
parser = argparse.ArgumentParser(description="hv2cli.py")
parser.add_argument('--config', '-c',
help="Config file, default is ./config/dbconfig.ini",
required=False,
default="./config/dbconfig.ini")
parser.add_argument('--operation', '-o',
help='Operation to perform.',
required=True)
parser.add_argument('--params', '-p',
help='JSON string with parameter for the selected operation, default: {}',
required=False,
default="{}")
parser.add_argument('--verbosity', '-v',
help='Minimal log level for output: DEBUG, INFO, WARNING, ..., default: DEBUG',
required=False,
default="DEBUG")
parser.add_argument('--nocolorize', '-n',
help='disable colored output (for cron)',
required=False,
action='store_true',
default=False)
args = parser.parse_args()
operation = args.operation
params = json.loads(args.params)
logLevel = args.verbosity
noColorize = args.nocolorize
DB_USER = ""
DB_PASS = ""
DB_HOST = ""
DB_NAME = ""
try:
DB_USER = os.environ["DB_USER"]
DB_PASS = os.environ["DB_PASS"]
DB_HOST = os.environ["DB_HOST"]
DB_NAME = os.environ["DB_NAME"]
except KeyError:
config = configparser.ConfigParser()
config.read(args.config)
DB_USER = config["database"]["user"]
DB_PASS = config["database"]["pass"]
DB_HOST = config["database"]["host"]
DB_NAME = config["database"]["name"]
logger.remove()
logger.add(sys.stderr, colorize=(not noColorize), level=logLevel)
dbh = None
try:
opMod = importlib.import_module(operation)
dbh = psycopg2.connect(user = DB_USER, password = DB_PASS,
host = DB_HOST, database = DB_NAME,
sslmode = 'require')
dbh.autocommit = False
with dbh:
opMod.perform(dbh, params)
except psycopg2.Error as err:
raise Exception("Error when working on the database: {}".format(err))
except Exception as err:
raise err
finally:
if dbh:
dbh.close()

74
cli/jahresabrechnung.tmpl Normal file
View File

@ -0,0 +1,74 @@
\documentclass[12pt]{dinbrief}
\usepackage{german}
\usepackage{eurosym}
\address{Nober Grundbesitz GbR\\
Eupenstr. 20\\
45259 Essen}
\backaddress{Nober Grundbesitz GbR, Eupenstr. 20, 45259 Essen}
\signature{Wolfgang Hottgenroth} %% Hier Unterschrift einfuegen
\nowindowrules
\writer{wh} %% Hier eigenen Namen oder Kuerzel einfuegen
\phone{0174}{3072474} %% Hier eigene Telefon einfuegen
\bottomtext{\sffamily\footnotesize Gesch"aftsf"uhrer: Wolfgang Hottgenroth, Robert Nober, Gregor Nober ---
EMail: hausverwaltung@nober.de\\
Bankverbindung: IBAN DE14 3605 0105 0001 5130 35, Sparkasse Essen}
\begin{document}
\pagenumbering{gobble}
\begin{letter}{$tenant['tenant_firstname'] $tenant['tenant_lastname']\\
#if $tenant['tenant_address1']
$tenant['tenant_address1']\\
#end if
#if $tenant['tenant_address2']
$tenant['tenant_address2']\\
#end if
#if $tenant['tenant_address3']
$tenant['tenant_address3']\\
#end if
$tenant['tenant_zip'] $tenant['tenant_city']}
\subject{Betriebskostenabrechnung $year}
\opening{$tenant['tenant_salutation'],}
f"ur die im vergangenen Jahr angefallenen Betriebskosten ergibt sich f"ur Sie folgende Abrechnung.
\begin{tabular}{|p{10cm}|r|}
\hline Jahr & \tt{$year} \\
\hline Haus & $tenant['house'] \\
\hline Betriebskosten gesamt & \tt{#echo '%.2f' % $total_overhead #\,\euro{}} \\
\hline Gesamt-Wohnfl"ache & \tt{$flat_area\,m\textsuperscript{2}} \\
\hline Ihre Wohnung & $tenant['flat'] \\
\hline Ihre Wohnfl"ache & \tt{$tenant['flat_area']\,m\textsuperscript{2}} \\
\hline Ihre Mietzeit & \tt{$tenant['rent_time']\,Monate} \\
\hline Ihr Betriebskostenanteil nach Fl"ache und Mietzeit & \tt{#echo '%.2f' % $receivable_overhead #\,\euro{}} \\
\hline Ihre Zahlungen & \tt{$tenant['paid_total']\,\euro{}} \\
\hline davon Anteil Miete & \tt{$tenant['receivable_fee']\,\euro{}} \\
\hline davon Anteil Betriebskostenvorauszahlung & \tt{$tenant['paid_overhead']\,\euro{}} \\
\hline
#if $unbalanced_overhead < 0
Zuwenig
#else
Zuviel
#end if
gezahlte Betriebskosten & \tt{#echo '%.2f' % $unbalanced_overhead_unsigned #\,\euro{}} \\
\hline
\end{tabular}
#if 1 < 0
Bitte "uberweisen Sie den Betrag von #echo '%.2f' % $unbalanced_overhead_unsigned #\,\euro{} kurzfristig auf mein Konto.
#else
Ich werde den Betrag von #echo '%.2f' % $unbalanced_overhead_unsigned #\,\euro{} in den n"achsten Tagen auf Ihr Konto "uberweisen.
#end if
Eine tabellarische "Ubersicht "uber die Zusammensetzung der Gesamt-Betriebskosten
finden Sie in der Anlage.
\closing{Mit freundlichen Gr"u"sen}
\end{letter}
\end{document}

5
cli/listTenants.py Normal file
View File

@ -0,0 +1,5 @@
from db import dbGetMany
def perform(dbh, params):
tenants = dbGetMany(dbh, { "statement": "SELECT * FROM tenant_t", "params": () })
print(tenants)

2
cli/utils.py Normal file
View File

@ -0,0 +1,2 @@
def getParam(params, attr, default):
return params[attr] if attr in params else default

View File

@ -3,6 +3,10 @@ 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.',

View File

@ -32,7 +32,9 @@
{ "name": "description", "sqltype": "varchar(128)", "selector": 0, "unique": true },
{ "name": "street", "sqltype": "varchar(128)", "notnull": true },
{ "name": "zip", "sqltype": "varchar(10)", "notnull": true },
{ "name": "city", "sqltype": "varchar(128)", "notnull": true }
{ "name": "city", "sqltype": "varchar(128)", "notnull": true },
{ "name": "minus_area", "sqltype": "numeric(10,2)", "notnull": true, "default": 0},
{ "name": "account", "sqltype": "integer", "notnull": true, "foreignkey": true, "immutable": true, "unique": true }
]
},
{
@ -78,7 +80,8 @@
"name": "commercial_premise",
"columns": [
{ "name": "description", "sqltype": "varchar(128)", "selector": 1 },
{ "name": "premise", "sqltype": "integer", "foreignkey": true, "selector": 0 }
{ "name": "premise", "sqltype": "integer", "foreignkey": true, "selector": 0 },
{ "name": "area", "sqltype": "numeric(10,2)", "notnull": false }
],
"tableConstraints": [
"unique(description, premise)"
@ -126,17 +129,20 @@
"immutable": true,
"columns": [
{ "name": "description", "sqltype": "varchar(128)", "notnull": true, "selector": 0, "unique": true },
{ "name": "overhead_relevant", "sqltype": "boolean", "notnull": true, "default": "true" }
{ "name": "considerMinusArea", "sqltype": "boolean", "notnull": true, "default": true },
{ "name": "overhead_relevant", "sqltype": "boolean", "notnull": true, "default": true }
]
},
{
"name": "account_entry",
"immutable": true,
"columns": [
{ "name": "description", "sqltype": "varchar(128)", "notnull": true },
{ "name": "description", "sqltype": "varchar(1024)", "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, "selector": 0 },
{ "name": "created_at", "sqltype": "timestamp", "notnull": true, "default": "now()", "selector": 0 },
{ "name": "fiscal_year", "sqltype": "integer", "notnull": true },
{ "name": "amount", "sqltype": "numeric(10,2)", "notnull": true },
{ "name": "document_no", "sqltype": "integer", "unique": true },
{ "name": "account_entry_category", "sqltype": "integer", "notnull": true, "foreignkey": true }
],
"tableConstraints": [
@ -147,7 +153,7 @@
"name": "note",
"immutable": true,
"columns": [
{ "name": "created_at", "sqltype": "timestamp", "notnull": true, "default": "now()" },
{ "name": "created_at", "sqltype": "timestamp", "notnull": true, "default": "now()", "selector": 0 },
{ "name": "tenant", "sqltype": "integer", "notnull": true, "foreignkey": true },
{ "name": "note", "sqltype": "varchar(4096)", "notnull": true }
]

View File

@ -0,0 +1,23 @@
create or replace view account_statement_v as
select ae.id as id,
ae.description as description,
ae.created_at::timestamp::date as created_at,
ae.amount as amount,
ae.document_no as document_no,
ae.fiscal_year as fiscal_year,
aec.description as category,
ac.description as account,
ae.is_reference as is_reference,
bac.description as base_account
from joined_account_entry_v ae,
account_entry_category_t aec,
account_t ac,
account_t bac
where ae.account_entry_category = aec.id and
ae.account = ac.id and
ae.base_account = bac.id and
ac.id = 1000
order by created_at;
grant select on account_statement_v to hv2;

6
schema/changes01.sql Normal file
View File

@ -0,0 +1,6 @@
alter table premise_t add column account integer;
alter table premise_t add constraint fk_premise_t_account foreign key (account) references account_t(id);
alter table premise_t add constraint uk_premise_t_account unique(account);
alter table account_entry_t add column document_no integer unique;
create sequence unique_number_s start with 1 increment by 1;

126
schema/changes02.sql Normal file
View File

@ -0,0 +1,126 @@
CREATE TABLE account_entry_reference_t (
id serial not null primary key,
account integer not null references account_t (id),
account_entry integer not null references account_entry_t (id)
);
CREATE OR REPLACE VIEW joined_account_entry_v AS
SELECT ae.id as id,
ae.description as description,
ae.account as account,
ae.created_at as created_at,
ae.amount as amount,
ae.account_entry_category as account_entry_category,
ae.document_no as document_no,
ae.fiscal_year as fiscal_year,
false as is_reference,
0 as base_account
FROM account_entry_t ae
UNION
SELECT ae.id as id,
ae.description as description,
aer.account as account,
ae.created_at as created_at,
ae.amount as amount,
ae.account_entry_category as account_entry_category,
ae.document_no as document_no,
ae.fiscal_year as fiscal_year,
true as is_reference,
ae.account as base_account
FROM account_entry_t ae,
account_entry_reference_t aer
WHERE ae.id = aer.account_entry;
update account_t set description = 'fallback_account' where id = 33;
delete from account_t where id = 32;
insert into account_t (id, description) values (1000, 'ledger');
update account_entry_t set amount = amount * -1.0 where account=33;
update account_entry_t set amount = amount * -1.0 where account in (34,35,36,37);
DO $$
DECLARE
entry_id integer;
BEGIN
RAISE NOTICE 'Start migration';
FOR entry_id IN
SELECT id
FROM account_entry_t
WHERE account IN (33,34,35,36,37)
LOOP
RAISE NOTICE 'About to migrate entry %', entry_id;
INSERT INTO account_entry_reference_t (account, account_entry) VALUES (1000, entry_id);
END LOOP;
END;
$$;
update account_entry_t
set description = 'Miete ' || extract(year from created_at)::text || ' ' || to_char(to_date(extract(month from created_at)::text, 'MM'), 'Month')
where account_entry_category = 2 and description = 'Miete';
DO $$
DECLARE
entry RECORD;
tenant RECORD;
BEGIN
RAISE NOTICE 'Start migration of tenant accounts';
FOR entry IN
SELECT id, description, account
FROM account_entry_t
WHERE account_entry_category = 2
LOOP
RAISE NOTICE 'About to migrate entry %', entry.id;
INSERT INTO account_entry_reference_t (account, account_entry) VALUES (1000, entry.id);
SELECT *
INTO tenant
FROM tenant_t
WHERE account = entry.account;
RAISE NOTICE 'Tenant: % %', tenant.firstname, tenant.lastname;
UPDATE account_entry_t
SET description = description || ' ' || tenant.firstname || ' ' || tenant.lastname
WHERE id = entry.id;
END LOOP;
END;
$$;
CREATE OR REPLACE FUNCTION maintain_ledger()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
tenant RECORD;
adjusted_description text;
BEGIN
IF ((NEW.description = 'Miete') AND (NEW.account_entry_category = 2)) THEN
SELECT firstname, lastname
INTO tenant
FROM tenant_t
WHERE account = NEW.account;
adjusted_description := 'Miete ' || extract(year from NEW.created_at)::text || ' ' || to_char(to_date(extract(month from NEW.created_at)::text, 'MM'), 'Month') || tenant.firstname || ' ' || tenant.lastname;
UPDATE account_entry_t
SET description = adjusted_description
WHERE id = NEW.id;
END IF;
INSERT INTO account_entry_reference_t (account, account_entry) VALUES (1000, NEW.id);
RETURN NEW;
END;
$$;
CREATE TRIGGER maintain_ledger_trigger
AFTER INSERT ON account_entry_t
FOR EACH ROW
WHEN (NEW.account != 1000 AND NEW.account_entry_category NOT IN (3, 4, 29))
EXECUTE FUNCTION maintain_ledger();
grant select, update on account_entry_reference_t_id_seq to hv2;
grant insert on account_entry_reference_t to hv2;
grant update on account_entry_t to hv2;

View File

@ -39,6 +39,8 @@ CREATE TABLE premise_t (
,street varchar(128) not null
,zip varchar(10) not null
,city varchar(128) not null
,minus_area numeric(10,2) not null default 0
,account integer not null references account_t (id) unique
);
GRANT SELECT, INSERT, UPDATE ON premise_t TO hv2;
@ -90,6 +92,7 @@ CREATE TABLE commercial_premise_t (
id serial not null primary key
,description varchar(128)
,premise integer references premise_t (id)
,area numeric(10,2)
,unique(description, premise)
);
@ -137,7 +140,8 @@ GRANT SELECT, UPDATE ON tenancy_fee_mapping_t_id_seq TO hv2;
CREATE TABLE account_entry_category_t (
id serial not null primary key
,description varchar(128) not null unique
,overhead_relevant boolean not null default true
,considerMinusArea boolean not null default True
,overhead_relevant boolean not null default True
);
GRANT SELECT, INSERT ON account_entry_category_t TO hv2;
@ -145,10 +149,12 @@ GRANT SELECT, UPDATE ON account_entry_category_t_id_seq TO hv2;
CREATE TABLE account_entry_t (
id serial not null primary key
,description varchar(128) not null
,description varchar(1024) not null
,account integer not null references account_t (id)
,created_at timestamp not null default now()
,fiscal_year integer not null
,amount numeric(10,2) not null
,document_no integer unique
,account_entry_category integer not null references account_entry_category_t (id)
,unique(description, account, created_at)
);

View File

@ -3,6 +3,10 @@ table {
border-spacing: 20px;
}
.mat-table {
border-spacing: 20px;
}
.spacer {
flex: 1 1 auto;
}

View File

@ -1,76 +1,66 @@
<mat-card class="defaultCard">
<mat-card-header>
<mat-card-title>
{{account?.description}} ({{account?.id}})
</mat-card-title>
</mat-card-header>
<mat-card-content>
<mat-accordion>
<mat-expansion-panel (opened)="collapse = true"
(closed)="collapse = false">
<mat-expansion-panel-header>
<mat-panel-title *ngIf="!collapse">
Kontoübersicht, Saldo: {{saldo?.saldo | number:'1.2-2'}} €
</mat-panel-title>
<mat-panel-description>
</mat-panel-description>
</mat-expansion-panel-header>
<div id="firstBlock">
<form (ngSubmit)="addAccountEntry()">
<mat-form-field appearance="outline" id="addEntryfield">
<mat-label>Datum</mat-label>
<input matInput name="createdAt" [(ngModel)]="newAccountEntry.created_at" [matDatepicker]="createdAtPicker"/>
<mat-datepicker-toggle matSuffix [for]="createdAtPicker"></mat-datepicker-toggle>
<mat-datepicker #createdAtPicker></mat-datepicker>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Kategorie</mat-label>
<mat-select [(ngModel)]="newAccountEntry.account_entry_category" name="category" disabled="shallBeRentPayment">
<mat-option *ngFor="let p of accountEntryCategories" [value]="p.id">{{p.description}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Betrag (€)</mat-label>
<input matInput type="number" name="amount" [(ngModel)]="newAccountEntry.amount"/>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Beschreibung</mat-label>
<input matInput name="description" [(ngModel)]="newAccountEntry.description"/>
</mat-form-field>
<button #addAccountEntryButton type="submit" mat-raised-button color="primary">Buchung speichern</button>
</form>
</div>
<div class="large">
Saldo: {{saldo?.saldo | number:'1.2-2'}} €
</div>
<div id="secondBlock">
<table mat-table [dataSource]="accountEntriesDataSource" #zftable>
<ng-container matColumnDef="createdAt">
<th mat-header-cell *matHeaderCellDef>Datum</th>
<td mat-cell *matCellDef="let element">{{element.rawAccountEntry.created_at | date}}</td>
</ng-container>
<ng-container matColumnDef="description">
<th mat-header-cell *matHeaderCellDef>Beschreibung</th>
<td mat-cell *matCellDef="let element">{{element.rawAccountEntry.description}}</td>
</ng-container>
<ng-container matColumnDef="amount">
<th mat-header-cell *matHeaderCellDef>Betrag</th>
<td mat-cell *matCellDef="let element" class="rightaligned">{{element.rawAccountEntry.amount | number:'1.2-2'}} €</td>
</ng-container>
<ng-container matColumnDef="category">
<th mat-header-cell *matHeaderCellDef>Kategorie</th>
<td mat-cell *matCellDef="let element">{{element.accountEntryCategory}}</td>
</ng-container>
<ng-container matColumnDef="overhead_relevant">
<th mat-header-cell *matHeaderCellDef>BK relevant</th>
<td mat-cell *matCellDef="let element">{{element.overheadRelevant}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="accountEntriesDisplayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: accountEntriesDisplayedColumns;"></tr>
</table>
</div>
</mat-expansion-panel>
</mat-accordion>
</mat-card-content>
</mat-card>
<div id="firstBlock">
<form (ngSubmit)="addAccountEntry(accountEntryForm)" #accountEntryForm="ngForm">
<mat-form-field appearance="outline" id="addEntryfield">
<mat-label>Datum</mat-label>
<input matInput ngModel name="createdAt" [matDatepicker]="createdAtPicker"/>
<mat-datepicker-toggle matSuffix [for]="createdAtPicker"></mat-datepicker-toggle>
<mat-datepicker #createdAtPicker></mat-datepicker>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Jahr</mat-label>
<input matInput type="number" name="fiscalYear" [formControl]="presetFiscalYear" ngModel/>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Kategorie</mat-label>
<mat-select ngModel name="category" [formControl]="presetCategory" >
<mat-option *ngFor="let p of accountEntryCategories" [value]="p.id">{{p.description}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Betrag (€)</mat-label>
<input matInput type="number" name="amount" ngModel/>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Beschreibung</mat-label>
<input matInput name="description" [formControl]="presetDescription" ngModel/>
</mat-form-field>
<button #addAccountEntryButton type="submit" mat-raised-button color="primary">Buchung speichern</button>
</form>
</div>
<div class="large">
Saldo: {{saldo?.saldo | number:'1.2-2'}} €
</div>
<div id="secondBlock">
<table mat-table [dataSource]="accountEntriesDataSource" #zftable>
<ng-container matColumnDef="createdAt">
<th mat-header-cell *matHeaderCellDef >Datum</th>
<td mat-cell *matCellDef="let element">{{element.rawAccountEntry.created_at | date}}</td>
</ng-container>
<ng-container matColumnDef="fiscalYear">
<th mat-header-cell *matHeaderCellDef >Jahr</th>
<td mat-cell *matCellDef="let element">{{element.rawAccountEntry.fiscal_year}}</td>
</ng-container>
<ng-container matColumnDef="description">
<th mat-header-cell *matHeaderCellDef>Beschreibung</th>
<td mat-cell *matCellDef="let element">{{element.rawAccountEntry.description}}</td>
</ng-container>
<ng-container matColumnDef="document_no">
<th mat-header-cell *matHeaderCellDef >Belegnummer</th>
<td mat-cell *matCellDef="let element">{{element.rawAccountEntry.document_no}}</td>
</ng-container>
<ng-container matColumnDef="amount">
<th mat-header-cell *matHeaderCellDef>Betrag</th>
<td mat-cell *matCellDef="let element" class="rightaligned">{{element.rawAccountEntry.amount | number:'1.2-2'}} €</td>
</ng-container>
<ng-container matColumnDef="category">
<th mat-header-cell *matHeaderCellDef >Kategorie</th>
<td mat-cell *matCellDef="let element">{{element.accountEntryCategory}}</td>
</ng-container>
<ng-container matColumnDef="overhead_relevant">
<th mat-header-cell *matHeaderCellDef >BK relevant</th>
<td mat-cell *matCellDef="let element">{{element.overheadRelevant}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="accountEntriesDisplayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: accountEntriesDisplayedColumns;"></tr>
</table>
</div>

View File

@ -1,10 +1,14 @@
import { ViewFlags } from '@angular/compiler/src/core';
import { Component, Input, OnInit, OnChanges, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatButton } from '@angular/material/button';
import { MatExpansionPanel } from '@angular/material/expansion';
import { MatTableDataSource } from '@angular/material/table';
import { AccountEntryCategoryService, AccountEntryService, AccountService } from '../data-object-service';
import { Account, AccountEntry, AccountEntryCategory, NULL_AccountEntry } from '../data-objects';
import { ErrorDialogService } from '../error-dialog.service';
import { ExtApiService } from '../ext-data-object-service';
import { Saldo } from '../ext-data-objects';
import { Saldo, UniqueNumber } from '../ext-data-objects';
import { MessageService } from '../message.service';
@ -27,29 +31,31 @@ export class AccountComponent implements OnInit {
@Input() shallBeRentPayment: boolean
@ViewChild('addAccountEntryButton') addAccountEntryButton: MatButton
collapse: boolean = false
account: Account
accountEntries: DN_AccountEntry[]
accountEntriesDataSource: MatTableDataSource<DN_AccountEntry>
accountEntriesDisplayedColumns: string[] = [ "description", "amount", "createdAt", "category", "overhead_relevant" ]
accountEntriesDisplayedColumns: string[] = [ "description", "document_no", "amount", "createdAt", "fiscalYear", "category", "overhead_relevant" ]
saldo: Saldo
accountEntryCategories: AccountEntryCategory[]
accountEntryCategoriesMap: Map<number, AccountEntryCategory>
accountEntryCategoriesInverseMap: Map<string, AccountEntryCategory>
newAccountEntry: AccountEntry = NULL_AccountEntry
presetFiscalYear: FormControl
presetCategory: FormControl
presetDescription: FormControl
constructor(
private accountService: AccountService,
private accountEntryService: AccountEntryService,
private extApiService: ExtApiService,
private accountEntryCategoryService: AccountEntryCategoryService,
private messageService: MessageService
private messageService: MessageService,
private errorDialogService: ErrorDialogService
) { }
async getAccount(): Promise<void> {
try {
if (this.selectedAccountId) {
@ -86,20 +92,35 @@ export class AccountComponent implements OnInit {
}
}
async addAccountEntry(): Promise<void> {
try {
this.addAccountEntryButton.disabled = true
this.newAccountEntry.account = this.account.id
this.messageService.add(`addAccountEntry: ${ JSON.stringify(this.newAccountEntry, undefined, 4) }`)
this.newAccountEntry = await this.accountEntryService.postAccountEntry(this.newAccountEntry)
this.messageService.add(`New accountEntry created: ${this.newAccountEntry.id}`)
this.newAccountEntry = { 'account': this.account.id, 'amount': undefined, 'created_at': '', 'description': '', 'id': 0, 'account_entry_category': 0 }
this.getAccountEntries()
} catch (err) {
this.messageService.add(`Error in addAccountEntry: ${JSON.stringify(err, undefined, 4)}`)
} finally {
this.addAccountEntryButton.disabled = false
async addAccountEntry(formData: any): Promise<void> {
try {
this.addAccountEntryButton.disabled = true
this.messageService.add(`${JSON.stringify(formData.value, undefined, 4)}`)
let uniquenumber: UniqueNumber = await this.extApiService.getUniqueNumber();
this.messageService.add(`Got unique number as document_no: ${uniquenumber.number}`)
let newAccountEntry: AccountEntry = {
description: this.presetDescription.value,
account: this.account.id,
created_at: formData.value.createdAt,
fiscal_year: this.presetFiscalYear.value,
amount: formData.value.amount,
id: 0,
document_no: uniquenumber.number,
account_entry_category: this.presetCategory.value
}
this.messageService.add(`addAccountEntry: ${ JSON.stringify(newAccountEntry, undefined, 4) }`)
newAccountEntry = await this.accountEntryService.postAccountEntry(newAccountEntry)
this.messageService.add(`New accountEntry created: ${newAccountEntry.id}`)
formData.reset()
this.getAccountEntries()
} catch (err) {
this.messageService.add(`Error in addAccountEntry: ${JSON.stringify(err, undefined, 4)}`)
this.errorDialogService.openDialog('AccountComponent', 'addAccountEntry', JSON.stringify(err, undefined, 4))
} finally {
this.addAccountEntryButton.disabled = false
}
}
async getAccountEntryCategories(): Promise<void> {
@ -119,13 +140,26 @@ export class AccountComponent implements OnInit {
}
private async init(): Promise<void> {
this.messageService.add(`AccountComponent.init start, account: ${this.selectedAccountId}`)
let currentDate = new Date()
let y = currentDate.getFullYear()
this.presetFiscalYear = new FormControl(y)
this.messageService.add(`AccountComponent.init a, account: ${this.selectedAccountId}`)
await this.getAccountEntryCategories()
if (this.shallBeRentPayment) {
this.messageService.add(`AccountComponent.init b, account: ${this.selectedAccountId}`)
this.presetCategory = new FormControl(this.accountEntryCategoriesInverseMap.get('Mietzahlung').id)
this.messageService.add(`AccountComponent.init c, account: ${this.selectedAccountId}`)
this.presetDescription = new FormControl("Miete")
this.messageService.add(`shall be rentpayment`)
this.messageService.add(`AccountComponent.init d, account: ${this.selectedAccountId}`)
}
this.messageService.add(`AccountComponent.init, account: ${this.selectedAccountId}`)
this.getAccount()
await this.getAccountEntryCategories()
if (this.shallBeRentPayment) {
this.messageService.add('shall be rentpayment')
this.newAccountEntry.account_entry_category = this.accountEntryCategoriesInverseMap.get('Mietzahlung').id
}
}
ngOnInit(): void {

View File

@ -17,6 +17,9 @@ import { OverheadAdvanceListComponent } from './overhead-advance-list/overhead-a
import { OverheadAdvanceDetailsComponent } from './overhead-advance-details/overhead-advance-details.component';
import { FeeListComponent } from './fee-list/fee-list.component';
import { FeeDetailsComponent } from './fee-details/fee-details.component';
import { EnterPaymentComponent } from './enter-payment/enter-payment.component';
import { HomeComponent } from './home/home.component';
import { LedgerComponent } from './ledger/ledger.component';
const routes: Routes = [
@ -41,8 +44,12 @@ const routes: Routes = [
{ path: 'fees', component: FeeListComponent, canActivate: [ AuthGuardService ] },
{ path: 'fee/:id', component: FeeDetailsComponent, canActivate: [ AuthGuardService ] },
{ path: 'fee', component: FeeDetailsComponent, canActivate: [ AuthGuardService ] },
{ path: 'enterPayment', component: EnterPaymentComponent, canActivate: [ AuthGuardService ] },
{ path: 'ledger', component: LedgerComponent, canActivate: [ AuthGuardService ] },
{ path: 'home', component: HomeComponent },
{ path: 'logout', component: LogoutComponent },
{ path: 'login', component: LoginComponent }
{ path: 'login', component: LoginComponent },
{ path: '', pathMatch: 'full', redirectTo: 'home' }
]
@NgModule({

View File

@ -45,7 +45,12 @@ import { FeeDetailsComponent } from './fee-details/fee-details.component';
import { MatExpansionModule } from '@angular/material/expansion';
import { AccountComponent } from './account/account.component';
import { NoteComponent } from './note/note.component'
import { MatMomentDateModule, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter'
import { MatMomentDateModule, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';
import { EnterPaymentComponent } from './enter-payment/enter-payment.component';
import { HomeComponent } from './home/home.component';
import { LedgerComponent } from './ledger/ledger.component';
import { ErrorDialogComponent } from './error-dialog/error-dialog.component'
import { MatSortModule } from '@angular/material/sort';
registerLocaleData(localeDe)
@ -72,7 +77,11 @@ registerLocaleData(localeDe)
FeeListComponent,
FeeDetailsComponent,
AccountComponent,
NoteComponent
NoteComponent,
EnterPaymentComponent,
HomeComponent,
LedgerComponent,
ErrorDialogComponent
],
imports: [
BrowserModule,
@ -94,7 +103,8 @@ registerLocaleData(localeDe)
MatSelectModule,
MatDatepickerModule,
MatNativeDateModule,
MatExpansionModule
MatExpansionModule,
MatSortModule
],
exports: [
MatMomentDateModule

View File

@ -22,6 +22,10 @@
<mat-option *ngFor="let p of premises" [value]="p.id">{{p.description}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Fläche</mat-label>
<input type="number" matInput name="area" [(ngModel)]="commercialPremise.area"/>
</mat-form-field>
</div>
<button #submitButton type="submit" mat-raised-button color="primary">Speichern</button>
</form>

View File

@ -1,5 +1,5 @@
// export const serviceBaseUrl = "https://api.hv.nober.de";
// export const serviceBaseUrl = "http://172.16.10.38:5000";
export const serviceBaseUrl = "http://localhost:8080"
export const serviceBaseUrl = "https://api.hv.nober.de";
// export const serviceBaseUrl = "http://172.16.3.96:8080";
// export const serviceBaseUrl = "http://localhost:8080"
export const authserviceBaseUrl = "https://authservice.hottis.de"
export const applicationId = "hv2"

View File

@ -130,6 +130,11 @@ export class PremiseService {
}
async getPremisesByAccount(id: number): Promise<Premise[]> {
this.messageService.add(`PremiseService: get data by Account ${id}`);
return this.http.get<Premise[]>(`${serviceBaseUrl}/v1/premises/account/${id}`).toPromise()
}
}

View File

@ -52,6 +52,8 @@ export interface Premise {
street: string
zip: string
city: string
minus_area: number
account: number
}
export const NULL_Premise: Premise = {
id: 0
@ -59,6 +61,8 @@ export const NULL_Premise: Premise = {
,street: ''
,zip: ''
,city: ''
,minus_area: undefined
,account: undefined
}
export interface Flat {
@ -117,11 +121,13 @@ export interface CommercialPremise {
id: number
description: string
premise: number
area: number
}
export const NULL_CommercialPremise: CommercialPremise = {
id: 0
,description: ''
,premise: undefined
,area: undefined
}
export interface Tenancy {
@ -176,11 +182,13 @@ export const NULL_TenancyFeeMapping: TenancyFeeMapping = {
export interface AccountEntryCategory {
id: number
description: string
considerMinusArea: boolean
overhead_relevant: boolean
}
export const NULL_AccountEntryCategory: AccountEntryCategory = {
id: 0
,description: ''
,considerMinusArea: false
,overhead_relevant: false
}
@ -189,7 +197,9 @@ export interface AccountEntry {
description: string
account: number
created_at: string
fiscal_year: number
amount: number
document_no: number
account_entry_category: number
}
export const NULL_AccountEntry: AccountEntry = {
@ -197,7 +207,9 @@ export const NULL_AccountEntry: AccountEntry = {
,description: ''
,account: undefined
,created_at: ''
,fiscal_year: undefined
,amount: undefined
,document_no: undefined
,account_entry_category: undefined
}

View File

@ -0,0 +1,22 @@
<mat-card class="defaultCard">
<mat-card-header>
<mat-card-title>
Mietzahlung eintragen
</mat-card-title>
</mat-card-header>
<mat-card-content>
<div>
<span>Mieter auswählen: </span>
<mat-form-field appearance="outline">
<mat-select #mapSelect [(ngModel)]="accountId" name="tenantAccount">
<mat-label>Mieter</mat-label>
<mat-option *ngFor="let p of tenants" [value]="p.id">{{p.firstname}} {{p.lastname}}</mat-option>
</mat-select>
</mat-form-field>
</div>
<app-account [selectedAccountId]="accountId" [shallBeRentPayment]="true"></app-account>
</mat-card-content>
</mat-card>

View File

@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { EnterPaymentComponent } from './enter-payment.component';
describe('EnterPaymentComponent', () => {
let component: EnterPaymentComponent;
let fixture: ComponentFixture<EnterPaymentComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ EnterPaymentComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(EnterPaymentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,37 @@
import { Component, OnInit } from '@angular/core';
import { TenantService } from '../data-object-service';
import { Tenant } from '../data-objects';
import { MessageService } from '../message.service';
@Component({
selector: 'app-enter-payment',
templateUrl: './enter-payment.component.html',
styleUrls: ['./enter-payment.component.css']
})
export class EnterPaymentComponent implements OnInit {
tenants: Tenant[]
accountId: number
constructor(
private tenantService: TenantService,
private messageService: MessageService
) { }
async getTenants(): Promise<void> {
try {
this.messageService.add("Trying to load tenants")
this.tenants = await this.tenantService.getTenants()
this.messageService.add("Tenants loaded")
} catch (err) {
this.messageService.add(JSON.stringify(err, undefined, 4))
}
}
ngOnInit(): void {
this.getTenants()
}
}

View File

@ -0,0 +1,6 @@
export interface ErrorDialogData {
module: string,
func: string,
msg: string
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ErrorDialogService } from './error-dialog.service';
describe('ErrorDialogService', () => {
let service: ErrorDialogService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ErrorDialogService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,18 @@
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ErrorDialogComponent } from './error-dialog/error-dialog.component';
@Injectable({
providedIn: 'root'
})
export class ErrorDialogService {
constructor(public dialog: MatDialog) { }
openDialog(module: string, func: string, msg: string): void {
const dialogRef = this.dialog.open(ErrorDialogComponent, {
width: '450px',
data: { module: module, func: func, msg: msg }
})
}
}

View File

@ -0,0 +1,11 @@
<h1>Fehler</h1>
<h2>Module</h2>
<p>{{data.module}}</p>
<h2>Function</h2>
<p>{{data.func}}</p>
<h2>Message</h2>
<p>{{data.msg}}</p>

View File

@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ErrorDialogComponent } from './error-dialog.component';
describe('ErrorDialogComponent', () => {
let component: ErrorDialogComponent;
let fixture: ComponentFixture<ErrorDialogComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ErrorDialogComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ErrorDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,24 @@
import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ErrorDialogData } from '../error-dialog-data';
@Component({
selector: 'app-error-dialog',
templateUrl: './error-dialog.component.html',
styleUrls: ['./error-dialog.component.css']
})
export class ErrorDialogComponent implements OnInit {
constructor(
public dialogRef: MatDialogRef<ErrorDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: ErrorDialogData
) { }
onNoClick(): void {
this.dialogRef.close()
}
ngOnInit(): void {
}
}

View File

@ -6,8 +6,8 @@ import { MessageService } from './message.service';
import { serviceBaseUrl } from './config';
import { Fee, OverheadAdvance } from './data-objects';
import { Saldo } from './ext-data-objects';
import { Account, Fee, OverheadAdvance } from './data-objects';
import { Saldo, Tenant_with_Saldo, UniqueNumber } from './ext-data-objects';
@Injectable({ providedIn: 'root' })
@ -19,6 +19,11 @@ export class ExtApiService {
return this.http.get<OverheadAdvance[]>(`${serviceBaseUrl}/v1/overhead_advances/flat/${id}`).toPromise()
}
async getAccountByDescription(description: string): Promise<Account> {
this.messageService.add(`ExtApiService: get account by description ${description}`);
return this.http.get<Account>(`${serviceBaseUrl}/v1/accounts/bydescription/${description}`).toPromise()
}
async getFeeByTenancies(id: number): Promise<Fee[]> {
this.messageService.add(`ExtApiService: get fees by flat ${id}`);
return this.http.get<Fee[]>(`${serviceBaseUrl}/v1/fees/tenancy/${id}`).toPromise()
@ -28,4 +33,14 @@ export class ExtApiService {
this.messageService.add(`ExtApiService: get saldo for account ${id}`);
return this.http.get<Saldo>(`${serviceBaseUrl}/v1/account/saldo/${id}`).toPromise()
}
async getTenantsWithSaldo(): Promise<Tenant_with_Saldo[]> {
this.messageService.add("ExtApiService: get tenants with saldo");
return this.http.get<Tenant_with_Saldo[]>(`${serviceBaseUrl}/v1/tenants/saldo`).toPromise()
}
async getUniqueNumber(): Promise<UniqueNumber> {
this.messageService.add("ExtApiService: get unique number");
return this.http.get<UniqueNumber>(`${serviceBaseUrl}/v1/uniquenumber`).toPromise()
}
}

View File

@ -2,4 +2,15 @@
export interface Saldo {
saldo: number
}
export interface Tenant_with_Saldo {
id: number
firstname: string
lastname: string
address1: string
saldo: number
}
export interface UniqueNumber {
number: number
}

View File

@ -0,0 +1 @@
<p>home works!</p>

View File

@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ HomeComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,15 @@
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}

View File

@ -0,0 +1,10 @@
<mat-card class="defaultCard">
<mat-card-header>
<mat-card-title>
Buchführung
</mat-card-title>
</mat-card-header>
<mat-card-content>
<app-account #fallbackAccountComponent [selectedAccountId]="fallbackAccountId" [shallBeRentPayment]="false"></app-account>
</mat-card-content>
</mat-card>

View File

@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LedgerComponent } from './ledger.component';
describe('LedgerComponent', () => {
let component: LedgerComponent;
let fixture: ComponentFixture<LedgerComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ LedgerComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(LedgerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,41 @@
import { Component, OnInit, ViewChild } from '@angular/core';
import { AccountComponent } from '../account/account.component';
import { Account } from '../data-objects';
import { ExtApiService } from '../ext-data-object-service';
import { MessageService } from '../message.service';
@Component({
selector: 'app-ledger',
templateUrl: './ledger.component.html',
styleUrls: ['./ledger.component.css']
})
export class LedgerComponent implements OnInit {
fallbackAccount: Account
fallbackAccountId: number
@ViewChild('fallbackAccountComponent') fallbackAccountComponent: AccountComponent
constructor(
private extApiService: ExtApiService,
private messageService: MessageService
) { }
async getAccount(): Promise<void> {
try {
this.messageService.add("Trying to load fallback account")
this.fallbackAccount = await this.extApiService.getAccountByDescription('fallback_account')
this.messageService.add("Account loaded")
} catch (err) {
this.messageService.add(JSON.stringify(err, undefined, 4))
}
}
async ngOnInit(): Promise<void> {
await this.getAccount()
this.fallbackAccountId = this.fallbackAccount.id
}
}

View File

@ -19,8 +19,13 @@
<th mat-header-cell *matHeaderCellDef>Haus</th>
<td mat-cell *matCellDef="let element">{{element.premise.description}}</td>
</ng-container>
<ng-container matColumnDef="area">
<th mat-header-cell *matHeaderCellDef>Fläche</th>
<td mat-cell *matCellDef="let element">{{element.commercialPremise.area | number:'1.2-2'}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;" [routerLink]="['/commercialunit/', row.commercialPremise.id]"></tr>
</table>
</div>
</mat-card-content>

View File

@ -21,7 +21,7 @@ export class MyCommercialUnitsComponent implements OnInit {
dnCommercialPremises: DN_CommercialPremise[] = []
dataSource: MatTableDataSource<DN_CommercialPremise>
displayedColumns: string[] = ["description", "premise"]
displayedColumns: string[] = ["description", "premise", "area"]
constructor(
private commercialPremiseService: CommercialPremiseService,

View File

@ -26,6 +26,14 @@
<th mat-header-cell *matHeaderCellDef>Ort</th>
<td mat-cell *matCellDef="let element">{{element.city}}</td>
</ng-container>
<ng-container matColumnDef="minusArea">
<th mat-header-cell *matHeaderCellDef>Minus-Fläche</th>
<td mat-cell *matCellDef="let element">{{element.minus_area | number:'1.2-2'}}</td>
</ng-container>
<ng-container matColumnDef="account">
<th mat-header-cell *matHeaderCellDef>Betriebskostenkonto</th>
<td mat-cell *matCellDef="let element">{{element.account}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;" [routerLink]="['/premise/', row.id]"></tr>
</table>

View File

@ -13,7 +13,8 @@ export class MyPremisesComponent implements OnInit {
premises: Premise[]
dataSource: MatTableDataSource<Premise>
displayedColumns: string[] = [ "description", "street", "zip", "city" ]
displayedColumns: string[] = [ "description", "street", "zip", "city", "minusArea", "account" ]
constructor(private premiseService: PremiseService, private messageService: MessageService) { }

View File

@ -22,6 +22,10 @@
<th mat-header-cell *matHeaderCellDef>Adresse 1</th>
<td mat-cell *matCellDef="let element">{{element.address1}}</td>
</ng-container>
<ng-container matColumnDef="saldo">
<th mat-header-cell *matHeaderCellDef>Saldo</th>
<td mat-cell *matCellDef="let element">{{element.saldo | number:'1.2-2'}} €</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;" [routerLink]="['/tenant/', row.id]"></tr>
</table>

View File

@ -3,6 +3,9 @@ import { MessageService } from '../message.service';
import { TenantService } from '../data-object-service';
import { Tenant } from '../data-objects';
import { MatTableDataSource } from '@angular/material/table'
import { Tenant_with_Saldo } from '../ext-data-objects';
import { ExtApiService } from '../ext-data-object-service';
@Component({
selector: 'app-my-tenants',
@ -11,19 +14,22 @@ import { MatTableDataSource } from '@angular/material/table'
})
export class MyTenantsComponent implements OnInit {
tenants: Tenant[]
dataSource: MatTableDataSource<Tenant>
displayedColumns: string[] = ["lastname", "firstname", "address1"]
tenants: Tenant_with_Saldo[]
dataSource: MatTableDataSource<Tenant_with_Saldo>
displayedColumns: string[] = ["lastname", "firstname", "address1", "saldo"]
constructor(private tenantService: TenantService, private messageService: MessageService) { }
constructor(
private extApiService: ExtApiService,
private messageService: MessageService
) { }
async getTenants(): Promise<void> {
try {
this.messageService.add("Trying to load tenants")
this.tenants = await this.tenantService.getTenants()
this.tenants = await this.extApiService.getTenantsWithSaldo()
this.messageService.add("Tenants loaded")
this.dataSource = new MatTableDataSource<Tenant>(this.tenants)
this.dataSource = new MatTableDataSource<Tenant_with_Saldo>(this.tenants)
} catch (err) {
this.messageService.add(JSON.stringify(err, undefined, 4))
}

View File

@ -4,17 +4,26 @@
[mode]="(isHandset$ | async) ? 'over' : 'side'"
[opened]="(isHandset$ | async) === false">
<mat-toolbar>Menu</mat-toolbar>
<mat-nav-list>
<mat-nav-list *ngIf="!authenticated">
<a mat-list-item href="/login">Anmelden</a>
</mat-nav-list>
<mat-nav-list *ngIf="authenticated">
<a mat-list-item href="/enterPayment">Mietzahlung eintragen</a>
</mat-nav-list><mat-divider *ngIf="authenticated"></mat-divider><mat-nav-list *ngIf="authenticated">
<a mat-list-item href="/tenants">Meine Mieter/innen</a>
</mat-nav-list><mat-divider></mat-divider><mat-nav-list>
</mat-nav-list><mat-divider *ngIf="authenticated"></mat-divider><mat-nav-list *ngIf="authenticated">
<a mat-list-item href="/flats">Meine Wohnungen</a>
<a mat-list-item href="/parkings">Meine Garagen</a>
<a mat-list-item href="/commercialunits">Meine Büros</a>
</mat-nav-list><mat-divider></mat-divider><mat-nav-list>
</mat-nav-list><mat-divider *ngIf="authenticated"></mat-divider><mat-nav-list *ngIf="authenticated">
<a mat-list-item href="/overheadadvances">Betriebskostensätze</a>
<a mat-list-item href="/fees">Mietsätze</a>
</mat-nav-list><mat-divider></mat-divider><mat-nav-list>
</mat-nav-list><mat-divider *ngIf="authenticated"></mat-divider><mat-nav-list *ngIf="authenticated">
<a mat-list-item href="/premises">Meine Häuser</a>
</mat-nav-list><mat-divider *ngIf="authenticated"></mat-divider><mat-nav-list *ngIf="authenticated">
<a mat-list-item href="/ledger">Buchführung</a>
</mat-nav-list><mat-divider *ngIf="authenticated"></mat-divider><mat-nav-list *ngIf="authenticated">
<a mat-list-item href="/logout">Abmelden</a>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
@ -31,13 +40,11 @@
<span class="spacer"></span>
<span class="gittagversion">GITTAGVERSION</span>
<span class="gittagversion" *ngIf="authenticated">Läuft aus in {{expiryTime | async }} Sekunden</span>
<a *ngIf="!authenticated" mat-button routerLink="/login">Login</a>
<a *ngIf="authenticated" mat-button routerLink="/logout">Logout</a>
</mat-toolbar>
<!-- Add Content Here -->
<router-outlet></router-outlet>
<app-messages></app-messages>
<app-messages *ngIf="authenticated"></app-messages>
</mat-sidenav-content>
</mat-sidenav-container>

View File

@ -9,31 +9,64 @@
</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<div>
<form (ngSubmit)="savePremise()">
<div>
<mat-form-field appearance="outline">
<mat-label>Beschreibung</mat-label>
<input matInput name="description" [(ngModel)]="premise.description"/>
</mat-form-field>
</div><div>
<mat-form-field appearance="outline">
<mat-label>Strasse</mat-label>
<input matInput name="street" [(ngModel)]="premise.street"/>
</mat-form-field>
</div><div>
<mat-form-field appearance="outline">
<mat-label>PLZ</mat-label>
<input matInput name="zip" [(ngModel)]="premise.zip"/>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Ort</mat-label>
<input matInput name="city" [(ngModel)]="premise.city"/>
</mat-form-field>
</div>
<button #submitButton type="submit" mat-raised-button color="primary">Speichern</button>
</form>
</div>
<mat-accordion>
<mat-expansion-panel (opened)="collapseDetails = true"
(closed)="collapseDetails = false"
[expanded]="premise.id == 0">
<mat-expansion-panel-header>
<mat-panel-title>
Details
</mat-panel-title>
<mat-panel-description>
</mat-panel-description>
</mat-expansion-panel-header>
<form (ngSubmit)="savePremise()">
<div>
<mat-form-field appearance="outline">
<mat-label>Beschreibung</mat-label>
<input matInput name="description" [(ngModel)]="premise.description"/>
</mat-form-field>
</div><div>
<mat-form-field appearance="outline">
<mat-label>Strasse</mat-label>
<input matInput name="street" [(ngModel)]="premise.street"/>
</mat-form-field>
</div><div>
<mat-form-field appearance="outline">
<mat-label>PLZ</mat-label>
<input matInput name="zip" [(ngModel)]="premise.zip"/>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Ort</mat-label>
<input matInput name="city" [(ngModel)]="premise.city"/>
</mat-form-field>
</div><div>
<mat-form-field appearance="outline">
<mat-label>Minus-Fläche</mat-label>
<input type="number" matInput name="minusArea" [(ngModel)]="premise.minus_area"/>
</mat-form-field>
</div><div>
<mat-form-field appearance="outline" *ngIf="premise.account">
<mat-label>Betriebskostenkonto</mat-label>
<input matInput name="account" [readonly]="true" [(ngModel)]="premise.account"/>
</mat-form-field>
</div>
<button #submitButton type="submit" mat-raised-button color="primary">Speichern</button>
</form>
</mat-expansion-panel>
<mat-expansion-panel (opened)="collapseOverheadAccount = true"
(closed)="collapseOverheadAccount = false">
<mat-expansion-panel-header>
<mat-panel-title>
Betriebskostenkonto
</mat-panel-title>
<mat-panel-description>
</mat-panel-description>
</mat-expansion-panel-header>
<app-account #incomeAccountComponent [selectedAccountId]="overheadAccountId" [shallBeRentPayment]="false"></app-account>
</mat-expansion-panel>
</mat-accordion>
</mat-card-content>
</mat-card>
</section>

View File

@ -1,8 +1,9 @@
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatButton } from '@angular/material/button';
import { MatExpansionPanel } from '@angular/material/expansion';
import { ActivatedRoute, Router } from '@angular/router';
import { PremiseService } from '../data-object-service';
import { Premise } from '../data-objects';
import { AccountService, PremiseService } from '../data-object-service';
import { Account, NULL_Premise, Premise } from '../data-objects';
import { MessageService } from '../message.service';
@Component({
@ -12,18 +13,19 @@ import { MessageService } from '../message.service';
})
export class PremiseDetailsComponent implements OnInit {
collapseDetails: boolean = false
collapseOverheadAccount: boolean = false
@ViewChild('submitButton') submitButton: MatButton
premise: Premise = {
id: 0,
description: '',
street: '',
zip: '',
city: ''
}
premise: Premise = NULL_Premise
overheadAccount: Account
overheadAccountId: number
constructor(
private premiseService: PremiseService,
private accountService: AccountService,
private messageService: MessageService,
private route: ActivatedRoute,
private router: Router
@ -34,6 +36,8 @@ export class PremiseDetailsComponent implements OnInit {
const id = +this.route.snapshot.paramMap.get('id')
if (id != 0) {
this.premise = await this.premiseService.getPremise(id)
this.overheadAccount = await this.accountService.getAccount(this.premise.account)
this.overheadAccountId = this.overheadAccount.id
}
} catch (err) {
this.messageService.add(JSON.stringify(err, undefined, 4))
@ -47,6 +51,12 @@ export class PremiseDetailsComponent implements OnInit {
this.messageService.add(JSON.stringify(this.premise, undefined, 4))
if (this.premise.id == 0) {
this.messageService.add("about to insert new premise")
this.overheadAccount = {
"id": 0,
"description": `overhead_account_${this.premise.description}`
}
this.overheadAccount = await this.accountService.postAccount(this.overheadAccount)
this.premise.account = this.overheadAccount.id
this.premise = await this.premiseService.postPremise(this.premise)
this.messageService.add(`Successfully added premises with id ${this.premise.id}`)
} else {

View File

@ -8,7 +8,8 @@
<mat-card-content>
<mat-accordion>
<mat-expansion-panel (opened)="collapseTenantDetails = true"
(closed)="collapseTenantDetails = false">
(closed)="collapseTenantDetails = false"
[expanded]="tenant.id == 0">
<mat-expansion-panel-header>
<mat-panel-title *ngIf="!collapseTenantDetails">
Details
@ -68,18 +69,18 @@
<input matInput name="iban" [(ngModel)]="tenant.iban"/>
</mat-form-field>
</div>
<!--
<div>
<mat-form-field appearance="outline">
<mat-form-field appearance="outline" *ngIf="tenant.account">
<mat-label>Account ID</mat-label>
<input matInput name="account_id" [readonly]="true" [ngModel]="account.id"/>
<input matInput name="account_id" [readonly]="true" [ngModel]="tenant.account"/>
</mat-form-field>
<!--
<mat-form-field appearance="outline">
<mat-label>Account Description</mat-label>
<input matInput name="account_desc" [readonly]="true" [ngModel]="account.description"/>
</mat-form-field>
</div>
-->
-->
</div>
<button #submitButton type="submit" mat-raised-button color="primary">Speichern</button>
</form>
</div>
@ -98,7 +99,8 @@
</mat-card-header>
<mat-card-content>
<mat-accordion>
<mat-expansion-panel (opened)="collapseTenancies = true"
<mat-expansion-panel #panelTenancies
(opened)="collapseTenancies = true"
(closed)="collapseTenancies = false">
<mat-expansion-panel-header>
<mat-panel-title *ngIf="!collapseTenancies">
@ -138,6 +140,54 @@
</table>
</div>
</mat-expansion-panel>
<mat-expansion-panel #panelAddMapping
(opened)="openTenancyMapping()"
(closed)="closeTenancyMapping()">
<mat-expansion-panel-header>
<mat-panel-title *ngIf="!collapseTenancyMapping">
Mietverhältnis hinzufügen
</mat-panel-title>
<mat-panel-description>
</mat-panel-description>
</mat-expansion-panel-header>
<div>
<form (ngSubmit)="addTenancyToTenant()">
<div>
<mat-form-field appearance="outline" id="setenddatefield">
<mat-label>Beginn</mat-label>
<input matInput name="startdate" [(ngModel)]="newTenancy.startdate" [matDatepicker]="newtenancystartdatepicker"/>
<mat-datepicker-toggle matSuffix [for]="newtenancystartdatepicker"></mat-datepicker-toggle>
<mat-datepicker #newtenancystartdatepicker></mat-datepicker>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Beschreibung</mat-label>
<input matInput name="description" [(ngModel)]="newTenancy.description"/>
</mat-form-field>
</div><div>
<mat-form-field appearance="outline">
<mat-select #mapSelect [(ngModel)]="newTenancy.flat" name="flat" (selectionChange)="flatSelected()">
<mat-label>Wohnung</mat-label>
<mat-option *ngFor="let p of allFlats" [value]="p.rawFlat.id">{{p.rawFlat.description}} {{p.premise}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Garage</mat-label>
<mat-select #mapSelect [(ngModel)]="newTenancy.parking" name="parking" (selectionChange)="parkingSelected()">
<mat-option *ngFor="let p of allParkings" [value]="p.rawParking.id">{{p.rawParking.description}} {{p.premise}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Büro</mat-label>
<mat-select #mapSelect [(ngModel)]="newTenancy.commercial_premise" name="commercial_premise" (selectionChange)="commercialPremiseSelected()">
<mat-option *ngFor="let p of allCommercialPremises" [value]="p.rawCommercialPremise.id">{{p.rawCommercialPremise.description}} {{p.premise}}</mat-option>
</mat-select>
</mat-form-field>
</div>
<button #addTenancyToTenantButton type="submit" mat-raised-button color="primary">Anlegen</button>
</form>
</div>
</mat-expansion-panel>
</mat-accordion>
</mat-card-content>
</mat-card>
@ -207,7 +257,27 @@
</mat-card-content>
</mat-card>
<app-account [selectedAccountId]="tenant.account" [shallBeRentPayment]="true"></app-account>
<mat-card class="defaultCard">
<mat-card-header>
<mat-card-title>
{{account?.description}} ({{account?.id}})
</mat-card-title>
</mat-card-header>
<mat-card-content>
<mat-accordion>
<mat-expansion-panel (opened)="collapseAccount = true"
(closed)="collapseAccount = false" #mep>
<mat-expansion-panel-header>
<mat-panel-title *ngIf="!collapseAccount">
Kontoübersicht, Saldo: {{saldo?.saldo | number:'1.2-2'}} €
</mat-panel-title>
<mat-panel-description>
</mat-panel-description>
</mat-expansion-panel-header>
<app-account [selectedAccountId]="tenant.account" [shallBeRentPayment]="true"></app-account>
</mat-expansion-panel>
</mat-accordion>
</mat-card-content>
</mat-card>
</section>

View File

@ -6,6 +6,7 @@ import { MessageService } from '../message.service';
import { MatButton } from '@angular/material/button';
import { MatTableDataSource } from '@angular/material/table';
import { ExtApiService } from '../ext-data-object-service';
import { MatExpansionPanel } from '@angular/material/expansion';
interface DN_Tenancy {
@ -15,6 +16,21 @@ interface DN_Tenancy {
commercialPremise: string
}
interface DN_Flat {
rawFlat: Flat
premise: string
}
interface DN_Parking {
rawParking: Parking
premise: string
}
interface DN_CommercialPremise {
rawCommercialPremise: CommercialPremise
premise: string
}
@Component({
selector: 'app-tenant-details',
templateUrl: './tenant-details.component.html',
@ -27,12 +43,16 @@ export class TenantDetailsComponent implements OnInit {
account: Account = NULL_Account
premisesMap: Map<number, Premise>
tenancies: DN_Tenancy[]
tenancyDataSource: MatTableDataSource<DN_Tenancy>
tenancyDisplayColumns: string[] = [ "description", "flat", "parking", "commercial_premise", "startdate", "enddate" ]
collapseTenantDetails: boolean = false
collapseTenancies: boolean = false
collapseTenancyMapping: boolean = false
collapseAccount: boolean = false
selectedTenancy: Tenancy = undefined
mappedFees: Fee[]
@ -41,9 +61,15 @@ export class TenantDetailsComponent implements OnInit {
allFees: Fee[]
selectedFee: number
newTenancy: Tenancy = NULL_Tenancy
allFlats: DN_Flat[]
allParkings: DN_Parking[]
allCommercialPremises: DN_CommercialPremise[]
@ViewChild('submitButton') submitButton: MatButton
@ViewChild('mapFeeButton') mapFeeButton: MatButton
@ViewChild('panelTenancies') panelTenancies: MatExpansionPanel
@ViewChild('panelAddMapping') panelAddMapping: MatExpansionPanel
constructor(
private tenantService: TenantService,
@ -64,11 +90,18 @@ export class TenantDetailsComponent implements OnInit {
async getTenant(): Promise<void> {
try {
const id = +this.route.snapshot.paramMap.get('id')
this.messageService.add(`getTenant, id=${id}`)
if (id != 0) {
this.messageService.add("getTenant, not-0-branch")
this.tenantId = id
this.tenant = await this.tenantService.getTenant(id)
this.account = await this.accountService.getAccount(this.tenant.account)
this.getTenancies()
} else {
this.messageService.add("getTenant, 0-branch")
this.tenant = NULL_Tenant
this.account = NULL_Account
this.tenancies = []
}
} catch (err) {
this.messageService.add(JSON.stringify(err, undefined, 4))
@ -78,20 +111,16 @@ export class TenantDetailsComponent implements OnInit {
async getTenancies(): Promise<void> {
try {
this.tenancies = []
const premises: Premise[] = await this.premiseService.getPremises()
const premisesDict = new Map<number, Premise>()
for (let p of premises) {
premisesDict.set(p.id, p)
}
await this.getPremises()
for (let t of await this.tenancyService.getTenancysByTenant(this.tenant.id)) {
const flat: Flat = (t.flat) ? await this.flatService.getFlat(t.flat) : NULL_Flat
const parking: Parking = (t.parking) ? await this.parkingService.getParking(t.parking) : NULL_Parking
const commercialPremise: CommercialPremise = (t.commercial_premise) ? await this.commercialPremiseService.getCommercialPremise(t.commercial_premise) : NULL_CommercialPremise
this.tenancies.push({
rawTenancy: t,
flat: (flat != NULL_Flat) ? `${flat.description} (${premisesDict.get(flat.premise).description})` : '',
parking: (parking != NULL_Parking) ? `${parking.description} (${premisesDict.get(parking.premise).description})` : '',
commercialPremise: (commercialPremise != NULL_CommercialPremise) ? `${commercialPremise.description} (${premisesDict.get(commercialPremise.premise).description})` : ''
flat: (flat != NULL_Flat) ? `${flat.description} (${this.premisesMap.get(flat.premise).description})` : '',
parking: (parking != NULL_Parking) ? `${parking.description} (${this.premisesMap.get(parking.premise).description})` : '',
commercialPremise: (commercialPremise != NULL_CommercialPremise) ? `${commercialPremise.description} (${this.premisesMap.get(commercialPremise.premise).description})` : ''
})
}
this.tenancyDataSource = new MatTableDataSource<DN_Tenancy>(this.tenancies)
@ -156,7 +185,25 @@ export class TenantDetailsComponent implements OnInit {
}
}
async addFee() {
async getPremises(): Promise<void> {
if ((! this.premisesMap) || (this.premisesMap.size == 0)) {
try {
this.messageService.add("Trying to load premises")
const premises = await this.premiseService.getPremises()
this.premisesMap = new Map<number, Premise>()
for (let p of premises) {
this.premisesMap.set(p.id, p)
}
this.messageService.add("Premises loaded")
} catch (err) {
this.messageService.add(`Error in getPremises: ${ JSON.stringify(err, undefined, 4) }`)
}
} else {
this.messageService.add("Premises already loaded")
}
}
async addFee(): Promise<void> {
try {
this.mapFeeButton.disabled = true
this.messageService.add(`fee: ${ JSON.stringify(this.selectedFee, undefined, 4) }`)
@ -174,6 +221,79 @@ export class TenantDetailsComponent implements OnInit {
}
}
async openTenancyMapping(): Promise<void> {
this.messageService.add("TenancyMapping opened")
this.collapseTenancyMapping = true
await this.getPremises()
if (! this.allFlats) {
let flats = await this.flatService.getFlats()
this.allFlats = []
for (let p of flats) {
this.allFlats.push({
rawFlat: p,
premise: this.premisesMap.get(p.premise).description
})
}
}
if (! this.allParkings) {
let parkings = await this.parkingService.getParkings()
this.allParkings = []
for (let p of parkings) {
this.allParkings.push({
rawParking: p,
premise: this.premisesMap.get(p.premise).description
})
}
}
if (! this.allCommercialPremises) {
let commercialPremises = await this.commercialPremiseService.getCommercialPremises()
this.allCommercialPremises = []
for (let p of commercialPremises) {
this.allCommercialPremises.push({
rawCommercialPremise: p,
premise: this.premisesMap.get(p.premise).description
})
}
}
}
async closeTenancyMapping(): Promise<void> {
this.messageService.add("TenancyMapping closed")
this.collapseTenancyMapping = false
}
flatSelected(): void {
this.newTenancy.parking = null
this.newTenancy.commercial_premise = null
}
parkingSelected(): void {
this.newTenancy.flat = null
this.newTenancy.commercial_premise = null
}
commercialPremiseSelected(): void {
this.newTenancy.parking = null
this.newTenancy.flat = null
}
async addTenancyToTenant(): Promise<void> {
try {
this.messageService.add(`Going to mapping ${JSON.stringify(this.newTenancy, undefined, 4)}`)
this.newTenancy.tenant = this.tenant.id
this.messageService.add(`new tenancy is ${JSON.stringify(this.newTenancy, undefined, 4)}`)
this.newTenancy = await this.tenancyService.postTenancy(this.newTenancy)
this.messageService.add(`New tenancy added with id ${this.newTenancy.id}`)
this.panelAddMapping.close()
this.panelTenancies.open()
this.getTenancies()
} catch (err) {
this.messageService.add(`Error in addTenancyToTenant: ${ JSON.stringify(err, undefined, 4)}`)
}
}
ngOnInit(): void {
this.getTenant()
this.getFees()

View File

@ -6,6 +6,7 @@ import jwt_decode from 'jwt-decode'
import { Observable, interval, Subject, Subscription } from 'rxjs'
import { map, takeWhile } from 'rxjs/operators'
import { authserviceBaseUrl, applicationId } from './config'
import { Router } from '@angular/router';
interface TokenTuple {
@ -24,8 +25,11 @@ export class TokenService {
private _expiryTime = new Subject<number>()
private subscription: Subscription
constructor(private http: HttpClient, private messageService: MessageService) {
}
constructor(
private http: HttpClient,
private router: Router,
private messageService: MessageService
) { }
checkAuthenticated(): boolean {
let result: boolean = false
@ -60,7 +64,15 @@ export class TokenService {
if (this.subscription && !this.subscription.closed) {
this.subscription.unsubscribe()
}
this.subscription = interval(1000).pipe(map(v => start - v)).pipe(takeWhile(v => v != 0)).subscribe(v => this._expiryTime.next(v))
this.subscription = interval(1000)
.pipe(map(v => start - v))
.pipe(takeWhile(v => v >= 0))
.subscribe((v) => {
this._expiryTime.next(v)
if (v == 0) {
this.router.navigate(['/logout'])
}
})
}
async login(login: string, password: string) : Promise<void> {

View File

@ -1,11 +1,15 @@
/* You can add global styles to this file, and also import other style files */
html, body { height: 100%; }
html, body {
height: 100%;
box-sizing: border-box;
margin: 0;
}
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
table {
width: 75%;
border-spacing: 20px;
}