Overslaan naar inhoud
Odoo Menu
  • Aanmelden
  • Probeer het gratis
  • Apps
    Financiën
    • Boekhouding
    • Facturatie
    • Onkosten
    • Spreadsheet (BI)
    • Documenten
    • Ondertekenen
    Verkoop
    • CRM
    • Verkoop
    • Kassasysteem winkel
    • Kassasysteem Restaurant
    • Abonnementen
    • Verhuur
    Websites
    • Websitebouwer
    • E-commerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Bevoorradingsketen
    • Voorraad
    • Productie
    • PLM
    • Inkoop
    • Onderhoud
    • Kwaliteit
    Personeelsbeheer
    • Werknemers
    • Werving & Selectie
    • Verlof
    • Evaluaties
    • Aanbevelingen
    • Wagenpark
    Marketing
    • Social media Marketing
    • E-mailmarketing
    • SMS Marketing
    • Evenementen
    • Marketingautomatisering
    • Enquêtes
    Diensten
    • Project
    • Urenstaten
    • Buitendienst
    • Helpdesk
    • Planning
    • Afspraken
    Productiviteit
    • Chat
    • Goedkeuringen
    • IoT
    • VoIP
    • Kennis
    • WhatsApp
    Apps van derden Odoo Studio Odoo Cloud Platform
  • Bedrijfstakken
    Detailhandel
    • Boekhandel
    • kledingwinkel
    • Meubelzaak
    • Supermarkt
    • Bouwmarkt
    • Speelgoedwinkel
    Food & Hospitality
    • Bar en Pub
    • Restaurant
    • Fastfood
    • Gastenverblijf
    • Drankenhandelaar
    • Hotel
    Vastgoed
    • Makelaarskantoor
    • Architectenbureau
    • Bouw
    • Vastgoedbeheer
    • Tuinieren
    • Vereniging van eigenaren
    Consulting
    • Accountantskantoor
    • Odoo Partner
    • Marketingbureau
    • Advocatenkantoor
    • Talentenwerving
    • Audit & Certificering
    Productie
    • Textiel
    • Metaal
    • Meubels
    • Eten
    • Brewery
    • Relatiegeschenken
    Gezondheid & Fitness
    • Sportclub
    • Opticien
    • Fitnesscentrum
    • Wellness-medewerkers
    • Apotheek
    • Kapper
    Trades
    • Klusjesman
    • IT-hardware & support
    • Zonne-energiesystemen
    • Schoenmaker
    • Schoonmaakdiensten
    • HVAC-diensten
    Andere
    • Non-profitorganisatie
    • Milieuagentschap
    • Verhuur van Billboards
    • Fotograaf
    • Fietsleasing
    • Softwareverkoper
    Browse all Industries
  • Community
    Leren
    • Tutorials
    • Documentatie
    • Certificeringen
    • Training
    • Blog
    • Podcast
    Versterk het onderwijs
    • Onderwijs- programma
    • Scale Up! Business Game
    • Bezoek Odoo
    Download de Software
    • Downloaden
    • Vergelijk edities
    • Releases
    Werk samen
    • Github
    • Forum
    • Evenementen
    • Vertalingen
    • Word een Partner
    • Services for Partners
    • Registreer je accountantskantoor
    Diensten
    • Vind een partner
    • Vind een boekhouder
    • Een adviseur ontmoeten
    • Implementatiediensten
    • Klantreferenties
    • Ondersteuning
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Vraag een demo aan
  • Prijzen
  • Help

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

  • CRM
  • e-Commerce
  • Boekhouding
  • Voorraad
  • PoS
  • Project
  • MRP
All apps
Je moet geregistreerd zijn om te kunnen communiceren met de community.
Alle posts Personen Badges
Labels (Bekijk alle)
odoo accounting v14 pos v15
Over dit forum
Je moet geregistreerd zijn om te kunnen communiceren met de community.
Alle posts Personen Badges
Labels (Bekijk alle)
odoo accounting v14 pos v15
Over dit forum
Help

How can I get the current user ID in Odoo version 18 using JavaScript

Inschrijven

Ontvang een bericht wanneer er activiteit is op deze post

Deze vraag is gerapporteerd
javascriptcrm
2 Antwoorden
2205 Weergaven
Avatar
Gowtham A
I got these these issues

Caused by: Error: Service session is not available
Caused by: TypeError: Cannot read properties of undefined (reading 'uid')
Caused by: TypeError: Cannot read properties of undefined (reading 'uid')
Caused by: Error: useService is not available


/** @odoo-module */

import { Component, useState, onWillStart, onMounted, useRef } from "@odoo/owl";
import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";

