how to inherit models.js in pos and make some changes? - javascript

models_extend.js
odoo.define('pos_ticket.models_extend', function (require) {
"use strict";
var x = require('point_of_sale.models');
var models = pos_model.PosModel.prototype.models;
models.push(
{
model: 'res.company',
fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' , 'country_id', 'tax_calculation_rounding_method','city','trn_no'],
ids: function(self){ return [self.user.company_id[0]]; },
loaded: function(self,companies){ self.company = companies[0]; },
},
{
model: 'product.product',
fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'barcode', 'default_code',
'to_weight', 'uom_id', 'description_sale', 'description',
'product_tmpl_id','tracking','arb'],
order: ['sequence','default_code','name'],
domain: [['sale_ok','=',true],['available_in_pos','=',true]],
context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
loaded: function(self, products){
self.db.add_products(products);
},
},
{
model: 'product.product',
fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'barcode', 'default_code',
'to_weight', 'uom_id', 'description_sale', 'description',
'product_tmpl_id','tracking','arb'],
order: ['sequence','default_code','name'],
domain: [['sale_ok','=',true],['available_in_pos','=',true]],
context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
loaded: function(self, products){
self.db.add_products(products);
},
}
);
x.Order = x.Order.extend({
export_for_printing: function(){
var self = this;
this.pos = options.pos;
var company = this.pos.company;
var receipt = {
company:{
city:company.city,
trn_no:company.trn_no,
}
}
return receipt;
},
});
I want to add city and trn_no in res.company and arb in product.product to see the arabic translation.Then only i can submit my project in time, i am literally trapped please help me .i am a trainee .
To add new field in POS modules necessary in models.js override PosModel in the parent models which we take from “point_of_sale.models”.
After some changes
odoo.define('pos_ticket.models_extend', function (require) {
"use strict";
var x = require('point_of_sale.models');
var _super = x.PosModel.prototype;
module.PosModel = x.PosModel.extend({
initialize: function (session, attributes) {
// call super to set all properties
_super.initialize.apply(this, arguments);
// here i can access the models list like this and add an element.
this.models.push(
{
// load allowed users
model: 'res.company',
fields: ['city','trn_no'],
domain: function(self){ return [['id','in',self.users.company_id]]; },
loaded: function(self,companies){
console.log(companies);
self.allowed_users = companies;
}
},{
model: 'product.product',
fields: ['arb'],
order: ['sequence','default_code','name'],
domain: [['sale_ok','=',true],['available_in_pos','=',true]],
context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
loaded: function(self, products){
self.db.add_products(products);
}
},
)
return this;
}
});
});
now i need to inherit another function called "export_for_printing" and add those new fields in it so that i can print these fields.how?

Just add the modifications to the self.models array like this. This works for the version 8. Maybe it you need to adapt it:
if (typeof jQuery === 'undefined') { throw new Error('Product multi POS needs jQuery'); }
+function ($) {
'use strict';
openerp.your_module_name = function(instance, module) {
var PosModelParent = instance.point_of_sale.PosModel;
instance.point_of_sale.PosModel = instance.point_of_sale.PosModel.extend({
load_server_data: function(){
var self = this;
self.models.forEach(function(elem) {
if (elem.model == 'res.company') {
elem.fields = // make your new assignations here
elem.domain = // ...
elem.loaded = // ...
} else if (elem.model == 'product.product') {
// [...]
}
})
var loaded = PosModelParent.prototype.load_server_data.apply(this, arguments);
return loaded;
},
});
}
}(jQuery);

Related

Update sales order in NetSuite where order status is pending fulfillment through map/reduce

