ผลต่างระหว่างรุ่นของ "Common Functions"

จาก คูนิฟ็อกซ์ วิกิ
 
(ไม่แสดง 16 รุ่นระหว่างกลางโดยผู้ใช้คนเดียวกัน)
บรรทัดที่ 49: บรรทัดที่ 49:
* '''main_entry counter''' ''([int, int])'': The first integer represents the order of the current document (starting from 1); the second integer is the number of documents present in the databse.
* '''main_entry counter''' ''([int, int])'': The first integer represents the order of the current document (starting from 1); the second integer is the number of documents present in the databse.
* '''flash''' ''(list)'': A list of flash message to appear on the client-side along with the requested document. Usually the messages sent this way are the First/Last entry notifications.
* '''flash''' ''(list)'': A list of flash message to appear on the client-side along with the requested document. Usually the messages sent this way are the First/Last entry notifications.
|}
'''<syntaxhighlight lang="python" id="prefetch_all_docs">
grab_some_entries(dbtype, tbname, model, grab_id_list, id_col="id", month=None,
                  order_by=None, get_dict=None, return_instance=False,
                  isgl=False, limit=None, custom_crits=[])
</syntaxhighlight>'''
{| style="margin-left:20px;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || Retrieve one or any number of database entries. This function is attuned to work best with standalone ''table''-typed databases. ''(For more complex databases, the more '''prefetch_all_docs''' is recommended.)''
|- style="vertical-align:top;"
| '''Parameters''' ||
* '''xxx''' ''(str)'': The database name (usually a three-lettered string).
* '''xxx''' ''(CuneiModel or [CuneiModel, list])'': The specification for master entry retrieval.
|- style="vertical-align:top;"
| '''Returns''' || 1 object:
* '''CuneiModel instance''' or '''list'''
|}
|}


บรรทัดที่ 164: บรรทัดที่ 181:
|}
|}


== User Authentication Functions ==
== Session-based Functions ==
'''<syntaxhighlight lang="python" id="check_modact_stat">
'''<syntaxhighlight lang="python" id="check_modact_stat">
check_modact_stat(modid=None, modcode=None, mode="activate", response="return")
check_modact_stat(modid=None, modcode=None, mode="activate", response="return")
บรรทัดที่ 181: บรรทัดที่ 198:
* If {{code|lang=python|1= response='return'}}: Returns {{code|lang=python|True}} if the module is activated and {{code|lang=python|False}} otherwise.
* If {{code|lang=python|1= response='return'}}: Returns {{code|lang=python|True}} if the module is activated and {{code|lang=python|False}} otherwise.
* If {{code|lang=python|1= response='abort'}}: Returns {{code|lang=python|True}} if the module is activated and {{code|lang=python|abort(424)}} otherwise.
* If {{code|lang=python|1= response='abort'}}: Returns {{code|lang=python|True}} if the module is activated and {{code|lang=python|abort(424)}} otherwise.
|}
'''<syntaxhighlight lang="python" id="process_beacon_args">
process_beacon_args(internal_args, request)
</syntaxhighlight>'''
{| style="margin-left:20px;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || XXXXXX
|- style="vertical-align:top;"
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
| '''Returns''' ||
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
|}
'''<syntaxhighlight lang="python" id="process_doclock">
process_doclock(beacon_args, module_name, perm_name, headmodel=None, paired_gl=None)
</syntaxhighlight>'''
{| style="margin-left:20px;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || XXXXXX
|- style="vertical-align:top;"
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
| '''Returns''' ||
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
|}
|}


บรรทัดที่ 224: บรรทัดที่ 205:
{| style="margin-left:20px;"
{| style="margin-left:20px;"
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || XXXXXX
| style="width:120px;" | '''Description''' || Change the session date-time as dictated by the DateTimeForm or as explicitly specified. And store the change in the session token database.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Parameters''' ||
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''form''' ''(CuneiForm or {{code|lang=python|None}})'': A DateTimeForm instance (usually with data submitted from the client-side). If a CuneiForm instance is supplied, the arguments '''date_obj''' and '''time_obj''' are ignored.
* '''xxx''' ''(xxx)'':
* '''reset''' ''(bool)'': Ignore all other arguments and set the session date-time to match the server time.
* '''date_obj''' ''(datetime or date or {{code|lang=python|None}})'': If specified, change the session's '''year, month, and date''' to match.
* '''time_obj''' ''(datetime or {{code|lang=python|None}})'': If specified, change the session's '''hour, minute, and second''' to match.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Returns''' ||
| '''Returns''' || 3 Objects:
* '''xxx''' ''(xxx)'':
* '''success''' ''(bool)'': Whether the date-time change is successful.
* '''xxx''' ''(xxx)'':
* '''message''' ''(str)'': The message to communicate the success/failure to the client. Developers are expected to pack this message into a response afterward.
|- style="vertical-align:top;"
* '''timediff''' ''(int)'': The difference between the session time and the server time ({{code|lang=python|session_time - server_time}}) in milliseconds.
| '''Notes''' || XXXXXX
|}
|}


