stammdaten-formular/edit_data_form.py

79 lines
2.5 KiB
Python
Raw Normal View History

#!/usr/bin/env python
# encoding: utf-8
import npyscreen
import json
2020-03-14 12:40:15 +01:00
import datetime
from sys import argv
from pathlib import Path
2020-03-14 15:03:53 +01:00
from base_data_model import base_data_model
from financial_data_model import financial_data_model
from membership_data_model import membership_data_model
class FormApp(npyscreen.NPSAppManaged):
def __init__(self, filename):
super().__init__()
self.dir_path = Path(filename).absolute().parent
self.member = json.load(open(filename, 'r'))
self.base_data = base_data_model(self.member['stammdaten'])
self.financial_data = financial_data_model(self.member['finanzdaten'])
self.membership_data = membership_data_model(self.member['mitgliederdaten'])
2020-03-14 15:03:53 +01:00
def main(self):
2020-03-14 15:03:53 +01:00
f = npyscreen.Form(name='Edit Member data')
2020-03-14 15:03:53 +01:00
self.base_data.add_edit_fields(f)
self.financial_data.add_edit_fields(f)
self.membership_data.add_edit_fields(f)
f.edit()
2020-03-14 15:03:53 +01:00
def get_data_from_form(self):
data_dict = {}
data_dict['stammdaten'] = self.base_data.get_form_values_dict()
data_dict['finanzdaten'] = self.financial_data.get_form_values_dict()
data_dict['mitgliederdaten'] = self.membership_data.get_form_values_dict()
data_dict['timestamp'] = datetime.datetime.now().replace(microsecond=0).isoformat()
return data_dict
def data_has_changed(self):
return self.base_data.has_changed() | self.financial_data.has_changed() | self.membership_data.has_changed()
def get_filepath(self):
2020-03-14 15:03:53 +01:00
name = self.base_data.get_form_values_dict()['fullname']
fn = '{}_{}.json'.format('_'.join(name.split()), datetime.datetime.now().replace(microsecond=0).isoformat())
file_path = Path(self.dir_path, fn)
return file_path
2020-03-14 15:03:53 +01:00
def main(*_args):
if len(argv) > 1:
filename = argv[1]
else:
filename = Path(Path(__file__).absolute().parent, 'example.json')
app = FormApp(filename)
try:
app.run()
except Exception as e:
print(e)
return 0
2020-03-14 15:03:53 +01:00
if app.data_has_changed():
out_data = app.get_data_from_form()
outfile_path = app.get_filepath()
print(f"Writing changed Member Data to {outfile_path}")
with open(outfile_path, 'w') as outfile:
2020-03-14 15:03:53 +01:00
json.dump(out_data, outfile, sort_keys=True, indent=4)
else:
print("Nothing has changed, skipping writing file")
if __name__ == "__main__":
npyscreen.wrapper_basic(main)