I need to do following operation performed when my Map/Reduce suiteScript run. It search all sales order where status is Pending Fulfillment, and update their custom checkbox field (field key is my_custom_field_is_proccessed).
How I am trying to do is like below;
/**
* #NApiVersion 2.0
* #NScriptType MapReduceScript
*/
define(['N/search', 'N/record'], function (search, record) {
function getInputData() {
var filter1 = search.createFilter({
name: 'orderstatus',
operator: search.Operator.IS,
values: 'Pending Fulfillment'
});
return search.create({
type: search.Type.SALES_ORDER,
columns: [],
filters: [filter1]
});
}
function map(context) {
try {
var data = JSON.parse(context.value); //read the data
var transId = data.tranid;
var orderstatus = data.orderstatus
var isProcessed = data.my_custom_field_is_proccessed
/*
var order = record.save({
'fromId':data.values['internalid'].value,
'my_custom_field_is_proccessed':true
});
*/
// Update as per below answer
data.forEach(function (order) {
var id = record.submitFields({
type: 'salesOrder',
id: order.internalid,
values: {
my_custom_field_is_proccessed: true
},
options: {
enableSourcing: false,
ignoreMandatoryFields: true
}
});
});
} catch (ex) {
log.error({ title: 'map: error saving records', details: ex });
}
}
function reduce(context) {
// your code here ...
}
function summarize(summary) {
// your code here ...
}
return {
getInputData: getInputData,
map: map,
reduce: reduce,
summarize: summarize
};
});
Can you give try with this code with few changes
/**
* #NApiVersion 2.0
* #NScriptType MapReduceScript
*/
define(['N/search', 'N/record'], function (search, record) {
function getInputData() {
var arrResults = [];
var filter1 = search.createFilter({
name: 'orderstatus',
operator: search.Operator.IS,
values: 'Pending Fulfillment'
});
return search.create({
type: search.Type.SALES_ORDER,
columns: ["internalid"],
filters: [filter1]
});
var id = result.getValue({name: "internalid"});
log.debug({ title: 'id',details: id});
if(id) {
arrResults.push({"id": id, "custom_field_id":custom_field_id});
}
return arrResults;
}
function map(context) {
try {
var data = JSON.parse(context.value); //read the data
var recordId = data.id;
var transId = data.tranid;
var orderstatus = data.orderstatus
var isProcessed = data.my_custom_field_is_proccessed
var recordUpdateData = {
"type": record.Type.SALES_ORDER,
"id": recordId,
"values": {}
};
recordUpdateData["values"][custom_field_id] = 10;
record.submitFields(recordUpdateData);
} catch (ex) {
log.error({ title: 'map: error saving records', details: ex });
}
}
function reduce(context) {
// your code here ...
}
function summarize(summary) {
// your code here ...
}
return {
getInputData: getInputData,
map: map,
reduce: reduce,
summarize: summarize
};
});
Use record.submitFields instead of record.save.
var id = record.submitFields({
type: recordType,
id: id,
values: {
fieldId: value
},
options: {
enableSourcing: false,
ignoreMandatoryFields : true
}
});

Model is not a constructor-Backbone

I have created a model and collection for a json to be fetched as shown here.When i'm instantiating in the service i'm getting error that my model is not a constructor.My model uses collection of models for storing time/value pairs.
ServiceMonitoringModel.js
define(function(require) {
'use strict';
var _ = require('underscore');
var Backbone = require('backbone');
var ServiceMonitoringCollection=require('./ServiceMonitoringCollection');
var ServiceMonitoringModel = Backbone.Model.extend({
modelNAme: 'ServiceMonitoringModel',
idAttribute: 'id',
defaults: {
// todo
content_type: '',
content_graph: {
capacity: null,
performance: {
memory: new ServiceMonitoringCollection(),
cpu: new ServiceMonitoringCollection()
}
}
},
initialize: function() {
//todo
},
validate: function(attributes) {
},
parse: function(response) {
return {
content_type: response.content_type,
content_graph: {
capacity:this.getDeepJsonValue(response, 'capacity'),
performance: {
memory: new ServiceMonitoringCollection(this.getDeepJsonValue(response, 'memory'),{parse:true}),
cpu: new ServiceMonitoringCollection(this.getDeepJsonValue(response, 'cpu'),{parse:true})
}
}
};
}
});
return ServiceMonitoringModel;
});
Service.js
...
var ServiceMonitoringModel=require('common/model/server/ServiceMonitoringModel');
var ServiceMonitoringModel = new ServiceMonitoringModel();
Your problem is:
var ServiceMonitoringModel = new ServiceMonitoringModel();
You are assigning a value to your Model definition. Try:
var serviceMonitoringModel = new ServiceMonitoringModel();
Notice the lowercase s

Meteor + polymer without blaze

I'm trying to use meteor + polymer without blaze templating.
I make this behavior:
MeteorBehavior = {
properties: {
isReady: {
type: Boolean,
value: false,
notify: true
},
currentUser: {
type: Object,
value: null,
notify: true
}
},
ready: function () {
var self = this;
self.subscriptions.forEach(function(itm){
itm = $.type(itm) == 'array' ? itm : [itm];
itm[itm.length] = function () {
self.isReady = true;
};
Meteor.subscribe.apply(null, itm);
});
Meteor.startup(function () {
Tracker.autorun(function(){
self.currentUser = Meteor.user();
});
Tracker.autorun(self.autorun.bind(self));
});
},
subscriptions: [],
autorun: function() { }
};
And i use it:
(function () {
Polymer({
is: 'posts-list',
posts: [],
behaviors: [MeteorBehavior],
autorun: function(){
this.posts = Posts.find().fetch();
},
subscriptions: ['posts']
});
})();
Is it good solution? And how i can animate data changing without blaze uihooks?

Weird Backbone.Validation bug when used with require.js and backbone.stickit

