-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Custom operations on Documents and Parts #40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
60664f4
add custom operation event for docs
848c3bd
add custom operation for part
770639d
Merge branch 'main' of github.com:cslab/functions-sdk-python into cus…
6c4303a
Merge branch 'main' of github.com:cslab/functions-sdk-python into cus…
b0a3353
feat: Add CustomOperationDocumentEvent and CustomOperationPartEvent t…
61066f6
feat: Add example for generating a basic report using custom operations
d27fe48
Update docs/examples/basic_report.md
jens-kuerten b78654c
Update docs/examples/basic_report.md
jens-kuerten aad2cd5
clarify why check_access is false
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| from typing import Literal | ||
|
|
||
| from pydantic import BaseModel, Field | ||
|
|
||
| from csfunctions.objects import Document, Part | ||
|
|
||
| from .base import BaseEvent, EventNames | ||
|
|
||
|
|
||
| # ----------- DOCUMENTS ----------- | ||
| class CustomOperationDocumentData(BaseModel): | ||
| documents: list[Document] = Field(..., description="List of documents that the custom operation was called on") | ||
| parts: list[Part] = Field(..., description="List of parts that belong to the documents") | ||
|
|
||
|
|
||
| class CustomOperationDocumentEvent(BaseEvent): | ||
| """ | ||
| Event triggered when a custom operation is called on a document. | ||
| """ | ||
|
|
||
| name: Literal[EventNames.CUSTOM_OPERATION_DOCUMENT] = EventNames.CUSTOM_OPERATION_DOCUMENT | ||
| data: CustomOperationDocumentData | ||
|
|
||
|
|
||
| # ----------- PARTS ----------- | ||
|
|
||
|
|
||
| class CustomOperationPartData(BaseModel): | ||
| parts: list[Part] = Field(..., description="List of parts that the custom operation was called on") | ||
| documents: list[Document] = Field(..., description="List of documents that belong to the parts") | ||
|
|
||
|
|
||
| class CustomOperationPartEvent(BaseEvent): | ||
| """ | ||
| Event triggered when a custom operation is called on a part. | ||
| """ | ||
|
|
||
| name: Literal[EventNames.CUSTOM_OPERATION_PART] = EventNames.CUSTOM_OPERATION_PART | ||
| data: CustomOperationPartData |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| # Basic Report | ||
|
|
||
| This example shows how you can use custom operations to generate a basic report on a document and attach that report to the document. | ||
|
|
||
| The example uses [python-docx](https://python-docx.readthedocs.io/en/latest/) to generate a Word file. | ||
| To install the library in your Function, you need to add it to the `requirements.txt`: | ||
|
|
||
| ```requirements.txt | ||
| contactsoftware-functions | ||
| python-docx | ||
| ``` | ||
|
|
||
| ```python | ||
| import os | ||
| import tempfile | ||
| from datetime import datetime | ||
|
|
||
| import requests | ||
| from docx import Document as DocxDocument | ||
|
|
||
| from csfunctions import MetaData, Service | ||
| from csfunctions.events import CustomOperationDocumentEvent | ||
| from csfunctions.objects import Document | ||
|
|
||
|
|
||
| def simple_report(metadata: MetaData, event: CustomOperationDocumentEvent, service: Service): | ||
| """ | ||
| Generates a simple report for each document the custom operation is called on. | ||
| The report contains basic information about the document and is saved as a new file | ||
| named "myreport.docx" within the document. | ||
| """ | ||
|
|
||
| for document in event.data.documents: | ||
| # generate a report for each document | ||
| report = _create_report(document, metadata) | ||
|
|
||
| temp_file_path = None | ||
| try: | ||
| # we need to use a tempfile, because the rest of the filesystem is read-only | ||
| with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as tmp: | ||
| temp_file_path = tmp.name | ||
| report.save(temp_file_path) | ||
|
|
||
| # check if the document already has a report file, so we can overwrite it | ||
| file_name = "myreport.docx" | ||
| existing_file = next((file for file in document.files if file.cdbf_name == file_name), None) | ||
|
|
||
| with open(temp_file_path, "rb") as file_stream: | ||
| if existing_file: | ||
| # overwrite the existing report file | ||
| # we set check_access to false to allow attaching reports to released documents | ||
| service.file_upload.upload_file_content( | ||
| file_object_id=existing_file.cdb_object_id, stream=file_stream, check_access=False | ||
| ) | ||
| else: | ||
| # create a new one | ||
| # we set check_access to false to allow attaching reports to released documents | ||
| service.file_upload.upload_new_file( | ||
| parent_object_id=document.cdb_object_id, # type: ignore | ||
| filename=file_name, | ||
| stream=file_stream, | ||
| check_access=False, | ||
jens-kuerten marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
| finally: | ||
| if temp_file_path: | ||
| # Clean up temp file | ||
| os.unlink(temp_file_path) | ||
|
|
||
|
|
||
| def _fetch_person_name(persno: str, metadata: MetaData) -> str | None: | ||
| """Fetches the name of a person given their personnel number via GraphQL.""" | ||
| graphql_url = str(metadata.db_service_url).rstrip("/") + "/graphql/v1" | ||
| headers = {"Authorization": f"Bearer {metadata.service_token}"} | ||
|
|
||
| query = f""" | ||
| {{ | ||
| persons(personalnummer: \"{persno}\", max_rows: 1) {{ | ||
| name | ||
| }} | ||
| }} | ||
| """ | ||
| response = requests.post( | ||
| graphql_url, | ||
| headers=headers, | ||
| json={"query": query}, | ||
| ) | ||
| response.raise_for_status() | ||
| data = response.json() | ||
| persons = data["data"]["persons"] | ||
| if persons: | ||
| return persons[0]["name"] | ||
| return None | ||
|
|
||
|
|
||
| def _create_report(document: Document, metadata: MetaData) -> DocxDocument: | ||
| """Creates a simple Word report for the given document.""" | ||
| doc = DocxDocument() | ||
|
|
||
| doc.add_heading("Simple Report", 0) | ||
|
|
||
| report_time_string = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | ||
| doc.add_paragraph(f"Report generated on: {report_time_string}") | ||
|
|
||
| # add some basic information about the document | ||
| doc.add_heading("Document Information", level=1) | ||
| doc.add_paragraph(f"Document ID: {document.z_nummer}@{document.z_index}") | ||
| doc.add_paragraph(f"Title: {document.titel}") | ||
| doc.add_paragraph(f"Created On: {document.cdb_cdate}") | ||
|
|
||
| # Fetch the name of the person who created the document via GraphQL | ||
| person_name = _fetch_person_name(document.cdb_cpersno, metadata) | ||
| doc.add_paragraph(f"Created By: {person_name or document.cdb_cpersno}") | ||
|
|
||
| return doc | ||
|
|
||
| ``` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.