class MSTSalesTrackingReport extends Component {
setup() {

this.orm = useService("orm");
this.session = useService("session");

const userId = this.session.uid;
console.log(userId, "======== Current User ID ========");
this.state = useState({
salesTeams: [],
allUsers: [],
salespersons: [],
accordionData: [],
userId: userId,
});

this.refs = {
accordion: useRef("accordion"),
};

onMounted(async () => {
try {
// Fetch teams and users
const [allTeams, allUsers] = await Promise.all([
this.orm.searchRead("crm.team", [], ["id", "name", "user_id", "member_ids"]),
this.orm.searchRead("res.users", [["share", "=", false]], ["id", "name"]),
]);

this.state.salesTeams = allTeams;
this.state.allUsers = allUsers;

// Get user groups and team info
const userDetails = await this.orm.searchRead("res.users", [["id", "=", userId]], ["groups_id", "sale_team_id"]);
const userInfo = userDetails[0] || {};
const userGroupIds = userInfo.groups_id || [];
const userTeamId = userInfo.sale_team_id?.[0] || null;

let teamDomain = [];
if (userGroupIds.includes("mst_mems_custom_crm.sales_team_access_controls_group_administrator")) {
teamDomain = [];
} else if (userGroupIds.includes("mst_mems_custom_crm.sales_team_access_controls_group_team_leader")) {
teamDomain = [["user_id", "=", userId]];
} else if (userGroupIds.includes("sales_team_access_controls_group_team_member")) {
teamDomain = [["member_ids", "=", userId]];
}

const filteredTeams = await this.orm.searchRead("crm.team", teamDomain, ["id", "name", "user_id", "member_ids"]);

// Populate team dropdown
const $teamFilter = document.getElementById("team_filter");
if ($teamFilter) {
$teamFilter.innerHTML = `<option value="">All Teams</option>`;
for (const team of filteredTeams) {
const option = document.createElement("option");
option.value = team.id;
option.textContent = team.name;
$teamFilter.appendChild(option);
}

const defaultTeamId = userTeamId || (filteredTeams.length ? filteredTeams[0].id : null);
if (defaultTeamId) {
$teamFilter.value = defaultTeamId;
$teamFilter.dispatchEvent(new Event("change"));
}

$teamFilter.addEventListener("change", (event) => {
const selectedTeamId = parseInt(event.target.value);
if (!selectedTeamId) {
this.state.salespersons = allUsers;
} else {
const selectedTeam = allTeams.find(t => t.id === selectedTeamId);
const memberIds = [...(selectedTeam.member_ids || [])];
if (selectedTeam.user_id?.[0]) memberIds.push(selectedTeam.user_id[0]);
this.state.salespersons = allUsers.filter(u => memberIds.includes(u.id));
}

this.populateSalespersonDropdown(selectedTeamId);
});

// Initial load
if (defaultTeamId) {
await this.populateSalespersonDropdown(defaultTeamId);
}
}

// Handle custom date filter toggle
const $dateFilter = document.getElementById("date_filter");
if ($dateFilter) {
$dateFilter.addEventListener("change", () => {
const show = $dateFilter.value === "custom_date";
document.getElementById("start_date_container").style.display = show ? "block" : "none";
document.getElementById("end_date_container").style.display = show ? "block" : "none";
});
}

// Apply filters
const $applyBtn = document.getElementById("apply_filters");
if ($applyBtn) {
$applyBtn.addEventListener("click", () => this.applyFilters());
}

// Open popup
document.addEventListener("click", (ev) => {
if (ev.target.closest(".open-popup")) {
this.onOpenPopup(ev);
}
});

} catch (error) {
console.error("Error in MSTSalesTracking setup:", error);
}
});
}
0
Avatar
Annuleer
Avatar
D Enterprise
Beste antwoord

Hii,

Fully Working OWL Component (with service check):

/** @odoo-module **/


import { Component, useState, onMounted, useRef } from "@odoo/owl";

import { registry } from "@web/core/registry";

import { useService } from "@web/core/utils/hooks";


class MSTSalesTrackingReport extends Component {