I amusing T. Hedersen's backbone.validation plugin (https://github.com/thedersen/backbone.validation) in conjunction with backbone.stickit plugin for model binding. I am running into a weird error where in it constantly validates all the fields when a single attribute of the model changes. Here is the code
Model
define(function(require) {
"use strict";
var $ = require('jquery'),
Backbone = require('backbone'),
Validation = require('backbone.validation'),
applicantModel = Backbone.Model.extend({
defaults: {
firstName: '',
middleName: '',
lastName: ''
},
initialize: function() {
},
validation: {
firstName: {
required: true
},
middleName: {
required: true
},
lastName: {
required: true
}
}
});
return new applicantModel;
});
View
define(function(require) {
"use strict";
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone'),
tpl = require('text!templates/primaryApplicantInfo.html'),
lovValues = require('application/models/lovModel'),
Stickit = require('stickit'),
ApplicantModel = require('application/models/applicantModel'),
Validation = require('backbone.validation'),
template = _.template(tpl),
applicantView = Backbone.View.extend({
initialize: function() {
console.log('Inside the initialization function');
this.render();
},
bindings: {
'[name=firstName]': {
observe: 'firstName',
setOptions: {
validate: true
}
},
'[name=middleName]': {
observe: 'middleName',
setOptions: {
validate: true
}
},
'[name=lastName]': {
observe: 'lastName',
setOptions: {
validate: true
}
}
},
render: function() {
console.log("Inside applicant view");
//Render application header
this.$el.html(template);
this.stickit();
Backbone.Validation.bind(this, {
//The problem is here, this executes for all the attributes of the model when changing a single attribute
forceUpdate: true,
valid: function(view, attr) {
console.log("Validity is proper for "+attr);
},
invalid: function(view, attr, error) {
console.log("Validity is improper for "+attr);
}
});
$.each(lovValues.toJSON().suffix, function(val, text) {
console.log(text.text);
$('#applicantInfoSuffix').append(new Option(text.text, text.value));
});
Do not set the default values of the model as ''. Remove the default values if possible.
define(function(require) {
"use strict";
var $ = require('jquery'),
Backbone = require('backbone'),
Validation = require('backbone.validation'),
applicantModel = Backbone.Model.extend({
initialize: function() {
},
validation: {
firstName: {
required: true
},
middleName: {
required: true
},
lastName: {
required: true
}
}
});
return new applicantModel;
});

KnockOutJS trigger parent function on child subscribe

I am currently trying to learn KnockOutJS. I thought it would be a great idea to create a simple task-list application.
I do not want to write a long text here, let's dive into my problem. I appreciate all kind of help - I am new to KnockOutJS tho!
The tasks are declared as followed:
var Task = function (data) {
var self = this;
self.name = ko.observable(data.name);
self.status = ko.observable(data.status);
self.priority = ko.observable(data.priority);
}
And the view model looks like this
var TaskListViewModel = function() {
var self = this;
self.currentTask = ko.observable();
self.currentTask(new Task({ name: "", status: false, priority: new Priority({ name: "", value: 0 }) }));
self.tasksArr = ko.observableArray();
self.tasks = ko.computed(function () {
return self.tasksArr.slice().sort(self.sortTasks);
}, self);
self.sortTasks = function (l, r) {
if (l.status() != r.status()) {
if (l.status()) return 1;
else return -1;
}
return (l.priority().value > r.priority().value) ? 1 : -1;
};
self.priorities = [
new Priority({ name: "Low", value: 3 }),
new Priority({ name: "Medium", value: 2 }),
new Priority({ name: "High", value: 1 })
];
// Adds a task to the list
// also saves updated task list to localstorage
self.addTask = function () {
self.tasksArr.push(new Task({ name: self.currentTask().name(), status: false, priority: self.currentTask().priority() }));
self.localStorageSave();
self.currentTask().name("");
};
// Removes a task to a list
// also saves updated task list to localstorage
self.removeTask = function (task) {
self.tasksArr.remove(task);
self.localStorageSave();
};
// Simple test function to check if event is fired.
self.testFunction = function (task) {
console.log("Test function called");
};
// Saves all tasks to localStorage
self.localStorageSave = function () {
localStorage.setItem("romaTasks", ko.toJSON(self.tasksArr));
};
// loads saved data from localstorage and parses them correctly.
self.localStorageLoad = function () {
var parsed = JSON.parse(localStorage.getItem("romaTasks"));
if (parsed != null) {
var tTask = null;
for (var i = 0; i < parsed.length; i++) {
tTask = new Task({
name: parsed[i].name,
status: parsed[i].status,
priority: new Priority({
name: parsed[i].priority.name,
value: parsed[i].priority.value
})
});
self.tasksArr.push(tTask);
}
}
};
self.localStorageLoad();
}
What I want to do in my html is pretty simple.
All tasks I have added are saved to localStorage. The save function is, as you can see, called each time an element has been added & removed. But I also want to save as soon as the status of each task has been changed, but it is not possible to use subscribe here, such as
self.status.subscribe(function() {});
because I cannot access self.tasksArr from the Task class.
Any idea? Is it possible to make the self.tasksArr public somehow?
Thanks in advance!
Try this:
self.addTask = function () {
var myTask = new Task({ name: self.currentTask().name(), status: false, priority: self.currentTask().priority() })
myTask.status.subscribe(function (newValue) {
self.localStorageSave();
});
self.tasksArr.push(myTask);
self.localStorageSave();
self.currentTask().name("");
};

Categories

Resources