Skip to content

Commit

Permalink
Added: UI repr for linked references (#344)
Browse files Browse the repository at this point in the history
  • Loading branch information
signebedi committed Sep 6, 2024
1 parent 918a712 commit c0703d3
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 12 deletions.
12 changes: 5 additions & 7 deletions libreforms_fastapi/app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1628,7 +1628,6 @@ async def api_form_get_linked_references(

for _form_name, _linked_fields in dict_of_relevant_links.items():


# read_all IS THE HIGHER PRIVILEGE OF THE TWO - SO WE SHOULD CHECK FOR THAT FIRST, AS IT
# INCLUDES read_own. https://github.com/signebedi/libreforms-fastapi/issues/307.
try:
Expand All @@ -1644,7 +1643,6 @@ async def api_form_get_linked_references(
raise HTTPException(status_code=403, detail=f"{e}")



for _linked_field in _linked_fields:
_documents = []
# This query param will only return that matches the given document_id
Expand All @@ -1654,7 +1652,7 @@ async def api_form_get_linked_references(
form_name=_form_name,
limit_users=limit_query_to,
exclude_journal=True,
collapse_data=True,
# collapse_data=True,
# sort_by_last_edited=True,
# newest_first=True,
query_params=query_params,
Expand All @@ -1665,7 +1663,7 @@ async def api_form_get_linked_references(
# Drop duplicates and sort!
unique_documents = {}
for doc in documents:
doc_id = doc['__metadata__document_id']
doc_id = doc['metadata']['document_id']

# Replace the document if this one is newer
if doc_id not in unique_documents:
Expand All @@ -1674,7 +1672,7 @@ async def api_form_get_linked_references(
# Now we have a dictionary of unique documents; we need to sort them by 'last_modified'
sorted_documents = sorted(
unique_documents.values(),
key=lambda x: datetime.fromisoformat(x['__metadata__last_modified'].replace('Z', '+00:00')),
key=lambda x: datetime.fromisoformat(x['metadata']['last_modified'].replace('Z', '+00:00')),
reverse=True
)

Expand Down Expand Up @@ -3548,8 +3546,8 @@ async def api_auth_get(
'related_user_id': x['user']['id'],
} for x in _received_relationships]

print("\n\n\n", profile_data['relationships'])
print("\n\n\n", profile_data['received_relationships'])
# print("\n\n\n", profile_data['relationships'])
# print("\n\n\n", profile_data['received_relationships'])


# Write this query to the TransactionLog
Expand Down
101 changes: 96 additions & 5 deletions libreforms_fastapi/app/templates/read_one_form.html.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,31 @@
<div class="tab-pane fade active show" id="documentContent" role="tabpanel"></div>
<div class="tab-pane fade" id="documentMetadata" role="tabpanel"></div>
</div>
<div id="documentHistory">

<div id="documentHistory"></div>

<div id="linkedRefsSection" class="mt-4" style="display: none;">
<h5>Linked References</h5>
<p>The section below will display back references made to this submission by other submissions</p>
<div class="container table-responsive" style="opacity: .7;">
<table id="linkedRefsTable" class="table table-hover table-striped table-light" style="display: none;">
<thead>
<tr>
<th>Document ID</th>
<th>Form Name</th>
<th>Details</th>
<th>Last Editor</th>
<th>Last Modified</th>
<th>Created By</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="noLinkedRefsMessage" style="display: none;">No linked references found.</div>
</div>
</div>




{% endblock %}

{% block scripts %}
Expand Down Expand Up @@ -150,6 +168,20 @@ function restoreVersion(){
}
// https://www.geeksforgeeks.org/how-to-truncate-a-string-in-javascript/
function GFG(str, maxLength) {
if (str.length > maxLength) {
return str.substring(0, maxLength) + '...';
}
return str;
}
function formatObject(obj) {
return Object.entries(obj)
.map(([key, value]) => `<strong>${key}</strong>: ${value}`)
.join(', ');
}
$(document).ready(function() {
Expand Down Expand Up @@ -454,7 +486,66 @@ $(document).ready(function() {
});
}
function fetchLinkedReferences() {
$.ajax({
url: `/api/form/get_linked_refs/${formName}/${documentId}`,
type: 'GET',
headers: {
'X-API-KEY': apiKey,
},
dataType: 'json',
success: function(response) {
if (response.length > 0) {
$('#linkedRefsSection').show(); // Show the section
$('#linkedRefsTable').show(); // Show the table
$('#noLinkedRefsMessage').hide(); // Hide the no data message
response.forEach(doc => {
let row = `<tr>
<td>
<a href="/ui/form/read_one/${doc['metadata']['form_name']}/${doc['metadata']['document_id']}">${doc.metadata.document_id}</a>
</td>
<td>${doc.metadata.form_name.replace(/_/g, ' ')}</td>
<td>${GFG(formatObject(doc['data']), 150)}</td>
<td>
<a target="_blank" href="/ui/auth/p/${doc['metadata']['last_editor']}" class="badge bg-primary text-decoration-none" style=" {%if not config['OTHER_PROFILES_ENABLED'] and not request.user.site_admin%} pointer-events: none;{%endif%}" aria-label="Link to ${doc['metadata']['last_editor']}">
${doc['metadata']['last_editor']}
</a>
</td>
<td><span title="${doc['metadata']['last_modified']}">${prettifyTimeDiff(doc['metadata']['last_modified'], "{{config['TIMEZONE']|string}}")}</span></td>
<td>
<a target="_blank" href="/ui/auth/p/${doc['metadata']['created_by']}" class="badge bg-primary text-decoration-none" style=" {%if not config['OTHER_PROFILES_ENABLED'] and not request.user.site_admin%} pointer-events: none;{%endif%}" aria-label="Link to ${doc['metadata']['created_by']}">
${doc['metadata']['created_by']}
</a>
</td>
<td><span title="${doc['metadata']['created_at']}">${prettifyTimeDiff(doc['metadata']['created_at'], "{{config['TIMEZONE']|string}}")}</span></td>
</tr>`;
$('#linkedRefsTable tbody').append(row);
});
$('#linkedRefsTable').DataTable({
"ordering": true,
"order": [[4, "desc"]],
"lengthChange": false,
"info": false,
// "searching": false,
"paging": false
});
} else {
$('#linkedRefsSection').hide(); // Hide the section
$('#noLinkedRefsMessage').show(); // Show the no data message
}
},
error: function(xhr) {
console.error('Failed to fetch linked references', xhr.responseText);
$('#linkedRefsSection').hide(); // Also hide on error
$('#noLinkedRefsMessage').show(); // Show the no data message
}
});
}
fetchDocument();
fetchLinkedReferences();
});
</script>

Expand Down

0 comments on commit c0703d3

Please sign in to comment.