บรรทัดที่ 244: บรรทัดที่ 226:
{| style="margin-left:20px;"
{| style="margin-left:20px;"
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || XXXXXX
| style="width:120px;" | '''Description''' || Initialize a long-task in the task database. If there are more parallel tasks running than the maximum number allowed, put the new task in the queue.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Parameters''' ||
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''job_token''' ''(str)'': Job token of the task (usually a randomly generated string).
* '''xxx''' ''(xxx)'':
* '''overall_load''' ''(int)'': The overall step/load of the task/stage.
* '''new_stat''' ''(str)'': A short string labeling the step/stage of the task.
* '''activity_str''' ''(str)'': A short string detailing the step/stage of the task.
* '''suppress_request''' ''(bool)'': Whether the task prevents the session from initiating another long-task while it is running.
* '''further_action''' ''(str)'': Details or JSON data that can be extracted and used at a later step/stage. This value is stored in a TextField, so it can be long.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Returns''' ||
| '''Returns''' || A '''{{code|Task}}''' ''(CuneiModel)'' instance corresponding to the newly initiated task.
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
|}
|}


บรรทัดที่ 263: บรรทัดที่ 245:
{| style="margin-left:20px;"
{| style="margin-left:20px;"
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || XXXXXX
| style="width:120px;" | '''Description''' || Update the status of a task in the task database.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Parameters''' ||
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''job_token''' ''(str)'': Job token of the task (usually a randomly generated string).
* '''xxx''' ''(xxx)'':
* '''finished_load''' ''(int)'': The number representing finished step/load of the task/stage.
* '''overall_load''' ''(int)'': The overall step/load of the task/stage.
* '''new_stat''' ''(str)'': A short string labeling the step/stage of the task.
* '''activity_str''' ''(str)'': A short string detailing the step/stage of the task.
* '''further_action''' ''(str)'': Details or JSON data that can be extracted and used at a later step/stage. This value is stored in a TextField, so it can be long.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Returns''' ||
| '''Returns''' || {{code|lang=python|None}}
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
| '''Notes''' ||
* If '''new_stat''' is set to {{code|lang=python|'complete'}}, the argument '''finished_load''' is ignored and set equal to '''overall_load''' ''(as given as another argument or, if not given, as already present in the database)''.
* If '''new_stat''' is set to {{code|lang=python|'complete'}} or {{code|lang=python|'killed'}}, the task queue is proceeded.
|}
|}


บรรทัดที่ 281: บรรทัดที่ 267:
{| style="margin-left:20px;"
{| style="margin-left:20px;"
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || XXXXXX
| style="width:120px;" | '''Description''' || Retrieve the '''{{code|Task}}''' instance with the token matching the given value.
|- style="vertical-align:top;"
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Returns''' ||
| '''Parameters''' || '''job_token''' ''(str)'': Job token of the task to be retrieved.
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
| '''Returns''' || A '''{{code|Task}}''' ''(CuneiModel)'' instance corresponding to the newly initiated task or {{code|lang=python|None}} if not found.
|}
|}


บรรทัดที่ 299: บรรทัดที่ 279:
{| style="margin-left:20px;"
{| style="margin-left:20px;"
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || XXXXXX
| style="width:120px;" | '''Description''' || A shortcut to extract the path to the file assciated with the task. This function expects the path to be stored as a string under the {{code|lang=python|'file_path'}} key in the Task's {{code|further_action}} attribute ({{code|lang=python|json.loads(current_task.further_action)['file_path']}}).
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Parameters''' ||
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''job_token''' ''(str)'': Job token of the task whose file is to be retrieved.
* '''xxx''' ''(xxx)'':
* '''will_abort''' ''(bool)'': Whether to return a 404 abortion ({{code|lang=python|abort(404)}}) when the file does not exist.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Returns''' ||
| '''Returns''' ||
* '''xxx''' ''(xxx)'':
* If the file path points to an existing file, return the path ''(str)''.
* '''xxx''' ''(xxx)'':
* If the file does not exist, return {{code|lang=python|None}} if {{code|lang=python|1= will_abort=False}}, return a 404 abortion otherwise.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
| '''Notes''' || One can also choose to use the function '''read_task_db''' and work their way from there without ever using this function.
|}
|}


== Printing Functions ==
== Printing Functions ==
'''<syntaxhighlight lang="python" id="print_in_thread">
'''<syntaxhighlight lang="python" id="replace_printsvg">
print_in_thread(job_token, doc_objs, pseudo_mapper, modcode, template_name,
replace_printsvg(tbfm_mapper, modcode, bookname=None, svg_name=None, suffix=None,
                svg_name=None, stat_cols=[], skip_company_template=False,
                job_data=None, clear_printed=True, skip_company_template=False,
                make_pdfa3=False)
                make_pdfa3=False)
               
# Example adapted from accounting journal printing.
tbfm_dict = {"f1":thisdoc, "t1":thisdoc.detail, "t2":thisdoc.vat_detail, "t3":thisdoc.wht_detail}
pdf_path = replace_printsvg(tbfm_dict, "cunei_gl", bookname="GL_BOOK",
                            svg_name="GL_{}".format(thisdoc.docno[:3]))
