Pular para o conteúdo
Odoo Menu
  • Entrar
  • Experimente grátis
  • Aplicativos
    Finanças
    • Financeiro
    • Faturamento
    • Despesas
    • Planilhas (BI)
    • Documentos
    • Assinar Documentos
    Vendas
    • CRM
    • Vendas
    • PDV Loja
    • PDV Restaurantes
    • Assinaturas
    • Locação
    Websites
    • Criador de Sites
    • e-Commerce
    • Blog
    • Fórum
    • Chat ao Vivo
    • e-Learning
    Cadeia de mantimentos
    • Inventário
    • Fabricação
    • PLM - Ciclo de Vida do Produto
    • Compras
    • Manutenção
    • Qualidade
    Recursos Humanos
    • Funcionários
    • Recrutamento
    • Folgas
    • Avaliações
    • Indicações
    • Frota
    Marketing
    • Redes Sociais
    • Marketing por E-mail
    • Marketing por SMS
    • Eventos
    • Automação de Marketing
    • Pesquisas
    Serviços
    • Projeto
    • Planilhas de Horas
    • Serviço de Campo
    • Central de Ajuda
    • Planejamento
    • Compromissos
    Produtividade
    • Mensagens
    • Aprovações
    • Internet das Coisas
    • VoIP
    • Conhecimento
    • WhatsApp
    Aplicativos de terceiros Odoo Studio Plataforma Odoo Cloud
  • Setores
    Varejo
    • Loja de livros
    • Loja de roupas
    • Loja de móveis
    • Mercearia
    • Loja de ferramentas
    • Loja de brinquedos
    Comida e hospitalidade
    • Bar e Pub
    • Restaurante
    • Fast Food
    • Hospedagem
    • Distribuidor de bebidas
    • Hotel
    Imóveis
    • Imobiliária
    • Escritório de arquitetura
    • Construção
    • Administração de propriedades
    • Jardinagem
    • Associação de proprietários de imóveis
    Consultoria
    • Escritório de Contabilidade
    • Parceiro Odoo
    • Agência de marketing
    • Escritório de advocacia
    • Aquisição de talentos
    • Auditoria e Certificação
    Fabricação
    • Têxtil
    • Metal
    • Móveis
    • Alimentação
    • Cervejaria
    • Presentes corporativos
    Saúde e Boa forma
    • Clube esportivo
    • Loja de óculos
    • Academia
    • Profissionais de bem-estar
    • Farmácia
    • Salão de cabeleireiro
    Comércio
    • Handyman
    • Hardware e Suporte de TI
    • Sistemas de energia solar
    • Sapataria
    • Serviços de limpeza
    • Serviços de climatização
    Outros
    • Organização sem fins lucrativos
    • Agência Ambiental
    • Aluguel de outdoors
    • Fotografia
    • Aluguel de bicicletas
    • Revendedor de software
    Navegar por todos os setores
  • Comunidade
    Aprenda
    • Tutoriais
    • Documentação
    • Certificações
    • Treinamento
    • Blog
    • Podcast
    Empodere a Educação
    • Programa de educação
    • Scale Up! Jogo de Negócios
    • Visite a Odoo
    Obtenha o Software
    • Baixar
    • Comparar edições
    • Releases
    Colaborar
    • Github
    • Fórum
    • Eventos
    • Traduções
    • Torne-se um parceiro
    • Serviços para parceiros
    • Cadastre seu escritório contábil
    Obtenha os serviços
    • Encontre um parceiro
    • Encontre um Contador
    • Conheça um consultor
    • Serviços de Implementação
    • Referências de Clientes
    • Suporte
    • Upgrades
    Github YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Faça uma demonstração
  • Preços
  • Ajuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Financeiro
  • Inventário
  • PoS
  • Projeto
  • MRP
All apps
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
Ajuda

How to create systray icon that shows data from model?

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
javascriptOdoo13.0systray
3 Respostas
7514 Visualizações
Avatar
Samo Arko

I'm very bad at JS. I've looked at the mail modules systray icons javascript and template files. I've read the javascript cheetsheet and referance documentation but I cannot get it to work.

I want to gave a systray icon that shows a number same as the mail systray icons and when you click on it, a div with the message apears. The number and message need to be gotten from a models method. This means that I've got a problem with asynchronous promise function. The custom module returns json dump of a dict

JS Code:

odoo.define('odoo13_demo_timer.DemoDays', function (require) {
    'use strict';

    var core = require('web.core');
    var session = require('web.session');
    var SystrayMenu = require('web.SystrayMenu');
    var Widget = require('web.Widget');
    var Qweb = core.qweb;

    var DemoDays = Widget.extend({
        name: 'demo_days_menu',
        template: 'odoo13_demo_timer.DemoDays',
        events: {
            'show.bs.dropdown': '_onDemoDaysShow',
            'hide.bs.dropdown': '_onDemoDaysHide',
        },
        start: function() {
            this._getDemoDaysData();
            return this._super();
        },
        _getDemoDaysData: function() {
            var self = this;

            return self._rpc({
                model: 'demo.installation',
                method: 'get_systray_dict',
                args: [],
                kwargs: {context: session.user_context},
            }).then(function (data) {
                self.demo_days_data = data;
                self.$('.o_demo_days_counter').addClass(data.message_class);
                self.$('.o_demo_days_counter').text(data.expires);
                self.$('.demo_days_message').append(data.message);
            });
        },
        _onDemoDaysShow: function () {
            document.body.classList.add('modal-open');
        },
        _onDemoDaysHide: function () {
            document.body.classList.remove('modal-open');
        },
    });
    DemoDays.prototype.sequence = 100;
    SystrayMenu.Items.push(DemoDays);

    return DemoDays;
});