    setup() {

        this.orm = useService("orm");


        let userId = null;

        try {

            const session = useService("session");

            userId = session?.uid ?? null;

            console.log(userId, "======== Current User ID ========");

        } catch (e) {

            console.warn("Session service not available:", e);

        }


        this.state = useState({

            salesTeams: [],

            allUsers: [],

            salespersons: [],

            accordionData: [],

            userId: userId,

        });


        this.refs = {

            accordion: useRef("accordion"),

        };


        onMounted(async () => {

            try {

               

                const [allTeams, allUsers] = await Promise.all([

                    this.orm.searchRead("crm.team", [], ["id", "name", "user_id", "member_ids"]),

                    this.orm.searchRead("res.users", [["share", "=", false]], ["id", "name"]),

                ]);

                this.state.allUsers = allUsers;


               

                const userDetails = await this.orm.searchRead("res.users", [["id", "=", userId]], ["groups_id", "sale_team_id"]);

                const userInfo = userDetails[0] || {};

                const userGroupIds = userInfo.groups_id || [];

                const userTeamId = userInfo.sale_team_id?.[0] || null;


               

                let teamDomain = [];

                if (userGroupIds.includes("mst_mems_custom_crm.sales_team_access_controls_group_administrator")) {

                    teamDomain = [];

                } else if (userGroupIds.includes("mst_mems_custom_crm.sales_team_access_controls_group_team_leader")) {

                    teamDomain = [["user_id", "=", userId]];

                } else if (userGroupIds.includes("sales_team_access_controls_group_team_member")) {

                    teamDomain = [["member_ids", "in", [userId]]];

                }


                const filteredTeams = await this.orm.searchRead("crm.team", teamDomain, ["id", "name", "user_id", "member_ids"]);


               

                const $teamFilter = document.getElementById("team_filter");

                if ($teamFilter) {

                    $teamFilter.innerHTML = `<option value="">All Teams</option>`;

                    for (const team of filteredTeams) {

                        const option = document.createElement("option");

                        option.value = team.id;

                        option.textContent = team.name;

                        $teamFilter.appendChild(option);

                    }


                    const defaultTeamId = userTeamId || (filteredTeams.length ? filteredTeams[0].id : null);

                    if (defaultTeamId) {

                        $teamFilter.value = defaultTeamId;

                        $teamFilter.dispatchEvent(new Event("change"));

                        await this.populateSalespersonDropdown(defaultTeamId);

                    }


                    $teamFilter.addEventListener("change", async (event) => {

                        const selectedTeamId = parseInt(event.target.value);

                        if (!selectedTeamId) {

                            this.state.salespersons = allUsers;

                        } else {

                            const selectedTeam = allTeams.find(t => t.id === selectedTeamId);

                            const memberIds = [...(selectedTeam.member_ids || [])];

                            if (selectedTeam.user_id?.[0]) memberIds.push(selectedTeam.user_id[0]);

                            this.state.salespersons = allUsers.filter(u => memberIds.includes(u.id));

                        }


                        await this.populateSalespersonDropdown(selectedTeamId);

                    });

                }



                const $dateFilter = document.getElementById("date_filter");

                if ($dateFilter) {

                    $dateFilter.addEventListener("change", () => {

                        const show = $dateFilter.value === "custom_date";

                        document.getElementById("start_date_container").style.display = show ? "block" : "none";

                        document.getElementById("end_date_container").style.display = show ? "block" : "none";

                    });

                }



                const $applyBtn = document.getElementById("apply_filters");

                if ($applyBtn) {

                    $applyBtn.addEventListener("click", () => this.applyFilters());

                }



                document.addEventListener("click", (house) => {

                    if (ev.target.closest(".open-popup")) {

                        this.onOpenPopup(ev);

                    }

                });


            } catch (error) {

                console.error("Error in MSTSalesTracking setup:", error);

            }

        });

    }


    async populateSalespersonDropdown(teamId) {

        console.log("Populate salesperson for team:", teamId);


    }


    applyFilters() {

        console.log("Applying filters...");

    }


    onOpenPopup(event) {


        console.log("Opening popup...");

    }

}


registry.category("actions").add("mst_sales_tracking_report", MSTSalesTrackingReport);


Make Sure:
  1. You have this JS module loaded in your manifest under assets like:

'assets': {

    'web.assets_backend': [

        'your_module_name/static/src/js/mst_sales_tracking_report.js',

    ],

}

The component is used in a proper web.client_action (backend only) if you're using useService.


i hope it is usefull

0
Avatar
Annuleer
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Beste antwoord

Hi,


Try the code below.


const userId = this.env.services.user


Hope it helps

0
Avatar
Annuleer
Geniet je van het gesprek? Blijf niet alleen lezen, doe ook mee!

Maak vandaag nog een account aan om te profiteren van exclusieve functies en deel uit te maken van onze geweldige community!

Aanmelden
Gerelateerde posts Antwoorden Weergaven Activiteit
BOTON "NUEVO" CRM
javascript crm
Avatar
Avatar
2
apr. 25
2022
Javascript error in openerp 7
javascript crm
Avatar
0
mrt. 15
4469
Add Selection field in top of tree view to filter data
javascript crm Odoo17
Avatar
Avatar
1
jun. 25
1609
Where to place my own javascript function in openerp
javascript crm js
Avatar
Avatar
1
mrt. 15
4457
Error While Installing Accounting Module in Odoo 19 Enterprise (Works on Another PC)
javascript
Avatar
0
nov. 25
195
Community
  • Tutorials
  • Documentatie
  • Forum
Open Source
  • Downloaden
  • Github
  • Runbot
  • Vertalingen
Diensten
  • Odoo.sh Hosting
  • Ondersteuning
  • Upgrade
  • Gepersonaliseerde ontwikkelingen
  • Onderwijs
  • Vind een boekhouder
  • Vind een partner
  • Word een Partner
Over ons
  • Ons bedrijf
  • Merkelementen
  • Neem contact met ons op
  • Vacatures
  • Evenementen
  • Podcast
  • Blog
  • Klanten
  • Juridisch • Privacy
  • Beveiliging
الْعَرَبيّة 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 is een suite van open source zakelijke apps die aan al je bedrijfsbehoeften voldoet: CRM, E-commerce, boekhouding, inventaris, kassasysteem, projectbeheer, enz.

Odoo's unieke waardepropositie is om tegelijkertijd zeer gebruiksvriendelijk en volledig geïntegreerd te zijn.

Website made with

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