Skip to content

Commit

Permalink
Bones: continue form data
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexanderWatzinger committed Jan 27, 2025
1 parent 797b208 commit 4af8397
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 138 deletions.
6 changes: 3 additions & 3 deletions openatlas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
from openatlas.models.logger import Logger
from openatlas.api import api
from openatlas.views import (
admin, ajax, annotation, arche, changelog, entity, entity_index, error,
export, file, hierarchy, index, imports, link, login, model, note, overlay,
profile, search, sql, tools, type as type_, user, vocabs)
admin, ajax, annotation, arche, bones, changelog, entity, entity_index,
error, export, file, hierarchy, index, imports, link, login, model, note,
overlay, profile, search, sql, tools, type as type_, user, vocabs)


@babel.localeselector
Expand Down
2 changes: 2 additions & 0 deletions openatlas/display/classes_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,8 @@ def add_tabs(self) -> None:
self.structure = entity.get_structure()
if self.structure:
for item in self.structure['subunits']:
if item.class_.name == 'bone':
continue
name = 'artifact' if item.class_.view == 'artifact' \
else item.class_.name
self.tabs[name].table.rows.append(get_base_table_data(item))
Expand Down
10 changes: 6 additions & 4 deletions openatlas/models/bones.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,26 @@ def create_bones(super_: Entity, name: str, category: dict[str, Any]):
break
if not bones_exist:
add_bone(super_, name, category)
add_values()
add_values(super_, category)
else:
update_values()
update_values(super_, category)


def add_bone(super_: Entity, name: str, category: dict[str, Any]):
entity = Entity.insert('bone', name)
entity.link('P46', super_, inverse=True)
# entity.link('P2', )
if 'subs' in category:
for name, sub in category['subs'].items():
# print(sub['data'])
add_bone(entity, name, sub)


def add_values():
def add_values(entity: Entity, category: dict[str, Any]):
pass


def update_values():
def update_values(entity: Entity, category: dict[str, Any]):
pass


Expand Down
1 change: 1 addition & 0 deletions openatlas/models/openatlas_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