Template:

<?xml version="1.0" encoding="UTF-8"?>
<templates>
    <t t-name="odoo13_demo_timer.DemoDays">
        <li class="o_timer_systray_item">
            <a class="dropdown-toggle o-no-caret" data-toggle="dropdown" data-display="static" aria-expanded="false" title="Demo Days" href="#" role="button">
                <i class="fa fa-history" role="img" aria-label="Demo Days"/> <span class="o_demo_days_counter badge badge-pill"/>
            </a>
            <div class="o_demo_days_systray_dropdown dropdown-menu dropdown-menu-right">
                <span class="demo_days_message"/>
            </div>
        </li>
    </t>
</templates>

If I hard code the number and message in the start function it works. Getting the data from the model doesn't work. I wasted hours with trying different things but I just cannot get it  to work.

start: function() {
    this.$('.o_demo_days_counter').addClass('green');
    this.$('.o_demo_days_counter').text('15');
    this.$('.demo_days_message').append('some text for message');
},


Can someone help?  


EDIT:

The data is now accessible, when I updated the code with the answer for promise. But it still does not show the data!? Really need help with this.


2
Avatar
Cancelar
Samo Arko
Autor

Finally I've got it to work.

Used @Ravi Gadhia answer for help with the promise. Moved the promise to willStart and only set the DOM elements in the start.

Avatar
Ravi Gadhia
Melhor resposta
start: function() {
var self = this;
return Promise.all([this._super.apply(this, arguments), this._getDemoDaysData()]).then(function () {
self.$('.o_demo_days_counter').addClass(self.demo_days_data.message_class);
self.$('.o_demo_days_counter').text(self.demo_days_data.expires);
self.$('.demo_days_message').append(self.demo_days_data.message);
});
});

},
_getDemoDaysData: function() { var self = this;
return this._rpc({
model: 'demo.installation',
method: 'get_systray_dict',
args: [],
kwargs: {context: session.user_context},
}).then(function (data) {
self.demo_days_data = data;
})
},

try this it will resolve if there is promise issue note: please corrent sytext error if any
2
Avatar
Cancelar
Samo Arko
Autor

Thanks, I have the data but it still does not show the counter or message. You have one to many }); in the return Promise.

Akshay Birajdar

Can you please post the get_systray_dict function?

Samo Arko
Autor

@api.model

def get_systray_dict(self):

demos_obj = dict()

demo_install = self.with_user(SUPERUSER_ID).search([])

if not demo_install:

return json.dumps(demos_obj)

demo_install = demo_install[0]

now = datetime.now().date()

delta = now - demo_install.database_creation

demos_obj['name'] = demo_install.name

demos_obj['days_ago'] = delta.days

demos_obj['expires'] = EXPIRATION_DAYS - demos_obj['days_ago']

demos_obj['deletes'] = DELETION_DAYS - demos_obj['days_ago']

demos_obj['message'] = u'MESSAGE'

if demos_obj['expires'] <= 3:

demos_obj['message_class'] = 'red'

elif demos_obj['expires'] <= 9:

demos_obj['message_class'] = 'yellow'

elif demos_obj['expires'] > 9:

demos_obj['message_class'] = 'green'

else:

demos_obj['message_class'] = 'green'

return json.dumps(demos_obj)

Está gostando da discussão? Não fique apenas lendo, participe!

Crie uma conta hoje mesmo para aproveitar os recursos exclusivos e interagir com nossa incrível comunidade!

Inscreva-se
Publicações relacionadas Respostas Visualizações Atividade
ODOO13 JS Framework how to load vis.js graph Resolvido
javascript Odoo13.0
Avatar
1
mai. 20
5187
How to refresh a kanban view automatically - Odoo13 ?
javascript Odoo13.0
Avatar
Avatar
Avatar
2
fev. 20
6577
How to insert new event in Odoo calendar using another application in javascript
javascript Odoo13.0
Avatar
0
dez. 19
4966
Javascript get model ID from where this JS Function is being called.
javascript Odoo13.0 v14
Avatar
Avatar
1
jun. 24
4287
How to create systray icon?
javascript systray v15
Avatar
Avatar
1
jun. 22
3636
Comunidade
  • Tutoriais
  • Documentação
  • Fórum
Open Source
  • Baixar
  • Github
  • Runbot
  • Traduções
Serviços
  • Odoo.sh Hosting
  • Suporte
  • Upgrade
  • Desenvolvimentos personalizados
  • Educação
  • Encontre um Contador
  • Encontre um parceiro
  • Torne-se um parceiro
Sobre nós
  • Nossa empresa
  • Ativos da marca
  • Contato
  • Empregos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidade
  • Segurança
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo é um conjunto de aplicativos de negócios em código aberto que cobre todas as necessidades de sua empresa: CRM, comércio eletrônico, contabilidade, estoque, ponto de venda, gerenciamento de projetos, etc.

A proposta de valor exclusiva Odoo é ser, ao mesmo tempo, muito fácil de usar e totalmente integrado.

Site feito com

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now