2
0
mirror of https://github.com/frappe/books.git synced 2024-11-10 07:40:55 +00:00
books/frappe/model/meta.js

111 lines
2.1 KiB
JavaScript
Raw Normal View History

2018-01-01 09:27:59 +00:00
const Document = require('./document').Document;
const frappe = require('frappe-core');
class Meta extends Document {
constructor(data) {
super(data);
this.event_handlers = {};
2018-01-09 13:40:56 +00:00
this.list_options = {
fields: ['name', 'modified']
};
if (this.setup_meta) {
this.setup_meta();
}
2018-01-01 09:27:59 +00:00
}
get_field(fieldname) {
if (!this.field_map) {
this.field_map = {};
for (let df of this.fields) {
this.field_map[df.fieldname] = df;
}
}
return this.field_map[fieldname];
}
on(key, fn) {
if (!this.event_handlers[key]) {
this.event_handlers[key] = [];
}
this.event_handlers[key].push(fn);
}
2018-01-09 13:40:56 +00:00
async set(fieldname, value) {
this[fieldname] = value;
await this.trigger(fieldname);
}
get(fieldname) {
return this[fieldname];
}
2018-01-01 09:27:59 +00:00
get_valid_fields() {
if (!this._valid_fields) {
this._valid_fields = [];
// standard fields
for (let df of frappe.model.standard_fields) {
this._valid_fields.push(df);
}
// parent fields
if (this.istable) {
for (let df of frappe.model.child_fields) {
this._valid_fields.push(df);
}
}
// doctype fields
for (let df of this.fields) {
2018-01-02 10:10:32 +00:00
if (frappe.db.type_map[df.fieldtype]) {
2018-01-01 09:27:59 +00:00
this._valid_fields.push(df);
}
}
}
return this._valid_fields;
}
validate_select(df, value) {
let options = df.options;
if (typeof options === 'string') {
// values given as string
options = df.options.split('\n');
}
if (!options.includes(value)) {
throw new frappe.ValueError(`${value} must be one of ${options.join(", ")}`);
}
}
2018-01-09 13:40:56 +00:00
async trigger(key, event = {}) {
2018-01-01 09:27:59 +00:00
2018-01-09 13:40:56 +00:00
Object.assign(event, {
doc: this,
name: key
});
if (this.event_handlers[key]) {
for (var handler of this.event_handlers[key]) {
await handler(event);
}
}
2018-01-01 09:27:59 +00:00
}
2018-01-08 12:30:14 +00:00
2018-01-09 13:40:56 +00:00
// collections
async get_list({start, limit=20, filters}) {
2018-01-08 12:30:14 +00:00
return await frappe.db.get_all({
doctype: this.name,
2018-01-09 13:40:56 +00:00
fields: this.list_options.fields,
filters: filters,
2018-01-08 12:30:14 +00:00
start: start,
limit: limit
});
}
get_row_html(data) {
return `<a href="/view/${this.name}/${data.name}">${data.name}</a>`;
}
2018-01-01 09:27:59 +00:00
}
module.exports = { Meta: Meta }