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.
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
- python-object parsed from raw values under <field.id>
"""
from ZTUtils import make_query
import json
from base64 import urlsafe_b64encode, urlsafe_b64decode
......@@ -63,6 +66,8 @@ from Products.ERP5Type.Utils import UpperCase
from Products.ZSQLCatalog.SQLCatalog import Query, ComplexQuery
from collections import OrderedDict
log("[DEBUG] ERP5Document_getHateoas script was called!!!!!!")
MARKER = []
COUNT_LIMIT = 1000
......@@ -72,7 +77,6 @@ if REQUEST is None:
if response is None:
response = REQUEST.RESPONSE
def isFieldType(field, type_name):
if field.meta_type == 'ProxyField':
field = field.getRecursiveTemplateField()
......@@ -765,6 +769,7 @@ def renderField(traversed_document, field, form, value=MARKER, meta_type=None, k
# get embedded form definition
embedded_form = getattr(formbox_context, field.get_value('formbox_target_id'))
# renderForm mutates `embedded_document` therefor no return/assignment
log("[DEBUG] calling renderForm from renderField")
renderForm(formbox_context, embedded_form, embedded_document, key_prefix=key)
# fix editability which is hard-coded to 0 in `renderForm` implementation
embedded_document['form_id']['editable'] = field.get_value("editable")
......@@ -834,6 +839,9 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti
# prevent allowing editing if user doesn't have permission
include_action = False
# [HARDCODED] edit is allow until I set the permissions properly
# TODO: solve this
include_action = True
if (include_action):
# Form action
response_dict['_actions'] = {
......@@ -882,6 +890,7 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti
'name': form.id
}
log("[DEBUG] calling calculateHateoas method from renderForm")
response_dict['_embedded'] = {
'form_definition': calculateHateoas(
traversed_document=form,
......@@ -890,7 +899,8 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti
is_portal=False,
mode='traverse',
restricted=1,
view='view'
view='view',
form_definition=True
)
}
......@@ -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
# BUT! when Report Section defines `path` that is the new context for
# form rendering and subsequent searches...
log("[DEBUG] calling renderForm recursively from renderForm")
renderForm(traversed_document if not report_item.path else report_context,
report_form,
report_result,
......@@ -1131,7 +1142,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
response=None, view=None, mode=None,
query=None, select_list=None, limit=None, form=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:
try:
......@@ -1147,13 +1158,20 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
if extra_param_json is None:
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 = {
'_debug': mode,
'_links': {
"self": {
# XXX Include query parameters
# 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
"site_root": {
......@@ -1201,9 +1219,9 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
response.setStatus(401)
return ""
elif mime_type != traversed_document.Base_handleAcceptHeader([mime_type]):
response.setStatus(406)
return ""
elif not is_context_appcache and mime_type != traversed_document.Base_handleAcceptHeader([mime_type]):
response.setStatus(406)
return ""
elif (mode == 'root') or (mode == 'traverse'):
##
......@@ -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()):
REQUEST.set(k, v)
# Add a link to the portal type if possible
if not is_portal:
# 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,
}
# Find current action URL and extract embedded view
erp5_action_dict = portal.Base_filterDuplicateActions(
portal.portal_actions.listFilteredActionsFor(traversed_document))
try:
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 view_action in erp5_action_dict[erp5_action_key]:
# Try to embed the form in the result
if (view == view_action['id']):
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):
# XXX Allow to directly render a form
current_action['view_id'] = view
current_action['url'] = '%s/%s' % (traversed_document.getRelativeUrl(), view)
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
# 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,
# 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
# selection_params so they get into callable's **kw.
log("[DEBUG] calling renderForm from calculateHateoas -core-")
renderForm(traversed_document, view_instance, embedded_dict,
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,
response.setStatus(405)
return ""
log("[DEBUG] calling renderForm from calculateHateoas - mode 'search'")
renderForm(traversed_document, form, result_dict, extra_param_json=extra_param_json)
elif mode == 'newContent':
......@@ -2071,10 +2113,79 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
else:
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
log(" ")
log("[DEBUG] beggining of script -sentences after function definition-")
log(" ")
mime_type = 'application/hal+json'
portal = context.getPortalObject()
sql_catalog = portal.portal_catalog.getSQLCatalog()
......@@ -2104,6 +2215,10 @@ temp_is_site_root = (temp_traversed_document.getPath() == site_root.getPath())
temp_is_portal = (temp_traversed_document.getPath() == portal.getPath())
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,
traversed_document=temp_traversed_document,
relative_url=relative_url,
......@@ -2113,6 +2228,11 @@ hateoas = calculateHateoas(is_portal=temp_is_portal, is_site_root=temp_is_site_r
default_param_json=default_param_json,
form_relative_url=form_relative_url,
extra_param_json=extra_param_json)
log(" ")
log("[DEBUG] returning final hateoas dict!!!")
log(" ")
if hateoas == "":
return hateoas
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