</syntaxhighlight>'''
</syntaxhighlight>'''
{| style="margin-left:20px;"
{| style="margin-left:20px;"
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || XXXXXX
| style="width:120px;" | '''Description''' || The main function for printing. Replace [[CuneiTongue]] tags in SVG templates with appropriate values.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Parameters''' ||
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''tbfm_mapper''' ''(dict)'': The dict matching the form/table references (as used in SVG templates) to the objects holding the values.
* '''xxx''' ''(xxx)'':
** A reference to a '''form''' take the format {{code|lang=python|'f1'}}, {{code|lang=python|'f2'}}, {{code|lang=python|'f3'}}, .... The corresponding value is an {{code|lang=python|Object}} (preferably a CuneiModel instance).
** A reference to a '''table''' take the format {{code|lang=python|'t1'}}, {{code|lang=python|'t2'}}, {{code|lang=python|'t3'}}, .... The corresponding value is an iterable (e.g. a list) of {{code|lang=python|Object}}s (preferably a CuneiModel instances).
* '''modcode''' ''(str)'': ''(Obsolete)'' The code of the module from which the printing is invoked.
* '''bookname''' ''(str)'': The name of the fallback template to be used in case the template '''svg_name''' is not found. Usually this coincides with the database file name, hence the argument name.
* '''svg_name''' ''(str)'': The name of the print template.
* '''suffix''' ''(int)'': The suffix to append to the PDF file name. This argument is only used internally via {{code|print_in_thread}} where multiple documents are printed as separated PDF files to be concatenated together in the final step.
* '''job_data''' ''(list or {{code|lang=python|None}})'': The task information. This argument is only applicable when printing in a long-job (usually via {{code|print_in_thread}}).
* '''clear_printed''' ''(bool)'': Whether to clear other residual PDFs that might be left in the company's {{code|temp}} directory. This argument is exclusively set to {{code|lang=python|True}} via {{code|print_in_thread}} where multiple PDFs are to be concatenated. ''(Only affects temporary PDFs created by the same user.)''
* '''skip_company_template''' ''(bool)'': Whether to skip looking for print templates in the company-specific folder and only look for CuneiFox official templates.
* '''make_pdfa3''' ''(bool)'': Whether to convert the final PDF to PDF/A-3b.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Returns''' ||
| '''Returns''' || The path to the output PDF file ''(str)'' or {{code|lang=python|None}} if the templates cannot be found.
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
| '''Notes''' || The final PDF is always located in the company's {{code|temp}} directory and named either {{code|lang=python|'<username>_out.pdf'}} or {{code|lang=python|'<username>_out_<suffix>.pdf'}}.
|}
|}


'''<syntaxhighlight lang="python" id="gen_qr">
'''<syntaxhighlight lang="python" id="print_in_thread">
gen_qr(num, qr_type="out", info=None)
print_in_thread(job_token, doc_objs, pseudo_mapper, modcode, template_name,
                svg_name=None, stat_cols=[], skip_company_template=False,
                make_pdfa3=False)
 
# Example adapted from accounting journal mass-printing.
print_in_thread(job_token, doc_objs, modcode="cunei_gl",
                pseudo_mapper={"f1":"self", "t1":"detail", "t2":"vat_detail", "t3":"wht_detail"},
                template_name="GL_BOOK", svg_name=chosen_template,
                stat_cols=["docno"], make_pdfa3=make_pdfa3)
# Example adapted from VAT report printing.
print_in_thread(job_token, doc_objs, modcode=gl_moddata["code"],
                pseudo_mapper=[{"f1":"self", "t1":"b_detail"},
                              {"f1":"self", "t1":"s_detail"},
                              {"f1":"self", "t1":"detail"},
                              {"f1":"self", "t1":"subst_detail"},
                              {"f1":"self", "t1":"subst_detail"}],
                template_name=["VT_RPRT_B_REPORT", "VT_RPRT_S_REPORT",
                              "VT_RPRT_SUM_REPORT", "VT_RPRT_SUBST_REPORT",
                              "VT36_RPRT_SUM_REPORT"],
                stat_cols=[["section_code", "section_name"], ["section_code", "section_name"],
                          ["section_code", "section_name"], ["section_code", "section_name"],
                          ["section_code", "section_name"]])
</syntaxhighlight>'''
</syntaxhighlight>'''
{| style="margin-left:20px;"
{| style="margin-left:20px;"
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || XXXXXX
| style="width:120px;" | '''Description''' || The custom printing function that enables using custom templates, printing multiple documents at once, and the PDF/A-3b option. Because it allows multiple-document printing and the process can potentially take a long time, this means of printing is done in as a long-job in a Thread.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Parameters''' ||
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''job_token''' ''(str)'': Job token of the task (usually a randomly generated string).
* '''xxx''' ''(xxx)'':
* '''doc_objs''' ''([CuneiModels_instance,])'': The list (iterable) containing the prefetched Cuneifox instances for the documents to be printed.
* '''pseudo_mapper''' ''(dict)'': The dict matching the form/table references (as used in SVG templates) to the objects holding the values. However, this argument can be one-level more abstracted than '''tbfm_mapper''' of {{code|replace_printsvg}} to facilitate multiple-document printing.
** A reference to a '''form''' take the format {{code|lang=python|'f1'}}, {{code|lang=python|'f2'}}, {{code|lang=python|'f3'}}, .... The corresponding value can be either:
*** An {{code|lang=python|Object}} (preferably a CuneiModel instance) '''OR'''
*** The string {{code|lang=python|'self'}} to indicate that the master entry itself is being referenced '''OR'''
*** A back-reference of the ForeignKeyField linking the entry of interest to the master entry ''(str)''.
** A reference to a '''table''' take the format {{code|lang=python|'t1'}}, {{code|lang=python|'t2'}}, {{code|lang=python|'t3'}}, .... The corresponding value can be either:
*** An iterable (e.g. a list) of {{code|lang=python|Object}}s (preferably a CuneiModel instances) '''OR'''
*** A back-reference of the ForeignKeyField linking the sub-entries to the master entry ''(str)''.
* '''modcode''' ''(str)'': ''(Obsolete)'' The code of the module from which the printing is invoked.
* '''template_name''' ''(str)'': The name of the fallback template to be used in case the template '''svg_name''' is not found.
* '''svg_name''' ''(str)'': The name of the print template.
* '''stat_cols''' ''([str,])'': The column of the master entries to use as the process indicator ''(e.g. 'Currently printing document <???>...')''.
* '''skip_company_template''' ''(bool)'': Whether to skip looking for print templates in the company-specific folder and only look for CuneiFox official templates.
* '''make_pdfa3''' ''(bool)'': Whether to convert the final PDF to PDF/A-3b.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Returns''' ||
| '''Returns''' || {{code|lang=python|None}}
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
| '''Notes''' ||
* The final concatenated PDF is always named {{code|lang=python|'<username>_out.pdf'}} and located in the company's {{code|temp}} directory.
* The arguments '''doc_objs, modcode, pseudo_mapper, template_name, svg_name,''' and '''stat_cols''' can be layered one level deeper into lists, as demonstrated in Example #2. ''(Note that, in the example '''modcode''' is not layered; the function can assume that the same '''modcode''' should apply to all iterations.)''
|}
|}


