size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
547
py
PYTHON
15.0
# Copyright 2020 Florent de Labarre # Copyright 2020 Tecnativa - João Marques # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Online Bank Statements: MyPonto.com", "version": "15.0.1.0.0", "category": "Account", "website": "https://github.com/OCA/bank-statement-import", "author": "Florent de Labarre, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["account_statement_import_online"], "data": ["view/online_bank_statement_provider.xml"], }
39
546
8,475
py
PYTHON
15.0
# Copyright 2020 Florent de Labarre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from datetime import date, datetime from unittest import mock from odoo import fields from odoo.tests import Form, common _module_ns = "odoo.addons.account_statement_import_online_ponto" _provider_class = ( _module_ns + ".models.online_bank_statement_provider_ponto" + ".OnlineBankStatementProviderPonto" ) class TestAccountBankAccountStatementImportOnlineQonto(common.TransactionCase): def setUp(self): super().setUp() self.now = fields.Datetime.now() self.currency_eur = self.env.ref("base.EUR") self.currency_usd = self.env.ref("base.USD") self.AccountJournal = self.env["account.journal"] self.ResPartnerBank = self.env["res.partner.bank"] self.OnlineBankStatementProvider = self.env["online.bank.statement.provider"] self.AccountBankStatement = self.env["account.bank.statement"] self.AccountBankStatementLine = self.env["account.bank.statement.line"] self.AccStatemenPull = self.env["online.bank.statement.pull.wizard"] self.currency_eur.write({"active": True}) self.bank_account = self.ResPartnerBank.create( { "acc_number": "FR0214508000302245362775K46", "partner_id": self.env.user.company_id.partner_id.id, } ) self.journal = self.AccountJournal.create( { "name": "Bank", "type": "bank", "code": "BANK", "currency_id": self.currency_eur.id, "bank_statements_source": "online", "online_bank_statement_provider": "ponto", "bank_account_id": self.bank_account.id, } ) self.provider = self.journal.online_bank_statement_provider_id self.mock_header = lambda: mock.patch( _provider_class + "._ponto_header", return_value={ "Accept": "application/json", "Authorization": "Bearer --TOKEN--", }, ) self.mock_account_ids = lambda: mock.patch( _provider_class + "._ponto_get_account_ids", return_value={"FR0214508000302245362775K46": "id"}, ) self.mock_synchronisation = lambda: mock.patch( _provider_class + "._ponto_synchronisation", return_value=None, ) self.mock_transaction = lambda: mock.patch( _provider_class + "._ponto_get_transaction", return_value=[ { "type": "transaction", "relationships": { "account": { "links": {"related": "https://api.myponto.com/accounts/"}, "data": { "type": "account", "id": "fd3d5b1d-fca9-4310-a5c8-76f2a9dc7c75", }, } }, "id": "701ab965-21c4-46ca-b157-306c0646e0e2", "attributes": { "valueDate": "2019-11-18T00:00:00.000Z", "remittanceInformationType": "unstructured", "remittanceInformation": "Minima vitae totam!", "executionDate": "2019-11-20T00:00:00.000Z", "description": "Wire transfer", "currency": "EUR", "counterpartReference": "BE26089479973169", "counterpartName": "Osinski Group", "amount": 6.08, }, }, { "type": "transaction", "relationships": { "account": { "links": {"related": "https://api.myponto.com/accounts/"}, "data": { "type": "account", "id": "fd3d5b1d-fca9-4310-a5c8-76f2a9dc7c75", }, } }, "id": "9ac50483-16dc-4a82-aa60-df56077405cd", "attributes": { "valueDate": "2019-11-04T00:00:00.000Z", "remittanceInformationType": "unstructured", "remittanceInformation": "Quia voluptatem blanditiis.", "executionDate": "2019-11-06T00:00:00.000Z", "description": "Wire transfer", "currency": "EUR", "counterpartReference": "BE97201830401438", "counterpartName": "Stokes-Miller", "amount": 5.48, }, }, { "type": "transaction", "relationships": { "account": { "links": {"related": "https://api.myponto.com/accounts/"}, "data": { "type": "account", "id": "fd3d5b1d-fca9-4310-a5c8-76f2a9dc7c75", }, } }, "id": "b21a6c65-1c52-4ba6-8cbc-127d2b2d85ff", "attributes": { "valueDate": "2019-11-04T00:00:00.000Z", "remittanceInformationType": "unstructured", "remittanceInformation": "Laboriosam repelo?", "executionDate": "2019-11-04T00:00:00.000Z", "description": "Wire transfer", "currency": "EUR", "counterpartReference": "BE10325927501996", "counterpartName": "Strosin-Veum", "amount": 5.83, }, }, ], ) def test_balance_start(self): st_form = Form(self.AccountBankStatement) st_form.journal_id = self.journal st_form.date = date(2019, 11, 1) st_form.balance_end_real = 100 with st_form.line_ids.new() as line_form: line_form.payment_ref = "test move" line_form.amount = 100 initial_statement = st_form.save() initial_statement.button_post() with self.mock_transaction(), self.mock_header(), self.mock_synchronisation(), self.mock_account_ids(): # noqa: B950 vals = { "provider_ids": self.provider.ids, "date_since": datetime(2019, 11, 4), "date_until": datetime(2019, 11, 5), } wizard = self.AccStatemenPull.with_context( active_model="account.journal", active_id=self.journal.id, ).create(vals) wizard.action_pull() statements = self.AccountBankStatement.search( [("journal_id", "=", self.journal.id)] ) new_statement = statements - initial_statement self.assertEqual(len(new_statement.line_ids), 1) self.assertEqual(new_statement.balance_start, 100) self.assertEqual(new_statement.balance_end_real, 105.83) def test_ponto(self): with self.mock_transaction(), self.mock_header(), self.mock_synchronisation(), self.mock_account_ids(): # noqa: B950 vals = { "provider_ids": self.provider.ids, "date_since": datetime(2019, 11, 3), "date_until": datetime(2019, 11, 17), } wizard = self.AccStatemenPull.with_context( active_model="account.journal", active_id=self.journal.id, ).create(vals) # To get all the moves at once self.provider.statement_creation_mode = "monthly" wizard.action_pull() statement = self.AccountBankStatement.search( [("journal_id", "=", self.journal.id)] ) self.assertEqual(len(statement), 1) self.assertEqual(len(statement.line_ids), 3) self.assertEqual(statement.line_ids.mapped("amount"), [6.08, 5.48, 5.83]) self.assertEqual(statement.balance_end_real, 17.39)
43.020305
8,475
9,602
py
PYTHON
15.0
# Copyright 2020 Florent de Labarre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import base64 import json import re import time from datetime import datetime import pytz import requests from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.addons.base.models.res_bank import sanitize_account_number PONTO_ENDPOINT = "https://api.myponto.com" class OnlineBankStatementProviderPonto(models.Model): _inherit = "online.bank.statement.provider" ponto_token = fields.Char(readonly=True) ponto_token_expiration = fields.Datetime(readonly=True) ponto_last_identifier = fields.Char(readonly=True) def ponto_reset_last_identifier(self): self.write({"ponto_last_identifier": False}) @api.model def _get_available_services(self): return super()._get_available_services() + [ ("ponto", "MyPonto.com"), ] def _obtain_statement_data(self, date_since, date_until): self.ensure_one() if self.service != "ponto": return super()._obtain_statement_data(date_since, date_until) return self._ponto_obtain_statement_data(date_since, date_until) ######### # ponto # ######### def _ponto_header_token(self): self.ensure_one() if self.username and self.password: login = "{}:{}".format(self.username, self.password) login = base64.b64encode(login.encode("UTF-8")).decode("UTF-8") return { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json", "Authorization": "Basic %s" % login, } raise UserError(_("Please fill login and key.")) def _ponto_header(self): self.ensure_one() if ( not self.ponto_token or not self.ponto_token_expiration or self.ponto_token_expiration <= fields.Datetime.now() ): url = PONTO_ENDPOINT + "/oauth2/token" response = requests.post( url, params={"grant_type": "client_credentials"}, headers=self._ponto_header_token(), ) if response.status_code == 200: data = json.loads(response.text) access_token = data.get("access_token", False) if not access_token: raise UserError(_("Ponto : no token")) else: self.sudo().ponto_token = access_token expiration_date = fields.Datetime.now() + relativedelta( seconds=data.get("expires_in", False) ) self.sudo().ponto_token_expiration = expiration_date else: raise UserError( _("{} \n\n {}").format(response.status_code, response.text) ) return { "Accept": "application/json", "Authorization": "Bearer %s" % self.ponto_token, } def _ponto_get_account_ids(self): url = PONTO_ENDPOINT + "/accounts" response = requests.get( url, params={"limit": 100}, headers=self._ponto_header() ) if response.status_code == 200: data = json.loads(response.text) res = {} for account in data.get("data", []): iban = sanitize_account_number( account.get("attributes", {}).get("reference", "") ) res[iban] = account.get("id") return res raise UserError(_("{} \n\n {}").format(response.status_code, response.text)) def _ponto_synchronisation(self, account_id): url = PONTO_ENDPOINT + "/synchronizations" data = { "data": { "type": "synchronization", "attributes": { "resourceType": "account", "resourceId": account_id, "subtype": "accountTransactions", }, } } response = requests.post(url, headers=self._ponto_header(), json=data) if response.status_code in (200, 201, 400): data = json.loads(response.text) sync_id = data.get("attributes", {}).get("resourceId", False) else: raise UserError( _("Error during Create Synchronisation {} \n\n {}").format( response.status_code, response.text ) ) # Check synchronisation if not sync_id: return url = PONTO_ENDPOINT + "/synchronizations/" + sync_id number = 0 while number == 100: number += 1 response = requests.get(url, headers=self._ponto_header()) if response.status_code == 200: data = json.loads(response.text) status = data.get("status", {}) if status in ("success", "error"): return time.sleep(4) def _ponto_get_transaction(self, account_id, date_since, date_until): page_url = PONTO_ENDPOINT + "/accounts/" + account_id + "/transactions" params = {"limit": 100} page_next = True last_identifier = self.ponto_last_identifier if last_identifier: params["before"] = last_identifier page_next = False transaction_lines = [] latest_identifier = False while page_url: response = requests.get( page_url, params=params, headers=self._ponto_header() ) if response.status_code != 200: raise UserError( _("Error during get transaction.\n\n{} \n\n {}").format( response.status_code, response.text ) ) if params.get("before"): params.pop("before") data = json.loads(response.text) links = data.get("links", {}) if page_next: page_url = links.get("next", False) else: page_url = links.get("prev", False) transactions = data.get("data", []) if transactions: current_transactions = [] for transaction in transactions: date = self._ponto_date_from_string( transaction.get("attributes", {}).get("executionDate") ) if date_since <= date < date_until: current_transactions.append(transaction) if current_transactions: if not page_next or (page_next and not latest_identifier): latest_identifier = current_transactions[0].get("id") transaction_lines.extend(current_transactions) if latest_identifier: self.ponto_last_identifier = latest_identifier return transaction_lines def _ponto_date_from_string(self, date_str): """Dates in Ponto are expressed in UTC, so we need to convert them to supplied tz for proper classification. """ dt = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ") dt = dt.replace(tzinfo=pytz.utc).astimezone(pytz.timezone(self.tz or "utc")) return dt.replace(tzinfo=None) def _ponto_obtain_statement_data(self, date_since, date_until): """Translate information from Ponto to Odoo bank statement lines.""" self.ensure_one() account_ids = self._ponto_get_account_ids() journal = self.journal_id iban = self.account_number account_id = account_ids.get(iban) if not account_id: raise UserError( _("Ponto : wrong configuration, unknow account %s") % journal.bank_account_id.acc_number ) self._ponto_synchronisation(account_id) transaction_lines = self._ponto_get_transaction( account_id, date_since, date_until ) new_transactions = [] sequence = 0 for transaction in transaction_lines: sequence += 1 vals_line = self._ponto_get_transaction_vals(transaction, sequence) new_transactions.append(vals_line) if new_transactions: return new_transactions, {} return def _ponto_get_transaction_vals(self, transaction, sequence): """Translate information from Ponto to statement line vals.""" attributes = transaction.get("attributes", {}) ref_list = [ attributes.get(x) for x in {"description", "counterpartName", "counterpartReference"} if attributes.get(x) ] ref = " ".join(ref_list) date = self._ponto_date_from_string(attributes.get("executionDate")) vals_line = { "sequence": sequence, "date": date, "ref": re.sub(" +", " ", ref) or "/", "payment_ref": attributes.get("remittanceInformation", ref), "unique_import_id": transaction["id"], "amount": attributes["amount"], "raw_data": transaction, } if attributes.get("counterpartReference"): vals_line["account_number"] = attributes["counterpartReference"] if attributes.get("counterpartName"): vals_line["partner_name"] = attributes["counterpartName"] return vals_line
38.408
9,602
741
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "CRM Only Security Groups", "summary": "Add new group in Sales to show only CRM", "version": "15.0.1.2.0", "category": "Customer Relationship Management", "website": "https://github.com/OCA/crm", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["crm", "sale_crm"], # sale_crm dependency is necessary to add groups in some view "maintainers": ["victoralmau"], "data": [ "security/security.xml", "security/ir.model.access.csv", "views/menu_items.xml", ], }
35.190476
739
3,487
py
PYTHON
15.0
# Copyright 2021-2022 Tecnativa - Víctor Martínez # License LGPL-3 - See https://www.gnu.org/licenses/lgpl-3.0.html from odoo.exceptions import AccessError from odoo.tests import Form, common, new_test_user from odoo.tests.common import users class TestCrmSecurity(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() group_crm_all_leads = "crm_security_group.group_crm_all_leads" group_sale_salesman_all_leads = "sales_team.group_sale_salesman_all_leads" new_test_user( cls.env, login="crm_user", groups=group_crm_all_leads, ) new_test_user( cls.env, login="sale_user", groups=group_sale_salesman_all_leads, ) new_test_user( cls.env, login="crm_sale_user", groups="%s,%s" % (group_crm_all_leads, group_sale_salesman_all_leads), ) cls.crm_menu = cls.env.ref("crm.crm_menu_root") cls.sale_menu = cls.env.ref("sale.sale_menu_root") # create items to test after cls.partner = cls.env["res.partner"].create({"name": "Test partner"}) cls.crm_lead = cls.env["crm.lead"].sudo().create({"name": "Lead"}) cls.sale_order = ( cls.env["sale.order"].sudo().create({"partner_id": cls.partner.id}) ) @users("crm_user") def test_user_crm_only(self): items = self.env["ir.ui.menu"]._visible_menu_ids() self.assertIn(self.crm_menu.id, items) self.assertNotIn(self.sale_menu.id, items) # Crm lead checks crm_lead = self.env["crm.lead"].browse(self.crm_lead.id) with self.assertRaises(AccessError): crm_lead.unlink() crm_lead_form = Form(self.env["crm.lead"]) crm_lead_form.name = "Lead" crm_lead_form.save() @users("sale_user") def test_user_sale(self): items = self.env["ir.ui.menu"]._visible_menu_ids() self.assertNotIn(self.crm_menu.id, items) self.assertIn(self.sale_menu.id, items) # Crm lead checks crm_lead = self.env["crm.lead"].browse(self.crm_lead.id) with self.assertRaises(AccessError): crm_lead.unlink() crm_lead_form = Form(self.env["crm.lead"]) crm_lead_form.name = "Lead" crm_lead_form.save() # Sale order checks sale_order = self.env["sale.order"].browse(self.sale_order.id) with self.assertRaises(AccessError): sale_order.unlink() sale_order_form = Form(self.env["sale.order"]) sale_order_form.partner_id = self.partner sale_order_form.save() @users("crm_sale_user") def test_user_crm_sale(self): items = self.env["ir.ui.menu"]._visible_menu_ids() self.assertIn(self.crm_menu.id, items) self.assertIn(self.sale_menu.id, items) # Crm lead checks crm_lead = self.env["crm.lead"].browse(self.crm_lead.id) with self.assertRaises(AccessError): crm_lead.unlink() crm_lead_form = Form(self.env["crm.lead"]) crm_lead_form.name = "Lead" crm_lead_form.save() # Sale order checks sale_order = self.env["sale.order"].browse(self.sale_order.id) with self.assertRaises(AccessError): sale_order.unlink() sale_order_form = Form(self.env["sale.order"]) sale_order_form.partner_id = self.partner sale_order_form.save()
38.722222
3,485
537
py
PYTHON
15.0
# Copyright 2015 Antiun Ingenieria - Endika Iglesias <[email protected]> # Copyright 2017 Tecnativa - Luis Martínez # License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html { "name": "CRM location", "category": "Customer Relationship Management", "version": "15.0.1.0.2", "depends": ["crm", "base_location"], "data": ["views/crm_lead_view.xml"], "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/crm", "license": "AGPL-3", "installable": True, }
35.733333
536
1,982
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Luis M. Ontalba # Copyright 2019 Tecnativa - Alexandre Díaz # License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0 from odoo.tests import common class TestCrmLocation(common.TransactionCase): @classmethod def setUpClass(cls): super(TestCrmLocation, cls).setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.country = cls.env["res.country"].create({"name": "Test country"}) cls.state = cls.env["res.country.state"].create( { "name": "Test state", "code": "Test state code", "country_id": cls.country.id, } ) cls.city = cls.env["res.city"].create( { "name": "Test city", "country_id": cls.country.id, "state_id": cls.state.id, } ) cls.location = cls.env["res.city.zip"].create( {"name": "12345", "city_id": cls.city.id} ) cls.lead = cls.env["crm.lead"].create({"name": "Test lead"}) cls.partner = cls.env["res.partner"].create( { "name": "Test partner name", "state_id": cls.state.id, "country_id": cls.country.id, "city_id": cls.city.id, } ) def test_on_change_city(self): self.lead.location_id = self.location.id self.lead.on_change_city() self.assertEqual(self.lead.zip, "12345") self.assertEqual(self.lead.city, "Test city") self.assertEqual(self.lead.state_id.name, "Test state") self.assertEqual(self.lead.country_id.name, "Test country") def test_onchange_partner_id_crm_location(self): self.partner.zip_id = self.location.id self.lead.partner_id = self.partner.id self.lead.onchange_partner_id_crm_location() self.assertEqual(self.lead.location_id.name, "12345")
37.377358
1,981
1,102
py
PYTHON
15.0
# Copyright 2015 Antiun Ingenieria - Endika Iglesias <[email protected]> # Copyright 2017 Tecnativa - Luis Martínez # Copyright 2019 Tecnativa - Alexandre Díaz # License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html from odoo import api, fields, models class CrmLead(models.Model): _inherit = "crm.lead" @api.onchange("location_id") def on_change_city(self): if self.location_id: self.update( { "zip": self.location_id.name, "city": self.location_id.city_id.name, "state_id": self.location_id.city_id.state_id, "country_id": self.location_id.city_id.country_id, } ) location_id = fields.Many2one( comodel_name="res.city.zip", string="Location", index=True, help="Use the city name or the zip code to search the location", ) @api.onchange("partner_id") def onchange_partner_id_crm_location(self): if self.partner_id: self.location_id = self.partner_id.zip_id
32.352941
1,100
682
py
PYTHON
15.0
# Copyright 2016 Tecnativa S.L. - Jairo Llopis # Copyright 2016 Tecnativa S.L. - Vicent Cubells # Copyright 2017 Tecnativa S.L. - David Vidal # Copyright 2018 Tecnativa S.L. - Cristina Martin R. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Tracking Fields in Partners", "summary": "Copy tracking fields from leads to partners", "version": "15.0.1.0.0", "category": "Marketing", "website": "https://github.com/OCA/crm", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["crm"], "data": ["views/res_partner_view.xml"], }
37.888889
682
1,206
py
PYTHON
15.0
# Copyright 2016 Tecnativa S.L. - Jairo Llopis # Copyright 2016 Tecnativa S.L. - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class LeadCase(TransactionCase): def setUp(self): super(LeadCase, self).setUp() self.medium = self.env["utm.medium"].create({"name": "Website"}) self.campaign = self.env["utm.campaign"].create({"name": "Dëmo campaign"}) self.source = self.env["utm.source"].create({"name": "Inteŕnet"}) self.lead = self.env["crm.lead"].create( { "name": "Lead1", "medium_id": self.medium.id, "campaign_id": self.campaign.id, "source_id": self.source.id, } ) def test_transfered_values(self): """Fields get transfered when creating partner.""" self.lead._handle_partner_assignment() if self.lead.partner_id: for _key, field, _cookie in self.env["utm.mixin"].tracking_fields(): self.assertEqual(self.lead[field], self.lead.partner_id[field]) self.assertIsNot(False, self.lead.partner_id[field])
41.517241
1,204
909
py
PYTHON
15.0
# Copyright 2016 Tecnativa S.L. - Jairo Llopis # Copyright 2016 Tecnativa S.L. - Vicent Cubells # Copyright 2016 Tecnativa S.L. - David Vidal # Copyright 2018 Tecnativa S.L. - Cristina Martin R. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, models class CRMLead(models.Model): _inherit = "crm.lead" @api.model def _prepare_customer_values(self, name, is_company, parent_id=False): """Populate marketing fields in partner.""" res = super()._prepare_customer_values(name, is_company, parent_id) # We use self.env['utm.mixin'] for not losing possible overrides # see https://github.com/odoo/odoo/blob/ # e5c8071484c883bf78478a39ef2120bcd8f2442d/addons/utm/models/utm.py#L51 for _key, field, _cookie in self.env["utm.mixin"].tracking_fields(): res[field] = self[field].id return res
41.318182
909
287
py
PYTHON
15.0
# Copyright 2016 Tecnativa S.L. - Jairo Llopis # Copyright 2016 Tecnativa S.L. - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models class ResPartner(models.Model): _name = "res.partner" _inherit = [_name, "utm.mixin"]
28.7
287
1,001
py
PYTHON
15.0
# Copyright 2015-2017 Odoo S.A. # Copyright 2017 Tecnativa - Vicent Cubells # Copyright 2018 Tecnativa - Cristina Martin R. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Claims Management", "version": "15.0.1.1.0", "category": "Customer Relationship Management", "author": "Odoo S.A., Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/crm", "license": "AGPL-3", "summary": "Track your customers/vendors claims and grievances.", "depends": ["crm", "mail"], "data": [ "security/ir.model.access.csv", "security/crm_claim_security.xml", "data/crm_claim_data.xml", "views/crm_claim_views.xml", "views/crm_claim_category_views.xml", "views/crm_claim_stage_views.xml", "views/res_partner_views.xml", "views/crm_claim_menu.xml", "report/crm_claim_report_view.xml", ], "demo": ["demo/crm_claim_demo.xml"], "installable": True, }
35.75
1,001
1,697
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests import common class TestCrmClaim(common.TransactionCase): @classmethod def setUpClass(cls): super(TestCrmClaim, cls).setUpClass() Claims = cls.env["crm.claim"].with_context(mail_create_nosubscribe=True) cls.claim = Claims.create( { "name": "Test Claim", "team_id": cls.env.ref("sales_team.salesteam_website_sales").id, } ) cls.partner = cls.env["res.partner"].create( { "name": "Partner Claim", "email": "[email protected]", "phone": "1234567890", } ) cls.claim_categ = cls.env.ref("crm_claim.categ_claim1") cls.sales_team = cls.claim_categ.team_id def test_crm_claim(self): self.assertNotEqual(self.claim.team_id, self.sales_team) self.assertTrue(self.claim.stage_id.id) self.claim.partner_id = self.partner self.claim.onchange_partner_id() self.assertEqual(self.claim.email_from, self.partner.email) self.assertEqual(self.claim.partner_phone, self.partner.phone) self.assertEqual(self.partner.claim_count, 1) self.claim.categ_id = self.claim_categ self.claim.onchange_categ_id() self.assertEqual(self.claim.team_id, self.sales_team) new_claim = self.claim.copy() self.assertEqual(new_claim.stage_id.id, 1) self.assertIn("copy", new_claim.name) self.assertTrue(new_claim.stage_id.id) self.assertEqual(self.partner.claim_count, 2)
38.568182
1,697
416
py
PYTHON
15.0
# Copyright 2015-2017 Odoo S.A. # Copyright 2017 Tecnativa - Vicent Cubells # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import fields, models class CrmClaimCategory(models.Model): _name = "crm.claim.category" _description = "Category of claim" name = fields.Char(required=True, translate=True) team_id = fields.Many2one(comodel_name="crm.team", string="Sales Team")
32
416
1,334
py
PYTHON
15.0
# Copyright 2015-2017 Odoo S.A. # Copyright 2017 Tecnativa - Vicent Cubells # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import fields, models class CrmClaimStage(models.Model): """Model for claim stages. This models the main stages of a claim management flow. Main CRM objects (leads, opportunities, project issues, ...) will now use only stages, instead of state and stages. Stages are for example used to display the kanban view of records. """ _name = "crm.claim.stage" _description = "Claim stages" _order = "sequence" name = fields.Char(string="Stage Name", required=True, translate=True) sequence = fields.Integer(default=1, help="Used to order stages. Lower is better.") team_ids = fields.Many2many( comodel_name="crm.team", relation="crm_team_claim_stage_rel", column1="stage_id", column2="team_id", string="Teams", help="Link between stages and sales teams. When set, this limitate " "the current stage to the selected sales teams.", ) case_default = fields.Boolean( string="Common to All Teams", help="If you check this field, this stage will be proposed by default " "on each sales team. It will not assign this stage to existing " "teams.", )
38.114286
1,334
1,007
py
PYTHON
15.0
# Copyright 2015-2017 Odoo S.A. # Copyright 2017 Tecnativa - Vicent Cubells # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import api, fields, models class ResPartner(models.Model): _inherit = "res.partner" claim_count = fields.Integer(string="# Claims", compute="_compute_claim_count") claim_ids = fields.One2many(comodel_name="crm.claim", inverse_name="partner_id") @api.depends("claim_ids", "child_ids", "child_ids.claim_ids") def _compute_claim_count(self): partners = self | self.mapped("child_ids") partner_data = self.env["crm.claim"].read_group( [("partner_id", "in", partners.ids)], ["partner_id"], ["partner_id"] ) mapped_data = {m["partner_id"][0]: m["partner_id_count"] for m in partner_data} for partner in self: partner.claim_count = mapped_data.get(partner.id, 0) for child in partner.child_ids: partner.claim_count += mapped_data.get(child.id, 0)
41.958333
1,007
6,575
py
PYTHON
15.0
# Copyright 2015-2017 Odoo S.A. # Copyright 2017 Tecnativa - Vicent Cubells # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import _, api, fields, models from odoo.tools import html2plaintext APPLICABLE_MODELS = [ "account.invoice", "event.registration", "hr.applicant", "res.partner", "product.product", "purchase.order", "purchase.order.line", "sale.order", "sale.order.line", ] class CrmClaim(models.Model): _name = "crm.claim" _description = "Claim" _order = "priority,date desc" _inherit = ["mail.thread", "mail.activity.mixin"] @api.model def _get_default_stage_id(self): """Gives default stage_id""" team_id = self.env["crm.team"]._get_default_team_id() return self.stage_find(team_id.id, [("sequence", "=", "1")]) @api.model def _get_default_team(self): return self.env["crm.team"]._get_default_team_id() @api.model def _selection_model(self): return [ (x, _(self.env[x]._description)) for x in APPLICABLE_MODELS if x in self.env ] name = fields.Char(string="Claim Subject", required=True) active = fields.Boolean(default=True) description = fields.Text() resolution = fields.Text() create_date = fields.Datetime(string="Creation Date", readonly=True) write_date = fields.Datetime(string="Update Date", readonly=True) date_deadline = fields.Date(string="Deadline") date_closed = fields.Datetime(string="Closed", readonly=True) date = fields.Datetime(string="Claim Date", index=True, default=fields.Datetime.now) model_ref_id = fields.Reference( selection="_selection_model", string="Model Reference" ) categ_id = fields.Many2one(comodel_name="crm.claim.category", string="Category") priority = fields.Selection( selection=[("0", "Low"), ("1", "Normal"), ("2", "High")], default="1" ) type_action = fields.Selection( selection=[ ("correction", "Corrective Action"), ("prevention", "Preventive Action"), ], string="Action Type", ) user_id = fields.Many2one( comodel_name="res.users", string="Responsible", tracking=True, default=lambda self: self.env.user, ) user_fault = fields.Char(string="Trouble Responsible") team_id = fields.Many2one( comodel_name="crm.team", string="Sales Team", index=True, default=_get_default_team, help="Responsible sales team. Define Responsible user and Email " "account for mail gateway.", ) company_id = fields.Many2one( comodel_name="res.company", string="Company", default=lambda self: self.env.company, ) partner_id = fields.Many2one(comodel_name="res.partner", string="Partner") email_cc = fields.Text( string="Watchers Emails", help="These email addresses will be added to the CC field of all " "inbound and outbound emails for this record before being sent. " "Separate multiple email addresses with a comma", ) email_from = fields.Char( string="Email", help="Destination email for email gateway." ) partner_phone = fields.Char(string="Phone") stage_id = fields.Many2one( comodel_name="crm.claim.stage", string="Stage", tracking=3, default=_get_default_stage_id, domain="['|', ('team_ids', '=', team_id), ('case_default', '=', True)]", ) cause = fields.Text(string="Root Cause") def stage_find(self, team_id, domain=None, order="sequence"): """Override of the base.stage method Parameter of the stage search taken from the lead: - team_id: if set, stages must belong to this team or be a default case """ if domain is None: # pragma: no cover domain = [] # collect all team_ids team_ids = [] if team_id: team_ids.append(team_id) team_ids.extend(self.mapped("team_id").ids) search_domain = [] if team_ids: search_domain += ["|"] * len(team_ids) for team_id in team_ids: search_domain.append(("team_ids", "=", team_id)) search_domain.append(("case_default", "=", True)) # AND with the domain in parameter search_domain += list(domain) # perform search, return the first found return ( self.env["crm.claim.stage"].search(search_domain, order=order, limit=1).id ) @api.onchange("partner_id") def onchange_partner_id(self): """This function returns value of partner address based on partner :param email: ignored """ if self.partner_id: self.email_from = self.partner_id.email self.partner_phone = self.partner_id.phone @api.onchange("categ_id") def onchange_categ_id(self): if self.stage_id: self.team_id = self.categ_id.team_id @api.model def create(self, values): ctx = self.env.context.copy() if values.get("team_id") and not ctx.get("default_team_id"): ctx["default_team_id"] = values.get("team_id") return super(CrmClaim, self.with_context(context=ctx)).create(values) def copy(self, default=None): default = dict( default or {}, stage_id=self._get_default_stage_id(), name=_("%s (copy)") % self.name, ) return super(CrmClaim, self).copy(default) # ------------------------------------------------------- # Mail gateway # ------------------------------------------------------- @api.model def message_new(self, msg, custom_values=None): """Overrides mail_thread message_new that is called by the mailgateway through message_process. This override updates the document according to the email. """ if custom_values is None: custom_values = {} desc = html2plaintext(msg.get("body")) if msg.get("body") else "" defaults = { "name": msg.get("subject") or _("No Subject"), "description": desc, "email_from": msg.get("from"), "email_cc": msg.get("cc"), "partner_id": msg.get("author_id", False), } if msg.get("priority"): defaults["priority"] = msg.get("priority") defaults.update(custom_values) return super(CrmClaim, self).message_new(msg, custom_values=defaults)
35.928962
6,575
4,263
py
PYTHON
15.0
# Copyright 2015-2017 Odoo S.A. # Copyright 2017 Tecnativa - Vicent Cubells # Copyright 2018 Tecnativa - Cristina Martin R. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from psycopg2.extensions import AsIs from odoo import fields, models, tools class CrmClaimReport(models.Model): """CRM Claim Report""" _name = "crm.claim.report" _auto = False _description = "CRM Claim Report" user_id = fields.Many2one(comodel_name="res.users", string="User", readonly=True) team_id = fields.Many2one(comodel_name="crm.team", string="Team", readonly=True) nbr_claims = fields.Integer(string="# of Claims", readonly=True) company_id = fields.Many2one( comodel_name="res.company", string="Company", readonly=True ) create_date = fields.Datetime(readonly=True, index=True) claim_date = fields.Datetime(readonly=True) delay_close = fields.Float( string="Delay to close", digits=(16, 2), readonly=True, group_operator="avg", help="Number of Days to close the case", ) stage_id = fields.Many2one( comodel_name="crm.claim.stage", string="Stage", readonly=True, domain="[('team_ids','=',team_id)]", ) categ_id = fields.Many2one( comodel_name="crm.claim.category", string="Category", readonly=True ) partner_id = fields.Many2one( comodel_name="res.partner", string="Partner", readonly=True ) priority = fields.Selection( selection=[("0", "Low"), ("1", "Normal"), ("2", "High")] ) type_action = fields.Selection( selection=[ ("correction", "Corrective Action"), ("prevention", "Preventive Action"), ], string="Action Type", ) date_closed = fields.Datetime(string="Close Date", readonly=True, index=True) date_deadline = fields.Date(string="Deadline", readonly=True, index=True) delay_expected = fields.Float( string="Overpassed Deadline", digits=(16, 2), readonly=True, group_operator="avg", ) email = fields.Integer(string="# Emails", readonly=True) subject = fields.Char(string="Claim Subject", readonly=True) def _select(self): select_str = """ SELECT min(c.id) AS id, c.date AS claim_date, c.date_closed AS date_closed, c.date_deadline AS date_deadline, c.user_id, c.stage_id, c.team_id, c.partner_id, c.company_id, c.categ_id, c.name AS subject, count(*) AS nbr_claims, c.priority AS priority, c.type_action AS type_action, c.create_date AS create_date, avg(extract( 'epoch' FROM ( c.date_closed-c.create_date)))/(3600*24) AS delay_close, ( SELECT count(id) FROM mail_message WHERE model='crm.claim' AND res_id=c.id) AS email, extract( 'epoch' FROM ( c.date_deadline - c.date_closed))/(3600*24) AS delay_expected """ return select_str def _from(self): from_str = """ crm_claim c """ return from_str def _group_by(self): group_by_str = """ GROUP BY c.date, c.user_id, c.team_id, c.stage_id, c.categ_id, c.partner_id, c.company_id, c.create_date, c.priority, c.type_action, c.date_deadline, c.date_closed, c.id """ return group_by_str def init(self): """Display Number of cases And Team Name @param cr: the current row, from the database cursor, """ tools.drop_view_if_exists(self.env.cr, self._table) self.env.cr.execute( """ CREATE OR REPLACE VIEW %s AS ( %s from %s %s) """, ( AsIs(self._table), AsIs(self._select()), AsIs(self._from()), AsIs(self._group_by()), ), )
31.813433
4,263
529
py
PYTHON
15.0
# Copyright 2015 Antiun Ingeniería, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "VAT in leads", "summary": "Add VAT field to leads", "version": "15.0.1.0.0", "category": "Customer Relationship Management", "website": "https://github.com/OCA/crm", "author": "Antiun Ingeniería S.L., Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["crm"], "data": ["views/crm_lead_views.xml"], }
32.9375
527
1,174
py
PYTHON
15.0
# Copyright 2015 Antiun Ingeniería, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class LeadCase(TransactionCase): def setUp(self): super(LeadCase, self).setUp() self.lead = self.env["crm.lead"].create( {"name": __file__, "partner_name": "HÎ"} ) self.partner = self.env["res.partner"].create({"name": __file__}) self.test_field = "ES98765432M" def test_transfered_values(self): """Field gets transfered when creating partner.""" self.lead.vat = self.test_field self.lead._handle_partner_assignment() self.assertEqual(self.lead.partner_id.vat, self.test_field) def test_onchange_partner_id(self): """Lead gets VAT from partner when linked to it.""" self.partner.vat = self.test_field result = self.lead._prepare_values_from_partner(self.lead.partner_id) self.assertNotIn("vat", result) self.lead.partner_id = self.partner result = self.lead._prepare_values_from_partner(self.lead.partner_id) self.assertEqual(result["vat"], self.test_field)
40.413793
1,172
820
py
PYTHON
15.0
# Copyright 2015 Antiun Ingeniería, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class Lead(models.Model): _inherit = "crm.lead" vat = fields.Char( string="TIN", help="Tax Identification Number. The first 2 characters are the " "country code.", ) def _create_customer(self): """Add VAT to partner.""" return super(Lead, self.with_context(default_vat=self.vat))._create_customer() def _prepare_values_from_partner(self, partner): """Recover VAT from partner if available.""" result = super(Lead, self)._prepare_values_from_partner(partner) if not partner: return result if partner.vat: result["vat"] = partner.vat return result
30.333333
819
1,117
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) { "name": "Crm Salesperson Planner", "version": "15.0.1.0.0", "development_status": "Beta", "category": "Customer Relationship Management", "author": "Sygel Technology," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/crm", "license": "AGPL-3", "depends": ["crm", "calendar"], "data": [ "data/crm_salesperson_planner_sequence.xml", "wizards/crm_salesperson_planner_visit_close_wiz_view.xml", "wizards/crm_salesperson_planner_visit_template_create.xml", "views/crm_salesperson_planner_visit_views.xml", "views/crm_salesperson_planner_visit_close_reason_views.xml", "views/crm_salesperson_planner_visit_template_views.xml", "views/crm_salesperson_planner_menu.xml", "views/res_partner.xml", "views/crm_lead.xml", "data/ir_cron_data.xml", "security/crm_salesperson_planner_security.xml", "security/ir.model.access.csv", ], "installable": True, }
41.37037
1,117
2,183
py
PYTHON
15.0
from openupgradelib import openupgrade column_spec = { "crm_salesperson_planner_visit_template": [ ("start", None), ("start_datetime", "start"), ("stop", None), ("stop_datetime", "stop"), ] } field_spec = [ ( "crm.salesperson.planner.visit.template", "crm_salesperson_planner_visit_template", "week_list", "weekday", ), ( "crm.salesperson.planner.visit.template", "crm_salesperson_planner_visit_template", "mo", "mon", ), ( "crm.salesperson.planner.visit.template", "crm_salesperson_planner_visit_template", "tu", "tue", ), ( "crm.salesperson.planner.visit.template", "crm_salesperson_planner_visit_template", "we", "wed", ), ( "crm.salesperson.planner.visit.template", "crm_salesperson_planner_visit_template", "th", "thu", ), ( "crm.salesperson.planner.visit.template", "crm_salesperson_planner_visit_template", "fr", "fri", ), ( "crm.salesperson.planner.visit.template", "crm_salesperson_planner_visit_template", "sa", "sat", ), ( "crm.salesperson.planner.visit.template", "crm_salesperson_planner_visit_template", "su", "sun", ), ] @openupgrade.migrate() def migrate(env, version): openupgrade.rename_columns(env.cr, column_spec) openupgrade.rename_fields(env, field_spec, False) openupgrade.logged_query( env.cr, """ UPDATE crm_salesperson_planner_visit_template SET weekday = CASE WHEN weekday = 'FR' THEN 'FRI' WHEN weekday = 'MO' THEN 'MON' WHEN weekday = 'SA' THEN 'SAT' WHEN weekday = 'SU' THEN 'SUN' WHEN weekday = 'TH' THEN 'THU' WHEN weekday = 'TU' THEN 'TUE' WHEN weekday = 'WE' THEN 'WED' END WHERE weekday IN ('FR', 'MO', 'SA', 'SU', 'TH', 'TU', 'WE')""", )
26.950617
2,183
5,623
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from dateutil.relativedelta import relativedelta from odoo import fields from odoo.tests import common class TestCrmSalespersonPlannerVisitBase(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.visit_model = cls.env["crm.salesperson.planner.visit"] cls.partner_model = cls.env["res.partner"] cls.close_model = cls.env["crm.salesperson.planner.visit.close.reason"] cls.close_wiz_model = cls.env["crm.salesperson.planner.visit.close.wiz"] cls.partner1 = cls.partner_model.create( { "name": "Partner Visit 1", "email": "[email protected]", "phone": "1234567890", } ) cls.partner1_contact1 = cls.partner_model.create( { "name": "Partner Contact Visit 1", "email": "[email protected]", "phone": "1234567890", "parent_id": cls.partner1.id, } ) cls.visit1 = cls.visit_model.create({"partner_id": cls.partner1.id}) cls.visit2 = cls.visit_model.create( {"partner_id": cls.partner1_contact1.id, "sequence": 1} ) cls.cancel = cls.close_model.create( { "name": "Cancel", "close_type": "cancel", "require_image": False, "reschedule": False, } ) cls.cancel_resch = cls.close_model.create( { "name": "Cancel", "close_type": "cancel", "require_image": False, "reschedule": True, } ) cls.cancel_img = cls.close_model.create( { "name": "Cancel", "close_type": "cancel", "require_image": True, "reschedule": False, } ) cls.incident = cls.close_model.create( { "name": "Incident", "close_type": "incident", "require_image": False, "reschedule": False, } ) class TestCrmSalespersonPlannerVisit(TestCrmSalespersonPlannerVisitBase): def test_crm_salesperson_planner_visit(self): self.assertNotEqual(self.visit1.name, "/") self.assertEqual(self.visit1.state, "draft") self.assertEqual(self.partner1.salesperson_planner_visit_count, 2) self.assertEqual(self.partner1_contact1.salesperson_planner_visit_count, 1) self.assertEqual(self.visit1.date, fields.Date.context_today(self.visit1)) self.assertEqual( self.visit_model.search( [("partner_id", "child_of", self.partner1.id)], limit=1 ), self.visit2, ) def config_close_wiz(self, att_close_type, vals): additionnal_context = { "active_model": self.visit_model._name, "active_ids": self.visit1.ids, "active_id": self.visit1.id, "att_close_type": att_close_type, } close_wiz = self.close_wiz_model.with_context(**additionnal_context).create( vals ) close_wiz.action_close_reason_apply() def test_crm_salesperson_close_wiz_cancel(self): self.visit1.action_confirm() self.assertEqual(self.visit1.state, "confirm") self.config_close_wiz("close", {"reason_id": self.cancel.id, "notes": "Test"}) self.assertEqual(self.visit1.state, "cancel") self.assertEqual(self.visit1.close_reason_id.id, self.cancel.id) self.assertEqual(self.visit1.close_reason_notes, "Test") self.assertEqual( self.visit_model.search_count( [("partner_id", "child_of", self.partner1.id)] ), 2, ) def test_crm_salesperson_close_wiz_cancel_resch(self): self.visit1.action_confirm() self.assertEqual(self.visit1.state, "confirm") self.config_close_wiz( "close", { "reason_id": self.cancel_resch.id, "new_date": self.visit1.date + relativedelta(days=10), "new_sequence": 40, }, ) self.assertEqual(self.visit1.close_reason_id.id, self.cancel_resch.id) self.assertEqual( self.visit_model.search_count( [ ("partner_id", "=", self.partner1.id), ("date", "=", self.visit1.date + relativedelta(days=10)), ("sequence", "=", 40), ("state", "=", "confirm"), ] ), 1, ) def test_crm_salesperson_close_wiz_cancel_img(self): self.visit1.action_confirm() self.assertEqual(self.visit1.state, "confirm") detail_image = b"R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" self.config_close_wiz( "close", {"reason_id": self.cancel_img.id, "image": detail_image} ) self.assertEqual(self.visit1.close_reason_id.id, self.cancel_img.id) self.assertEqual(self.visit1.close_reason_image, detail_image) def test_crm_salesperson_close_wiz_incident(self): self.visit1.action_confirm() self.assertEqual(self.visit1.state, "confirm") self.config_close_wiz("incident", {"reason_id": self.incident.id}) self.assertEqual(self.visit1.state, "incident")
37.738255
5,623
6,475
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # Copyright 2021 Sygel - Manuel Regidor # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from datetime import timedelta from odoo import exceptions, fields from odoo.tests import common class TestCrmSalespersonPlannerVisitTemplate(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.visit_template_model = cls.env["crm.salesperson.planner.visit.template"] cls.partner_model = cls.env["res.partner"] cls.close_reason_mode = cls.env["crm.salesperson.planner.visit.close.reason"] cls.partner1 = cls.partner_model.create( { "name": "Partner Visit 1", "email": "[email protected]", "phone": "1234567890", } ) cls.visit_template_base = cls.visit_template_model.create( { "partner_ids": [(6, False, cls.partner1.ids)], "start_date": fields.Date.today(), "stop_date": fields.Date.today(), "start": fields.Date.today(), "stop": fields.Date.today(), } ) cls.close_reason = cls.close_reason_mode.create( {"name": "close reason", "close_type": "cancel"} ) def test_01_repeat_days(self): self.visit_template_base.write( { "auto_validate": False, "interval": 1, "rrule_type": "daily", "end_type": "count", "count": 10, } ) self.visit_template_base.action_validate() self.visit_template_base.create_visits(days=4) self.assertEqual(self.visit_template_base.visit_ids_count, 4) self.assertEqual( len( self.visit_template_base.visit_ids.filtered( lambda a: a.state == "draft" ) ), 4, ) self.assertEqual( len( self.visit_template_base.visit_ids.filtered( lambda a: a.calendar_event_id.id ) ), 0, ) self.assertEqual(self.visit_template_base.state, "in-progress") self.visit_template_base.create_visits(days=9) self.visit_template_base._compute_visit_ids_count() self.assertEqual(self.visit_template_base.visit_ids_count, 10) self.assertEqual( len( self.visit_template_base.visit_ids.filtered( lambda a: a.state == "draft" ) ), 10, ) self.assertEqual( len( self.visit_template_base.visit_ids.filtered( lambda a: a.calendar_event_id.id ) ), 0, ) self.assertEqual(self.visit_template_base.state, "done") def test_02_repeat_days_autovalidate(self): self.visit_template_base.write( { "auto_validate": True, "interval": 1, "rrule_type": "daily", "end_type": "count", "count": 10, } ) self.visit_template_base.action_validate() self.visit_template_base.create_visits(days=4) self.assertEqual(self.visit_template_base.visit_ids_count, 4) self.assertEqual( len( self.visit_template_base.visit_ids.filtered( lambda a: a.state == "draft" ) ), 0, ) self.assertEqual( len( self.visit_template_base.visit_ids.filtered( lambda a: a.calendar_event_id.id ) ), 4, ) self.assertEqual(self.visit_template_base.state, "in-progress") self.visit_template_base.create_visits(days=9) self.visit_template_base._compute_visit_ids_count() self.assertEqual(self.visit_template_base.visit_ids_count, 10) self.assertEqual( len( self.visit_template_base.visit_ids.filtered( lambda a: a.state == "draft" ) ), 0, ) self.assertEqual( len( self.visit_template_base.visit_ids.filtered( lambda a: a.calendar_event_id.id ) ), 10, ) self.assertEqual(self.visit_template_base.state, "done") def test_03_change_visit_date(self): visit_template = self.visit_template_base.copy() visit_template.write( { "auto_validate": True, "interval": 1, "rrule_type": "daily", "end_type": "count", "count": 10, } ) visit_template.create_visits(days=10) visit_0 = fields.first(visit_template.visit_ids) event_id_0 = visit_0.calendar_event_id self.assertEqual(visit_0.date, event_id_0.start_date) visit_0.write({"date": fields.Date.today() + timedelta(days=7)}) self.assertEqual(event_id_0.start_date, fields.Date.today() + timedelta(days=7)) event_id_0.write( { "start": fields.Datetime.today() + timedelta(days=14), "stop": fields.Datetime.today() + timedelta(days=14), } ) self.assertEqual(visit_0.date, fields.Date.today() + timedelta(days=14)) def test_04_cancel_visit(self): visit_template = self.visit_template_base.copy() visit_template.write( { "auto_validate": True, "interval": 1, "rrule_type": "daily", "end_type": "count", "count": 10, } ) visit_template.create_visits(days=10) first_visit = fields.first(visit_template.visit_ids) self.assertTrue(first_visit.calendar_event_id) with self.assertRaises(exceptions.ValidationError): first_visit.unlink() self.assertEqual(len(visit_template.visit_ids), 10) first_visit.action_cancel(self.close_reason) self.assertFalse(first_visit.calendar_event_id) first_visit.unlink() self.assertEqual(len(visit_template.visit_ids), 9)
35
6,475
677
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import fields, models class CrmSalespersonPlannerVisitCloseReason(models.Model): _name = "crm.salesperson.planner.visit.close.reason" _description = "SalesPerson Planner Visit Close Reason" name = fields.Char(string="Description", required=True, translate=True) close_type = fields.Selection( selection=[("cancel", "Cancel"), ("incident", "Incident")], string="Type", required=True, default="cancel", ) require_image = fields.Boolean(default=False) reschedule = fields.Boolean(default=False)
35.631579
677
6,950
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # Copyright 2021 Sygel - Manuel Regidor # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import _, api, fields, models from odoo.exceptions import ValidationError class CrmSalespersonPlannerVisit(models.Model): _name = "crm.salesperson.planner.visit" _description = "Salesperson Planner Visit" _order = "date desc,sequence" _inherit = ["mail.thread", "mail.activity.mixin"] name = fields.Char( string="Visit Number", required=True, default="/", readonly=True, copy=False, ) partner_id = fields.Many2one( comodel_name="res.partner", string="Customer", required=True, ) partner_phone = fields.Char(string="Phone", related="partner_id.phone") partner_mobile = fields.Char(string="Mobile", related="partner_id.mobile") date = fields.Date( default=fields.Date.context_today, required=True, ) sequence = fields.Integer( help="Used to order Visits in the different views", default=20, ) company_id = fields.Many2one( comodel_name="res.company", string="Company", default=lambda self: self.env.company, ) user_id = fields.Many2one( comodel_name="res.users", string="Salesperson", index=True, tracking=True, default=lambda self: self.env.user, domain=lambda self: [ ("groups_id", "in", self.env.ref("sales_team.group_sale_salesman").id) ], ) opportunity_ids = fields.Many2many( comodel_name="crm.lead", relation="crm_salesperson_planner_visit_crm_lead_rel", string="Opportunities", copy=False, domain="[('type', '=', 'opportunity'), ('partner_id', 'child_of', partner_id)]", ) description = fields.Html() state = fields.Selection( string="Status", required=True, readonly=True, copy=False, tracking=True, selection=[ ("draft", "Draft"), ("confirm", "Validated"), ("done", "Visited"), ("cancel", "Cancelled"), ("incident", "Incident"), ], default="draft", ) close_reason_id = fields.Many2one( comodel_name="crm.salesperson.planner.visit.close.reason", string="Close Reason" ) close_reason_image = fields.Image(max_width=1024, max_height=1024, attachment=True) close_reason_notes = fields.Text() visit_template_id = fields.Many2one( comodel_name="crm.salesperson.planner.visit.template", string="Visit Template" ) calendar_event_id = fields.Many2one( comodel_name="calendar.event", string="Calendar Event" ) _sql_constraints = [ ( "crm_salesperson_planner_visit_name", "UNIQUE (name)", "The visit number must be unique!", ), ] @api.model_create_multi def create(self, vals_list): for vals in vals_list: if vals.get("name", "/") == "/": vals["name"] = self.env["ir.sequence"].next_by_code( "salesperson.planner.visit" ) return super().create(vals_list) def action_draft(self): if self.state not in ["cancel", "incident", "done"]: raise ValidationError( _("The visit must be in cancelled, incident or visited state") ) if self.calendar_event_id: self.calendar_event_id.with_context(bypass_cancel_visit=True).unlink() self.write({"state": "draft"}) def action_confirm(self): if self.filtered(lambda a: not a.state == "draft"): raise ValidationError(_("The visit must be in draft state")) events = self.create_calendar_event() if events: self.browse(events.mapped("res_id")).write({"state": "confirm"}) def action_done(self): if not self.state == "confirm": raise ValidationError(_("The visit must be in confirmed state")) self.write({"state": "done"}) def action_cancel(self, reason_id, image=None, notes=None): if self.state not in ["draft", "confirm"]: raise ValidationError(_("The visit must be in draft or validated state")) if self.calendar_event_id: self.calendar_event_id.with_context(bypass_cancel_visit=True).unlink() self.write( { "state": "cancel", "close_reason_id": reason_id.id, "close_reason_image": image, "close_reason_notes": notes, } ) def _prepare_calendar_event_vals(self): return { "name": self.name, "partner_ids": [(6, 0, [self.partner_id.id, self.user_id.partner_id.id])], "user_id": self.user_id.id, "start_date": self.date, "stop_date": self.date, "start": self.date, "stop": self.date, "allday": True, "res_model": self._name, "res_model_id": self.env.ref( "crm_salesperson_planner.model_crm_salesperson_planner_visit" ).id, "res_id": self.id, } def create_calendar_event(self): events = self.env["calendar.event"] for item in self: event = self.env["calendar.event"].create( item._prepare_calendar_event_vals() ) if event: event.activity_ids.unlink() item.calendar_event_id = event events += event return events def action_incident(self, reason_id, image=None, notes=None): if self.state not in ["draft", "confirm"]: raise ValidationError(_("The visit must be in draft or validated state")) self.write( { "state": "incident", "close_reason_id": reason_id.id, "close_reason_image": image, "close_reason_notes": notes, } ) def unlink(self): if any(sel.state not in ["draft", "cancel"] for sel in self): raise ValidationError(_("Visits must be in cancelled state")) return super().unlink() def write(self, values): ret_val = super().write(values) if (values.get("date") or values.get("user_id")) and not self.env.context.get( "bypass_update_event" ): new_vals = {} for item in self.filtered(lambda a: a.calendar_event_id): if values.get("date"): new_vals["start"] = values.get("date") new_vals["stop"] = values.get("date") if values.get("user_id"): new_vals["user_id"] = values.get("user_id") item.calendar_event_id.write(new_vals) return ret_val
35.10101
6,950
2,504
py
PYTHON
15.0
# Copyright 2021 Sygel - Manuel Regidor # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import _, fields, models from odoo.exceptions import ValidationError class CalendarEvent(models.Model): _inherit = "calendar.event" salesperson_planner_visit_ids = fields.One2many( string="Salesperson Visits", comodel_name="crm.salesperson.planner.visit", inverse_name="calendar_event_id", ) def write(self, values): if values.get("start") or values.get("user_id"): salesperson_visit_events = self.filtered( lambda a: a.res_model == "crm.salesperson.planner.visit" ) if salesperson_visit_events: new_vals = {} if values.get("start"): new_vals["date"] = values.get("start") if values.get("user_id"): new_vals["user_id"] = values.get("user_id") user_id = self.env["res.users"].browse(values.get("user_id")) if user_id: partner_ids = self.partner_ids.filtered( lambda a: a != self.user_id.partner_id ).ids partner_ids.append(user_id.partner_id.id) values["partner_ids"] = [(6, 0, partner_ids)] salesperson_visit_events.mapped( "salesperson_planner_visit_ids" ).with_context(bypass_update_event=True).write(new_vals) return super().write(values) def unlink(self): if not self.env.context.get("bypass_cancel_visit"): salesperson_visit_events = self.filtered( lambda a: a.res_model == "crm.salesperson.planner.visit" and a.salesperson_planner_visit_ids ) if salesperson_visit_events: error_msg = "" for event in salesperson_visit_events: error_msg += _( "Event %(event_name)s is related to salesperson visit " "%(partner_name)s. Cancel it to delete this event.\n" ) % { "event_name": event.name, "partner_name": fields.first( event.salesperson_planner_visit_ids ).name, } raise ValidationError(error_msg) return super().unlink()
42.440678
2,504
6,886
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # Copyright 2021 Sygel - Manuel Regidor # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from datetime import timedelta from odoo import _, api, fields, models from odoo.exceptions import ValidationError class CrmSalespersonPlannerVisitTemplate(models.Model): _name = "crm.salesperson.planner.visit.template" _description = "Crm Salesperson Planner Visit Template" _inherit = "calendar.event" name = fields.Char( string="Visit Template Number", default="/", readonly=True, copy=False, ) partner_ids = fields.Many2many( string="Customer", relation="salesperson_planner_res_partner_rel", default=False, required=True, ) sequence = fields.Integer( help="Used to order Visits in the different views", default=20, ) company_id = fields.Many2one( comodel_name="res.company", string="Company", default=lambda self: self.env.company, ) user_id = fields.Many2one( string="Salesperson", tracking=True, default=lambda self: self.env.user, domain=lambda self: [ ("groups_id", "in", self.env.ref("sales_team.group_sale_salesman").id) ], ) categ_ids = fields.Many2many( relation="visit_category_rel", ) alarm_ids = fields.Many2many(relation="visit_calendar_event_rel") state = fields.Selection( string="Status", required=True, copy=False, tracking=True, selection=[ ("draft", "Draft"), ("in-progress", "In Progress"), ("done", "Done"), ("cancel", "Cancelled"), ], default="draft", ) visit_ids = fields.One2many( comodel_name="crm.salesperson.planner.visit", inverse_name="visit_template_id", string="Visit Template", ) visit_ids_count = fields.Integer( string="Number of Sales Person Visits", compute="_compute_visit_ids_count" ) auto_validate = fields.Boolean(default=True) rrule_type = fields.Selection( default="daily", required=True, ) last_visit_date = fields.Date(compute="_compute_last_visit_date", store=True) final_date = fields.Date(string="Repeat Until") allday = fields.Boolean(default=True) recurrency = fields.Boolean(default=True) _sql_constraints = [ ( "crm_salesperson_planner_visit_template_name", "UNIQUE (name)", "The visit template number must be unique!", ), ] def _compute_visit_ids_count(self): visit_data = self.env["crm.salesperson.planner.visit"].read_group( [("visit_template_id", "in", self.ids)], ["visit_template_id"], ["visit_template_id"], ) mapped_data = { m["visit_template_id"][0]: m["visit_template_id_count"] for m in visit_data } for sel in self: sel.visit_ids_count = mapped_data.get(sel.id, 0) @api.depends("visit_ids.date") def _compute_last_visit_date(self): for sel in self.filtered(lambda x: x.visit_ids): sel.last_visit_date = sel.visit_ids.sorted(lambda x: x.date)[-1].date @api.constrains("partner_ids") def _constrains_partner_ids(self): for item in self: if len(item.partner_ids) > 1: raise ValidationError(_("Only one customer is allowed")) @api.model_create_multi def create(self, vals_list): for vals in vals_list: if vals.get("name", "/") == "/": vals["name"] = self.env["ir.sequence"].next_by_code( "salesperson.planner.visit.template" ) return super().create(vals_list) # overwrite # Calling _update_cron from default write funciont is not # necessary in this case def write(self, vals): return super(models.Model, self).write(vals) def action_view_salesperson_planner_visit(self): action = self.env["ir.actions.act_window"]._for_xml_id( "crm_salesperson_planner.all_crm_salesperson_planner_visit_action" ) action["domain"] = [("id", "=", self.visit_ids.ids)] action["context"] = { "default_partner_id": self.partner_id.id, "default_visit_template_id": self.id, "default_description": self.description, } return action def action_validate(self): self.write({"state": "in-progress"}) def action_cancel(self): self.write({"state": "cancel"}) def action_draft(self): self.write({"state": "draft"}) def _prepare_crm_salesperson_planner_visit_vals(self, dates): return [ { "partner_id": ( fields.first(self.partner_ids).id if self.partner_ids else False ), "date": date, "sequence": self.sequence, "user_id": self.user_id.id, "description": self.description, "company_id": self.company_id.id, "visit_template_id": self.id, } for date in dates ] def _get_max_date(self): return self._increase_date(self.start_date, self.count) def _increase_date(self, date, value): if self.rrule_type == "daily": date += timedelta(days=value) elif self.rrule_type == "weekly": date += timedelta(weeks=value) elif self.rrule_type == "monthly": date += timedelta(months=value) elif self.rrule_type == "yearly": date += timedelta(years=value) return date def _get_recurrence_dates(self, items): dates = [] max_date = self._get_max_date() from_date = self._increase_date(self.last_visit_date or self.start_date, 1) if max_date > from_date: for _x in range(items): if from_date <= max_date: dates.append(from_date) from_date = self._increase_date(from_date, 1) return dates def _create_visits(self, days=7): return self._prepare_crm_salesperson_planner_visit_vals( self._get_recurrence_dates(days) ) def create_visits(self, days=7): for item in self: visits = self.env["crm.salesperson.planner.visit"].create( item._create_visits(days) ) if visits and item.auto_validate: visits.action_confirm() if item.last_visit_date >= item._get_max_date(): item.state = "done" def _cron_create_visits(self, days=7): templates = self.search([("state", "=", "in-progress")]) templates.create_visits(days)
33.590244
6,886
487
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import fields, models class CrmLead(models.Model): _inherit = "crm.lead" crm_salesperson_planner_visit_ids = fields.Many2many( comodel_name="crm.salesperson.planner.visit", relation="crm_salesperson_planner_visit_crm_lead_rel", string="Visits", copy=False, domain="[('partner_id', 'child_of', partner_id)]", )
30.4375
487
1,345
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" salesperson_planner_visit_count = fields.Integer( string="Number of Salesperson Visits", compute="_compute_salesperson_planner_visit_count", ) def _compute_salesperson_planner_visit_count(self): partners = self | self.mapped("child_ids") partner_data = self.env["crm.salesperson.planner.visit"].read_group( [("partner_id", "in", partners.ids)], ["partner_id"], ["partner_id"] ) mapped_data = {m["partner_id"][0]: m["partner_id_count"] for m in partner_data} for partner in self: visit_count = mapped_data.get(partner.id, 0) for child in partner.child_ids: visit_count += mapped_data.get(child.id, 0) partner.salesperson_planner_visit_count = visit_count def action_view_salesperson_planner_visit(self): action = self.env["ir.actions.act_window"]._for_xml_id( "crm_salesperson_planner.all_crm_salesperson_planner_visit_action" ) operator = "child_of" if self.is_company else "=" action["domain"] = [("partner_id", operator, self.id)] return action
40.757576
1,345
2,362
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import _, fields, models class CrmSalespersonPlannerVisitCloseWiz(models.TransientModel): _name = "crm.salesperson.planner.visit.close.wiz" _description = "Get Close Reason" def _default_new_date(self): visits = self.env["crm.salesperson.planner.visit"].browse( self.env.context.get("active_id") ) return visits.date def _default_new_sequence(self): visits = self.env["crm.salesperson.planner.visit"].browse( self.env.context.get("active_id") ) return visits.sequence reason_id = fields.Many2one( comodel_name="crm.salesperson.planner.visit.close.reason", string="Reason", required=True, ) image = fields.Image(max_width=1024, max_height=1024) new_date = fields.Date(default=lambda self: self._default_new_date()) new_sequence = fields.Integer( string="Sequence", help="Used to order Visits in the different views", default=lambda self: self._default_new_sequence(), ) require_image = fields.Boolean( string="Require Image", related="reason_id.require_image" ) reschedule = fields.Boolean(default=True) allow_reschedule = fields.Boolean( string="Allow Reschedule", related="reason_id.reschedule" ) notes = fields.Text() def action_close_reason_apply(self): visits = self.env["crm.salesperson.planner.visit"].browse( self.env.context.get("active_id") ) visit_close_find_method_name = "action_%s" % self.reason_id.close_type if hasattr(visits, visit_close_find_method_name): getattr(visits, visit_close_find_method_name)( self.reason_id, self.image, self.notes ) if self.allow_reschedule and self.reschedule: visits.copy( { "date": self.new_date, "sequence": self.new_sequence, "opportunity_ids": visits.opportunity_ids.ids, } ).action_confirm() else: raise ValueError(_("The close reason type haven't a function.")) return {"type": "ir.actions.act_window_close"}
37.492063
2,362
1,417
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from datetime import timedelta from odoo import _, fields, models from odoo.exceptions import ValidationError class CrmSalespersonPlannerVisitTemplateCreate(models.TransientModel): _name = "crm.salesperson.planner.visit.template.create" _description = "crm salesperson planner visit template create" def _default_date_to(self): template = self.env["crm.salesperson.planner.visit.template"].browse( self.env.context.get("active_id") ) date = template.last_visit_date or fields.Date.context_today(self) return date + timedelta(days=7) date_to = fields.Date( string="Date to", default=lambda self: self._default_date_to(), required=True ) def create_visits(self): template = self.env["crm.salesperson.planner.visit.template"].browse( self.env.context.get("active_id") ) days = (self.date_to - fields.Date.context_today(self)).days if days < 0: raise ValidationError(_("The date can't be earlier than today")) visits = self.env["crm.salesperson.planner.visit"].create( template._create_visits(days=days) ) if visits and template.auto_validate: visits.action_confirm() return {"type": "ir.actions.act_window_close"}
38.297297
1,417
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
1,502
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-crm", description="Meta package for oca-crm Odoo addons", version=version, install_requires=[ 'odoo-addon-crm_claim>=15.0dev,<15.1dev', 'odoo-addon-crm_claim_type>=15.0dev,<15.1dev', 'odoo-addon-crm_industry>=15.0dev,<15.1dev', 'odoo-addon-crm_lead_code>=15.0dev,<15.1dev', 'odoo-addon-crm_lead_firstname>=15.0dev,<15.1dev', 'odoo-addon-crm_lead_vat>=15.0dev,<15.1dev', 'odoo-addon-crm_location>=15.0dev,<15.1dev', 'odoo-addon-crm_multicompany_reporting_currency>=15.0dev,<15.1dev', 'odoo-addon-crm_partner_assign>=15.0dev,<15.1dev', 'odoo-addon-crm_phonecall>=15.0dev,<15.1dev', 'odoo-addon-crm_phonecall_planner>=15.0dev,<15.1dev', 'odoo-addon-crm_phonecall_summary_predefined>=15.0dev,<15.1dev', 'odoo-addon-crm_project>=15.0dev,<15.1dev', 'odoo-addon-crm_salesperson_planner>=15.0dev,<15.1dev', 'odoo-addon-crm_salesperson_planner_sale>=15.0dev,<15.1dev', 'odoo-addon-crm_security_group>=15.0dev,<15.1dev', 'odoo-addon-crm_stage_probability>=15.0dev,<15.1dev', 'odoo-addon-crm_won_reason>=15.0dev,<15.1dev', 'odoo-addon-marketing_crm_partner>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
41.722222
1,502
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
888
py
PYTHON
15.0
# Copyright 2015 Vauxoo: Yanina Aular <[email protected]>, # Copyright 2015 Vauxoo: Osval Reyes <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "CRM Claim Types", "category": "Customer Relationship Management", "summary": "Claim types for CRM", "author": "Vauxoo, " "Ursa Information Systems, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/crm", "license": "AGPL-3", "version": "15.0.1.0.0", "depends": ["crm_claim"], "data": [ "data/crm_claim_type.xml", "data/crm_claim_stage.xml", "security/ir.model.access.csv", "views/crm_claim.xml", "views/crm_claim_stage.xml", "views/crm_claim_type.xml", ], "demo": ["demo/crm_claim.xml", "demo/crm_claim_stage.xml"], "installable": True, "auto_install": False, }
32.888889
888
518
py
PYTHON
15.0
# Copyright 2015 Vauxoo: Yanina Aular <[email protected]>, # Osval Reyes <[email protected]> # Copyright 2017 Bhavesh Odedra <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class CrmClaimType(models.Model): _name = "crm.claim.type" _description = "Claim Type" name = fields.Char(required=True, translate=True) active = fields.Boolean(default=True) description = fields.Text(translate=True)
34.533333
518
588
py
PYTHON
15.0
# Copyright 2009-2013 Akretion # Copyright 2013 Camptocamp # Copyright 2015 Vauxoo # Copyright 2017 URSA Information Systems # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class CrmClaimStage(models.Model): _inherit = "crm.claim.stage" claim_type = fields.Many2one("crm.claim.type", help="Claim classification") claim_common = fields.Boolean( string="Common to All Claim Types", help="If you check this field," " this stage will be proposed" " by default on each claim type.", )
28
588
725
py
PYTHON
15.0
# Copyright 2015 Vauxoo: Yanina Aular <[email protected]>, # Osval Reyes <[email protected]> # Copyright 2017 Bhavesh Odedra <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class CrmClaim(models.Model): _inherit = "crm.claim" claim_type = fields.Many2one("crm.claim.type", help="Claim classification") stage_id = fields.Many2one( "crm.claim.stage", string="Stage", tracking=True, domain="[ '&'," "'|',('team_ids', '=', team_id), " "('case_default', '=', True), " "'|',('claim_type', '=', claim_type)" ",('claim_common', '=', True)]", )
31.521739
725
616
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) { "name": "Crm Salesperson Planner Sale", "version": "15.0.1.0.0", "development_status": "Beta", "category": "Customer Relationship Management", "author": "Sygel Technology, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/crm", "license": "AGPL-3", "depends": ["crm_salesperson_planner", "sale"], "data": [ "views/sale_order_views.xml", "views/crm_salesperson_planner_visit_views.xml", ], "installable": True, }
36.235294
616
1,464
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo.tests import Form from odoo.addons.crm_salesperson_planner.tests.test_crm_salesperson_planner_visit import ( TestCrmSalespersonPlannerVisitBase, ) class TestCrmSalespersonPlannerSale(TestCrmSalespersonPlannerVisitBase): def _create_sale_order_from_visit(self, visit): res = self.visit1.action_sale_quotation_new() order_form = Form(self.env[res["res_model"]].with_context(**res["context"])) return order_form.save() def test_visit_process(self): self.assertFalse(self.visit1.order_ids) order = self._create_sale_order_from_visit(self.visit1) self.assertEqual(order.visit_id, self.visit1) self.assertIn(order, self.visit1.order_ids) self.assertEqual(self.visit1.sale_order_count, 0) self.assertEqual(self.visit1.quotation_count, 1) res = self.visit1.action_view_sale_quotation() self.assertIn(order, self.env[res["res_model"]].search(res["domain"])) self.assertEqual(res["res_id"], order.id) order.write({"state": "sale"}) self.assertEqual(self.visit1.sale_order_count, 1) self.assertEqual(self.visit1.quotation_count, 0) res = self.visit1.action_view_sale_order() self.assertIn(order, self.env[res["res_model"]].search(res["domain"])) self.assertEqual(res["res_id"], order.id)
45.6875
1,462
486
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import fields, models class SaleOrder(models.Model): _inherit = "sale.order" visit_id = fields.Many2one( comodel_name="crm.salesperson.planner.visit", string="Visit", check_company=True, domain="[('partner_id', 'child_of', partner_id)," " '|', ('company_id', '=', False), ('company_id', '=', company_id)]", )
30.375
486
3,675
py
PYTHON
15.0
# Copyright 2021 Sygel - Valentin Vinagre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import api, fields, models class CrmSalespersonPlannerVisit(models.Model): _inherit = "crm.salesperson.planner.visit" order_ids = fields.One2many("sale.order", "visit_id", string="Orders") sale_order_count = fields.Integer( compute="_compute_sale_data", string="Number of Sale Orders", store=True ) quotation_count = fields.Integer( compute="_compute_sale_data", string="Number of Quotations", store=True ) @api.depends("order_ids.state") def _compute_sale_data(self): quotation_domain = [ ("visit_id", "in", self.ids), ("state", "in", ("draft", "sent")), ] quotation_data = self.env["sale.order"].read_group( domain=quotation_domain, fields=["visit_id"], groupby=["visit_id"] ) sale_domain = [ ("visit_id", "in", self.ids), ("state", "not in", ("draft", "sent", "cancel")), ] sale_data = self.env["sale.order"].read_group( domain=sale_domain, fields=["visit_id"], groupby=["visit_id"] ) mapped_quotation_data = { m["visit_id"][0]: m["visit_id_count"] for m in quotation_data } mapped_sale_data = {m["visit_id"][0]: m["visit_id_count"] for m in sale_data} for sel in self: sel.quotation_count = mapped_quotation_data.get(sel.id, 0) sel.sale_order_count = mapped_sale_data.get(sel.id, 0) def _prepare_context_from_action(self): return { "search_default_visit_id": self.id, "default_visit_id": self.id, "search_default_partner_id": self.partner_id.commercial_partner_id.id, "default_partner_id": self.partner_id.commercial_partner_id.id, "default_origin": self.name, "default_company_id": self.company_id.id or self.env.company.id, "default_user_id": self.user_id.id, } def action_sale_quotation_new(self): action = self.env["ir.actions.act_window"]._for_xml_id( "crm_salesperson_planner_sale.crm_salesperson_visit_action_quotation_new" ) action["context"] = self._prepare_context_from_action() return action def action_view_sale_quotation(self): action = self.env["ir.actions.act_window"]._for_xml_id( "sale.action_quotations_with_onboarding" ) ctx = self._prepare_context_from_action() ctx.update(search_default_draft=1) action["context"] = ctx action["domain"] = [ ("visit_id", "=", self.id), ("state", "in", ("draft", "sent")), ] if self.quotation_count == 1: action["views"] = [(self.env.ref("sale.view_order_form").id, "form")] quotation = self.order_ids.filtered(lambda l: l.state in ("draft", "sent")) action["res_id"] = quotation.id return action def action_view_sale_order(self): action = self.env["ir.actions.act_window"]._for_xml_id("sale.action_orders") action["context"] = self._prepare_context_from_action() action["domain"] = [ ("visit_id", "=", self.id), ("state", "not in", ("draft", "sent", "cancel")), ] if self.sale_order_count == 1: action["views"] = [(self.env.ref("sale.view_order_form").id, "form")] order = self.order_ids.filtered( lambda l: l.state not in ("draft", "sent", "cancel") ) action["res_id"] = order.id return action
40.833333
3,675
564
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) { "name": "CRM won reason", "version": "15.0.1.0.0", "category": "Customer Relationship Management", "author": "Camptocamp, Odoo Community Association (OCA)", "website": "https://github.com/OCA/crm", "license": "AGPL-3", "depends": ["crm"], "data": [ "security/ir.model.access.csv", "wizard/crm_lead_won.xml", "views/crm_views.xml", ], "installable": True, "maintainers": ["ajaniszewska-dev"], }
29.684211
564
2,106
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo.tests import Form from odoo.tests.common import TransactionCase class TestCrmLeadReason(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.crm_lead_model = cls.env["crm.lead"] cls.lead_reason = cls.env["crm.lost.reason"] cls.won_reason = cls.lead_reason.create( {"name": "won reason 1", "reason_type": "won"} ) cls.lost_reason = cls.lead_reason.create( {"name": "lost reason 1", "reason_type": "lost"} ) cls.unspecified_reason = cls.lead_reason.create({"name": "too expensive"}) def test_won_reason(self): crm_lead = self.crm_lead_model.create({"name": "Testing lead won reason"}) wizard_model = self.env["crm.lead.won"].with_context( active_id=crm_lead.id, active_model="crm.lead" ) wizard_form = Form(wizard_model) wizard_form.won_reason_id = self.won_reason wizard_id = wizard_form.save()["id"] wizard_record = wizard_model.browse(wizard_id) wizard_record.with_context(active_ids=crm_lead.id).action_win_reason_apply() self.assertTrue(crm_lead.stage_id.is_won) self.assertEqual(crm_lead.won_reason_id.name, self.won_reason.name) def test_lost_reason(self): crm_lead = self.crm_lead_model.create({"name": "Testing lead lost reason"}) crm_lead.action_set_lost(lost_reason=self.lost_reason) self.assertFalse(crm_lead.stage_id.is_won) self.assertEqual(crm_lead.lost_reason.name, self.lost_reason.name) def test_unspecified_reason(self): crm_lead = self.crm_lead_model.create( {"name": "Testing lead unspecified reason"} ) crm_lead.action_set_lost(lost_reason=self.unspecified_reason) self.assertFalse(crm_lead.stage_id.is_won) self.assertEqual(crm_lead.lost_reason.name, self.unspecified_reason.name)
42.979592
2,106
297
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo import fields, models class CrmLeadLost(models.TransientModel): _inherit = "crm.lead.lost" lost_reason_id = fields.Many2one(domain="[('reason_type', 'in', (False, 'lost'))]")
27
297
612
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo import fields, models class CrmLeadReason(models.TransientModel): _name = "crm.lead.won" _description = "Get Won Reason" won_reason_id = fields.Many2one( "crm.lost.reason", "Won Reason", domain="[('reason_type', 'in', (False, 'won'))]", ) def action_win_reason_apply(self): leads = self.env["crm.lead"].browse(self.env.context.get("active_ids")) leads.action_set_won() return leads.write({"won_reason_id": self.won_reason_id.id})
30.6
612
291
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import fields, models class CrmLostReason(models.Model): _inherit = "crm.lost.reason" reason_type = fields.Selection([("won", "Won"), ("lost", "Lost")], default="lost")
29.1
291
246
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import fields, models class CrmLead(models.Model): _inherit = "crm.lead" won_reason_id = fields.Many2one("crm.lost.reason")
24.6
246
1,483
py
PYTHON
15.0
############################################################################## # # Copyright (c) # 2015 Serv. Tec. Avanzados - Pedro M. Baeza (http://www.serviciosbaeza.com) # 2015 AvanzOsc (http://www.avanzosc.es) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Sequential Code for Leads / Opportunities", "version": "15.0.1.0.0", "category": "Customer Relationship Management", "author": "Tecnativa, AvanzOSC, Odoo Community Association (OCA)", "website": "https://github.com/OCA/crm", "license": "AGPL-3", "depends": ["crm"], "data": ["data/lead_sequence.xml", "views/crm_lead_view.xml"], "installable": True, "pre_init_hook": "create_code_equal_to_id", "post_init_hook": "assign_old_sequences", }
43.617647
1,483
1,418
py
PYTHON
15.0
############################################################################## # For copyright and license notices, see __manifest__.py file in root directory ############################################################################## from odoo.tests.common import TransactionCase class TestCrmLeadCode(TransactionCase): def setUp(self): super(TestCrmLeadCode, self).setUp() self.crm_lead_model = self.env["crm.lead"] self.ir_sequence_model = self.env["ir.sequence"] self.crm_sequence = self.env.ref("crm_lead_code.sequence_lead") self.crm_lead = self.env.ref("crm.crm_case_1") def test_old_lead_code_assign(self): crm_leads = self.crm_lead_model.search([]) for crm_lead in crm_leads: self.assertNotEqual(crm_lead.code, "/") def test_new_lead_code_assign(self): code = self._get_next_code() crm_lead = self.crm_lead_model.create({"name": "Testing lead code"}) self.assertNotEqual(crm_lead.code, "/") self.assertEqual(crm_lead.code, code) def test_copy_lead_code_assign(self): code = self._get_next_code() crm_lead_copy = self.crm_lead.copy() self.assertNotEqual(crm_lead_copy.code, self.crm_lead.code) self.assertEqual(crm_lead_copy.code, code) def _get_next_code(self): return self.crm_sequence.get_next_char(self.crm_sequence.number_next_actual)
41.705882
1,418
896
py
PYTHON
15.0
############################################################################## # For copyright and license notices, see __manifest__.py file in root directory ############################################################################## from odoo import _, api, fields, models class CrmLead(models.Model): _inherit = "crm.lead" code = fields.Char( string="Lead Number", required=True, default="/", readonly=True, copy=False ) _sql_constraints = [ ("crm_lead_unique_code", "UNIQUE (code)", _("The code must be unique!")), ] @api.model_create_multi def create(self, vals_list): for vals in vals_list: if vals.get("code", "/") == "/": vals["code"] = self.env.ref( "crm_lead_code.sequence_lead", raise_if_not_found=False ).next_by_id() return super().create(vals_list)
34.461538
896
586
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "CRM Multicompany Reporting Currency", "summary": "Adds Amount in multicompany reporting currency to CRM Lead", "version": "15.0.1.0.3", "category": "Sales", "author": "Camptocamp SA, Odoo Community Association (OCA)", "license": "AGPL-3", "depends": ["crm", "base_multicompany_reporting_currency"], "website": "https://github.com/OCA/crm", "data": ["views/crm_lead_views.xml"], "installable": True, "maintainers": ["yankinmax"], }
39.066667
586
3,409
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo import fields from odoo.tests.common import TransactionCase from odoo.addons.mail.tests.common import mail_new_test_user class TestAmountMulticompanyReportingCurrency(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.currency_swiss_id = cls.env.ref("base.CHF").id cls.currency_euro_id = cls.env.ref("base.EUR").id cls.belgium = cls.env.ref("base.be").id cls.company = cls.env["res.company"].create({"name": "My company"}) cls.company.currency_id = cls.currency_euro_id cls.user_sales_salesman = mail_new_test_user( cls.env, login="user_sales_salesman_1", name="John Doe", email="[email protected]", company_id=cls.company.id, notification_type="inbox", groups="sales_team.group_sale_salesman", ) cls.env["res.currency.rate"].create( { "name": fields.Date.today(), "rate": 1.0038, "currency_id": cls.currency_swiss_id, "company_id": cls.company.id, } ) cls.env["res.currency.rate"].create( { "name": fields.Date.today(), "rate": 1, "currency_id": cls.currency_euro_id, "company_id": cls.company.id, } ) def test_amount_multicompany_reporting_currency(self): # Company currency is in EUR, Amount Multicompany Reporting Currency is CHF self.env["res.config.settings"].create( {"multicompany_reporting_currency": self.currency_swiss_id} ).execute() self.lead_1 = ( self.env["crm.lead"] .with_company(self.company) .create( { "name": "Lead 1", "user_id": self.user_sales_salesman.id, "country_id": self.belgium, "expected_revenue": 1000, } ) ) self.assertAlmostEqual( self.lead_1.amount_multicompany_reporting_currency, 1003.8 ) # Company currency is in EUR, Amount Multicompany Reporting Currency is EUR self.env["res.config.settings"].create( {"multicompany_reporting_currency": self.currency_euro_id} ).execute() self.lead_2 = ( self.env["crm.lead"] .with_company(self.company) .create( { "name": "Lead 2", "user_id": self.user_sales_salesman.id, "country_id": self.belgium, "expected_revenue": 1230, } ) ) self.assertAlmostEqual(self.lead_2.amount_multicompany_reporting_currency, 1230) # Company isn't set on the Lead, Amount Multicompany Reporting Currency is EUR self.lead_2 = self.env["crm.lead"].create( { "name": "Lead 2", "user_id": self.user_sales_salesman.id, "country_id": self.belgium, "expected_revenue": 842, } ) self.assertAlmostEqual(self.lead_2.amount_multicompany_reporting_currency, 842)
37.054348
3,409
688
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo import models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" def set_values(self): crm_lead = self.env["crm.lead"] applied_currency = crm_lead._get_multicompany_reporting_currency_id() super().set_values() to_apply_currency = self.multicompany_reporting_currency if applied_currency.id != to_apply_currency.id: crm_lead.with_context(active_test=False).search([]).write( {"multicompany_reporting_currency_id": to_apply_currency.id} ) return True
36.210526
688
3,131
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo import api, fields, models class CrmLead(models.Model): _inherit = "crm.lead" def _get_multicompany_reporting_currency_id(self): multicompany_reporting_currency_parameter = ( self.env["ir.config_parameter"] .sudo() .get_param( "base_multicompany_reporting_currency.multicompany_reporting_currency" ) ) return self.env["res.currency"].browse( int(multicompany_reporting_currency_parameter) ) multicompany_reporting_currency_id = fields.Many2one( "res.currency", compute="_compute_multicompany_reporting_currency_id", readonly=True, store=True, default=_get_multicompany_reporting_currency_id, ) currency_rate = fields.Float( compute="_compute_currency_rate", store=True, digits=(12, 6) ) amount_multicompany_reporting_currency = fields.Monetary( currency_field="multicompany_reporting_currency_id", compute="_compute_amount_multicompany_reporting_currency", store=True, index=True, readonly=True, ) @api.depends("company_currency") def _compute_multicompany_reporting_currency_id(self): multicompany_reporting_currency_id = ( self._get_multicompany_reporting_currency_id() ) for record in self: record.multicompany_reporting_currency_id = ( multicompany_reporting_currency_id ) @api.depends("create_date", "company_id", "multicompany_reporting_currency_id") def _compute_currency_rate(self): # similar to currency_rate on sale.order for record in self: date = record.create_date or fields.Date.today() if not record.company_id: record.currency_rate = ( record.multicompany_reporting_currency_id.with_context( date=date ).rate or 1.0 ) elif ( record.company_currency and record.multicompany_reporting_currency_id ): # the following crashes if any one is undefined record.currency_rate = self.env["res.currency"]._get_conversion_rate( record.company_currency, record.multicompany_reporting_currency_id, record.company_id, date, ) else: record.currency_rate = 1.0 @api.depends( "expected_revenue", "currency_rate", "multicompany_reporting_currency_id" ) def _compute_amount_multicompany_reporting_currency(self): for record in self: if record.company_currency == record.multicompany_reporting_currency_id: to_amount = record.expected_revenue else: to_amount = record.expected_revenue * record.currency_rate record.amount_multicompany_reporting_currency = to_amount
37.722892
3,131
744
py
PYTHON
15.0
# @@ -1,11 +1,10 @@ # Copyright 2017 Tecnativa - Vicent Cubells { "name": "CRM Phone Calls", "version": "15.0.1.1.0", "category": "Customer Relationship Management", "author": "Odoo S.A., Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/crm", "license": "AGPL-3", "depends": ["crm", "calendar"], "data": [ "security/crm_security.xml", "security/ir.model.access.csv", "wizard/crm_phonecall_to_phonecall_view.xml", "views/crm_phonecall_view.xml", "views/res_partner_view.xml", "views/crm_lead_view.xml", "views/res_config_settings_views.xml", "report/crm_phonecall_report_view.xml", ], "installable": True, }
32.347826
744
7,747
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests import Form, common class TestCrmPhoneCall(common.SavepointCase): """Unit test case of the Crm Phonecall module.""" @classmethod def setUpClass(cls): """Created required data.""" super().setUpClass() cls.company = cls.env.ref("base.main_company") partner_obj = cls.env["res.partner"] cls.campaign1 = cls.env["utm.campaign"].create({"name": "campaign 1"}) cls.source1 = cls.env["utm.source"].create({"name": "source 1"}) cls.medium1 = cls.env["utm.medium"].create({"name": "medium 1"}) cls.partner1 = partner_obj.create( { "name": "Partner1", "phone": "123 456 789", "mobile": "123 456 789", "type": "contact", } ) cls.partner2 = partner_obj.create( {"name": "Partner2", "phone": "789 654 321", "mobile": "789 654 321"} ) cls.phonecall1 = cls.env["crm.phonecall"].create( { "name": "Call #1 for test", "partner_id": cls.partner1.id, "campaign_id": cls.campaign1.id, "source_id": cls.source1.id, "medium_id": cls.medium1.id, } ) cls.phonecall2 = cls.env["crm.phonecall"].create( { "name": "Call #2 for test", "partner_phone": "123 456 789", "partner_mobile": "987 654 321", "campaign_id": cls.campaign1.id, "source_id": cls.source1.id, "medium_id": cls.medium1.id, } ) cls.opportunity1 = cls.env["crm.lead"].create( { "name": "Opportunity #1", "phone": "111 111 111", "mobile": "222 222 222", "partner_id": cls.partner1.id, } ) cls.opportunity2 = cls.env["crm.lead"].create( { "name": "Opportunity #2", "phone": "222 222 222", "mobile": "333 333 333", "partner_id": cls.partner2.id, } ) cls.tag = cls.env.ref("sales_team.categ_oppor1") def test_compute_phonecall_count_partner(self): partner = self.env["res.partner"].create( {"name": "Partner3", "phone": "123 654 007", "mobile": "123 654 007"} ) phonecall = self.env["crm.phonecall"].create( { "name": "Call #2 for test", } ) phonecall_form = Form(phonecall) phonecall_form.partner_id = partner phonecall_form.save() self.assertEqual(partner.phonecall_count, 1) def test_compute_duration(self): partner = self.env["res.partner"].create( {"name": "Partner4", "phone": "123 456 007", "mobile": "123 456 007"} ) phonecall = self.env["crm.phonecall"].create( { "name": "Call #3 for test", "partner_id": partner.id, "duration": 1, } ) phonecall.compute_duration() self.assertEqual(phonecall.duration, 0.0) def test_onchange_partner(self): """Partner change method test.""" phonecall_form = Form(self.phonecall1) phonecall_form.partner_id = self.partner2 phonecall_form.save() self.assertEqual(self.phonecall1.partner_phone, self.partner2.phone) self.assertEqual(self.phonecall1.partner_mobile, self.partner2.mobile) self.assertFalse(self.phonecall1.date_closed) self.phonecall1.state = "done" self.assertTrue(self.phonecall1.date_closed) self.phonecall1.state = "open" self.assertEqual(self.phonecall1.duration, 0.0) def test_schedule_another_phonecall(self): """Schedule another phonecall.""" phonecall2 = self.phonecall1.schedule_another_phonecall( { "schedule_time": False, "name": "Test schedule method", "action": "schedule", "tag_ids": self.tag.ids, } )[self.phonecall1.id] self.assertNotEqual(phonecall2.id, self.phonecall1.id) self.assertEqual(self.phonecall1.state, "open") phonecall3 = self.phonecall1.schedule_another_phonecall( { "schedule_time": "2017-12-31 00:00:00", "name": "Test schedule method2", "action": "log", } )[self.phonecall1.id] self.assertNotEqual(phonecall3.id, self.phonecall1.id) self.assertNotEqual(phonecall3.id, phonecall2.id) self.assertEqual(self.phonecall1.state, "done") result = phonecall2.redirect_phonecall_view() self.assertEqual(result["res_id"], phonecall2.id) for phonecall in (self.phonecall1, phonecall2, phonecall3): self.assertEqual(phonecall.campaign_id, self.campaign1) self.assertEqual(phonecall.source_id, self.source1) self.assertEqual(phonecall.medium_id, self.medium1) def test_onchange_opportunity(self): """Change the opportunity.""" phonecall_form = Form(self.phonecall1) phonecall_form.opportunity_id = self.opportunity1 phonecall_form.save() self.assertEqual(self.phonecall1.partner_phone, self.opportunity1.phone) self.assertEqual(self.opportunity1.phonecall_count, 1) def test_convert2opportunity(self): """Convert lead to opportunity test.""" # convert call with linked partner record result = self.phonecall1.action_button_convert2opportunity() self.assertEqual(result["res_model"], "crm.lead") lead = self.env["crm.lead"].browse(result["res_id"]) self.assertEqual(lead.campaign_id, self.campaign1) self.assertEqual(lead.source_id, self.source1) self.assertEqual(lead.medium_id, self.medium1) # convert call without linked partner record result = self.phonecall2.action_button_convert2opportunity() lead = self.env["crm.lead"].browse(result["res_id"]) self.assertEqual(lead.phone, self.phonecall2.partner_phone) self.assertEqual(lead.mobile, self.phonecall2.partner_mobile) def test_make_meeting(self): """Make a meeting test.""" self.phonecall1.partner_id.email = "[email protected]" result = self.phonecall1.action_make_meeting() self.assertEqual(result["context"]["default_phonecall_id"], self.phonecall1.id) def test_wizard(self): """Schedule a call from wizard.""" wizard = ( self.env["crm.phonecall2phonecall"] .with_context(active_ids=self.phonecall1.ids, active_id=self.phonecall1.id) .create({}) ) result = wizard.action_schedule() search_view_id = self.env.ref( "crm_phonecall.view_crm_case_phonecalls_filter" ).id self.assertEqual(result["search_view_id"], search_view_id) self.assertNotEqual(result["res_id"], self.phonecall1.id) def test_opportunity_open_phonecall(self): action_dict = self.opportunity2.button_open_phonecall() action_context = action_dict.get("context") self.assertEqual( action_context.get("default_opportunity_id"), self.opportunity2.id ) self.assertEqual( action_context.get("search_default_opportunity_id"), self.opportunity2.id ) self.assertEqual( action_context.get("default_partner_id"), self.opportunity2.partner_id.id )
40.560209
7,747
2,815
py
PYTHON
15.0
# Copyright 2004-2010 Tiny SPRL (<http://tiny.be>) # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import time from odoo import api, fields, models class CrmPhonecall2phonecall(models.TransientModel): """Added the details of the crm phonecall2phonecall.""" _name = "crm.phonecall2phonecall" _description = "Phonecall To Phonecall" name = fields.Char(string="Call summary", required=True, index=True) user_id = fields.Many2one(comodel_name="res.users", string="Assign To") contact_name = fields.Char(string="Contact") phone = fields.Char() tag_ids = fields.Many2many( comodel_name="crm.tag", relation="crm_phonecall2phonecall_tag_rel", string="Tags", column1="phone_id", column2="tag_id", ) date = fields.Datetime() team_id = fields.Many2one(comodel_name="crm.team", string="Sales Team") action = fields.Selection( selection=[("schedule", "Schedule a call"), ("log", "Log a call")], required=True, ) partner_id = fields.Many2one(comodel_name="res.partner", string="Partner") note = fields.Text() def get_vals_action_schedule(self): vals = { "schedule_time": self.date, "name": self.name, "user_id": self.user_id.id, "team_id": self.team_id.id or False, "tag_ids": self.tag_ids.ids, "action": self.action, } return vals def action_schedule(self): """Schedule a phonecall.""" phonecall_obj = self.env["crm.phonecall"] phonecalls = phonecall_obj.browse(self._context.get("active_ids", [])) vals = self.get_vals_action_schedule() new_phonecalls = phonecalls.schedule_another_phonecall( vals, return_recordset=True ) return new_phonecalls.redirect_phonecall_view() @api.model def default_get(self, fields): """Function gets default values.""" res = super().default_get(fields) res.update({"action": "schedule", "date": time.strftime("%Y-%m-%d %H:%M:%S")}) for phonecall in self.env["crm.phonecall"].browse( self.env.context.get("active_id") ): if "tag_ids" in fields: res.update({"tag_ids": phonecall.tag_ids.ids}) if "user_id" in fields: res.update({"user_id": phonecall.user_id.id}) if "team_id" in fields: res.update({"team_id": phonecall.team_id.id}) if "partner_id" in fields: res.update({"partner_id": phonecall.partner_id.id}) for field in ("name", "date"): if field in fields: res[field] = getattr(phonecall, field) return res
37.039474
2,815
8,914
py
PYTHON
15.0
# Copyright 2004-2016 Odoo SA (<http://www.odoo.com>) # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from functools import reduce from odoo import _, api, fields, models class CrmPhonecall(models.Model): """Model for CRM phonecalls.""" _name = "crm.phonecall" _description = "Phonecall" _order = "id desc" _inherit = ["mail.thread", "utm.mixin"] date_action_last = fields.Datetime(string="Last Action", readonly=True) date_action_next = fields.Datetime(string="Next Action", readonly=True) create_date = fields.Datetime(string="Creation Date", readonly=True) team_id = fields.Many2one( comodel_name="crm.team", string="Sales Team", index=True, help="Sales team to which Case belongs to.", ) user_id = fields.Many2one( comodel_name="res.users", string="Responsible", default=lambda self: self.env.user, ) partner_id = fields.Many2one(comodel_name="res.partner", string="Contact") company_id = fields.Many2one(comodel_name="res.company", string="Company") description = fields.Text() state = fields.Selection( [ ("open", "Confirmed"), ("cancel", "Cancelled"), ("pending", "Pending"), ("done", "Held"), ], string="Status", tracking=3, default="open", help="The status is set to Confirmed, when a case is created.\n" "When the call is over, the status is set to Held.\n" "If the callis not applicable anymore, the status can be set " "to Cancelled.", ) email_from = fields.Char(string="Email", help="These people will receive email.") date_open = fields.Datetime(string="Opened", readonly=True) name = fields.Char(string="Call Summary", required=True) active = fields.Boolean(required=False, default=True) duration = fields.Float(help="Duration in minutes and seconds.") tag_ids = fields.Many2many( comodel_name="crm.tag", relation="crm_phonecall_tag_rel", string="Tags", column1="phone_id", column2="tag_id", ) partner_phone = fields.Char(string="Phone") partner_mobile = fields.Char("Mobile") priority = fields.Selection( selection=[("0", "Low"), ("1", "Normal"), ("2", "High")], default="1", ) date_closed = fields.Datetime(string="Closed", readonly=True) date = fields.Datetime(default=lambda self: fields.Datetime.now()) opportunity_id = fields.Many2one(comodel_name="crm.lead", string="Lead/Opportunity") direction = fields.Selection( [("in", "In"), ("out", "Out")], default="out", required=True ) @api.onchange("partner_id") def _onchange_partner_id(self): """Contact number details should be change based on partner.""" if self.partner_id: self.partner_phone = self.partner_id.phone self.partner_mobile = self.partner_id.mobile @api.onchange("opportunity_id") def _onchange_opportunity_id(self): """Based on opportunity, change contact, tags, partner, team.""" if self.opportunity_id: self.team_id = self.opportunity_id.team_id.id self.partner_phone = self.opportunity_id.phone self.partner_mobile = self.opportunity_id.mobile self.partner_id = self.opportunity_id.partner_id.id self.tag_ids = self.opportunity_id.tag_ids.ids def write(self, values): """Override to add case management: open/close dates.""" if values.get("state"): if values.get("state") == "done": values["date_closed"] = fields.Datetime.now() self.compute_duration() elif values.get("state") == "open": values["date_open"] = fields.Datetime.now() values["duration"] = 0.0 return super().write(values) def compute_duration(self): """Calculate duration based on phonecall date.""" phonecall_dates = self.filtered("date") phonecall_no_dates = self - phonecall_dates for phonecall in phonecall_dates: if phonecall.duration <= 0 and phonecall.date: duration = fields.Datetime.now() - phonecall.date values = {"duration": duration.seconds / 60.0} phonecall.write(values) else: phonecall.duration = 0.0 phonecall_no_dates.write({"duration": 0.0}) return True def get_values_schedule_another_phonecall(self, vals): res = { "name": vals.get("name"), "user_id": vals.get("user_id") or self.user_id.id, "description": self.description, "date": vals.get("schedule_time") or self.date, "team_id": vals.get("team_id") or self.team_id.id, "partner_id": self.partner_id.id, "partner_phone": self.partner_phone, "partner_mobile": self.partner_mobile, "priority": self.priority, "opportunity_id": self.opportunity_id.id, "campaign_id": self.campaign_id.id, "source_id": self.source_id.id, "medium_id": self.medium_id.id, } if vals.get("tag_ids"): res.update({"tag_ids": [(6, 0, vals.get("tag_ids"))]}) return res def schedule_another_phonecall(self, vals, return_recordset=False): """Action :('schedule','Schedule a call'), ('log','Log a call').""" phonecall_dict = {} for call in self: values = call.get_values_schedule_another_phonecall(vals) new_id = self.create(values) if vals.get("action") == "log": call.write({"state": "done"}) phonecall_dict[call.id] = new_id if return_recordset: return reduce(lambda x, y: x + y, phonecall_dict.values()) else: return phonecall_dict def redirect_phonecall_view(self): """Redirect on the phonecall related view.""" # Select the view tree_view_id = self.env.ref("crm_phonecall.crm_case_phone_tree_view").id form_view_id = self.env.ref("crm_phonecall.crm_case_phone_form_view").id search_view_id = self.env.ref( "crm_phonecall.view_crm_case_phonecalls_filter" ).id value = {} for call in self: value = { "name": _("Phone Call"), "view_type": "form", "view_mode": "tree,form", "res_model": "crm.phonecall", "res_id": call.id, "views": [ (form_view_id or False, "form"), (tree_view_id or False, "tree"), (False, "calendar"), ], "type": "ir.actions.act_window", "search_view_id": search_view_id or False, } return value def action_make_meeting(self): """Open meeting's calendar view to schedule a meeting on phonecall.""" partner_ids = [self.env["res.users"].browse(self.env.uid).partner_id.id] res = {} for phonecall in self: if phonecall.partner_id and phonecall.partner_id.email: partner_ids.append(phonecall.partner_id.id) res = self.env["ir.actions.act_window"]._for_xml_id( "calendar.action_calendar_event" ) res["context"] = { "default_phonecall_id": phonecall.id, "default_partner_ids": partner_ids, "default_user_id": self.env.uid, "default_email_from": phonecall.email_from, "default_name": phonecall.name, } return res def _prepare_opportunity_vals(self): return { "name": self.name, "partner_id": self.partner_id.id, "phone": self.partner_phone or self.partner_id.phone, "mobile": self.partner_mobile or self.partner_id.mobile, "email_from": self.partner_id.email, "team_id": self.team_id.id, "description": self.description, "priority": self.priority, "type": "opportunity", "campaign_id": self.campaign_id.id, "source_id": self.source_id.id, "medium_id": self.medium_id.id, "tag_ids": [(6, 0, self.tag_ids.ids)], } def action_button_convert2opportunity(self): """Convert a phonecall into an opp and redirect to the opp view.""" self.ensure_one() opportunity = self.env["crm.lead"] opportunity_id = opportunity.create(self._prepare_opportunity_vals()) self.write({"opportunity_id": opportunity_id.id, "state": "done"}) return opportunity_id.redirect_lead_opportunity_view()
40.703196
8,914
412
py
PYTHON
15.0
# Copyright 2004-2016 Odoo SA (<http://www.odoo.com>) # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class CalendarEvent(models.Model): """Enhance the calendar event to add phonecall data.""" _inherit = "calendar.event" phonecall_id = fields.Many2one(comodel_name="crm.phonecall", string="Phonecall")
31.692308
412
381
py
PYTHON
15.0
from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" group_show_form_view = fields.Boolean( "Enable form view for phone calls", help="By default form is disabled for calls, with this group it is enabled.", implied_group="crm_phonecall.group_show_form_view", default=True, )
31.75
381
1,403
py
PYTHON
15.0
# Copyright 2004-2016 Odoo SA (<http://www.odoo.com>) # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models from odoo.tools.safe_eval import safe_eval class CrmLead(models.Model): """Added the phonecall related details in the lead.""" _inherit = "crm.lead" phonecall_ids = fields.One2many( comodel_name="crm.phonecall", inverse_name="opportunity_id", string="Phonecalls" ) phonecall_count = fields.Integer(compute="_compute_phonecall_count") def _compute_phonecall_count(self): """Calculate number of phonecalls.""" for lead in self: lead.phonecall_count = self.env["crm.phonecall"].search_count( [("opportunity_id", "=", lead.id)] ) def button_open_phonecall(self): self.ensure_one() action = self.env.ref("crm_phonecall.crm_case_categ_phone_incoming0") action_dict = action.read()[0] if action else {} action_dict["context"] = safe_eval(action_dict.get("context", "{}")) action_dict["context"].update( { "default_opportunity_id": self.id, "search_default_opportunity_id": self.id, "default_partner_id": self.partner_id.id, "default_duration": 1.0, } ) return action_dict
35.974359
1,403
777
py
PYTHON
15.0
# Copyright 2004-2016 Odoo SA (<http://www.odoo.com>) # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ResPartner(models.Model): """Added the details of phonecall in the partner.""" _inherit = "res.partner" phonecall_ids = fields.One2many( comodel_name="crm.phonecall", inverse_name="partner_id", string="Phonecalls" ) phonecall_count = fields.Integer(compute="_compute_phonecall_count") def _compute_phonecall_count(self): """Calculate number of phonecalls.""" for partner in self: partner.phonecall_count = self.env["crm.phonecall"].search_count( [("partner_id", "=", partner.id)] )
33.782609
777
3,101
py
PYTHON
15.0
# Copyright 2004-2010 Tiny SPRL (<http://tiny.be>) # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from psycopg2.extensions import AsIs from odoo import fields, models, tools AVAILABLE_STATES = [ ("draft", "Draft"), ("open", "Todo"), ("cancel", "Cancelled"), ("done", "Held"), ("pending", "Pending"), ] class CrmPhonecallReport(models.Model): """Generate BI report based on phonecall.""" _name = "crm.phonecall.report" _description = "Phone calls by user" _auto = False user_id = fields.Many2one(comodel_name="res.users", string="User", readonly=True) team_id = fields.Many2one(comodel_name="crm.team", string="Team", readonly=True) priority = fields.Selection( selection=[("0", "Low"), ("1", "Normal"), ("2", "High")] ) nbr_cases = fields.Integer(string="# of Cases", readonly=True) state = fields.Selection(AVAILABLE_STATES, string="Status", readonly=True) create_date = fields.Datetime(readonly=True, index=True) delay_close = fields.Float( string="Delay to close", digits=(16, 2), readonly=True, group_operator="avg", help="Number of Days to close the case", ) duration = fields.Float(digits=(16, 2), readonly=True, group_operator="avg") delay_open = fields.Float( string="Delay to open", digits=(16, 2), readonly=True, group_operator="avg", help="Number of Days to open the case", ) partner_id = fields.Many2one( comodel_name="res.partner", string="Partner", readonly=True ) company_id = fields.Many2one( comodel_name="res.company", string="Company", readonly=True ) opening_date = fields.Datetime(readonly=True, index=True) date_closed = fields.Datetime(string="Close Date", readonly=True, index=True) def _select(self): select_str = """ select id, c.date_open as opening_date, c.date_closed as date_closed, c.state, c.user_id, c.team_id, c.partner_id, c.duration, c.company_id, c.priority, 1 as nbr_cases, c.create_date as create_date, extract( 'epoch' from ( c.date_closed-c.create_date))/(3600*24) as delay_close, extract( 'epoch' from ( c.date_open-c.create_date))/(3600*24) as delay_open """ return select_str def _from(self): from_str = """ from crm_phonecall c """ return from_str def init(self): """Initialize the report.""" tools.drop_view_if_exists(self.env.cr, self._table) self.env.cr.execute( """ create or replace view %s as ( %s %s )""", (AsIs(self._table), AsIs(self._select()), AsIs(self._from())), )
32.302083
3,101
642
py
PYTHON
15.0
# Copyright 2017 Jairo Llopis <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Phonecall planner", "summary": "Schedule phone calls according to some criteria", "version": "15.0.1.0.0", "category": "Customer Relationship Management", "website": "https://github.com/OCA/crm", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["crm_phonecall", "partner_phonecall_schedule"], "data": ["security/ir.model.access.csv", "wizards/crm_phonecall_planner_view.xml"], }
42.8
642
5,643
py
PYTHON
15.0
# Copyright 2017 Jairo Llopis <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from __future__ import division from datetime import datetime, timedelta from odoo import fields from odoo.exceptions import ValidationError from odoo.tests.common import SavepointCase from odoo.tools import float_compare class PlannerCase(SavepointCase): @classmethod def setUpClass(cls): super(PlannerCase, cls).setUpClass() cls.mondays = cls.env["resource.calendar"].create( { "name": "mondays", "attendance_ids": [ ( 0, 0, { "name": "Monday morning", "dayofweek": "0", "hour_from": 9, "hour_to": 12, }, ), ( 0, 0, { "name": "Monday evening", "dayofweek": "0", "hour_from": 15, "hour_to": 20, }, ), ], } ) cls.tuesdays = cls.env["resource.calendar"].create( { "name": "tuesdays", "attendance_ids": [ ( 0, 0, { "name": "Tuesday morning", "dayofweek": "1", "hour_from": 9, "hour_to": 12, }, ), ( 0, 0, { "name": "One Tuesday evening", "dayofweek": "1", "hour_from": 15, "hour_to": 20, "date_from": "2017-10-02", "date_to": "2017-10-08", }, ), ], } ) cls.partners = cls.env["res.partner"].create({"name": "partner0"}) cls.partners += cls.env["res.partner"].create( {"name": "partner1", "phonecall_calendar_ids": [(6, 0, cls.mondays.ids)]} ) cls.partners += cls.env["res.partner"].create( {"name": "partner2", "phonecall_calendar_ids": [(6, 0, cls.tuesdays.ids)]} ) cls.partners += cls.env["res.partner"].create( { "name": "partner3", "phonecall_calendar_ids": [(6, 0, (cls.mondays | cls.tuesdays).ids)], } ) cls.wizard = ( cls.env["crm.phonecall.planner"] .with_context(tz="UTC") .create( { "name": "Test call", "start": "2017-09-20 08:00:00", "end": "2017-10-20 16:00:00", "duration": 1, "res_partner_domain": str([("id", "in", cls.partners.ids)]), } ) ) def test_defaults(self): """The planner provides the expected default values.""" wizard = self.wizard.create({"name": "Test defaults!"}) self.assertEqual(0, float_compare(wizard.duration, 7 / 60, 6)) self.assertLessEqual(wizard.start, fields.Datetime.now()) start = wizard.start end = wizard.end self.assertEqual(end, start + timedelta(days=30, hours=8)) def test_start_before_end(self): """A wizard with start date bigger than end date is not allowed.""" with self.assertRaises(ValidationError): self.wizard.write({"start": self.wizard.end, "end": self.wizard.start}) def test_plan_no_repeat(self): """The planner creates one call per partner.""" self.wizard.action_accept() expected_dates = { datetime(2017, 9, 25, 9), datetime(2017, 9, 25, 10), datetime(2017, 9, 26, 9), } real_dates = self.wizard.planned_calls.mapped("date") self.assertEqual(expected_dates, set(real_dates)) self.assertEqual(len(expected_dates), len(real_dates)) self.assertEqual( self.wizard.planned_calls.mapped("partner_id"), self.partners[1:] ) def test_plan_repeat(self): """The planner repeats calls each day.""" self.wizard.write({"repeat_calls": True, "start": "2017-09-20 12:00:00"}) self.wizard.action_accept() expected_dates = { datetime(2017, 9, 25, 12), datetime(2017, 9, 25, 15), datetime(2017, 9, 26, 12), datetime(2017, 10, 2, 12), datetime(2017, 10, 2, 15), datetime(2017, 10, 3, 12), datetime(2017, 10, 3, 15), datetime(2017, 10, 9, 12), datetime(2017, 10, 9, 15), datetime(2017, 10, 10, 12), datetime(2017, 10, 16, 12), datetime(2017, 10, 16, 15), datetime(2017, 10, 17, 12), } real_dates = self.wizard.planned_calls.mapped("date") self.assertEqual(expected_dates, set(real_dates)) self.assertEqual(len(expected_dates), len(real_dates)) self.assertEqual( self.wizard.planned_calls.mapped("partner_id"), self.partners[1:] )
36.642857
5,643
7,593
py
PYTHON
15.0
# Copyright 2017 Jairo Llopis <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from __future__ import division from datetime import datetime, timedelta from logging import getLogger from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.tools.safe_eval import safe_eval _logger = getLogger(__name__) class CrmPhonecallPlan(models.TransientModel): _name = "crm.phonecall.planner" _description = "Phonecall planner" _inherit = [ "utm.mixin", ] name = fields.Char( "Call Summary", required=True, ) user_id = fields.Many2one( comodel_name="res.users", string="Responsible", ) team_id = fields.Many2one( comodel_name="crm.team", string="Sales Team", ) tag_ids = fields.Many2many( comodel_name="crm.tag", string="Tags", ) res_partner_domain = fields.Char( "Partners filter", help="Filter the parters that will get a scheduled call.", ) duration = fields.Float( string="Call duration", default=lambda self: self._default_duration(), required=True, help="Leave this free time between phone calls.", ) start = fields.Datetime( default=lambda self: self._default_start(), required=True, help="Schedule calls from this moment. The time you select will be " "used as the plan starting time for each day in the range.", ) end = fields.Datetime( default=lambda self: self._default_end(), required=True, help="Schedule calls until this moment. The time you select will be " "used as the plan ending time for each day in the range.", ) repeat_calls = fields.Boolean( help="Allow repeated calls for the same partner, campaign, medium " "and source combination?", ) days_gap = fields.Integer( default=1, required=True, help="Schedule one call each X days to the same partner.", ) planned_calls = fields.Many2many( comodel_name="crm.phonecall", ) @api.model def _default_duration(self): return 7 / 60 # 7 minutes @api.model def _default_start(self): return fields.Datetime.now() @api.model def _default_end(self): return self._default_start() + timedelta(days=30, hours=8) @api.constrains("start", "end") def _constrains_plan_dates(self): for one in self: if one.start > one.end: raise ValidationError(_("Starting date must be less than ending date")) def action_accept(self): """Generate phonecall plan according to given criteria.""" self.ensure_one() Phonecall = self.env["crm.phonecall"] Partner = self.env["res.partner"] # Prepare all required time variables start = self.start end = self.end call_duration = timedelta(hours=self.duration) now = start - call_duration repetition_gap = timedelta(days=self.days_gap) tomorrow = timedelta(days=1) - call_duration oldest_call_to_partner = """ SELECT res_partner.id FROM res_partner LEFT JOIN crm_phonecall ON res_partner.id = crm_phonecall.partner_id WHERE res_partner.id IN ({}) GROUP BY res_partner.id ORDER BY COUNT(crm_phonecall.id), MAX(crm_phonecall.date) LIMIT 1 """ # Get preexisting calls utm_domain = [ ("campaign_id", "=", self.campaign_id.id), ("source_id", "=", self.source_id.id), ("medium_id", "=", self.medium_id.id), ] existing_calls = Phonecall.search( utm_domain + [("partner_id", "!=", False)], order="date", ) # Get partners to plan partner_domain = safe_eval(self.res_partner_domain or "[]") + [ ("phonecall_calendar_ids", "!=", False), ] forbidden_partners = existing_calls.mapped("partner_id") partners = Partner.search(partner_domain) # And now the hot chili... while partners and now <= end: now += call_duration _logger.debug( "Plannig phonecalls for %s", fields.Datetime.to_string(now), ) # Should we continue tomorrow? if not start.time() <= now.time() <= end.time(): _logger.info( "Finished plannig phonecalls for %s with %d calls so far", fields.Date.to_string(now.date()), len(self.planned_calls), ) now = datetime.combine(now.date(), start.time()) + tomorrow continue # Know partners that we cannot call right now if self.repeat_calls: forbidden_partners = Phonecall.search( utm_domain + [ ("partner_id", "in", partners.ids), ("date", ">", fields.Datetime.to_string(now - repetition_gap)), ] ).mapped("partner_id") # Know partners we can call right now available_partners = Partner.with_context(now=now).search( [ ("id", "in", partners.ids), ("id", "not in", forbidden_partners.ids), ("phonecall_available", "=", True), ] ) # Continue when nobody is available if not available_partners: continue # Just pick the first one and continue if not self.repeat_calls: winner = available_partners[:1] self._schedule_call(winner, now) partners -= winner continue # Get a partner with no calls, or with the oldest one # pylint: disable=E8103 self.env.cr.execute( oldest_call_to_partner.format( ",".join(["%s"] * len(available_partners)), ), available_partners.ids, ) winner = Partner.browse(self.env.cr.fetchone()[0]) self._schedule_call(winner, now) _logger.info("Total planned phonecalls: %d", len(self.planned_calls)) return { "name": "Generated calls", "type": "ir.actions.act_window", "res_model": "crm.phonecall", "views": [[False, "tree"], [False, "calendar"], [False, "form"]], "domain": [("id", "in", self.planned_calls.ids)], } def _schedule_call(self, partner, when): _logger.debug( "Planning a call for %s at %s", partner.display_name, fields.Datetime.to_string(when), ) self.planned_calls |= self.env["crm.phonecall"].create( { "campaign_id": self.campaign_id.id, "date": when, "duration": self.duration, "medium_id": self.medium_id.id, "partner_mobile": partner.mobile, "name": self.name, "partner_id": partner.id, "partner_phone": partner.phone, "source_id": self.source_id.id, "tag_ids": [(6, 0, self.tag_ids.ids)], "team_id": self.team_id.id, "user_id": self.user_id.id, } )
35.816038
7,593
793
py
PYTHON
15.0
# Copyright 2017 Vicent Cubells <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from psycopg2 import IntegrityError from odoo import SUPERUSER_ID, api def convert_names_to_many2one(cr, registry): # pragma: no cover """Convert old string names to new Many2one""" with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) summary = env["crm.phonecall.summary"] phone_call = env["crm.phonecall"] for s in phone_call.search([("summary_id", "=", False)]): try: with env.cr.savepoint(): s.summary_id = summary.create({"name": s.name}) except IntegrityError: s.summary_id = summary.search([("name", "=", s.name)])
39.65
793
900
py
PYTHON
15.0
# Copyright 2016 Antiun Ingeniería S.L. - Jairo Llopis # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Restricted Summary for Phone Calls", "summary": "Allows to choose from a defined summary list", "version": "15.0.1.0.0", "category": "Customer Relationship Management", "website": "https://github.com/OCA/crm", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "post_init_hook": "convert_names_to_many2one", "depends": ["crm_phonecall", "sales_team"], "data": [ "security/ir.model.access.csv", "views/crm_phonecall_summary_view.xml", "views/crm_phonecall_view.xml", "wizard/crm_phonecall_to_phonecall_view.xml", ], "images": ["images/summary_picker.png", "images/summary_editor.png"], }
40.863636
899
1,853
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from psycopg2 import IntegrityError from odoo.tests import common from odoo.tools import mute_logger class TestCrmPhoneCallSummaryPredefined(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.summary = cls.env["crm.phonecall.summary"].create({"name": "Test summary"}) cls.partner = cls.env["res.partner"].create({"name": "Mr Odoo"}) cls.phonecall = cls.env["crm.phonecall"].create( { "name": "Test phonecall", "partner_id": cls.partner.id, "summary_id": cls.summary.id, } ) def test_summary_constraint(self): with self.assertRaises(IntegrityError), mute_logger("odoo.sql_db"): self.summary.copy() def test_schedule_another_phonecall(self): new_phonecall = self.phonecall.schedule_another_phonecall( { "name": "Test schedule method", "action": "schedule", "summary_id": self.phonecall.summary_id.id, } )[self.phonecall.id] self.assertEqual(new_phonecall.summary_id, self.phonecall.summary_id) def test_wizard(self): wizard = ( self.env["crm.phonecall2phonecall"] .with_context( active_ids=self.phonecall.ids, active_id=self.phonecall.id, active_model="crm.phonecall", ) .create({}) ) self.assertEqual(wizard.summary_id, self.summary) result = wizard.action_schedule() new_phonecall = self.env["crm.phonecall"].browse(result["res_id"]) self.assertEqual(new_phonecall.summary_id, self.phonecall.summary_id)
36.294118
1,851
1,044
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class CrmPhonecall2phonecall(models.TransientModel): _inherit = "crm.phonecall2phonecall" name = fields.Char( related="summary_id.name", store=True, required=False, readonly=True, ) summary_id = fields.Many2one( comodel_name="crm.phonecall.summary", string="Summary", required=True, ondelete="restrict", ) @api.model def default_get(self, fields): """Function gets default values.""" res = super().default_get(fields) model = self.env.context.get("active_model") if model == "crm.phonecall": phonecall = self.env[model].browse(self.env.context.get("active_id")) res["summary_id"] = phonecall.summary_id.id return res def get_vals_action_schedule(self): res = super().get_vals_action_schedule() res.update({"summary_id": self.summary_id.id}) return res
29
1,044
1,317
py
PYTHON
15.0
# Copyright 2016 Antiun Ingeniería S.L. - Jairo Llopis # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class CRMPhonecall(models.Model): """Added number and summary in the phonecall.""" _inherit = "crm.phonecall" name = fields.Char( related="summary_id.name", store=True, required=False, readonly=True, ) summary_id = fields.Many2one( comodel_name="crm.phonecall.summary", string="Summary", required=True, ondelete="restrict", ) def get_values_schedule_another_phonecall(self, vals): res = super().get_values_schedule_another_phonecall(vals) res.update({"summary_id": vals.get("summary_id")}) return res class CRMPhonecallSummary(models.Model): """Added phonecall summary feature.""" _name = "crm.phonecall.summary" _description = "Crm Phonecall Summary" _sql_constraints = [ ("name_unique", "UNIQUE (name)", "Name must be unique"), ] name = fields.Char(required=True) phonecall_ids = fields.One2many( comodel_name="crm.phonecall", inverse_name="summary_id", string="Phonecalls", help="Phonecalls with this summary.", )
28
1,316
549
py
PYTHON
15.0
# Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "CRM Industry", "summary": "Link leads/opportunities to industries", "version": "15.0.1.1.1", "category": "Customer Relationship Management", "website": "https://github.com/OCA/crm", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["crm", "partner_industry_secondary"], "data": ["views/crm_lead_view.xml"], }
36.6
549
2,750
py
PYTHON
15.0
# Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta # Copyright 2018 ForgeFlow, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.exceptions import UserError from odoo.tests import Form from odoo.tests.common import TransactionCase class TestCrmLead(TransactionCase): def test_check_industries(self): industry = self.env["res.partner.industry"].create({"name": "Test"}) with self.assertRaises(UserError): self.env["crm.lead"].create( { "name": "Test", "industry_id": industry.id, "secondary_industry_ids": [(4, industry.id)], } ) def test_lead_create_contact(self): industry_pool = self.env["res.partner.industry"] industry_1 = industry_pool.create({"name": "Test 01"}) industry_2 = industry_pool.create( {"name": "Test 02", "parent_id": industry_1.id} ) industry_3 = industry_pool.create( {"name": "Test 03", "parent_id": industry_1.id} ) lead_vals = { "name": "test", "partner_name": "test", "industry_id": industry_1.id, "secondary_industry_ids": [(4, industry_2.id, 0), (4, industry_3.id, 0)], } lead = self.env["crm.lead"].create(lead_vals) partner = self.env["res.partner"].create( lead._prepare_customer_values(lead.partner_name, is_company=True) ) self.assertEqual(partner.industry_id, lead.industry_id) self.assertEqual(partner.secondary_industry_ids, lead.secondary_industry_ids) def test_propagate_industries_from_contact(self): res_partner_industry = self.env["res.partner.industry"] industry_1 = res_partner_industry.create({"name": "IT/Communications"}) industry_2 = res_partner_industry.create( {"name": "AI/Machine Learning", "parent_id": industry_1.id} ) industry_3 = res_partner_industry.create( {"name": "ERP Systems", "parent_id": industry_1.id} ) customer = self.env["res.partner"].create( { "name": "Test Customer", "industry_id": industry_1.id, "secondary_industry_ids": [ (4, industry_2.id, 0), (4, industry_3.id, 0), ], } ) lead_form = Form(self.env["crm.lead"]) lead_form.name = "Test Lead" lead_form.partner_id = customer lead = lead_form.save() self.assertEqual(lead.industry_id, customer.industry_id) self.assertEqual(lead.secondary_industry_ids, customer.secondary_industry_ids)
40.441176
2,750
2,554
py
PYTHON
15.0
# Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta # Copyright 2018 ForgeFlow, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, exceptions, fields, models class CrmLead(models.Model): _inherit = "crm.lead" industry_id = fields.Many2one( comodel_name="res.partner.industry", string="Main Industry" ) secondary_industry_ids = fields.Many2many( comodel_name="res.partner.industry", string="Secondary Industries", domain="[('id', '!=', industry_id)]", ) @api.constrains("industry_id", "secondary_industry_ids") def _check_industries(self): for lead in self: if lead.industry_id in lead.secondary_industry_ids: raise exceptions.UserError( _( "The secondary industries must be different from the" " main industry." ) ) def _prepare_customer_values(self, partner_name, is_company=False, parent_id=False): """Propagate industries in the creation of partner.""" values = super()._prepare_customer_values( partner_name, is_company=is_company, parent_id=parent_id ) main, secondary = self.industry_id, self.secondary_industry_ids values.update( { "industry_id": main.id, "secondary_industry_ids": [(6, 0, secondary.ids)], } ) return values @api.onchange("partner_id") def _onchange_partner_id(self): if self.partner_id: if self.partner_id.industry_id: self.industry_id = self.partner_id.industry_id if self.partner_id.secondary_industry_ids: self.secondary_industry_ids = self.partner_id.secondary_industry_ids @api.model def create(self, vals): if vals.get("partner_id"): customer = self.env["res.partner"].browse(vals["partner_id"]) if customer.industry_id and not vals.get("industry_id"): vals.update({"industry_id": customer.industry_id.id}) if customer.secondary_industry_ids and not vals.get( "secondary_industry_ids" ): vals.update( { "secondary_industry_ids": [ (6, 0, customer.secondary_industry_ids.ids) ] } ) return super().create(vals)
37.014493
2,554
666
py
PYTHON
15.0
# Copyright 2023 Moduon Team S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0) { "name": "CRM Partner Assign", "summary": "Assign a Partner to an Opportunity/Lead/Partner to indicate Partnership", "version": "15.0.0.1.1", "development_status": "Alpha", "category": "Sales/CRM", "website": "https://github.com/OCA/crm", "author": "Moduon, Odoo Community Association (OCA)", "maintainers": ["Shide"], "license": "AGPL-3", "application": False, "installable": True, "depends": [ "crm", ], "data": [ "views/crm_lead_view.xml", "views/res_partner_view.xml", ], }
28.956522
666
701
py
PYTHON
15.0
# Copyright 2023 Moduon Team S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0) from odoo.tests.common import TransactionCase class CRMLead(TransactionCase): def test_crm_lead_date_partner_assign(self): """Test that `date_partner_assign` is set when assigning a partner.""" lead = self.env["crm.lead"].create( { "name": "Lead 1", "partner_contact_assigned_id": self.env["res.partner"] .create( { "name": "Partner 1", } ) .id, } ) self.assertTrue(lead.date_partner_assign)
31.863636
701
1,629
py
PYTHON
15.0
# Copyright 2023 Moduon Team S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0) from odoo import api, fields, models class CRMLead(models.Model): _inherit = "crm.lead" partner_contact_assigned_id = fields.Many2one( comodel_name="res.partner", domain="[('is_company', '=', False)]", string="Assigned Partner Contact", tracking=True, help="Partner Contact this case has been assigned to.", check_company=True, ) partner_assigned_id = fields.Many2one( comodel_name="res.partner", string="Assigned Partner", help="Partner this case has been assigned to.", related="partner_contact_assigned_id.commercial_partner_id", store=True, readonly=True, check_company=True, ) date_partner_assign = fields.Date( compute="_compute_date_partner_assign", string="Partner Assignment Date", readonly=False, store=True, copy=True, help="Last date this case was assigned to a partner", ) @api.depends("partner_assigned_id") def _compute_date_partner_assign(self): for lead in self: if not lead.partner_assigned_id: lead.date_partner_assign = False else: lead.date_partner_assign = fields.Date.context_today(lead) def _merge_get_fields(self): fields_list = super()._merge_get_fields() fields_list += [ "partner_assigned_id", "partner_contact_assigned_id", "date_partner_assign", ] return fields_list
31.941176
1,629
854
py
PYTHON
15.0
# Copyright 2023 Moduon Team S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0) from odoo import api, fields, models class ResPartner(models.Model): _inherit = "res.partner" assigned_partner_id = fields.Many2one( comodel_name="res.partner", string="Implemented by", ) implemented_partner_ids = fields.One2many( comodel_name="res.partner", inverse_name="assigned_partner_id", string="Implementation References", ) implemented_count = fields.Integer( compute="_compute_implemented_partner_count", store=True, ) @api.depends("implemented_partner_ids", "implemented_partner_ids.active") def _compute_implemented_partner_count(self): for partner in self: partner.implemented_count = len(partner.implemented_partner_ids)
31.62963
854
684
py
PYTHON
15.0
# Copyright 2010-2020 Odoo S. A. # Copyright 2021 Tecnativa - Pedro M. Baeza # License LGPL-3 - See https://www.gnu.org/licenses/lgpl-3.0.html { "name": "Lead to Task", "summary": "Create Tasks from Leads/Opportunities", "sequence": "19", "category": "Project", "complexity": "easy", "author": "Odoo S.A., Odoo Community Association (OCA), Tecnativa", "website": "https://github.com/OCA/crm", "depends": ["crm", "project"], "version": "15.0.1.0.2", "license": "LGPL-3", "installable": True, "data": [ "security/ir.model.access.csv", "wizard/crm_lead_convert2task_views.xml", "views/crm_lead_views.xml", ], }
32.571429
684