view_class_mapping = {
'actor': ['person', 'group'],
'bone': [],
'event': [
'activity', 'acquisition', 'creation', 'event', 'modification', 'move',
'production'],
Expand Down
147 changes: 147 additions & 0 deletions openatlas/views/bones.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
from typing import Any

from flask import flash, g, render_template, url_for
from flask_babel import lazy_gettext as _
from flask_wtf import FlaskForm
from markupsafe import Markup
from werkzeug.wrappers import Response
from wtforms import IntegerField, SelectField

from openatlas import app
from openatlas.database.connect import Transaction
from openatlas.display.tab import Tab
from openatlas.display.util import required_group
from openatlas.display.util2 import is_authorized, manual
from openatlas.forms.field import SubmitField
from openatlas.models.bones import bone_inventory, create_bones
from openatlas.models.entity import Entity
from openatlas.models.type import Type
from openatlas.views.tools import tools_start_crumbs


@app.route('/tools/bones/<int:id_>')
@required_group('readonly')
def bones(id_: int) -> str | Response:
entity = Entity.get_by_id(id_, types=True)
buttons = [manual('tools/anthropological_analyses')]
if is_authorized('contributor'):
pass
return render_template(
'tabs.html',
entity=entity,
tabs={
'info': Tab(
'bones',
render_template(
'tools/bones.html',
entity=entity,
data=bone_inventory),
buttons=buttons)},
crumbs=tools_start_crumbs(entity) + [
[_('tools'), url_for('tools_index', id_=entity.id)],
_('bone inventory')])


@app.route('/tools/bones_update/<int:id_>/<category>', methods=['GET', 'POST'])
@required_group('contributor')
def bones_update(id_: int, category: str) -> str | Response:
entity = Entity.get_by_id(id_, types=True)
form = bones_form(entity, category)
current_bones = bone_inventory[category.replace('_', ' ')]
if form.validate_on_submit():
if current_bones['preservation']:
current_bones['data'] = getattr(form, category).data
bones_add_form_data_to_structure(form, current_bones)
try:
Transaction.begin()
create_bones(entity, category.replace('_', ' '), current_bones)
Transaction.commit()
except Exception as e: # pragma: no cover
Transaction.rollback()
g.logger.log('error', 'database', 'transaction failed', e)
flash(_('error transaction'), 'error')

return render_template(
'tabs.html',
entity=entity,
tabs={
'info': Tab(
'bones',
content=
Markup(f'<form method="post">{form.csrf_token}') +
bone_rows(form, category, current_bones) +
form.save +
Markup('</form>'),
buttons=[manual('tools/anthropological_analyses')])},
crumbs=tools_start_crumbs(entity) + [
[_('tools'), url_for('tools_index', id_=entity.id)],
[_('bone inventory'), url_for('bones', id_=entity.id)],
_('edit')])


def bones_add_form_data_to_structure(
form: FlaskForm,
structure_: dict[str, Any]):
if 'subs' in structure_:
for label, value in structure_['subs'].items():
if value['preservation']:
value['data'] = getattr(form, label.replace(' ', '-')).data
if 'subs' in value:
for item in value['subs'].values():
bones_add_form_data_to_structure(form, item)


def bones_form(entity: Entity, category: str) -> Any:
class Form(FlaskForm):
pass

inventory = bone_inventory[category.replace('_', ' ')]
options = {
g.types[id_].name: id_ for id_
in Type.get_hierarchy('Bone preservation').subs}
choices = [
('', _('undefined')),
(options['0%'], '0%'),
(options['1-24%'], '1-24%'),
(options['25-74%'], '25-74%'),
(options['75-99%'], '75-99%'),
(options['100%'], '100%')]
if inventory['preservation'] == 'percent':
setattr(
Form,
category.replace(' ', '-'),
SelectField(category, choices=choices))
for label, sub in inventory['subs'].items():
bone_fields_recursive(Form, label, sub, choices)
setattr(Form, 'save', SubmitField(_('save')))
return Form()


def bone_fields_recursive(form, label, item, choices):
if item['preservation'] == 'percent':
setattr(
form,
label.replace(' ', '-'),
SelectField(label, choices=choices))
elif item['preservation'] == 'number':
setattr(form, label.replace(' ', '-'), IntegerField())
if 'subs' in item:
for label, sub in item['subs'].items():
bone_fields_recursive(form, label, sub, choices)


def bone_rows(
form: Any,
label: str,
item: dict[str, Any],
offset: float = 0):
html = Markup(
f'<div style="margin:0.5em;margin-left:{0.5 + offset * 2}em">'
f'<span style="margin-right:2em;">{label.replace("_", " ")}</span>')
if item['preservation']:
html += str(getattr(form, label.replace(' ', '-')))
html += Markup('</div>')
if 'subs' in item:
for label, sub in item['subs'].items():
html += bone_rows(form, label, sub, offset + 0.5)
return html
131 changes: 0 additions & 131 deletions openatlas/views/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from flask import flash, g, json, render_template, request, url_for
from flask_babel import lazy_gettext as _
from flask_wtf import FlaskForm
from markupsafe import Markup
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from wtforms import IntegerField, SelectField, StringField
Expand All @@ -17,11 +16,9 @@
from openatlas.display.util2 import is_authorized, manual
from openatlas.forms.display import display_form
from openatlas.forms.field import SubmitField
from openatlas.models.bones import create_bones, bone_inventory
from openatlas.models.entity import Entity, Link
from openatlas.models.tools import (
SexEstimation, get_carbon_link, get_sex_types, update_carbon)
from openatlas.models.type import Type


def name_result(result: float) -> str:
Expand Down Expand Up @@ -270,131 +267,3 @@ class Form(FlaskForm):
[_('tools'), url_for('tools_index', id_=entity.id)],
[_('radiocarbon dating'), url_for('carbon_update', id_=entity.id)],
_('edit')])