'''<syntaxhighlight lang="python" id="replace_printsvg">
'''<syntaxhighlight lang="python" id="gen_qr">
replace_printsvg(tbfm_mapper, modcode, bookname=None, svg_name=None, suffix=None,
gen_qr(num, qr_type="out", info=None)
                job_data=None, clear_printed=True, skip_company_template=False,
                make_pdfa3=False)
</syntaxhighlight>'''
</syntaxhighlight>'''
{| style="margin-left:20px;"
{| style="margin-left:20px;"
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| style="width:120px;" | '''Description''' || XXXXXX
| style="width:120px;" | '''Description''' || Generate QR code for making or receiving payment. The QR code expects '''Thailand's Tax ID Promptpay''' format.
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Parameters''' ||
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''num''' ''(float)'': The numerical value to embed in the QR code (in THB).
* '''xxx''' ''(xxx)'':
* '''qr_type''' ''({{code|lang=python|'in'}} or {{code|lang=python|'out'}})'': Whether the QR code is for paying or receiving money.
|- style="vertical-align:top;"
* '''info''' ''([str:company_name, str:company_taxID] or {{code|lang=python|None}})'': If the argument is {{code|lang=python|None}}, the function assumes the company name and tax ID of the current company.
| '''Returns''' ||
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
| '''Returns''' || The path to the output PNG file ''(str)'' or a 404-abortion the image cannot be created.
|}
|}


บรรทัดที่ 380: บรรทัดที่ 402:
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Parameters''' ||
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''specs''' ''(dict)'':
* '''xxx''' ''(xxx)'':
* '''round_all''' ''(int or {{code|lang=python|None}})'':
* '''col_desc''' ''(dict)'':
* '''col_size''' ''(dict)'':
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Returns''' ||
| '''Returns''' || The path to the exported spreadsheet (XLSX) file.
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
|}
|}


บรรทัดที่ 401: บรรทัดที่ 421:
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Parameters''' ||
| '''Parameters''' ||
* '''xxx''' ''(xxx)'':
* '''file_path''' ''(str)'':
* '''xxx''' ''(xxx)'':
* '''dbtype''' ''(str: {{code|lang=python|'table'}}, {{code|lang=python|'data'}}, or {{code|lang=python|'report'}})'': The data type (location) of the database file.
|- style="vertical-align:top;"
* '''dbname''' ''(str)'': The database name.
| '''Returns''' ||
* '''models''' ''([CuneiModel,])'': The list of the database models.
* '''xxx''' ''(xxx)'':
* '''specs''' ''(dict)'':
* '''xxx''' ''(xxx)'':
* '''month''' ''(date, or datetime)'': The data month (effective for {{code|lang=python|1= datatype='data'}}). If the argument is a string, it must be formatted either as {{code|YYYYMM}} or {{code|YYYYMMDD}}.
* '''verify_cmd''' ''(function)'':
* '''post_cmd''' ''(function)'':
* '''addi_args''' ''(list)'':
* '''autorun_specs''' ''(list)'':
* '''job_token''' ''(str)'': Job token of the task (usually a randomly generated string).
* '''custom_datasets''' ''([[[list,],],] or {{code|lang=python|None}})'':
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
| '''Returns''' || A Boolean indicating whether the import process invokes any error.
|}
|}


บรรทัดที่ 466: บรรทัดที่ 492:
| '''Notes''' || XXXXXX
| '''Notes''' || XXXXXX
|}
|}


{{The Tenko Shrine}}
{{The Tenko Shrine}}

รุ่นแก้ไขปัจจุบันเมื่อ 10:52, 24 ตุลาคม 2567

Database Read Functions

