TypeError: instance.web.core is undefined - odoo

I can not add new action in Odoo9
openerp.pr_finance = function(instance, local) {
var _t = instance.web._t, _lt = instance.web._lt;
var QWeb = instance.web.qweb;
var Widget = instance.web.Widget;
var core = instance.web.core;
var data = instance.web.data;
var session = instance.web.session;
var utils = instance.web.utils;
var Model = instance.web.Model;
var ControlPanelMixin = instance.web.ControlPanelMixin;
instance.web.ListView.include({
init: function() {
//console.log('JS loaded');
this._super.apply(this, arguments);
},
render_buttons: function(data) {
console.log('JS loaded load_list');
console.log(data);
this._super(data);
if (this.$buttons) {
this.$buttons.find('.oe_my_button').click(this.proxy('do_import_file_csv_ya_tz')) ;
}
},
do_import_file_csv_ya_tz: function () {
console.log('123123123123123123 ooops....');
this.do_action(
{
name: _t("IMPORT MY FILE"),
type: "ir.actions.client",
tag: 'import_csv',
params: {}
}
);
}
});
var import_csv_yandex = Widget.extend({
template: 'ImportViewYaTC',
start: function () {
console.log("ImportViewYandexTC page loaded");
},
});
var DataImport = Widget.extend(ControlPanelMixin, {
template: 'ImportView',
init: function(parent, action) {
console.log("init ImportView");
this._super.apply(this, arguments);
action.display_name = _t('Import a File');
},
start: function () {
console.log("ImportView page loaded");
},
});
console.log("core.action_registry.add");
try {
instance.web.core.action_registry.add('import_csv', DataImport);
} catch (err) {
console.log(err);
}
console.log("core.action_registry.add - OK!");
}
I received error here:
instance.web.core.action_registry.add('import_csv', DataImport);
Error:
TypeError: instance.web.core is undefined Stack trace:
openerp.pr_finance#http//localhost:8069/web/content/2798-e13ba1c/web.assets_backend.js:4579:1276
start_modules#http//localhost:8069/web/content/2798-e13ba1c/web.assets_backend.js:3235:1
.init#http//localhost:8069/web/content/2798-e13ba1c/web.assets_backend.js:3229:3951
OdooClass.extend/Class.include/
Why this variable is undefined?

You need to use require to get the variables of the env: ie.
odoo.define('yourmodulename.pr_finance', function (require) {
"use strict";
var core = require('web.core');
});
a good place to look at to understand inheritance in odoo is the github.com/oca/web repo.

Related

Error: Unknown named module: "./constants"

I am having an issue where I am trying to import an API, specifically the what3words API, in to my react native app. The problem is that every time I try to import the module, I receive the error 'Unknown named module'
I have managed to pinpoint the issue. When i go in to the node_modules folder, and go to the what3words/api folder and comment out all the 'requires', the error goes away, but then I am unable to use the api.
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "./constants", "./requests/autosuggest", "./requests/autosuggest-selection", "./requests/available-languages", "./requests/convert-to-3wa", "./requests/convert-to-coordinates", "./requests/grid-section", "./utils"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.valid3wa = exports.getWords = exports.getOptions = exports.setOptions = exports.gridSectionGeoJson = exports.gridSection = exports.convertToCoordinatesGeoJson = exports.convertToCoordinates = exports.convertTo3waGeoJson = exports.convertTo3wa = exports.availableLanguages = exports.autosuggestSelection = exports.autosuggest = exports.W3W_REGEX = void 0;
var constants_1 = require("./constants");
Object.defineProperty(exports, "W3W_REGEX", { enumerable: true, get: function () { return constants_1.W3W_REGEX; } });
// var autosuggest_1 = require("./requests/autosuggest");
Object.defineProperty(exports, "autosuggest", { enumerable: true, get: function () { return autosuggest_1.autosuggest; } });
// var autosuggest_selection_1 = require("./requests/autosuggest-selection");
Object.defineProperty(exports, "autosuggestSelection", { enumerable: true, get: function () { return autosuggest_selection_1.autosuggestSelection; } });
// var available_languages_1 = require("./requests/available-languages");
Object.defineProperty(exports, "availableLanguages", { enumerable: true, get: function () { return available_languages_1.availableLanguages; } });
// var convert_to_3wa_1 = require("./requests/convert-to-3wa");
Object.defineProperty(exports, "convertTo3wa", { enumerable: true, get: function () { return convert_to_3wa_1.convertTo3wa; } });
Object.defineProperty(exports, "convertTo3waGeoJson", { enumerable: true, get: function () { return convert_to_3wa_1.convertTo3waGeoJson; } });
// var convert_to_coordinates_1 = require("./requests/convert-to-coordinates");
Object.defineProperty(exports, "convertToCoordinates", { enumerable: true, get: function () { return convert_to_coordinates_1.convertToCoordinates; } });
Object.defineProperty(exports, "convertToCoordinatesGeoJson", { enumerable: true, get: function () { return convert_to_coordinates_1.convertToCoordinatesGeoJson; } });
// var grid_section_1 = require("./requests/grid-section");
Object.defineProperty(exports, "gridSection", { enumerable: true, get: function () { return grid_section_1.gridSection; } });
Object.defineProperty(exports, "gridSectionGeoJson", { enumerable: true, get: function () { return grid_section_1.gridSectionGeoJson; } });
// var utils_1 = require("../es2015/utils.js");
Object.defineProperty(exports, "setOptions", { enumerable: true, get: function () { return utils_1.setOptions; } });
Object.defineProperty(exports, "getOptions", { enumerable: true, get: function () { return utils_1.getOptions; } });
Object.defineProperty(exports, "getWords", { enumerable: true, get: function () { return utils_1.getWords; } });
Object.defineProperty(exports, "valid3wa", { enumerable: true, get: function () { return utils_1.valid3wa; } });
});
After searching online, it appears that this issue is to do with metro and the require function. Please help, Thanks
Managed to fix it!! With some help from one of the contributors of the what3words api. It seems that this is an issue with metro not being able to bundle umd modules. Luckily, the what3words api has es2015 module which we can use instead, so i just used
const api = require('#what3words/api/es2015');
Instead of the previous
const api = require('#what3words/api');
Check https://github.com/what3words/w3w-node-wrapper/issues/28 for the full debugging

