### Example Yao Model Definition (JSON) Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md This JSON snippet illustrates a system-built Yao model definition. It defines a 'User' model with a corresponding 'admin_user' table. It includes column definitions for 'id' and 'type', specifying data types, options, comments, default values, and validation rules. The example also shows placeholders for relations, default data values, and global options like timestamps and soft deletes. ```JSON { "name": "用户", "table": { "name": "admin_user", "comment": "用户表", "engine": "InnoDB" }, "columns": [ { "label": "ID", "name": "id", "type": "ID" }, { "label": "类型", "name": "type", "type": "enum", "option": ["super", "admin", "staff", "user", "robot"], "comment": "账号类型 super 超级管理员,admin 管理员, staff 员工, user 用户, robot 机器人", "default": "user", "validations": [ { "method": "typeof", "args": ["string"], "message": "{{input}}类型错误, {{label}}应该为字符串" }, { "method": "enum", "args": ["super", "admin", "staff", "user", "robot"], "message": "{{input}}不在许可范围, {{label}}应该为 super/admin/staff/user/robot" } ] } ], "relations": {}, "values": [ { "name": "管理员", "type": "super", "email": "xiang@iqka.com", "mobile": null, "password": "A123456p+", "status": "enabled", "extra": { "sex": "男" } } ], "option": { "timestamps": true, "soft_deletes": true } } ``` -------------------------------- ### Generate TypeScript Documentation with TypeDoc Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/README.md Instructions to install TypeDoc globally using pnpm and then generate TypeScript documentation from script files located in the ./scripts/ directory, outputting to ./dist/docs. ```sh pnpm add -g typedoc; typedoc --out ./dist/docs ./scripts/**/* ``` -------------------------------- ### JavaScript for AMIS Page Embedding and Configuration Loading Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/register.html This asynchronous JavaScript function initializes the AMIS embed library, uses Axios to fetch a JSON configuration file (register.json) for the user registration page, and then embeds the AMIS application into the #root element using the fetched configuration. ```JavaScript (async function () { let amis = amisRequire('amis/embed'); const axios = amisRequire('axios').default || amisRequire('axios'); const configJson = await axios.get("pages/user/register.json") // 通过替换下面这个配置来生成不同页面 let amisJSON = configJson.data; let amisScoped = amisEmbed.embed('#root', amisJSON); })(); ``` -------------------------------- ### Template String Operations Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/data/suis/blog/website/index/index.html Demonstrates basic string operations within the templating syntax, including string concatenation and direct string literal usage. ```Template {{ '::hello world' + '::why you cry' }} ``` ```Template {{ "::hello yao" }} ``` -------------------------------- ### Basic CSS for Full-Page Layout Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/register.html Provides essential CSS rules to ensure the HTML body and the main application wrapper (.app-wrapper) occupy the full viewport height and width, removing default margins and padding. It also defines a CSS variable for page body padding. ```CSS html, body, .app-wrapper { position: relative; width: 100%; height: 100%; margin: 0; padding: 0; } :root { --Page-body-padding: 0px; } ``` -------------------------------- ### Basic HTML/CSS Styling for Full-Page Layout Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/login.html This CSS snippet defines fundamental styling for HTML and body elements, ensuring they occupy the entire viewport width and height. It also initializes a custom CSS variable for page body padding, providing a base for consistent layout. ```CSS html, body, .app-wrapper { position: relative; width: 100%; height: 100%; margin: 0; padding: 0; } :root { --Page-body-padding: 0px; } ``` -------------------------------- ### JavaScript Amis Login Page Initialization with Yao Backend Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/login.html This JavaScript code initializes an Amis-based login page by dynamically loading its configuration. It interacts with a Yao backend API to retrieve application settings, including the preferred token storage type, and then embeds the Amis JSON into the DOM. Additionally, it generates and stores a unique session ID for client-side tracking. ```JavaScript // call by user/login.json // request by /api/__yao/login/admin (async function () { let amisEmbed = amisRequire('amis/embed'); const axios = amisRequire('axios').default || amisRequire('axios'); // 在yao.app中设置token的保存位置 const appInfo = await axios.get("/api/__yao/app/setting") const token_storage_type = appInfo.data.token?.storage || 'sessionStorage' yao_amis.setTokenStorageType(token_storage_type) const configJson = await axios.get("pages/user/login.json") // 通过替换下面这个配置来生成不同页面 let amisJSON = configJson.data; let amisScoped = amisEmbed.embed('#root', amisJSON, { data: { app: appInfo.data } }); let temp_id = yao_amis.generateUniqueId(); yao_amis.xgenSetStorage('xgen:temp_sid', temp_id) localStorage.temp_sid = temp_id; })(); ``` -------------------------------- ### Article Display Template Structure Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/data/suis/blog/website/index/index.html A comprehensive template snippet for rendering individual article information. It includes placeholders for article title, image, category (with a 'General' fallback), excerpt, publication date, estimated reading time, and likes. The structure is designed for displaying articles in a list or grid format. ```Template * [ ![{{ article.title }}]({{ article.img }}) {{ article.category || 'General' }} ### {{ article.title }} {{ article.excerpt }} {{ article.date }} • {{ article.reading\_time }} read {{ article.likes }} ]({{ article.url }}) ``` -------------------------------- ### JavaScript Function to Get URL Parameters Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/preview-word.html This JavaScript function, `getURLParameter`, extracts the value of a specified query parameter from the current URL. It uses `URLSearchParams` for efficient parsing. ```JavaScript function getURLParameter(parameterName) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(parameterName); } ``` -------------------------------- ### Get Records by Condition in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md Queries data records based on conditions, returning a result set that matches the criteria. Similar to SQL's SELECT, this is a frequently used processor. Returns a collection of matching data records (Key-Value Object structure). AES fields are automatically decrypted. Associated models appear as independent fields, with the field name being the association name; hasOne associations are Object data records, hasMany associations are Array data records. Note: Multiple hasMany associations might cause exceptions. Processor: `models.模型标识.Get`. Parameter 1: Query conditions, example: `{"wheres":[{"column":"name", "value":"张三"}],"withs":{"manu":{}}}`. Query conditions use the [QueryParam](../Query/QueryParam%E8%AF%AD%E6%B3%95.md) structure. ```javascript function Get() { return Process('models.category.get', { wheres: [{ column: 'parent_id', value: null }], }); } ``` ```js //直接返回[0],而不会报错 return Process('models.ai.setting.Get', { wheres: [ { Column: 'default', Value: true, }, { Column: 'deleted_at', Value: null, }, ], })[0]; ``` ```js //使用解构的方法 const [user] = Process('models.admin.user.get', { wheres: [ { column: 'mobile', value: account }, { column: 'status', value: '启用' }, { method: 'orwhere', column: 'email', value: account }, ], limit: 1, }); ``` -------------------------------- ### Define Username Validation Rules (JSON) Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md This JSON snippet defines a schema for a 'name' field, including its type, length, and validation rules. It specifies 'typeof' to ensure it's a string, and 'minLength' and 'maxLength' to restrict the length of the username. ```json { "label": "姓名", "name": "name", "type": "string", "length": 80, "comment": "姓名", "index": true, "validations": [ { "method": "typeof", "args": ["string"], "message": "{{input}}类型错误, {{label}}应该为字符串" }, { "method": "minLength", "args": [2], "message": "{{label}}至少需要2个字" }, { "method": "maxLength", "args": [40], "message": "{{label}}不能超过20个字" } ] } ``` -------------------------------- ### Permanently Delete Records by Condition in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md Permanently deletes data based on specified conditions. Returns the number of deleted rows. Processor: `models.模型标识.DestroyWhere`. Parameter 1: Query conditions, example: `{"wheres":[{"column":"name", "value":"张三"}]}`. Returns the number of deleted rows. ```javascript function Destroywhere() { return Process('models.category.destroywhere', { wheres: [{ column: 'parent_id', value: 4 }], }); } ``` -------------------------------- ### Define Minimum and Maximum Length Validation Rules (JSON) Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md This JSON snippet demonstrates how to define minimum and maximum length validation rules for a field. It uses 'minLength' and 'maxLength' methods with an array of arguments specifying the length and a custom error message. ```json { "validations": [ { "method": "minLength", "args": [6], "message": "{{label}} Error" }, { "method": "maxLength", "args": [18], "message": "{{label}} Error" } ] } ``` -------------------------------- ### Save Single Record in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md Creates or updates a single record in a Yao model. If the data record contains an 'id', it performs an update; otherwise, it creates a new record. Returns the ID of the created or updated record. Processor: `models.模型标识.Save`. Parameter 1: Data record, example: `{"name": "用户创建","manu_id": 2,"type": "user"}`. Returns the ID of the created or updated record. ```javascript function Save() { return Process('models.category.save', { parent_id: 1, name: '语文', }); } ``` -------------------------------- ### Delete Records by Condition in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md Deletes data based on specified conditions. If `soft_deletes` is not enabled in the model definition, records are permanently deleted. Returns the number of deleted rows. Processor: `models.模型标识.DeleteWhere`. Parameter 1: Query conditions, example: `{"wheres":[{"column":"name", "value":"张三"}]}`. Returns the number of deleted rows. ```javascript function Deletewhere() { return Process('models.category.deletewhere', { wheres: [{ column: 'parent_id', value: 4 }], }); } ``` -------------------------------- ### Paginate Records by Condition in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md Queries data records based on conditions, returning a data object with pagination information. Processor: `models.模型标识.Paginate`. Parameter 1: Query conditions. Parameter 2: Current page number. Parameter 3: Number of records per page. ```javascript function Paginate() { return Process( 'models.user.Paginate', { select: ['id', 'name', 'mobile', 'status', 'extra'], withs: { manu: {}, mother: {}, addresses: {} }, wheres: [{ column: 'status', value: 'enabled' }], limit: 2, }, 1, 2, ); } ``` ```APIDOC Object Paginate 数据结构: data: Array - 数据记录集合 next: Integer - 下一页,如没有下一页返回 -1 prev: Integer - 上一页,如没有上一页返回 -1 page: Integer - 当前页码 pagesize: Integer - 每页记录数量 pagecnt: Integer - 总页数 total: Integer - 总 ``` -------------------------------- ### Delete Single Record by ID in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md Deletes data by ID. If `soft_deletes` is not enabled in the model definition, the record is permanently deleted. Returns `null` on success. Processor: `models.模型标识.Delete`. Parameter 1: Data record ID. ```javascript function deletes() { return Process('models.category.delete', 10); } ``` -------------------------------- ### JavaScript Function to Get URL Parameter Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/preview-excel.html This JavaScript function, `getURLParameter`, extracts the value of a specified query parameter from the current URL. It utilizes the `URLSearchParams` API for efficient parsing of the URL's query string. The function returns the parameter's value or null if not found. ```JavaScript function getURLParameter(parameterName) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(parameterName); } ``` -------------------------------- ### Permanently Delete Single Record by Primary Key in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md Permanently deletes a single data record based on its primary key ID. Returns `null` on success. Processor: `models.模型标识.Destroy`. Parameter 1: Model primary key ID. ```javascript function Destroy() { return Process('models.category.destroy', 9); } ``` -------------------------------- ### Define Password Validation Rules (JSON) Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md This JSON snippet outlines a comprehensive set of validation rules for a 'password' field. It includes checks for string type, minimum and maximum length, and multiple 'pattern' rules to enforce the presence of digits, uppercase letters, lowercase letters, and special characters, ensuring a strong password policy. ```json { "label": "登录密码", "name": "password", "type": "string", "length": 256, "comment": "登录密码", "crypt": "PASSWORD", "index": true, "validations": [ { "method": "typeof", "args": ["string"], "message": "{{input}}类型错误, {{label}}应该为字符串" }, { "method": "minLength", "args": [6], "message": "{{label}}应该由6-18位,大小写字母、数字和符号构成" }, { "method": "maxLength", "args": [18], "message": "{{label}}应该由6-18位,大小写字母、数字和符号构成" }, { "method": "pattern", "args": ["[0-9]+"], "message": "{{label}}应该至少包含一个数字" }, { "method": "pattern", "args": ["[A-Z]+"], "message": "{{label}}应该至少包含一个大写字母" }, { "method": "pattern", "args": ["[a-z]+"], "message": "{{label}}应该至少包含一个小写字母" }, { "method": "pattern", "args": ["[@#$&*]+"], "message": "{{label}}应该至少包含一个符号" } ] } ``` -------------------------------- ### Batch Create or Update Multiple Records in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md Batch creates or updates multiple records. Records without a primary key field are created, while existing records are updated. Returns a collection of created or updated record IDs. Processor: `models.模型标识.EachSave`. Parameter 1 (required): Collection of data records to be saved. Parameter 2 (optional): Common fields to be merged into each data record; if a field value is `$index`, it will be replaced with the index of the data record in the collection. Returns a collection of created or updated record IDs. Note: Each save operation invokes a database operation. ```js const ids = Process( 'models.user.EachSave', [{ id: 101, name: '张三' }, { name: '李四' }], { manu_id: 2, balance: '$index' }, ); //[101, 107] return ids; ``` -------------------------------- ### Define Regular Expression Pattern Validation Rules (JSON) Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md This JSON snippet illustrates various regular expression (regex) pattern validation rules. It covers checks for digits, uppercase letters, lowercase letters, special characters, specific ID formats (e.g., Chinese ID card), and fixed-length alphanumeric strings with symbols. These patterns can replace specific validations like email or phone numbers. ```json [ { "method": "pattern", "args": ["[0-9]+"], "message": "{{label}}应该至少包含一个数字" }, { "method": "pattern", "args": ["[A-Z]+"], "message": "{{label}}应该至少包含一个大写字母" }, { "method": "pattern", "args": ["[a-z]+"], "message": "{{label}}应该至少包含一个小写字母" }, { "method": "pattern", "args": ["[@#$&*]+"], "message": "{{label}}应该至少包含一个符号" }, { "method": "pattern", "args": ["^(\\d{18})|(\\d{14}X)$"], "message": "{{label}}身份证格式错误" }, { "method": "pattern", "args": ["^[0-9A-Za-z@#$&*]{8}$"], "message": " {{label}}应该由8位,大小写字母、数字和符号构成" }, { "method": "pattern", "args": ["^[0-9A-Za-z@#$&*]{32}$"], "message": "{{label}}应该由32位,大小写字母、数字和符号构成" } ] ``` -------------------------------- ### Delete and Batch Save Records in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md Deletes records by given IDs and then saves multiple records. Records without a primary key field are created, while existing records are updated. Returns a collection of created or updated record IDs. Processor: `models.模型标识.EachSaveAfterDelete`. Parameter 1 (required): Collection of record IDs to be deleted. Parameter 2 (required): Collection of data records to be saved. Parameter 3 (optional): Common fields to be merged into each data record; if a field value is `$index`, it will be replaced with the index of the data record in the collection. Returns a collection of created or updated record IDs. ```js const ids = Process( 'models.user.EachSaveAfterDelete', [1, 2, 3], [{ id: 101, name: '张三' }, { name: '李四' }], { manu_id: 2, balance: '$index' }, ); //[101, 107] return ids; ``` -------------------------------- ### Find Single Record by Primary Key in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/schema/assets/yao.md Queries a single record based on its primary key ID. Returns the data record object. AES fields are automatically decrypted. Associated models appear as independent fields, with the field name being the association name; hasOne associations are Object data records, hasMany associations are Array data records. Note: Multiple hasMany associations might cause exceptions. Processor: `models.模型标识.Find`. Parameter 1: Model primary key. Parameter 2: Query conditions. ```javascript function Find() { return Process('models.user.find', 1, { withs: { manu: {}, mother: {}, addresses: {} }, }); } ``` -------------------------------- ### Get Records by Condition in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/model/assets/yao.md This processor queries data records based on specified conditions, returning a collection of matching results. It is similar to SQL's SELECT statement and is frequently used. AES fields are automatically decrypted. 'hasOne' relations return an object, 'hasMany' relations return an array of objects. Note: Multiple 'hasMany' relations might cause issues. ```javascript function Get() { return Process('models.category.get', { wheres: [{ column: 'parent_id', value: null }], }); } ``` ```javascript //直接返回[0],而不会报错 return Process('models.ai.setting.Get', { wheres: [ { Column: 'default', Value: true, }, { Column: 'deleted_at', Value: null, }, ], })[0]; ``` ```javascript //使用解构的方法 const [user] = Process('models.admin.user.get', { wheres: [ { column: 'mobile', value: account }, { column: 'status', value: '启用' }, { method: 'orwhere', column: 'email', value: account }, ], limit: 1, }); ``` ```APIDOC models.模型标识.Get Parameters: 1. Query Conditions (Object): Example: {"wheres":[{"column":"name", "value":"张三"}],"withs":{"manu":{}}}. Uses QueryParam structure. Returns: Collection of matching data records (Key-Value Object structure). Notes: AES fields are automatically decrypted. Associated models are included as separate fields. 'hasOne' relations return an Object, 'hasMany' relations return an Array. Multiple 'hasMany' relations may cause exceptions. ``` -------------------------------- ### CSS Styling for Full-Page Layout Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/login2.html Defines basic CSS rules to ensure the HTML, body, and the main application wrapper (`.app-wrapper`) occupy the full width and height of the viewport, removing default margins and paddings. ```CSS html, body, .app-wrapper { position: relative; width: 100%; height: 100%; margin: 0; padding: 0; } ``` -------------------------------- ### jshERP Database Schema Overview Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/models/app/readme.md This section provides a comprehensive list of the database tables used in the jshERP system, detailing their names and purposes. It serves as a reference for understanding the underlying data structure of the ERP application. ```APIDOC app_jsh_account: Account Information app_jsh_account_head: Financial Main Table app_jsh_account_item: Financial Sub Table app_jsh_depot: Warehouse Table app_jsh_depot_head: Document Main Table app_jsh_depot_item: Document Sub Table app_jsh_function: Function Module Table app_jsh_in_out_item: Income/Expense Item app_jsh_log: Operation Log app_jsh_material: Product Table app_jsh_material_attribute: Product Attribute Table app_jsh_material_category: Product Type Table app_jsh_material_current_stock: Product Current Stock app_jsh_material_extend: Product Price Extension app_jsh_material_initial_stock: Product Initial Stock app_jsh_material_property: Product Extension Field Table app_jsh_msg: Message Table app_jsh_organization: Organization Table app_jsh_orga_user_rel: Organization User Relationship Table app_jsh_person: Handler Table app_jsh_platform_config: Platform Parameters app_jsh_role: Role Table app_jsh_sequence: Document Number Table app_jsh_serial_number: Serial Number Table app_jsh_supplier: Supplier/Customer Information Table app_jsh_system_config: System Parameters app_jsh_tenant: Tenant app_jsh_unit: Multi-Unit Table app_jsh_user: User Table app_jsh_user_business: User/Role/Module Relationship Table ``` -------------------------------- ### AMIS Login Page Initialization with Dynamic Data Loading Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/login2.html An asynchronous JavaScript IIFE (Immediately Invoked Function Expression) that initializes an AMIS application. It uses `amisRequire` to load `amis/embed` and `axios`, then fetches application settings from `/api/__yao/app/setting` and a login page configuration from `pages/user/login2.json`. Finally, it embeds the AMIS JSON configuration into the `#root` element, passing the fetched application data. ```JavaScript (async function () { let amis = amisRequire('amis/embed'); const axios = amisRequire('axios').default || amisRequire('axios'); const appInfo = await axios.get("/api/__yao/app/setting") const configJson = await axios.get("pages/user/login2.json") // 通过替换下面这个配置来生成不同页面 let amisJSON = configJson.data; let amisScoped = amisEmbed.embed('#root', amisJSON, { data: { app: appInfo.data } }); // console.log(JSON.stringify(amisJSON)) })(); ``` -------------------------------- ### Initialize and Use jsPreviewDocx for Word Document Preview Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/preview-word.html This JavaScript code initializes the `jsPreviewDocx` library, retrieves a filename from the URL using the `getURLParameter` function, and then attempts to preview the document. It includes basic error handling for missing files and preview failures. ```JavaScript const myDocxPreviewer = jsPreviewDocx.init(document.getElementById('containter')); const fname = getURLParameter('file'); if (!fname) { alert('Failed to get the word file') } myDocxPreviewer.preview(fname).then(res => { console.log('预览完成'); }).catch(e => { console.log('预览失败', e); }) ``` -------------------------------- ### Basic CSS for Document Body and Main Container Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/preview-word.html This CSS snippet sets the margin and padding of the `body` and `.main` elements to zero, providing a clean slate for layout. ```CSS body, .main { margin: 0; padding: 0; } ``` -------------------------------- ### JavaScript: Initialize and Preview PDF Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/preview-pdf.html This JavaScript code initializes a PDF previewer using `jsPreviewPdf`, retrieves the PDF file name from the URL using the `getURLParameter` function, and attempts to preview the document. It includes an alert for missing file names and console logging for preview success or failure. ```JavaScript const myPdfPreviewer = jsPreviewPdf.init(document.getElementById('container')); const fname = getURLParameter('file'); if (!fname) { alert('Failed to get the pdf file') } myPdfPreviewer.preview(fname).then(res => { console.log('预览完成'); }).catch(e => { console.log('预览失败', e); }) ``` -------------------------------- ### Configure Cross-Origin (CORS) Access for Yao API Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/README.md Allows frontend projects to access the Yao API by setting the YAO_ALLOW_FROM environment variable in the .env file. Multiple allowed origins can be separated by a pipe (|). ```sh YAO_ALLOW_FROM="localhost"。 # 如果多个地址,使用|进行分隔 YAO_ALLOW_FROM="localhost|localhost:5099"。 ``` -------------------------------- ### JavaScript: Initialize LuckyExcel for Excel File Display Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/luckysheet.html This snippet uses jQuery's document ready function to initialize the LuckyExcel library for displaying an Excel file. It retrieves the file URL from page parameters, handles missing URLs or unsupported file types (e.g., .xls), then transforms and renders the Excel data in the 'luckysheet' container. It ensures proper cleanup by destroying any existing `luckysheet` instance before creation. ```JavaScript $(function () { let fnameUrl = getURLParameter('file'); if (!fnameUrl) { alert('Failed to get the sheet file') return } fnameUrl = decodeURIComponent(fnameUrl) const fname = getQuery(fnameUrl, 'name') const filename = fname.split('/').pop() LuckyExcel.transformExcelToLuckyByUrl(fnameUrl, filename, (exportJson, luckysheetfile) => { if (exportJson.sheets == null || exportJson.sheets.length == 0) { alert('Failed to read the content of the excel file, currently does not support xls files!') return } isFunction(window?.luckysheet?.destroy) && window.luckysheet.destroy() window.__currentFile = exportJson; window.luckysheet.create({ container: 'luckysheet', //luckysheet is the container id showinfobar: false, data: exportJson.sheets, title: exportJson.info.name, userInfo: exportJson.info.name.creator, }) }) }) ``` -------------------------------- ### JavaScript Initialize and Use jsPreviewExcel Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/preview-excel.html This JavaScript snippet initializes the `jsPreviewExcel` library on a specified HTML element. It then attempts to retrieve a file name from the URL using the `getURLParameter` function. If a file name is found, it proceeds to preview the Excel file, logging success or failure to the console. ```JavaScript const myExcelPreviewer = jsPreviewExcel.init(document.getElementById('container')); const fname = getURLParameter('file'); if (!fname) { alert('Failed to get the sheet file') } myExcelPreviewer.preview(fname).then(res => { console.log('预览完成'); }).catch(e => { console.log('预览失败', e); }) ``` -------------------------------- ### CSS Styling for Page Layout and Excel Viewer Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/preview-excel.html These CSS rules provide basic styling for the `body` and `.main` elements, setting margins and padding to zero and ensuring they occupy the full viewport height. Additionally, it sets the `.vue-office-excel` element to take 100% height, likely to ensure the Excel previewer fills its container. ```CSS body, .main { margin: 0; padding: 0; } .main { height: 100vh; } .vue-office-excel { height: 100%; } ``` -------------------------------- ### CSS: Basic Page Styling for PDF Preview Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/preview-pdf.html This CSS snippet provides basic styling to remove default margins and padding from the body and main elements, preparing the layout for the PDF previewer to occupy the full available space. ```CSS body, .main { margin: 0; padding: 0; } ``` -------------------------------- ### Basic Layout Styling for yao-amis admin Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/index.html Defines fundamental CSS rules for the HTML, body, and the main application wrapper (.app-wrapper) to ensure full-page coverage and reset default margins/paddings. This sets up the base layout for the application, making it occupy 100% of the viewport height and width. ```CSS html, body, .app-wrapper { position: relative; width: 100%; height: 100%; margin: 0; padding: 0; } ``` -------------------------------- ### yshop Database Table Definitions Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/models/app/readme.md A detailed list of all database tables within the yshop project, including their names and a brief description of their function. This serves as a schema reference for the application's data model. ```APIDOC yshop Database Tables: - app_yshop_shipping_templates: 运费模板表 (Shipping Template Table) - app_yshop_store_canvas: 画布信息表 (Canvas Information Table) - app_yshop_store_cart: 购物车表 (Shopping Cart Table) - app_yshop_store_category: 商品分类表 (Product Category Table) - app_yshop_store_order: 订单表 (Order Table) - app_yshop_store_order_cart_info: 订单购物详情表 (Order Shopping Details Table) - app_yshop_store_order_status: 订单操作记录表 (Order Operation Record Table) - app_yshop_store_product: 商品表 (Product Table) - app_yshop_store_product_attr: 商品属性表 (Product Attribute Table) - app_yshop_store_product_attr_result: 商品属性详情表 (Product Attribute Details Table) - app_yshop_store_product_attr_value: 商品属性值表 (Product Attribute Value Table) - app_yshop_store_product_relation: 商品点赞和收藏表 (Product Like and Collection Table) - app_yshop_store_product_reply: 评论表 (Comment Table) - app_yshop_store_product_rule: 商品规则值(规格)表 (Product Rule Value (Specification) Table) - app_yshop_system_city: 城市表 (City Table) - app_yshop_user: 用户表 (User Table) - app_yshop_user_address: 用户地址表 (User Address Table) - app_yshop_user_bill: 用户账单表 (User Bill Table) - app_yshop_user_extract: 用户提现表 (User Withdrawal Table) - app_yshop_wechat_article: 文章管理表 (Article Management Table) - app_yshop_wechat_menu: 微信缓存表 (WeChat Cache Table) - app_yshop_infra_api_access_log: API 访问日志表 (API Access Log Table) - app_yshop_infra_api_error_log: 系统异常日志 (System Error Log) - app_yshop_infra_codegen_column: 代码生成表字段定义 (Code Generation Table Column Definition) - app_yshop_infra_codegen_table: 代码生成表定义 (Code Generation Table Definition) - app_yshop_infra_config: 参数配置表 (Parameter Configuration Table) - app_yshop_infra_data_source_config: 数据源配置表 (Data Source Configuration Table) - app_yshop_infra_file: 文件表 (File Table) - app_yshop_infra_file_config: 文件配置表 (File Configuration Table) - app_yshop_infra_job: 定时任务表 (Scheduled Task Table) - app_yshop_infra_job_log: 定时任务日志表 (Scheduled Task Log Table) - app_yshop_merchant_details: 支付服务商配置 (Payment Service Provider Configuration) - app_yshop_mp_account: 公众号账号表 (Official Account Table) - app_yshop_mp_auto_reply: 公众号消息自动回复表 (Official Account Message Auto-Reply Table) - app_yshop_mp_material: 公众号素材表 (Official Account Material Table) - app_yshop_mp_menu: 公众号菜单表 (Official Account Menu Table) - app_yshop_mp_message: 公众号消息表 (Official Account Message Table) - app_yshop_mp_tag: 公众号标签表 (Official Account Tag Table) - app_yshop_mp_user: 公众号粉丝表 (Official Account Fan Table) - app_yshop_system_dept: 部门表 (Department Table) - app_yshop_system_dict_data: 字典数据表 (Dictionary Data Table) - app_yshop_system_dict_type: 字典类型表 (Dictionary Type Table) - app_yshop_system_error_code: 错误码表 (Error Code Table) - app_yshop_system_login_log: 系统访问记录 (System Access Record) - app_yshop_system_mail_account: 邮箱账号表 (Email Account Table) - app_yshop_system_mail_log: 邮件日志表 (Email Log Table) - app_yshop_system_mail_template: 邮件模版表 (Email Template Table) - app_yshop_system_menu: 菜单权限表 (Menu Permission Table) - app_yshop_system_notice: 通知公告表 (Notification Announcement Table) - app_yshop_system_notify_message: 站内信消息表 (In-site Message Table) - app_yshop_system_notify_template: 站内信模板表 (In-site Template Table) - app_yshop_system_oauth2_access_token: OAuth2 访问令牌 (OAuth2 Access Token) - app_yshop_system_oauth2_approve: OAuth2 批准表 (OAuth2 Approval Table) - app_yshop_system_oauth2_client: OAuth2 客户端表 (OAuth2 Client Table) - app_yshop_system_oauth2_code: OAuth2 授权码表 (OAuth2 Authorization Code Table) - app_yshop_system_oauth2_refresh_token: OAuth2 刷新令牌 (OAuth2 Refresh Token) - app_yshop_system_operate_log: 操作日志记录 V2 版本 (Operation Log Record V2 Version) - app_yshop_system_post: 岗位信息表 (Post Information Table) - app_yshop_system_role: 角色信息表 (Role Information Table) - app_yshop_system_role_menu: 角色和菜单关联表 (Role and Menu Association Table) - app_yshop_system_sensitive_word: 敏感词 (Sensitive Word) - app_yshop_system_sms_channel: 短信渠道 (SMS Channel) - app_yshop_system_sms_code: 手机验证码 (Mobile Verification Code) - app_yshop_system_sms_log: 短信日志 (SMS Log) - app_yshop_system_sms_template: 短信模板 (SMS Template) - app_yshop_system_social_user: 社交用户表 (Social User Table) - app_yshop_system_social_user_bind: 社交绑定表 (Social Binding Table) - app_yshop_system_tenant: 租户表 (Tenant Table) - app_yshop_system_tenant_package: 租户套餐表 (Tenant Package Table) ``` -------------------------------- ### Basic CSS Styling for Conversion Utility Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/json.html Provides fundamental CSS styling for the HTML elements of the JS/JSON conversion utility, including styles for the body, labels, input fields, text areas, and buttons, ensuring a clean and user-friendly interface. ```CSS body { font-family: Arial, sans-serif; background-color: #f5f5f5; padding: 20px; } label { display: block; margin-bottom: 5px; font-weight: bold; } input\[type="text"\] , textarea { display: block; width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; resize: vertical; } button { background-color: #4CAF50; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; } button:hover { background-color: #3e8e41; } ``` -------------------------------- ### JavaScript: Implement Excel Download Functionality Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/luckysheet.html This JavaScript code attaches an `onclick` event listener to an HTML element with the ID 'myLink'. It prevents the default link navigation and triggers the `downloadExcel` function. The `downloadExcel` function utilizes `luckysheet.getAllSheets()` to retrieve the current spreadsheet data and `exportExcel` to initiate the download, naming the exported file '下载'. ```JavaScript const link = document.getElementById("myLink"); // Attach an onclick event listener link.onclick = function (event) { event.preventDefault(); // Prevents the default link behavior (e.g., navigating to another page) downloadExcel(); }; const downloadExcel = () => { exportExcel(luckysheet.getAllSheets(), '下载') } ``` -------------------------------- ### JavaScript: Extract URL Parameter Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/preview-pdf.html This JavaScript function extracts a specific parameter's value from the current page's URL query string. It leverages the `URLSearchParams` API for efficient and modern URL parsing. ```JavaScript function getURLParameter(parameterName) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(parameterName); } ``` -------------------------------- ### JavaScript: URL Parameter and Type Utility Functions Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/luckysheet.html This snippet provides foundational JavaScript utility functions: `getURLParameter` to extract a parameter from the current URL's query string, `getType` for robust type checking, `isFunction` as a shortcut for function type checking, and `getQuery` to extract a specific query parameter from a given URL string. These functions are essential for client-side data extraction and validation. ```JavaScript function getURLParameter(parameterName) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(parameterName); } function getType(val) { return Object.prototype.toString.call(val).slice(8, -1) } function isFunction(val) { return getType(val) === 'Function' } function getQuery(url, name) { // Find the index of '?' to get the start position of the query parameters const queryStartIndex = url.indexOf('?'); if (queryStartIndex !== -1) { // Extract the query string const queryStr = url.slice(queryStartIndex + 1); // Split the query string into individual parameters const queryParams = queryStr.split('&'); // Iterate over each parameter to find the "name" parameter for (const param of queryParams) { const [key, value] = param.split('='); if (key === name) { return decodeURIComponent(value); break; } } } } ``` -------------------------------- ### JavaScript Function to Convert Input to JSON String Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/json.html This JavaScript function retrieves the current value from an input element, converts it into a JSON string using `JSON.stringify()`, and then displays the resulting JSON data in an output element. It's designed for straightforward string-to-JSON conversion. ```JavaScript function convertToJSON() {\n // Get input value\n const inputValue = document.getElementById("input").value;\n\n // Convert to JSON\n const jsonData = JSON.stringify(inputValue);\n\n // Output JSON data\n document.getElementById("output").value = jsonData;\n} ``` -------------------------------- ### JavaScript Client-Side Authentication and Redirection Logic Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/redirect.html This JavaScript immediately invoked function expression (IIFE) handles the initial authentication check and redirection logic for the AMIS Admin application. It first verifies if an authentication token exists using `yao_amis.getToken()`. If no token is found, the user is redirected to the `/amis-admin/login.html` page. Otherwise, if a token is present, the user is redirected to the `/amis-admin/index.html` dashboard. Finally, it calls `yao_amis.checkToken()` to validate the token, regardless of the initial redirection path. ```JavaScript (function () { if (!yao_amis.getToken()) { window.location.href = "/amis-admin/login.html" } else { window.location.href = "/amis-admin/index.html" } yao_amis.checkToken(); })() ``` -------------------------------- ### Batch Create or Update Records in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/model/assets/yao.md This processor allows for batch creation or updating of multiple records. Records without a primary key field are created, while those with a primary key are updated. It returns a collection of IDs for the created or updated records. ```javascript const ids = Process( 'models.user.EachSave', [{ id: 101, name: '张三' }, { name: '李四' }], { manu_id: 2, balance: '$index' }, ); //[101, 107] return ids; ``` ```APIDOC models.模型标识.EachSave Parameters: 1. Required: Data Record Collection (Array) 2. Optional: Common Fields (Object) - Merged into each record; '$index' is replaced by the record's index. Returns: Collection of IDs for created or updated records. ``` -------------------------------- ### Paginate Records with Pagination Information in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/model/assets/yao.md This processor queries data records based on conditions and returns a data object that includes pagination information. It allows specifying query conditions, current page number, and records per page. ```javascript ``` -------------------------------- ### Delete and Batch Save Records in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/model/assets/yao.md This processor first deletes records based on a given set of IDs, then proceeds to save multiple new records. Records without a primary key are created, while existing ones are updated. It returns a collection of IDs for the newly created or updated records. ```javascript const ids = Process( 'models.user.EachSaveAfterDelete', [1, 2, 3], [{ id: 101, name: '张三' }, { name: '李四' }], { manu_id: 2, balance: '$index' }, ); //[101, 107] return ids; ``` ```APIDOC models.模型标识.EachSaveAfterDelete Parameters: 1. Required: IDs to delete (Array) 2. Required: Data Record Collection to save (Array) 3. Optional: Common Fields (Object) - Merged into each record; '$index' is replaced by the record's index. Returns: Collection of IDs for created or updated records. ``` -------------------------------- ### DropDownButton Component Menu Styling in yao-amis admin Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/index.html Modifies the styling of the dropdown menu for the DropDownButton component within the AMIS scope. It ensures the dropdown menu takes up at least 100% of its parent's width and centers its text content, improving its appearance and usability. ```CSS .amis-scope .cxd-DropDown-menu { min-width: 100%; text-align: center; } ``` -------------------------------- ### Save Single Record in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/model/assets/yao.md This processor creates or updates a single record in a Yao model. If the record includes an 'id', it performs an update; otherwise, it creates a new record. It returns the ID of the created or updated record. ```javascript function Save() { return Process('models.category.save', { parent_id: 1, name: '语文', }); } ``` ```APIDOC models.模型标识.Save Parameters: 1. Data Record (Object): Example: {"name": "用户创建","manu_id": 2,"type": "user"} Returns: ID of the created or updated record. ``` -------------------------------- ### JavaScript Function to Convert JSON String to JS Value Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/public/amis-admin/json.html This JavaScript function attempts to parse an input string as JSON using `JSON.parse()`. In case of a parsing error, it includes a fallback mechanism to replace common escaped newline sequences (like `\\r\\n` and `\\n`) with actual newlines, providing a more robust conversion for potentially malformed or escaped JSON strings before outputting the result. ```JavaScript function convertToJS() {\n // Get input value\n const inputValue = document.getElementById("input").value;\n let jsonData = "";\n try {\n // Convert to JSON\n jsonData = JSON.parse(inputValue);\n } catch (error) {\n jsonData = inputValue.replace(/\\\\r\\\\n/g, '\n');\n jsonData = jsonData.replace(/\\n/g, '\n');\n }\n\n // Output JSON data\n document.getElementById("output").value = jsonData;\n} ``` -------------------------------- ### Delete Records by Condition in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/model/assets/yao.md This processor deletes records based on specified query conditions. If the model definition does not have 'soft_deletes' enabled, the records will be permanently deleted. It returns the number of deleted rows. ```javascript function Deletewhere() { return Process('models.category.deletewhere', { wheres: [{ column: 'parent_id', value: 4 }], }); } ``` ```APIDOC models.模型标识.DeleteWhere Parameters: 1. Query Conditions (Object): Example: {"wheres":[{"column":"name", "value":"张三"}]} Returns: Number of deleted rows. ``` -------------------------------- ### Delete Single Record by ID in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/model/assets/yao.md This processor deletes a single record based on its ID. If the model definition does not have 'soft_deletes' enabled, the record will be permanently deleted. It returns null on success. ```javascript function deletes() { return Process('models.category.delete', 10); } ``` ```APIDOC models.模型标识.Delete Parameters: 1. Data Record ID (Number) Returns: null on success. ``` -------------------------------- ### Permanently Delete Single Record by Primary ID in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/model/assets/yao.md This processor performs a hard delete of a single record based on its primary key ID, bypassing any soft delete mechanisms. It returns null on success. ```javascript function Destroy() { return Process('models.category.destroy', 9); } ``` ```APIDOC models.模型标识.Destroy Parameters: 1. Model Primary Key ID (Number) Returns: null on success. ``` -------------------------------- ### Permanently Delete Records by Condition in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/model/assets/yao.md This processor performs a hard delete of records based on specified query conditions, bypassing any soft delete mechanisms. It returns the number of deleted rows. ```javascript function Destroywhere() { return Process('models.category.destroywhere', { wheres: [{ column: 'parent_id', value: 4 }], }); } ``` ```APIDOC models.模型标识.DestroyWhere Parameters: 1. Query Conditions (Object): Example: {"wheres":[{"column":"name", "value":"张三"}]} Returns: Number of deleted rows. ``` -------------------------------- ### Find Single Record by Primary ID in Yao Model Source: https://github.com/wwsheng009/yao-amis-admin/blob/main/assistants/model/assets/yao.md This processor queries a single record based on its primary key ID. It can also include associated models. AES fields are automatically decrypted. 'hasOne' relations return an object, 'hasMany' relations return an array of objects. Note: Multiple 'hasMany' relations might cause issues. ```javascript function Find() { return Process('models.user.find', 1, { withs: { manu: {}, mother: {}, addresses: {} }, }); } ``` ```APIDOC models.模型标识.Find Parameters: 1. Model Primary Key (Number) 2. Query Conditions (Object) Returns: Data Record Object. Notes: AES fields are automatically decrypted. Associated models are included as separate fields. 'hasOne' relations return an Object, 'hasMany' relations return an Array. Multiple 'hasMany' relations may cause exceptions. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.