grab_id(bookcode, sch_kw, models, isgl=False, datatype="data", month=None, sch_col="docno")
Description Fetch the ID of the looked-up entry. Because this function is usually utilized in the page-level search function, it is designed to target string-based column by looking for values that starts-with the search keyword. In case of multiple matches, the ID of the first match (ordered by the search column).
Parameters
  • bookcode (str): The database name (usually a three-lettered string).
  • sch_kw (str): The search keyword.
  • models (CuneiModel or [CuneiModel,]): The model(s) of the database entry. Developers may choose to feed all the relevant models or only the master model.
  • isgl (bool): Whether the database is considered an accounting journal database. (One can also feed the argument bookcode in the format GL_XXX and ignore this argument.)
  • datatype (str: 'table', 'data', or 'report'): The data type (location) of the database file.
  • month (str, date, or datetime): The data month (effective for datatype='data'). If the argument is a string, it must be formatted either as YYYYMM or YYYYMMDD.
  • sch_col (str): the name of the search column.
Returns
  • If a match is found: Returns the match's ID (int).
  • Otherwise: Returns None.
grab_whole_doc(bookcode, identifiers, master_model, detail_models, isgl=False,
               datatype="data", month=None)
Description Retrieve a single document (along with all its sub-entries) to display on the client-side. This function is tailored to the client-side mass-populate routine, so its algorithm leans heavily in that direction. For a more server-friendly retrieval, use prefetch_all_docs instead.
Parameters DO NOT rely on argument order beyond detail_models.
  • bookcode (str): The database name (usually a three-lettered string).
  • identifiers (dict): Under CuneiFox usual routine, this argument is extracted from the request via json.loads(request.form.get('identifier')). Since this function is tailored to fit the most common usage of multi-component pages, it expects the keys 'master.id' and 'pagenav' be present in this argument. (See Multi-component Page#Mass Populate Route for details.)
  • master_model (list or tuple): The list of specifications for master entry retrieval. Its members are:
    1. The CuneiModel for the master entry.
    2. The string to be used (in the returned dict) as the reference to the master entry.
    3. (Optional) The list of ordering column(s) for the main table. This list is used to determined the First/Previous/Next/Last master entry. If not given, the master table is sorted by fn.LOWER(master_model[0].docno).asc().
  • detail_models (list): The list of specifications for sub-entry retrievals. Each member of this argument is itself a list or a tuple corresponding to one sub-entry table, the sub-member are, in order:
    1. The CuneiModel for the sub-entry.
    2. The string to be used (in the returned dict) as the reference to the sub-entry list.
    3. The list of ordering column(s) for the sub-table. If not given (assigned as None), the sub-table is sorted by fn.LOWER(detail_models[i][0].id).
    4. The back-reference string (backref) of the ForeignKeyField linking the sub-entries to the master entry.
  • isgl (bool): Whether the database is considered an accounting journal database. (One can also feed the argument bookcode in the format GL_XXX and ignore this argument.)
  • datatype (str: 'table', 'data', or 'report'): The data type (location) of the database file.
  • month (str, date, or datetime): The data month (effective for datatype='data'). If the argument is a string, it must be formatted either as YYYYMM or YYYYMMDD.
Returns 3 objects:
  • return_data (dict): The retrieved document in a dict format. The keys of the dict are the strings given as master_model[1] and detail_models[i][1]. The dict values are a CuneiModel object for the master entry and a list of CuneiModel objects for sub-entries.
  • main_entry counter ([int, int]): The first integer represents the order of the current document (starting from 1); the second integer is the number of documents present in the databse.
  • flash (list): A list of flash message to appear on the client-side along with the requested document. Usually the messages sent this way are the First/Last entry notifications.
grab_some_entries(dbtype, tbname, model, grab_id_list, id_col="id", month=None,
                  order_by=None, get_dict=None, return_instance=False,
                  isgl=False, limit=None, custom_crits=[])
Description Retrieve one or any number of database entries. This function is attuned to work best with standalone table-typed databases. (For more complex databases, the more prefetch_all_docs is recommended.)
Parameters
  • xxx (str): The database name (usually a three-lettered string).
  • xxx (CuneiModel or [CuneiModel, list]): The specification for master entry retrieval.
Returns 1 object:
  • CuneiModel instance or list
prefetch_all_docs(bookcode, master_spec, detail_specs, isgl=False, datatype="data",
                  month=None, headid=None, id_col="id", return_instance=False, crossers=[])
Description Retrieve one or any number of database entries. Since this function allows retrieval from a master table with sub-tables, it is mostly used with (and thus named) documents, however using it with complex code tables is also valid.
Parameters
  • bookcode (str): The database name (usually a three-lettered string).
  • master_spec (CuneiModel or [CuneiModel, list]): The specification for master entry retrieval.
    1. The given CuneiModel corresponds to the master table.
    2. When given as a list, its second member lists the ordering column(s) for the master table. If not given, the master table is sorted by master_model.id.
  • detail_specs ([CuneiModel,] or [[CuneiModel, list],]): The list of specifications for sub-entry retrievals.
    1. The CuneiModels given in this argument correspond to the database sub-tables.
    2. The optional list sub-members hold the ordering column(s) for the sub-tables. If not given, each sub-table is sorted by sub_model.id).
  • isgl (bool): Whether the database is considered an accounting journal database. (One can also feed the argument bookcode in the format GL_XXX and ignore this argument.)
  • datatype (str: 'table', 'data', or 'report'): The data type (location) of the database file.
  • month (str, date, or datetime): The data month (effective for datatype='data'). If the argument is a string, it must be formatted either as YYYYMM or YYYYMMDD.
  • headid (value or list): (See explanation under idcol argument.)
  • idcol (str): This argument works with headid in 2 mode:
    • In simple mode, idcol is the name of the column to be screened by headid value.
      • If headid is a list, any entry whose idcol match any of the members is considered a match.
      • If headid is not a list, any entry whose idcol match the value is considered a match.
    • In raw-criteria mode, idcol is set to '__raw_crits'. headid is the list of criteria (where-clause as interpreted by Peewee) to be directly applied to the query.
  • return_instance (bool): Whether to return only the first match as a CuneiModel instance.
  • crossers (list): Currently not-in-use. It is a part of the plan to expand the capacity of this function to allow something similar to CuneiModel#Cross-table references.