@app.route('/tools/bones/<int:id_>')
@required_group('readonly')
def bones(id_: int) -> str | Response:
entity = Entity.get_by_id(id_, types=True)
buttons = [manual('tools/anthropological_analyses')]
if is_authorized('contributor'):
pass
return render_template(
'tabs.html',
entity=entity,
tabs={
'info': Tab(
'bones',
render_template(
'tools/bones.html',
entity=entity,
data=bone_inventory),
buttons=buttons)},
crumbs=tools_start_crumbs(entity) + [
[_('tools'), url_for('tools_index', id_=entity.id)],
_('bone inventory')])


@app.route('/tools/bones_update/<int:id_>/<category>', methods=['GET', 'POST'])
@required_group('contributor')
def bones_update(id_: int, category: str) -> str | Response:
entity = Entity.get_by_id(id_, types=True)
form = bones_form(entity, category)
current_bones = bone_inventory[category.replace('_', ' ')]
if form.validate_on_submit():
if current_bones['preservation']:
current_bones['data'] = getattr(form, category).data
bones_add_form_data_to_structure(form, current_bones)
try:
Transaction.begin()
create_bones(entity, category.replace('_', ' '), current_bones)
Transaction.commit()
except Exception as e: # pragma: no cover
Transaction.rollback()
g.logger.log('error', 'database', 'transaction failed', e)
flash(_('error transaction'), 'error')

return render_template(
'tabs.html',
entity=entity,
tabs={
'info': Tab(
'bones',
content=
Markup(f'<form method="post">{form.csrf_token}') +
bone_rows(form, category, current_bones) +
form.save +
Markup('</form>'),
buttons=[manual('tools/anthropological_analyses')])},
crumbs=tools_start_crumbs(entity) + [
[_('tools'), url_for('tools_index', id_=entity.id)],
[_('bone inventory'), url_for('bones', id_=entity.id)],
_('edit')])


def bones_add_form_data_to_structure(
form: FlaskForm,
structure_: dict[str, Any]):
if 'subs' in structure_:
for label, value in structure_['subs'].items():
if value['preservation']:
value['data'] = getattr(form, label.replace(' ', '-')).data
if 'subs' in value:
for item in value['subs'].values():
bones_add_form_data_to_structure(form, item)


def bones_form(entity: Entity, category: str) -> Any:
class Form(FlaskForm):
pass

inventory = bone_inventory[category.replace('_', ' ')]
options = {
g.types[id_].name: id_ for id_
in Type.get_hierarchy('Bone preservation').subs}
choices = [
(0, _('undefined')),
(options['0%'], '0%'),
(options['1-24%'], '1-24%'),
(options['25-74%'], '25-74%'),
(options['75-99%'], '75-99%'),
(options['100%'], '100%')]
if inventory['preservation'] == 'percent':
setattr(
Form,
category.replace(' ', '-'),
SelectField(category, choices=choices))
for label, sub in inventory['subs'].items():
bone_fields_recursive(Form, label, sub, choices)
setattr(Form, 'save', SubmitField(_('save')))
return Form()


def bone_fields_recursive(form, label, item, choices):
if item['preservation'] == 'percent':
setattr(
form,
label.replace(' ', '-'),
SelectField(label, choices=choices))
elif item['preservation'] == 'number':
setattr(form, label.replace(' ', '-'), IntegerField())
if 'subs' in item:
for label, sub in item['subs'].items():
bone_fields_recursive(form, label, sub, choices)


def bone_rows(
form: Any,
label: str,
item: dict[str, Any],
offset: float = 0):
html = Markup(
f'<div style="margin:0.5em;margin-left:{0.5 + offset * 2}em">'
f'<span style="margin-right:2em;">{label.replace("_", " ")}</span>')
if item['preservation']:
html += str(getattr(form, label.replace(' ', '-')))
html += Markup('</div>')
if 'subs' in item:
for label, sub in item['subs'].items():
html += bone_rows(form, label, sub, offset + 0.5)
return html

0 comments on commit 4af8397

Please sign in to comment.