How to access local component variable from a callback in vue?

I am trying to set my components variable using an api rest command. I wanted to handle all responses through a function in its own file called handleResponse() which is below.
// api/tools/index.js
function handleResponse (promise, cb, cbError) {
var cbErrorRun = (cbError && typeof cb === "function")
promise.then(function (response) {
if (!response.error) {
cb(response)
}
else if (cbErrorRun) {
cbError(response)
}
}).catch(function (error) {
console.log(error)
if (cbErrorRun) {
var responseError = {
"status": 404,
"error": true,
"message": error.toString()
}
cbError(responseError)
}
})
}
export {handleResponse}
In my component file I have this
.... More above....
<script>
import { fetchStock } from '#/api/stock'
export default {
data () {
return {
stock: {},
tabs: [
{
title: 'Info',
id: 'info'
},
{
title: 'Listings',
id: 'listings'
},
{
title: 'Company',
id: 'company'
}
],
}
},
validate ({params}) {
return /^\d+$/.test(params.id)
},
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
fetchStock(
params,
function(response) { //on successful data retrieval
this.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
}
</script>
The current code gives me this error: "Uncaught (in promise) TypeError: Cannot set property 'stock' of undefinedAc". I think this happens because I no longer have access to 'this' within the callback I pass in the fetchStock function. How would I fix this without changing the current handleResponse layout.
You can try this trick
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
var self = this;
fetchStock(
params,
function(response) { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
You can either use an arrow function for you callback since arrow functions maintain and use the this of their containing scope:
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
fetchStock(
params,
(response) => { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
(responseError) => { //on error
console.log(responseError)
}
)
}
Or you can assign const vm = this n the beginning of your method before the callbacks like so.
vm stands for "View Model"
created: function() {
var params = {'id': this.$route.params.stockId}
//this.$route.params.stockId}
const vm = this;
fetchStock(
params,
function(response) { //on successful data retrieval
self.stock = response.data.payload // payload = {'name': test123}
console.log(response)
},
function(responseError) { //on error
console.log(responseError)
}
)
}
I advise using the const as opposed to var in the vm declaration to make it obvious the value of vm is a constant.

Import sequelize model in vuejs

I'm building a CRUD app using electron + vuejs + sequelize, i have used sequelize init and configured the .sequelizerc as below
const path = require('path');
module.exports = {
'config': path.resolve('src/renderer/database/config', 'config.json'),
'models-path': path.resolve('src/renderer/database', 'models'),
'seeders-path': path.resolve('src/renderer/database', 'seeders'),
'migrations-path': path.resolve('src/renderer/database', 'migrations')
}
Now i'm trying to populate a table with data from the database, I've tried to import the models in many ways, always leading to errors.
Error: Uncaught TypeError: Path must be a string. Received undefined
Component:
var models = require('./../../database/models'); // LINE WITH ERROR
export default {
name: "user-index",
data: function() {
return {
users: []
};
},
created: function() {
models.Users.findAll().then(users => {
//
});
},
components: {},
methods: {}
};
Thanks.
EDIT:
I found the problem, it is in the models/index.js:
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(__filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
var model = sequelize['import'](path.join(__dirname, file)); // THIS LINE
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
I fixed by changing path.join to path.resolve and changing this:
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
to
for (var modelName in db) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
}
in models/index.js file.

Jasmine unit testing throwing error :Unknown provider : $urlRouterProvider

angular.module('myApp.mainview', [])
.config([ '$urlRouterProvider', '$stateProvider', MainGridConfig ])
.controller('homeCtrl',[ '$scope', '$location', '$timeout','quotesservice','base64service', MainPageGrid ]);
function MainGridConfig($urlRouterProvider, $stateProvider) {
'use strict';
$urlRouterProvider.otherwise('/');
$stateProvider.state('home', {
url : '/',
templateUrl : 'template/home.html',
controller : 'homeCtrl'
});
}
function MainPageGrid($scope, $location, $timeout,quotesservice,base64service) {
.....
}
describe('Controller:homeCtrl',function(){
var $controller, scope;
var urlRouterProviderMock = {
};
beforeEach(function(){
module('myApp.mainview');
});
beforeEach(function () {
module(function ($provide) {
$provide.value('$urlRouterProvider', urlRouterProviderMock);
});
});
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('test function',function(){
it('should be true', inject(function($rootScope){
scope = $rootScope.$new();
var ctrl = $controller('mainCtrl', { $scope: scope, $urlRouterProvider: urlRouterProviderMock });
}));
});
});

Invalidate session with custom authenticator

Using ember-cli 0.1.2 and ember-cli-simple-auth 0.7.0, I need to invalidate the session both on client and server. As explained here I need to do something similar to the authenticate method making an ajax request to the server and ensuring its success before emptying the session:
import Ember from 'ember';
import Base from "simple-auth/authenticators/base";
var CustomAuthenticator = Base.extend({
tokenEndpoint: 'http://127.0.0.1:3000/api/v1/auth/login',
restore: function(data) {
},
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
url: _this.tokenEndpoint,
type: 'POST',
data: JSON.stringify({ email: credentials.identification, password: credentials.password }),
contentType: 'application/json'
}).then(function(response) {
Ember.run(function() {
resolve({ token: response.token });
});
}, function(xhr, status, error) {
var response = JSON.parse(xhr.responseText);
Ember.run(function() {
reject(response.error);
});
});
});
},
invalidate: function() {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
url: _this.tokenEndpoint,
type: 'DELETE'
}).then(function(response) {
resolve();
}, function(xhr, status, error) {
var response = JSON.parse(xhr.responseText);
Ember.run(function() {
reject(response.error);
});
});
});
}
// invalidate: function() {
// var _this = this;
// return new Ember.RSVP.Promise(function(resolve) {
// Ember.$.ajax({ url: _this.tokenEndpoint, type: 'DELETE' }).always(function() {
// resolve();
// });
// });
// }
});
export default {
name : 'authentication',
before : 'simple-auth',
initialize : function(container) {
container.register('authenticator:custom', CustomAuthenticator);
}
};
My logout API endpoint need the token (in the headers). How do I pass it? I read this but my authorizer seems ignoring it and I got a 401:
import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';
var CustomAuthorizer = Base.extend({
authorize: function(jqXHR, requestOptions){
Ember.debug("AUTHORIZING!");
}
});
export default {
name : 'authorization',
before : 'simple-auth',
initialize : function(container) {
container.register('authorizer:custom', CustomAuthorizer);
}
};
My environment.js:
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'wishhhh',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
// TODO: disabled because of https://github.com/stefanpenner/ember-cli/issues/2174
ENV.contentSecurityPolicyHeader = 'Disabled-Content-Security-Policy'
ENV['simple-auth'] = {
authorizer: 'authorizer:custom',
// crossOriginWhitelist: ['http://localhost:3000']
crossOriginWhitelist: ['*']
}
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
The following is the Ember inspector output when, eventually, I try to logout:
Did you actually configure Ember Simple Auth to use your custom authorizer? In that case it should authorize the session invalidation request automatically.
Alternatively you could add the token in the authenticator's invalidate method which gets passed the session's contents.
Thanks to marcoow, I found out that it was actually a problem with every request not only the logout one. My authorizer never got called. Problem was environment setup of crossOriginWhitelist which, in order to work with my dev API, I had to set to ['http://127.0.0.1:3000']. Neither ['http://localhost:3000'] nor [*] worked.