Returns 2 objects:
  • doccount (int): The total number of matching documents found.
  • doclist (list) or doc (CuneiModel instance or None): The matching document(s). The format of this returned value depends on the input argument return_instance.

Database Write Functions

gen_dbcommit_resp(dbtype, tbname, model, form, perm_bit=None, allowed_action=None,
                  suppress_success_msg=False, lock_on_add=True, head_id_col="id",
                  get_dict=None, skip_validation=False, month=None)
Description Conduct form validation and, if passed, commit the form data to database.
Parameters DO NOT rely on argument order beyond perm_bit.
  • dbtype (str): Pointer to let CuneiFox grab the correct database file. Options include 'data', 'table', 'report', and 'temp'.
  • tbname (str): The database file name (without file extension).
  • model (CuneiModel): The model to commit to.
  • form (FlaskForm-CuneiForm): The form to read the committing data from.
  • perm_bit (int): The integer permission bit. This form of permission control is quite rigid and works well with single-table databases.
  • allowed_action ({'add':<bool>, 'edit':<bool>, 'delete':<bool>}): A more complicated form of permission control. This allows for more precise control. However, it cannot be read directly from a permission database, but must be interpreted from the stored integer value upon use.
  • suppress_success_msg (bool): Whether to show a message on action success.
  • lock_on_add (bool): Lock the document upon successful add-type commit. (This works for multi-table databases by putting the current username in the editting column of the header table.)
  • head_id_col (str): The name of the field unique to each entry. (The field must be present both in the form and in the database table.)
  • get_dict (list): If provided, new_entry is returned as a dict instead of a CuneiModel instance. (Values from field names listed in this argument are returned as their integer references. This is useful for ForeignKeyFields.)
  • skip_validation (bool): Whether the form validation step is skipped. ONLY SET THIS IF THE FORM IS VALIDATED ELSEWHERE.
  • month (date or datetime): (Only applies for dbtype 'data') The month sub-directory of the database. If not given, the program infers the month from the session time.
Returns
  • db_mod_code (int or None): The returned value can be:
    • None: Indicate a permission error.
    • 2: For a successful/failed addition attempt.
    • 3: For a successful/failed edit attempt.
    • 4: For a successful/failed deletion attempt.
  • new_entry (CuneiModel instance or dict or None): CuneiModel instance or a dict representing the successfully added/edited entry. Returned None for a failed attempt.
  • resp_dict (dict or int):
    • For a successful/failed attempt: The data dict to be sent to the client-side. This function takes care of the 'data', 'flash_messages', and 'err' keys.
    • For a permission error: Integer 403.

Copy-based Functions

prep_copy(cp_form, bookcode, head_model, detail_models=[], isgl=False)
Description Interpret and validate the Copy Form. If the validation is successful, retrieve the original document as well.
Parameters
  • cp_form (CuneiForm): The Copy Form to be read and validated.
  • bookcode (str): The database name (usually a three-lettered string).
  • head_model (CuneiModel): The model corresponding to the master table.
  • detail_models ([CuneiModel,]): The models corresponding to the sub-tables.
  • isgl (bool): Whether the database is considered an accounting journal database. (One can also feed the argument bookcode in the format GL_XXX and ignore this argument.)
Returns 3 objects:
  • return_dict (dict): A starter for the reply of a non-redirecting form submit request (see CuneiForm#Non-redirecting Form). This function takes care of the dict's 'err' key in case of CuneiForm ValidationError or when the original document cannot be retrieve.
  • orig_doc (CuneiModel instance or None): The original document. When not all values are copied verbatim, this object is meant to be manipulated before being fed to create_doc_copy.
  • copy_params (dict): The data from the Copy Form extracted to a dict form for easier access.
create_doc_copy(cp_form, copy_params, bookcode, orig_doc, head_model, detail_models={},
                isgl=False, omit_cols=[])
Description Commit the document copying to the proper database.
Parameters
  • cp_form (CuneiForm): The Copy Form to be read and validated.
  • copy_params (dict): The copy parameters. The function expects the argument to include keys 'docno', 'docdate', 'section_stid', 'section_code', and 'section_name'. (The dict returned from prep_copy can be fed directly here.)
  • bookcode (str): The database name (usually a three-lettered string).
  • orig_doc (CuneiModel instance): The instance to be committed to the target database. Note that all the values except those read from copy_params are copied verbatim in this function. If that is not the requirement, modify the instance before feeding it here.
  • head_model (CuneiModel): The model corresponding to the master table.
  • detail_models ([CuneiModel,]): The models corresponding to the sub-tables.
  • isgl (bool): Whether the database is considered an accounting journal database. (One can also feed the argument bookcode in the format GL_XXX and ignore this argument.)
  • omit_cols ([str,]): The list of columns not to be copied from orig_doc. The default value of each column is used instead.
Returns The newly copied document (if successfully copied) or None (if copying failed).
Notes A notable kink in this function is that the cp_form and copy_params arguments are quite redundant. In the algorithm, cp_form is only used for its automatic document number attribute. If the function assign_autorun is well modified, the need for cp_form might cease to exist.

Session-based Functions

check_modact_stat(modid=None, modcode=None, mode="activate", response="return")
Description Check whether certain module is activated. (See more on Activation Level.)
Parameters
  • modid (int or None): The module ID to be checked. (If both modid and modcode are both given, modid takes precedence.)
  • modcode (str or None): The Module code to be checked. (If both modid and modcode are both given, modid takes precedence.)
  • mode ('menu' or 'activate'): The activation level to check for.
  • response ('abort' or 'return'): The reaction when the activation check fails.
Returns
  • If response='return': Returns True if the module is activated and False otherwise.
  • If response='abort': Returns True if the module is activated and abort(424) otherwise.
change_datetime(form, reset=False, date_obj=None, time_obj=None)
Description Change the session date-time as dictated by the DateTimeForm or as explicitly specified. And store the change in the session token database.
Parameters
  • form (CuneiForm or None): A DateTimeForm instance (usually with data submitted from the client-side). If a CuneiForm instance is supplied, the arguments date_obj and time_obj are ignored.
  • reset (bool): Ignore all other arguments and set the session date-time to match the server time.
  • date_obj (datetime or date or None): If specified, change the session's year, month, and date to match.
  • time_obj (datetime or None): If specified, change the session's hour, minute, and second to match.
Returns 3 Objects:
  • success (bool): Whether the date-time change is successful.
  • message (str): The message to communicate the success/failure to the client. Developers are expected to pack this message into a response afterward.
  • timediff (int): The difference between the session time and the server time (session_time - server_time) in milliseconds.

Thread Functions

init_task_db(job_token, overall_load, new_stat="", activity_str="",
             suppress_request=True, further_action="")
Description Initialize a long-task in the task database. If there are more parallel tasks running than the maximum number allowed, put the new task in the queue.
Parameters
  • job_token (str): Job token of the task (usually a randomly generated string).
  • overall_load (int): The overall step/load of the task/stage.
  • new_stat (str): A short string labeling the step/stage of the task.
  • activity_str (str): A short string detailing the step/stage of the task.
  • suppress_request (bool): Whether the task prevents the session from initiating another long-task while it is running.
  • further_action (str): Details or JSON data that can be extracted and used at a later step/stage. This value is stored in a TextField, so it can be long.
Returns A Task (CuneiModel) instance corresponding to the newly initiated task.
update_task_db(job_token, finished_load=0, overall_load=None,
               new_stat=None, activity_str=None, further_action=None)
Description Update the status of a task in the task database.
Parameters
  • job_token (str): Job token of the task (usually a randomly generated string).
  • finished_load (int): The number representing finished step/load of the task/stage.
  • overall_load (int): The overall step/load of the task/stage.
  • new_stat (str): A short string labeling the step/stage of the task.
  • activity_str (str): A short string detailing the step/stage of the task.
  • further_action (str): Details or JSON data that can be extracted and used at a later step/stage. This value is stored in a TextField, so it can be long.
Returns None
Notes
  • If new_stat is set to 'complete', the argument finished_load is ignored and set equal to overall_load (as given as another argument or, if not given, as already present in the database).
  • If new_stat is set to 'complete' or 'killed', the task queue is proceeded.
read_task_db(job_token)
Description Retrieve the Task instance with the token matching the given value.
Parameters job_token (str): Job token of the task to be retrieved.
Returns A Task (CuneiModel) instance corresponding to the newly initiated task or None if not found.
read_resus_import_file(job_token, will_abort=False)
Description A shortcut to extract the path to the file assciated with the task. This function expects the path to be stored as a string under the 'file_path' key in the Task's further_action attribute (json.loads(current_task.further_action)['file_path']).
Parameters
  • job_token (str): Job token of the task whose file is to be retrieved.
  • will_abort (bool): Whether to return a 404 abortion (abort(404)) when the file does not exist.
Returns
  • If the file path points to an existing file, return the path (str).
  • If the file does not exist, return None if will_abort=False, return a 404 abortion otherwise.
Notes One can also choose to use the function read_task_db and work their way from there without ever using this function.

Printing Functions

replace_printsvg(tbfm_mapper, modcode, bookname=None, svg_name=None, suffix=None,
                 job_data=None, clear_printed=True, skip_company_template=False,
                 make_pdfa3=False)
                 
# Example adapted from accounting journal printing.
tbfm_dict = {"f1":thisdoc, "t1":thisdoc.detail, "t2":thisdoc.vat_detail, "t3":thisdoc.wht_detail}
pdf_path = replace_printsvg(tbfm_dict, "cunei_gl", bookname="GL_BOOK",
                            svg_name="GL_{}".format(thisdoc.docno[:3]))
Description The main function for printing. Replace CuneiTongue tags in SVG templates with appropriate values.
Parameters
  • tbfm_mapper (dict): The dict matching the form/table references (as used in SVG templates) to the objects holding the values.
    • A reference to a form take the format 'f1', 'f2', 'f3', .... The corresponding value is an Object (preferably a CuneiModel instance).
    • A reference to a table take the format 't1', 't2', 't3', .... The corresponding value is an iterable (e.g. a list) of Objects (preferably a CuneiModel instances).
  • modcode (str): (Obsolete) The code of the module from which the printing is invoked.
  • bookname (str): The name of the fallback template to be used in case the template svg_name is not found. Usually this coincides with the database file name, hence the argument name.
  • svg_name (str): The name of the print template.
  • suffix (int): The suffix to append to the PDF file name. This argument is only used internally via print_in_thread where multiple documents are printed as separated PDF files to be concatenated together in the final step.
  • job_data (list or None): The task information. This argument is only applicable when printing in a long-job (usually via print_in_thread).
  • clear_printed (bool): Whether to clear other residual PDFs that might be left in the company's temp directory. This argument is exclusively set to True via print_in_thread where multiple PDFs are to be concatenated. (Only affects temporary PDFs created by the same user.)
  • skip_company_template (bool): Whether to skip looking for print templates in the company-specific folder and only look for CuneiFox official templates.
  • make_pdfa3 (bool): Whether to convert the final PDF to PDF/A-3b.
Returns The path to the output PDF file (str) or None if the templates cannot be found.
Notes The final PDF is always located in the company's temp directory and named either '<username>_out.pdf' or '<username>_out_<suffix>.pdf'.
Description The custom printing function that enables using custom templates, printing multiple documents at once, and the PDF/A-3b option. Because it allows multiple-document printing and the process can potentially take a long time, this means of printing is done in as a long-job in a Thread.
Parameters
  • job_token (str): Job token of the task (usually a randomly generated string).
  • doc_objs ([CuneiModels_instance,]): The list (iterable) containing the prefetched Cuneifox instances for the documents to be printed.
  • pseudo_mapper (dict): The dict matching the form/table references (as used in SVG templates) to the objects holding the values. However, this argument can be one-level more abstracted than tbfm_mapper of replace_printsvg to facilitate multiple-document printing.
    • A reference to a form take the format 'f1', 'f2', 'f3', .... The corresponding value can be either:
      • An Object (preferably a CuneiModel instance) OR
      • The string 'self' to indicate that the master entry itself is being referenced OR
      • A back-reference of the ForeignKeyField linking the entry of interest to the master entry (str).
    • A reference to a table take the format 't1', 't2', 't3', .... The corresponding value can be either:
      • An iterable (e.g. a list) of Objects (preferably a CuneiModel instances) OR
      • A back-reference of the ForeignKeyField linking the sub-entries to the master entry (str).
  • modcode (str): (Obsolete) The code of the module from which the printing is invoked.
  • template_name (str): The name of the fallback template to be used in case the template svg_name is not found.
  • svg_name (str): The name of the print template.
  • stat_cols ([str,]): The column of the master entries to use as the process indicator (e.g. 'Currently printing document <???>...').
  • skip_company_template (bool): Whether to skip looking for print templates in the company-specific folder and only look for CuneiFox official templates.
  • make_pdfa3 (bool): Whether to convert the final PDF to PDF/A-3b.
Returns None
Notes
  • The final concatenated PDF is always named '<username>_out.pdf' and located in the company's temp directory.
  • The arguments doc_objs, modcode, pseudo_mapper, template_name, svg_name, and stat_cols can be layered one level deeper into lists, as demonstrated in Example #2. (Note that, in the example modcode is not layered; the function can assume that the same modcode should apply to all iterations.)
gen_qr(num, qr_type="out", info=None)
Description Generate QR code for making or receiving payment. The QR code expects Thailand's Tax ID Promptpay format.
Parameters
  • num (float): The numerical value to embed in the QR code (in THB).
  • qr_type ('in' or 'out'): Whether the QR code is for paying or receiving money.
  • info ([str:company_name, str:company_taxID] or None): If the argument is None, the function assumes the company name and tax ID of the current company.
Returns The path to the output PNG file (str) or a 404-abortion the image cannot be created.

Spreadsheet Export Functions

gen_spreadsheet(specs, round_all=None, col_desc=None, col_size={})
Description XXXXXX
Parameters
  • specs (dict):
  • round_all (int or None):
  • col_desc (dict):
  • col_size (dict):
Returns The path to the exported spreadsheet (XLSX) file.

Import & Mass Delete Functions

docimport_to_db(file_path, dbtype, dbname, models, specs, month=None,
                verify_cmd=None, post_cmd=None, addi_args=[], autorun_specs=None,
                job_token=None, custom_datasets=None)
Description XXXXXX
Parameters
  • file_path (str):
  • dbtype (str: 'table', 'data', or 'report'): The data type (location) of the database file.
  • dbname (str): The database name.
  • models ([CuneiModel,]): The list of the database models.
  • specs (dict):
  • month (date, or datetime): The data month (effective for datatype='data'). If the argument is a string, it must be formatted either as YYYYMM or YYYYMMDD.
  • verify_cmd (function):
  • post_cmd (function):
  • addi_args (list):
  • autorun_specs (list):
  • job_token (str): Job token of the task (usually a randomly generated string).
  • custom_datasets ([[[list,],],] or None):
Returns A Boolean indicating whether the import process invokes any error.
doc_mass_delete(dbtype, dbname, models, doc_objs=[], month=None, post_cmd=None,
                job_token=None, addi_args=[], docno_to_skip=[])
Description XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX

Miscellaneous

process_doc_file(dbtype, tbname, model, at_form, isgl=False, month=None)
Description XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX
gen_random_token(length=10, lower=True, upper=True, number=True)
Description XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX