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

จาก คูนิฟ็อกซ์ วิกิ
บรรทัดที่ 164: บรรทัดที่ 164:
|}
|}


== 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: บรรทัดที่ 181:
* 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''' || Extract beacon keys/values from the Request Data ({{code|lang=python|request.data}} or {{code|lang=python|request.form['bdata']}}) and Request Parameters into a dict form for easier access.
|- style="vertical-align:top;"
| '''Parameters''' ||
* '''internal_args''' ''(dict or {{code|lang=python|None}})'': Provides beacon keys-values in cases of beacon-like internal operations. When this value is not {{code|lang=python|None}}, the beacon aruguments are only read from this argument.
* '''request''' ''(Flask request)'': The client-side request. If no '''internal_args''' is not given, this function automatically extracts beacon keys-values from request parameters and {{code|lang=python|request.data}} (or {{code|lang=python|request.form['bdata']}}).
|- style="vertical-align:top;"
| '''Returns''' ||
* '''beacon_args''' ''(dict)'': Beacon keys-values repacked in the easily accessible dict form.
|- style="vertical-align:top;"
| '''Notes''' ||
The function throws a '''461 exception (Session-time Error)''' if the beacon value '''time_diff''' is invalid or does not agree with the session time.
|}
'''<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''' || Standard document lock/unlock algorithm.
|- style="vertical-align:top;"
| '''Parameters''' ||
* '''beacon_args''' ''(dict)'': Beacon keys-values as a dict. Usually this dict is what returned from '''{{code|process_beacon_args}}'''
* '''module_name''' ''(str)'': The code of the CuneiFox module that the current operation belongs to. This argument is used along side '''perm_name''' to navigate for the user's permission bit.
* '''perm_name''' ''(str)'': The permission bit name related to the current operation.
* '''headmodel''' ''(CuneiModel)'': The model of the document's master record (usually the document header). If this argument is not given, the document locking/unlocking is skipped.
* '''paired_gl''' ''(list)'': The specification for the accounting journal database corresponding to the current operation. The member's of the list are:
*# '''glname''': The account journal name in the form of '''{{code|lang=python|'GL_<code>'}}''' (for example, GL_PAY, GL_REC).
*# '''gl_headmodel''': The CuneiModel for the journal header.
*# '''paired_col_doc''' ''(optional, defaults to {{code|lang=python|'docno'}})'': The reference column in '''headmodel'''.
*# '''paired_col_gl''' ''(optional, defaults to {{code|lang=python|'docno'}})'': The reference column in '''gl_headmodel'''.
*# '''lock_fld''' ''(optional, defaults to {{code|lang=python|'lock'}})'': The journal lock column in '''gl_headmodel'''.
|- style="vertical-align:top;"
| '''Returns''' ||
* '''{{code|lang=python|None}}''' if the locking/unlocking is skipped.
* '''{{code|lang=python|403}}''' if the user does not have the valid permission to initiate the document lock.
* '''beacon_args''': If the locking/unlocking is successful, the function spits back the '''beacon_args''' as given.
|}
|}


บรรทัดที่ 231: บรรทัดที่ 188:
{| 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.
|- style="vertical-align:top;"
* '''date_obj''' ''(datetime or date or {{code|lang=python|None}})'': If specified, change the session's '''year, month, and date''' to match.
| '''Returns''' ||
* '''time_obj''' ''(datetime or {{code|lang=python|None}})'': If specified, change the session's '''hour, minute, and second''' to match.
* '''xxx''' ''(xxx)'':
* '''xxx''' ''(xxx)'':
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| '''Notes''' || XXXXXX
| '''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 ({{code|lang=python|session_time - server_time}}) in milliseconds.
|}
|}



รุ่นแก้ไขเมื่อ 11:50, 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.
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 XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX
update_task_db(job_token, finished_load=0, overall_load=None,
               new_stat=None, activity_str=None, further_action=None)
Description XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX
read_task_db(job_token)
Description XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX
read_resus_import_file(job_token, will_abort=False)
Description XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX

Printing Functions

Description XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX
gen_qr(num, qr_type="out", info=None)
Description XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX
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)
Description XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX

Spreadsheet Export Functions

gen_spreadsheet(specs, round_all=None, col_desc=None, col_size={})
Description XXXXXX
Parameters
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX

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
  • xxx (xxx):
  • xxx (xxx):
Returns
  • xxx (xxx):
  • xxx (xxx):
Notes XXXXXX
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