Commit 45216535 authored by Roque's avatar Roque

erp5_hal_json_style: moving form definition to hateoas script

parent fcd8ef76
#return "fake hateoas return!!!"
"""Hello. This will be long because this godly script does almost everything. """Hello. This will be long because this godly script does almost everything.
It **always** return a JSON reponse in HATEOAS format specification. It **always** return a JSON reponse in HATEOAS format specification.
...@@ -47,6 +49,7 @@ When handling form, we can expect field values to be stored in REQUEST.form in t ...@@ -47,6 +49,7 @@ When handling form, we can expect field values to be stored in REQUEST.form in t
- python-object parsed from raw values under <field.id> - python-object parsed from raw values under <field.id>
""" """
from ZTUtils import make_query from ZTUtils import make_query
import json import json
from base64 import urlsafe_b64encode, urlsafe_b64decode from base64 import urlsafe_b64encode, urlsafe_b64decode
...@@ -63,6 +66,8 @@ from Products.ERP5Type.Utils import UpperCase ...@@ -63,6 +66,8 @@ from Products.ERP5Type.Utils import UpperCase
from Products.ZSQLCatalog.SQLCatalog import Query, ComplexQuery from Products.ZSQLCatalog.SQLCatalog import Query, ComplexQuery
from collections import OrderedDict from collections import OrderedDict
log("[DEBUG] ERP5Document_getHateoas script was called!!!!!!")
MARKER = [] MARKER = []
COUNT_LIMIT = 1000 COUNT_LIMIT = 1000
...@@ -72,7 +77,6 @@ if REQUEST is None: ...@@ -72,7 +77,6 @@ if REQUEST is None:
if response is None: if response is None:
response = REQUEST.RESPONSE response = REQUEST.RESPONSE
def isFieldType(field, type_name): def isFieldType(field, type_name):
if field.meta_type == 'ProxyField': if field.meta_type == 'ProxyField':
field = field.getRecursiveTemplateField() field = field.getRecursiveTemplateField()
...@@ -765,6 +769,7 @@ def renderField(traversed_document, field, form, value=MARKER, meta_type=None, k ...@@ -765,6 +769,7 @@ def renderField(traversed_document, field, form, value=MARKER, meta_type=None, k
# get embedded form definition # get embedded form definition
embedded_form = getattr(formbox_context, field.get_value('formbox_target_id')) embedded_form = getattr(formbox_context, field.get_value('formbox_target_id'))
# renderForm mutates `embedded_document` therefor no return/assignment # renderForm mutates `embedded_document` therefor no return/assignment
log("[DEBUG] calling renderForm from renderField")
renderForm(formbox_context, embedded_form, embedded_document, key_prefix=key) renderForm(formbox_context, embedded_form, embedded_document, key_prefix=key)
# fix editability which is hard-coded to 0 in `renderForm` implementation # fix editability which is hard-coded to 0 in `renderForm` implementation
embedded_document['form_id']['editable'] = field.get_value("editable") embedded_document['form_id']['editable'] = field.get_value("editable")
...@@ -834,6 +839,9 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti ...@@ -834,6 +839,9 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti
# prevent allowing editing if user doesn't have permission # prevent allowing editing if user doesn't have permission
include_action = False include_action = False
# [HARDCODED] edit is allow until I set the permissions properly
# TODO: solve this
include_action = True
if (include_action): if (include_action):
# Form action # Form action
response_dict['_actions'] = { response_dict['_actions'] = {
...@@ -882,6 +890,7 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti ...@@ -882,6 +890,7 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti
'name': form.id 'name': form.id
} }
log("[DEBUG] calling calculateHateoas method from renderForm")
response_dict['_embedded'] = { response_dict['_embedded'] = {
'form_definition': calculateHateoas( 'form_definition': calculateHateoas(
traversed_document=form, traversed_document=form,
...@@ -890,7 +899,8 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti ...@@ -890,7 +899,8 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti
is_portal=False, is_portal=False,
mode='traverse', mode='traverse',
restricted=1, restricted=1,
view='view' view='view',
form_definition=True
) )
} }
...@@ -1050,6 +1060,7 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti ...@@ -1050,6 +1060,7 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti
# addressable by the user = have actions (object_view) attached to it # addressable by the user = have actions (object_view) attached to it
# BUT! when Report Section defines `path` that is the new context for # BUT! when Report Section defines `path` that is the new context for
# form rendering and subsequent searches... # form rendering and subsequent searches...
log("[DEBUG] calling renderForm recursively from renderForm")
renderForm(traversed_document if not report_item.path else report_context, renderForm(traversed_document if not report_item.path else report_context,
report_form, report_form,
report_result, report_result,
...@@ -1131,7 +1142,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1131,7 +1142,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
response=None, view=None, mode=None, response=None, view=None, mode=None,
query=None, select_list=None, limit=None, form=None, query=None, select_list=None, limit=None, form=None,
relative_url=None, restricted=None, list_method=None, relative_url=None, restricted=None, list_method=None,
default_param_json=None, form_relative_url=None, extra_param_json=None): default_param_json=None, form_relative_url=None, extra_param_json=None, form_definition=False):
if relative_url: if relative_url:
try: try:
...@@ -1147,13 +1158,20 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1147,13 +1158,20 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
if extra_param_json is None: if extra_param_json is None:
extra_param_json = {} extra_param_json = {}
is_context_appcache = False
try:
href = traversed_document.Base_getRequestUrl()
except:
is_context_appcache = True
href = "https://softinst112382.host.vifib.net/erp5/web_site_module/officejs_discussion_tool/portal_skins/erp5_officejs_jio_connector/HTMLPost_viewAsJio/ERP5Form_viewAsJio"
result_dict = { result_dict = {
'_debug': mode, '_debug': mode,
'_links': { '_links': {
"self": { "self": {
# XXX Include query parameters # XXX Include query parameters
# FIXME does not work in case of bulk queries # FIXME does not work in case of bulk queries
"href": traversed_document.Base_getRequestUrl() "href": href #traversed_document.Base_getRequestUrl()
}, },
# Always inform about site root # Always inform about site root
"site_root": { "site_root": {
...@@ -1201,9 +1219,9 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1201,9 +1219,9 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
response.setStatus(401) response.setStatus(401)
return "" return ""
elif mime_type != traversed_document.Base_handleAcceptHeader([mime_type]): elif not is_context_appcache and mime_type != traversed_document.Base_handleAcceptHeader([mime_type]):
response.setStatus(406) response.setStatus(406)
return "" return ""
elif (mode == 'root') or (mode == 'traverse'): elif (mode == 'root') or (mode == 'traverse'):
## ##
...@@ -1233,6 +1251,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1233,6 +1251,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
for k, v in byteify(extra_param_json.items()): for k, v in byteify(extra_param_json.items()):
REQUEST.set(k, v) REQUEST.set(k, v)
# Add a link to the portal type if possible # Add a link to the portal type if possible
if not is_portal: if not is_portal:
# traversed_document should always have its Portal Type in ERP5 Portal Types # traversed_document should always have its Portal Type in ERP5 Portal Types
...@@ -1264,19 +1283,40 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1264,19 +1283,40 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
} }
# Find current action URL and extract embedded view # Find current action URL and extract embedded view
erp5_action_dict = portal.Base_filterDuplicateActions( try:
portal.portal_actions.listFilteredActionsFor(traversed_document)) erp5_action_dict = portal.Base_filterDuplicateActions(
portal.portal_actions.listFilteredActionsFor(traversed_document))
except AttributeError as error:
erp5_action_dict = {}
for erp5_action_key in erp5_action_dict.keys(): for erp5_action_key in erp5_action_dict.keys():
for view_action in erp5_action_dict[erp5_action_key]: for view_action in erp5_action_dict[erp5_action_key]:
# Try to embed the form in the result # Try to embed the form in the result
if (view == view_action['id']): if (view == view_action['id']):
current_action = parseActionUrl('%s' % view_action['url']) # current action/view being rendered current_action = parseActionUrl('%s' % view_action['url']) # current action/view being rendered
if current_action.get('view_id', None) is not None:
log("[DEBUG] current_action['view_id'] after iterate on Base_filterDuplicateActions")
log("[DEBUG] " + str(current_action['view_id']))
if is_context_appcache:
current_action['url'] = 'https://softinst112382.host.vifib.net/erp5/web_site_module/officejs_discussion_tool/portal_skins/erp5_officejs_jio_connector/HTMLPost_viewAsJio/ERP5Form_viewAsJio'
current_action['view_id'] = "ERP5Form_viewAsJio"
current_action['params'] = {}
log("[DEBUG] current_action['view_id'] after hardcoded is_context_appcache")
log("[DEBUG] " + str(current_action['view_id']))
if view and (view != 'view') and (current_action.get('view_id', None) is None): if view and (view != 'view') and (current_action.get('view_id', None) is None):
# XXX Allow to directly render a form # XXX Allow to directly render a form
current_action['view_id'] = view current_action['view_id'] = view
current_action['url'] = '%s/%s' % (traversed_document.getRelativeUrl(), view) current_action['url'] = '%s/%s' % (traversed_document.getRelativeUrl(), view)
current_action['params'] = {} current_action['params'] = {}
log("[DEBUG] current_action['view_id'] after assign view")
log("[DEBUG] " + str(current_action['view_id']))
if current_action.get('view_id', None) is not None:
log("[DEBUG] FINAL current_action['view_id']")
log("[DEBUG] " + str(current_action['view_id']))
# If we have current action definition we are able to render embedded view # If we have current action definition we are able to render embedded view
# which should be a "ERP5 Form" but in reality can be anything # which should be a "ERP5 Form" but in reality can be anything
...@@ -1321,6 +1361,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1321,6 +1361,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
# REQUEST but expect all (formerly) URL query parameters to appear in their **kw # REQUEST but expect all (formerly) URL query parameters to appear in their **kw
# thus we send extra_param_json (=rjs way of passing parameters to REQUEST) as # thus we send extra_param_json (=rjs way of passing parameters to REQUEST) as
# selection_params so they get into callable's **kw. # selection_params so they get into callable's **kw.
log("[DEBUG] calling renderForm from calculateHateoas -core-")
renderForm(traversed_document, view_instance, embedded_dict, renderForm(traversed_document, view_instance, embedded_dict,
selection_params=extra_param_json, extra_param_json=extra_param_json) selection_params=extra_param_json, extra_param_json=extra_param_json)
...@@ -1984,6 +2025,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1984,6 +2025,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
response.setStatus(405) response.setStatus(405)
return "" return ""
log("[DEBUG] calling renderForm from calculateHateoas - mode 'search'")
renderForm(traversed_document, form, result_dict, extra_param_json=extra_param_json) renderForm(traversed_document, form, result_dict, extra_param_json=extra_param_json)
elif mode == 'newContent': elif mode == 'newContent':
...@@ -2071,10 +2113,79 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -2071,10 +2113,79 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
else: else:
raise NotImplementedError("Unsupported mode %s" % mode) raise NotImplementedError("Unsupported mode %s" % mode)
#if form has my_form_definition field, set it for the json-form
if "_embedded" in result_dict:
if "_view" in result_dict["_embedded"]:
if "my_form_definition" in result_dict["_embedded"]["_view"]:
result_dict["_embedded"]["_view"]["my_form_definition"]["default"] = result_dict["_embedded"]["_view"]["_embedded"]["form_definition"].copy()
result_dict["_embedded"]["_view"]["my_form_definition"]["default"]["group_list"] = result_dict["group_list"]
result_dict["_embedded"]["_view"]["my_form_definition"]["default"]["_actions"] = result_dict["_embedded"]["_view"]["_actions"]
# [HARDCODED] the form definition must contain a field_info_dict with all the rendered fields
# for now is hardcoded only for "HTML Post"
# TODO: achieve this iterating the group_list fields and calling renderField
if result_dict["title"] == "HTML Post":
result_dict["_embedded"]["_view"]["my_form_definition"]["default"]["field_info_dict"] = {
"my_title": {
"title": "Title",
"default": "Undefined title",
"editable": 1,
"key": "title",
"type": "StringField"
},
"my_text_content": {
"editable": 1,
"key": "text_content",
"renderjs_extra": '{"editor": "fck_editor",' +
'"maximize": true}',
"type": "GadgetField",
"url": "gadget_editor.html",
"sandbox": "public"
},
"my_source_reference": {
"title": "source reference",
"default": "Undefined ref",
"editable": 0,
"key": "source_reference",
"type": "StringField"
},
"my_portal_type": {
"title": "Portal type",
"default": "Undefined title",
"editable": 0,
"key": "portal_type",
"type": "StringField"
},
"your_modification_date": {
"title": "modification_date",
"default": "",
"editable": 0,
"key": "modification_date",
"type": "StringField"
},
"my_translated_validation_state_title": {
"title": "translated",
"default": "Undefined translated",
"editable": 0,
"key": "translated",
"type": "StringField"
},
"form_id": {
"title": "form id",
"default": "Undefined form id",
"editable": 0,
"key": "form_id",
"type": "StringField"
}
}
return result_dict return result_dict
log(" ")
log("[DEBUG] beggining of script -sentences after function definition-")
log(" ")
mime_type = 'application/hal+json' mime_type = 'application/hal+json'
portal = context.getPortalObject() portal = context.getPortalObject()
sql_catalog = portal.portal_catalog.getSQLCatalog() sql_catalog = portal.portal_catalog.getSQLCatalog()
...@@ -2104,6 +2215,10 @@ temp_is_site_root = (temp_traversed_document.getPath() == site_root.getPath()) ...@@ -2104,6 +2215,10 @@ temp_is_site_root = (temp_traversed_document.getPath() == site_root.getPath())
temp_is_portal = (temp_traversed_document.getPath() == portal.getPath()) temp_is_portal = (temp_traversed_document.getPath() == portal.getPath())
response.setHeader('Content-Type', mime_type) response.setHeader('Content-Type', mime_type)
log(" ")
log("[DEBUG] calling calculateHateoas method from beggining")
log(" ")
hateoas = calculateHateoas(is_portal=temp_is_portal, is_site_root=temp_is_site_root, hateoas = calculateHateoas(is_portal=temp_is_portal, is_site_root=temp_is_site_root,
traversed_document=temp_traversed_document, traversed_document=temp_traversed_document,
relative_url=relative_url, relative_url=relative_url,
...@@ -2113,6 +2228,11 @@ hateoas = calculateHateoas(is_portal=temp_is_portal, is_site_root=temp_is_site_r ...@@ -2113,6 +2228,11 @@ hateoas = calculateHateoas(is_portal=temp_is_portal, is_site_root=temp_is_site_r
default_param_json=default_param_json, default_param_json=default_param_json,
form_relative_url=form_relative_url, form_relative_url=form_relative_url,
extra_param_json=extra_param_json) extra_param_json=extra_param_json)
log(" ")
log("[DEBUG] returning final hateoas dict!!!")
log(" ")
if hateoas == "": if hateoas == "":
return hateoas return hateoas
else: else:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment