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
|
---|---|---|---|---|---|---|
357 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
openupgrade.delete_record_translations(
env.cr, "helpdesk_mgmt", ["closed_ticket_template", "changed_stage_template"]
)
| 32.454545 | 357 |
825 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
closed_ticket_template = env.ref(
"helpdesk_mgmt.closed_ticket_template", raise_if_not_found=False
)
if closed_ticket_template:
closed_ticket_template.body_html = closed_ticket_template.body_html.replace(
"${object.number}", '"${object.display_name}"'
)
changed_stage_template = env.ref(
"helpdesk_mgmt.changed_stage_template", raise_if_not_found=False
)
if changed_stage_template:
changed_stage_template.body_html = changed_stage_template.body_html.replace(
"${object.number}", '"${object.display_name}"'
)
| 37.5 | 825 |
379 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Carlos Roca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
"""Delete noupdate record as it will not be used anymore."""
openupgrade.delete_records_safely_by_xml_id(
env, ["helpdesk_mgmt.assignment_email_template"]
)
| 31.583333 | 379 |
319 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
openupgrade.load_data(
env.cr, "helpdesk_mgmt", "migrations/15.0.3.2.0/noupdate_changes.xml"
)
| 28.818182 | 317 |
397 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
env.ref("helpdesk_mgmt.group_helpdesk_user").implied_ids = [
(
6,
0,
[env.ref("helpdesk_mgmt.group_helpdesk_user_team").id],
)
]
| 26.333333 | 395 |
417 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
xmlid_renames = [
(
"helpdesk_mgmt.helpesk_ticket_personal_rule",
"helpdesk_mgmt.helpdesk_ticket_personal_rule",
),
]
@openupgrade.migrate()
def migrate(env, version):
openupgrade.rename_xmlids(env.cr, xmlid_renames)
| 26.0625 | 417 |
327 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
openupgrade.load_data(
env.cr, "helpdesk_mgmt", "migrations/15.0.1.3.1/noupdate_changes.xml"
)
| 32.7 | 327 |
3,550 |
py
|
PYTHON
|
15.0
|
import time
from .common import TestHelpdeskTicketBase
class TestHelpdeskTicket(TestHelpdeskTicketBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.ticket = cls.ticket_a_unassigned
def test_helpdesk_ticket_datetimes(self):
old_stage_update = self.ticket.last_stage_update
self.assertTrue(
self.ticket.last_stage_update,
"Helpdesk Ticket: Helpdesk ticket should "
"have a last_stage_update at all times.",
)
self.assertFalse(
self.ticket.closed_date,
"Helpdesk Ticket: No closed date "
"should be set for a non closed "
"ticket.",
)
time.sleep(1)
self.ticket.write({"stage_id": self.stage_closed.id})
self.assertTrue(
self.ticket.closed_date,
"Helpdesk Ticket: A closed ticket " "should have a closed_date value.",
)
self.assertTrue(
old_stage_update < self.ticket.last_stage_update,
"Helpdesk Ticket: The last_stage_update "
"should be updated at every stage_id "
"change.",
)
self.ticket.write({"user_id": self.user.id})
self.assertTrue(
self.ticket.assigned_date,
"Helpdesk Ticket: An assigned ticket " "should contain a assigned_date.",
)
def test_helpdesk_ticket_number(self):
self.assertNotEqual(
self.ticket.number,
"/",
"Helpdesk Ticket: A ticket should have " "a number.",
)
ticket_number_1 = int(self.ticket._prepare_ticket_number(values={})[2:])
ticket_number_2 = int(self.ticket._prepare_ticket_number(values={})[2:])
self.assertEqual(ticket_number_1 + 1, ticket_number_2)
def test_helpdesk_ticket_copy(self):
old_ticket_number = self.ticket.number
copy_ticket_number = self.ticket.copy().number
self.assertTrue(
copy_ticket_number != "/" and old_ticket_number != copy_ticket_number,
"Helpdesk Ticket: A new ticket can not "
"have the same number than the origin ticket.",
)
def test_helpdesk_ticket_message_new(self):
Partner = self.env["res.partner"]
Ticket = self.env["helpdesk.ticket"]
newPartner = Partner.create(
{
"name": "Jill",
"email": "[email protected]",
}
)
title = "Test Helpdesk ticket message new"
msg_id = "[email protected]"
msg_dict = {
"message_id": msg_id,
"subject": title,
"email_from": "Bob <[email protected]>",
"to": "[email protected]",
"cc": "[email protected]",
"recipients": "[email protected][email protected]",
"partner_ids": [newPartner.id],
"body": "This the body",
"date": "2021-10-10",
}
try:
t = Ticket.message_new(msg_dict)
except Exception as error:
self.fail("%s: %s" % (type(error), error))
self.assertEqual(t.name, title, "The ticket should have the correct title.")
title = "New title"
update_vals = {"name": title}
try:
t.message_update(msg_dict, update_vals)
except Exception as error:
self.fail("%s: %s" % (type(error), error))
self.assertEqual(
t.name, title, "The ticket should have the correct (new) title."
)
| 35.858586 | 3,550 |
9,120 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Víctor Martínez
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
# import odoo.tests
from odoo import http
from odoo.tests.common import new_test_user
from odoo.addons.base.tests.common import HttpCaseWithUserPortal
class TestHelpdeskPortal(HttpCaseWithUserPortal):
"""Test controllers defined for portal mode.
This is mostly for basic coverage; we don't go as far as fully validating
HTML produced by our routes.
"""
def setUp(self):
super().setUp()
ctx = {
"mail_create_nolog": True,
"mail_create_nosubscribe": True,
"mail_notrack": True,
"no_reset_password": True,
}
self.new_ticket_title = "portal-new-submitted-ticket-subject"
self.new_ticket_desc_lines = ( # multiline description to check line breaks
"portal-new-submitted-ticket-description-line-1",
"portal-new-submitted-ticket-description-line-2",
)
self.company = self.env.ref("base.main_company")
self.partner_portal.parent_id = self.company.partner_id
# Create a basic user with no helpdesk permissions.
self.basic_user = new_test_user(self.env, login="test-basic-user", context=ctx)
self.basic_user.parent_id = self.company.partner_id
# Create a ticket submitted by our portal user.
self.portal_ticket = self._create_ticket(
self.partner_portal, "portal-ticket-title"
)
def get_new_tickets(self, user):
return self.env["helpdesk.ticket"].with_user(user).search([])
def _submit_ticket(self):
resp = self.url_open(
"/submitted/ticket",
data={
"category": self.env.ref("helpdesk_mgmt.helpdesk_category_1").id,
"csrf_token": http.WebRequest.csrf_token(self),
"subject": self.new_ticket_title,
"description": "\n".join(self.new_ticket_desc_lines),
},
)
self.assertEqual(resp.status_code, 200)
def test_submit_ticket_01(self):
self.authenticate("test-basic-user", "test-basic-user")
self._submit_ticket()
tickets = self.get_new_tickets(self.basic_user)
self.assertNotIn(self.portal_ticket, tickets)
self.assertIn(self.new_ticket_title, tickets.mapped("name"))
self.assertIn(
"<p>" + "<br>".join(self.new_ticket_desc_lines) + "</p>",
tickets.mapped("description"),
)
def test_submit_ticket_02(self):
self.authenticate("portal", "portal")
self._submit_ticket()
tickets = self.get_new_tickets(self.user_portal)
self.assertIn(self.portal_ticket, tickets)
self.assertIn(self.new_ticket_title, tickets.mapped("name"))
self.assertIn(
"<p>" + "<br>".join(self.new_ticket_desc_lines) + "</p>",
tickets.mapped("description"),
)
def test_ticket_list(self):
"""List tickets in portal mode, ensure it contains our test ticket."""
self.authenticate("portal", "portal")
resp = self.url_open("/my/tickets")
self.assertEqual(resp.status_code, 200)
self.assertIn("portal-ticket-title", resp.text)
def test_ticket_form(self):
"""Open our test ticket in portal mode."""
self.authenticate("portal", "portal")
resp = self.url_open(f"/my/ticket/{self.portal_ticket.id}")
self.assertEqual(resp.status_code, 200)
self.assertIn("portal-ticket-title", resp.text)
self.assertIn(
"<h4><strong>Message and communication history</strong></h4>", resp.text
)
def test_close_ticket(self):
"""Close a ticket from the portal."""
self.assertFalse(self.portal_ticket.closed)
self.authenticate("portal", "portal")
resp = self.url_open(f"/my/ticket/{self.portal_ticket.id}")
self.assertEqual(self._count_close_buttons(resp), 2) # 2 close stages in data/
stage = self.env.ref("helpdesk_mgmt.helpdesk_ticket_stage_done")
self._call_close_ticket(self.portal_ticket, stage)
self.assertTrue(self.portal_ticket.closed)
self.assertEqual(self.portal_ticket.stage_id, stage)
resp = self.url_open(f"/my/ticket/{self.portal_ticket.id}")
self.assertEqual(self._count_close_buttons(resp), 0) # no close buttons now
def test_close_ticket_invalid_stage(self):
"""Attempt to close a ticket from the portal with an invalid target stage."""
self.authenticate("portal", "portal")
stage = self.env.ref("helpdesk_mgmt.helpdesk_ticket_stage_awaiting")
self._call_close_ticket(self.portal_ticket, stage)
self.assertFalse(self.portal_ticket.closed)
self.assertNotEqual(self.portal_ticket.stage_id, stage)
def test_ticket_list_unauthenticated(self):
"""Attempt to list tickets without auth, ensure we get sent back to login."""
resp = self.url_open("/my/tickets", allow_redirects=False)
self.assertEqual(resp.status_code, 303)
self.assertTrue(resp.is_redirect)
# http://127.0.0.1:8069/web/login?redirect=http%3A%2F%2F127.0.0.1%3A8069%2Fmy%2Ftickets
self.assertIn("/web/login", resp.headers["Location"])
def test_ticket_list_authorized(self):
"""Attempt to list tickets without helpdesk permissions."""
self.authenticate("test-basic-user", "test-basic-user")
resp = self.url_open("/my/tickets", allow_redirects=False)
self.assertEqual(resp.status_code, 200)
self.assertFalse(resp.is_redirect)
def test_tickets_2_users(self):
"""Check tickets between 2 portal users; ensure they can't access each
others' tickets.
"""
self.partner_portal.parent_id = False
portal_user_1 = self.user_portal # created by HttpCaseWithUserPortal
portal_user_2 = self.user_portal.copy(
default={"login": "portal2", "password": "portal2"}
)
ticket_1 = self._create_ticket(portal_user_1.partner_id, "ticket-user-1")
ticket_2 = self._create_ticket(portal_user_2.partner_id, "ticket-user-2")
# Portal ticket list: portal_user_1 only sees ticket_1
self.authenticate("portal", "portal")
resp = self.url_open("/my/tickets")
self.assertEqual(resp.status_code, 200)
self.assertIn("ticket-user-1", resp.text)
self.assertNotIn("ticket-user-2", resp.text)
# Portal ticket list: portal_user_2 only sees ticket_2
self.authenticate("portal2", "portal2")
resp = self.url_open("/my/tickets")
self.assertEqual(resp.status_code, 200)
self.assertNotIn("ticket-user-1", resp.text)
self.assertIn("ticket-user-2", resp.text)
# Portal ticket form: portal_user_1 can open ticket_1 but not ticket_2
self.authenticate("portal", "portal")
resp = self.url_open(f"/my/ticket/{ticket_1.id}")
self.assertEqual(resp.status_code, 200)
self.assertIn("ticket-user-1", resp.text)
resp = self.url_open(f"/my/ticket/{ticket_2.id}", allow_redirects=False)
self.assertEqual(resp.status_code, 303)
self.assertTrue(resp.is_redirect)
self.assertTrue(resp.headers["Location"].endswith("/my"))
# Portal ticket form: portal_user_2 can open ticket_2 but not ticket_1
self.authenticate("portal2", "portal2")
resp = self.url_open(f"/my/ticket/{ticket_1.id}", allow_redirects=False)
self.assertEqual(resp.status_code, 303)
self.assertTrue(resp.is_redirect)
self.assertTrue(resp.headers["Location"].endswith("/my"))
resp = self.url_open(f"/my/ticket/{ticket_2.id}")
self.assertEqual(resp.status_code, 200)
self.assertIn("ticket-user-2", resp.text)
def _count_close_buttons(self, resp) -> int:
"""Count close buttons in a form by counting forms with that target."""
return resp.text.count('action="/ticket/close"')
def _call_close_ticket(self, ticket, stage):
"""Call /ticket/close with the specified target stage, check redirect."""
resp = self.url_open(
"/ticket/close",
data={
"csrf_token": http.WebRequest.csrf_token(self),
"stage_id": stage.id,
"ticket_id": ticket.id,
},
allow_redirects=False,
)
self.assertEqual(resp.status_code, 302)
self.assertTrue(resp.is_redirect) # http://127.0.0.1:8069/my/ticket/<ticket-id>
self.assertTrue(resp.headers["Location"].endswith(f"/my/ticket/{ticket.id}"))
return resp
def _create_ticket(self, partner, ticket_title):
"""Create a ticket submitted by the specified partner."""
return self.env["helpdesk.ticket"].create(
{
"name": ticket_title,
"description": "test-description",
"partner_id": partner.id,
"partner_email": partner.email,
"partner_name": partner.name,
}
)
| 44.262136 | 9,118 |
2,413 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Víctor Martínez
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo.tests import common, new_test_user
class TestHelpdeskTicketBase(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
helpdesk_ticket_team = cls.env["helpdesk.ticket.team"]
ctx = {
"mail_create_nolog": True,
"mail_create_nosubscribe": True,
"mail_notrack": True,
"no_reset_password": True,
}
cls.user_own = new_test_user(
cls.env,
login="helpdesk_mgmt-user_own",
groups="helpdesk_mgmt.group_helpdesk_user_own",
context=ctx,
)
cls.user_team = new_test_user(
cls.env,
login="helpdesk_mgmt-user_team",
groups="helpdesk_mgmt.group_helpdesk_user_team",
context=ctx,
)
cls.user = new_test_user(
cls.env,
login="helpdesk_mgmt-user",
groups="helpdesk_mgmt.group_helpdesk_user",
context=ctx,
)
cls.stage_closed = cls.env.ref("helpdesk_mgmt.helpdesk_ticket_stage_done")
cls.team_a = helpdesk_ticket_team.create(
{"name": "Team A", "user_ids": [(6, 0, [cls.user_own.id, cls.user.id])]}
)
cls.team_b = helpdesk_ticket_team.create(
{"name": "Team B", "user_ids": [(6, 0, [cls.user_team.id])]}
)
cls.ticket_a_unassigned = cls._create_ticket(cls, cls.team_a)
cls.ticket_a_unassigned.priority = "3"
cls.ticket_a_user_own = cls._create_ticket(cls, cls.team_a, cls.user_own)
cls.ticket_a_user_team = cls._create_ticket(cls, cls.team_a, cls.user_team)
cls.ticket_b_unassigned = cls._create_ticket(cls, cls.team_b)
cls.ticket_b_user_own = cls._create_ticket(cls, cls.team_b, cls.user_own)
cls.ticket_b_user_team = cls._create_ticket(cls, cls.team_b, cls.user_team)
def _create_ticket(self, team, user=False):
return self.env["helpdesk.ticket"].create(
{
"name": "Ticket %s (%s)"
% (team.name, user.login if user else "unassigned"),
"description": "Description",
"team_id": team.id,
"user_id": user.id if user else False,
"priority": "1",
}
)
| 40.183333 | 2,411 |
1,811 |
py
|
PYTHON
|
15.0
|
from odoo.tests.common import TransactionCase
class TestPartner(TransactionCase):
def setUp(self):
super().setUp()
self.partner_obj = self.env["res.partner"]
self.ticket_obj = self.env["helpdesk.ticket"]
self.stage_id_closed = self.env.ref("helpdesk_mgmt.helpdesk_ticket_stage_done")
self.parent_id = self.partner_obj.create({"name": "Parent 1"})
self.child_id_1 = self.partner_obj.create({"name": "Child 1"})
self.child_id_2 = self.partner_obj.create({"name": "Child 2"})
self.child_id_3 = self.partner_obj.create({"name": "Child 3"})
self.tickets = []
self.parent_id.child_ids = [
(4, self.child_id_1.id),
(4, self.child_id_2.id),
(4, self.child_id_3.id),
]
for i in [69, 155, 314, 420]:
self.tickets.append(
self.ticket_obj.create(
{
"name": "Nice ticket {}".format(i),
"description": "Nice ticket {} description".format(i),
}
)
)
self.parent_id.helpdesk_ticket_ids = [(4, self.tickets[0].id)]
self.child_id_1.helpdesk_ticket_ids = [(4, self.tickets[1].id)]
self.child_id_2.helpdesk_ticket_ids = [(4, self.tickets[2].id)]
self.child_id_3.helpdesk_ticket_ids = [(4, self.tickets[3].id)]
self.child_id_3.helpdesk_ticket_ids[-1].stage_id = self.stage_id_closed
def test_ticket_count(self):
self.assertEqual(self.parent_id.helpdesk_ticket_count, 4)
def test_ticket_active_count(self):
self.assertEqual(self.parent_id.helpdesk_ticket_active_count, 3)
def test_ticket_string(self):
self.assertEqual(self.parent_id.helpdesk_ticket_count_string, "3 / 4")
| 43.119048 | 1,811 |
3,007 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Víctor Martínez
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo.tests.common import users
from .common import TestHelpdeskTicketBase
class TestHelpdeskTicketTeam(TestHelpdeskTicketBase):
@users("helpdesk_mgmt-user_own")
def test_helpdesk_ticket_user_own(self):
tickets = self.env["helpdesk.ticket"].search([])
self.assertIn(self.ticket_a_unassigned, tickets)
self.assertIn(self.ticket_a_user_own, tickets)
self.assertNotIn(self.ticket_a_user_team, tickets)
self.assertNotIn(self.ticket_b_unassigned, tickets)
self.assertIn(self.ticket_b_user_own, tickets)
self.assertNotIn(self.ticket_b_user_team, tickets)
@users("helpdesk_mgmt-user_team")
def test_helpdesk_ticket_user_team(self):
tickets = self.env["helpdesk.ticket"].search([])
self.assertNotIn(self.ticket_a_unassigned, tickets)
self.assertNotIn(self.ticket_a_user_own, tickets)
self.assertIn(self.ticket_a_user_team, tickets)
self.assertIn(self.ticket_b_unassigned, tickets)
self.assertIn(self.ticket_b_user_own, tickets)
self.assertIn(self.ticket_b_user_team, tickets)
@users("helpdesk_mgmt-user")
def test_helpdesk_ticket_user(self):
tickets = self.env["helpdesk.ticket"].search([])
self.assertIn(self.ticket_a_unassigned, tickets)
self.assertIn(self.ticket_a_user_own, tickets)
self.assertIn(self.ticket_a_user_team, tickets)
self.assertIn(self.ticket_b_unassigned, tickets)
self.assertIn(self.ticket_b_user_own, tickets)
self.assertIn(self.ticket_b_user_team, tickets)
def test_helpdesk_ticket_todo(self):
self.assertEqual(
self.team_a.todo_ticket_count,
3,
"Helpdesk Ticket: Helpdesk ticket team should have three tickets to do.",
)
self.assertEqual(
self.team_a.todo_ticket_count_unassigned,
1,
"Helpdesk Ticket: Helpdesk ticket team should "
"have one tickets unassigned.",
)
self.assertEqual(
self.team_a.todo_ticket_count_high_priority,
1,
"Helpdesk Ticket: Helpdesk ticket team should "
"have one ticket with high priority.",
)
self.assertEqual(
self.team_a.todo_ticket_count_unattended,
3,
"Helpdesk Ticket: Helpdesk ticket team should "
"have three tickets unattended.",
)
self.ticket_a_unassigned.write({"stage_id": self.stage_closed.id})
self.assertEqual(
self.team_a.todo_ticket_count_unattended,
2,
"Helpdesk Ticket: Helpdesk ticket team should "
"have two tickets unattended.",
)
self.assertEqual(
self.team_a.todo_ticket_count,
2,
"Helpdesk Ticket: Helpdesk ticket team should have two ticket to do.",
)
| 40.066667 | 3,005 |
3,898 |
py
|
PYTHON
|
15.0
|
from odoo import api, fields, models
from odoo.tools.safe_eval import safe_eval
class HelpdeskTeam(models.Model):
_name = "helpdesk.ticket.team"
_description = "Helpdesk Ticket Team"
_inherit = ["mail.thread", "mail.alias.mixin"]
_order = "sequence, id"
sequence = fields.Integer(default=10)
name = fields.Char(required=True)
user_ids = fields.Many2many(
comodel_name="res.users",
string="Members",
relation="helpdesk_ticket_team_res_users_rel",
column1="helpdesk_ticket_team_id",
column2="res_users_id",
)
active = fields.Boolean(default=True)
category_ids = fields.Many2many(
comodel_name="helpdesk.ticket.category", string="Category"
)
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="Team Leader",
check_company=True,
)
alias_id = fields.Many2one(
comodel_name="mail.alias",
string="Email",
ondelete="restrict",
required=True,
help="The email address associated with \
this channel. New emails received will \
automatically create new tickets assigned \
to the channel.",
)
color = fields.Integer(string="Color Index", default=0)
ticket_ids = fields.One2many(
comodel_name="helpdesk.ticket",
inverse_name="team_id",
string="Tickets",
)
todo_ticket_count = fields.Integer(
string="Number of tickets", compute="_compute_todo_tickets"
)
todo_ticket_count_unassigned = fields.Integer(
string="Number of tickets unassigned", compute="_compute_todo_tickets"
)
todo_ticket_count_unattended = fields.Integer(
string="Number of tickets unattended", compute="_compute_todo_tickets"
)
todo_ticket_count_high_priority = fields.Integer(
string="Number of tickets in high priority", compute="_compute_todo_tickets"
)
show_in_portal = fields.Boolean(
string="Show in portal form",
default=True,
help="Allow to select this team when creating a new ticket in the portal.",
)
@api.depends("ticket_ids", "ticket_ids.stage_id")
def _compute_todo_tickets(self):
ticket_model = self.env["helpdesk.ticket"]
fetch_data = ticket_model.read_group(
[("team_id", "in", self.ids), ("closed", "=", False)],
["team_id", "user_id", "unattended", "priority"],
["team_id", "user_id", "unattended", "priority"],
lazy=False,
)
result = [
[
data["team_id"][0],
data["user_id"] and data["user_id"][0],
data["unattended"],
data["priority"],
data["__count"],
]
for data in fetch_data
]
for team in self:
team.todo_ticket_count = sum(r[4] for r in result if r[0] == team.id)
team.todo_ticket_count_unassigned = sum(
r[4] for r in result if r[0] == team.id and not r[1]
)
team.todo_ticket_count_unattended = sum(
r[4] for r in result if r[0] == team.id and r[2]
)
team.todo_ticket_count_high_priority = sum(
r[4] for r in result if r[0] == team.id and r[3] == "3"
)
def _alias_get_creation_values(self):
values = super()._alias_get_creation_values()
values["alias_model_id"] = self.env.ref(
"helpdesk_mgmt.model_helpdesk_ticket"
).id
values["alias_defaults"] = defaults = safe_eval(self.alias_defaults or "{}")
defaults["team_id"] = self.id
return values
| 36.092593 | 3,898 |
414 |
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class HelpdeskTicketTag(models.Model):
_name = "helpdesk.ticket.tag"
_description = "Helpdesk Ticket Tag"
name = fields.Char()
color = fields.Integer(string="Color Index")
active = fields.Boolean(default=True)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
default=lambda self: self.env.company,
)
| 27.6 | 414 |
1,402 |
py
|
PYTHON
|
15.0
|
from odoo import api, fields, models
class HelpdeskTicketStage(models.Model):
_name = "helpdesk.ticket.stage"
_description = "Helpdesk Ticket Stage"
_order = "sequence, id"
name = fields.Char(string="Stage Name", required=True, translate=True)
description = fields.Html(translate=True, sanitize_style=True)
sequence = fields.Integer(default=1)
active = fields.Boolean(default=True)
unattended = fields.Boolean()
closed = fields.Boolean()
close_from_portal = fields.Boolean(
help="Display button in portal ticket form to allow closing ticket "
"with this stage as target."
)
mail_template_id = fields.Many2one(
comodel_name="mail.template",
string="Email Template",
domain=[("model", "=", "helpdesk.ticket")],
help="If set an email will be sent to the "
"customer when the ticket"
"reaches this step.",
)
fold = fields.Boolean(
string="Folded in Kanban",
help="This stage is folded in the kanban view "
"when there are no records in that stage "
"to display.",
)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
default=lambda self: self.env.company,
)
@api.onchange("closed")
def _onchange_closed(self):
if not self.closed:
self.close_from_portal = False
| 33.380952 | 1,402 |
461 |
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class HelpdeskTicketChannel(models.Model):
_name = "helpdesk.ticket.channel"
_description = "Helpdesk Ticket Channel"
_order = "sequence, id"
sequence = fields.Integer(default=10)
name = fields.Char(required=True)
active = fields.Boolean(default=True)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
default=lambda self: self.env.company,
)
| 27.117647 | 461 |
512 |
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class HelpdeskCategory(models.Model):
_name = "helpdesk.ticket.category"
_description = "Helpdesk Ticket Category"
_order = "sequence, id"
sequence = fields.Integer(default=10)
active = fields.Boolean(
default=True,
)
name = fields.Char(
required=True,
translate=True,
)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
default=lambda self: self.env.company,
)
| 23.272727 | 512 |
315 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class Company(models.Model):
_inherit = "res.company"
helpdesk_mgmt_portal_select_team = fields.Boolean(
string="Select team in Helpdesk portal"
)
| 26.083333 | 313 |
9,701 |
py
|
PYTHON
|
15.0
|
from odoo import _, api, fields, models, tools
from odoo.exceptions import AccessError
class HelpdeskTicket(models.Model):
_name = "helpdesk.ticket"
_description = "Helpdesk Ticket"
_rec_name = "number"
_order = "priority desc, number desc, id desc"
_mail_post_access = "read"
_inherit = ["mail.thread.cc", "mail.activity.mixin", "portal.mixin"]
def _get_default_stage_id(self):
return self.env["helpdesk.ticket.stage"].search([], limit=1).id
@api.model
def _read_group_stage_ids(self, stages, domain, order):
stage_ids = self.env["helpdesk.ticket.stage"].search([])
return stage_ids
number = fields.Char(string="Ticket number", default="/", readonly=True)
name = fields.Char(string="Title", required=True)
description = fields.Html(required=True, sanitize_style=True)
user_id = fields.Many2one(
comodel_name="res.users",
string="Assigned user",
tracking=True,
index=True,
domain="team_id and [('share', '=', False),('id', 'in', user_ids)] or [('share', '=', False)]", # noqa: B950
)
user_ids = fields.Many2many(
comodel_name="res.users", related="team_id.user_ids", string="Users"
)
stage_id = fields.Many2one(
comodel_name="helpdesk.ticket.stage",
string="Stage",
group_expand="_read_group_stage_ids",
default=_get_default_stage_id,
tracking=True,
ondelete="restrict",
index=True,
copy=False,
)
partner_id = fields.Many2one(comodel_name="res.partner", string="Contact")
partner_name = fields.Char()
partner_email = fields.Char(string="Email")
last_stage_update = fields.Datetime(default=fields.Datetime.now)
assigned_date = fields.Datetime()
closed_date = fields.Datetime()
closed = fields.Boolean(related="stage_id.closed")
unattended = fields.Boolean(related="stage_id.unattended", store=True)
tag_ids = fields.Many2many(comodel_name="helpdesk.ticket.tag", string="Tags")
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
required=True,
default=lambda self: self.env.company,
)
channel_id = fields.Many2one(
comodel_name="helpdesk.ticket.channel",
string="Channel",
help="Channel indicates where the source of a ticket"
"comes from (it could be a phone call, an email...)",
)
category_id = fields.Many2one(
comodel_name="helpdesk.ticket.category",
string="Category",
)
team_id = fields.Many2one(
comodel_name="helpdesk.ticket.team",
string="Team",
)
priority = fields.Selection(
selection=[
("0", "Low"),
("1", "Medium"),
("2", "High"),
("3", "Very High"),
],
default="1",
)
attachment_ids = fields.One2many(
comodel_name="ir.attachment",
inverse_name="res_id",
domain=[("res_model", "=", "helpdesk.ticket")],
string="Media Attachments",
)
color = fields.Integer(string="Color Index")
kanban_state = fields.Selection(
selection=[
("normal", "Default"),
("done", "Ready for next stage"),
("blocked", "Blocked"),
],
)
active = fields.Boolean(default=True)
def name_get(self):
res = []
for rec in self:
res.append((rec.id, rec.number + " - " + rec.name))
return res
def assign_to_me(self):
self.write({"user_id": self.env.user.id})
@api.onchange("partner_id")
def _onchange_partner_id(self):
if self.partner_id:
self.partner_name = self.partner_id.name
self.partner_email = self.partner_id.email
# ---------------------------------------------------
# CRUD
# ---------------------------------------------------
def _creation_subtype(self):
return self.env.ref("helpdesk_mgmt.hlp_tck_created")
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
if vals.get("number", "/") == "/":
vals["number"] = self._prepare_ticket_number(vals)
if vals.get("user_id") and not vals.get("assigned_date"):
vals["assigned_date"] = fields.Datetime.now()
return super().create(vals_list)
def copy(self, default=None):
self.ensure_one()
if default is None:
default = {}
if "number" not in default:
default["number"] = self._prepare_ticket_number(default)
res = super().copy(default)
return res
def write(self, vals):
for _ticket in self:
now = fields.Datetime.now()
if vals.get("stage_id"):
stage = self.env["helpdesk.ticket.stage"].browse([vals["stage_id"]])
vals["last_stage_update"] = now
if stage.closed:
vals["closed_date"] = now
if vals.get("user_id"):
vals["assigned_date"] = now
return super().write(vals)
def action_duplicate_tickets(self):
for ticket in self.browse(self.env.context["active_ids"]):
ticket.copy()
def _prepare_ticket_number(self, values):
seq = self.env["ir.sequence"]
if "company_id" in values:
seq = seq.with_company(values["company_id"])
return seq.next_by_code("helpdesk.ticket.sequence") or "/"
def _compute_access_url(self):
res = super()._compute_access_url()
for item in self:
item.access_url = "/my/ticket/%s" % (item.id)
return res
# ---------------------------------------------------
# Mail gateway
# ---------------------------------------------------
def _track_template(self, tracking):
res = super()._track_template(tracking)
ticket = self[0]
if "stage_id" in tracking and ticket.stage_id.mail_template_id:
res["stage_id"] = (
ticket.stage_id.mail_template_id,
{
"auto_delete_message": True,
"subtype_id": self.env["ir.model.data"]._xmlid_to_res_id(
"mail.mt_note"
),
"email_layout_xmlid": "mail.mail_notification_light",
},
)
return res
@api.model
def message_new(self, msg, custom_values=None):
"""Override message_new from mail gateway so we can set correct
default values.
"""
if custom_values is None:
custom_values = {}
defaults = {
"name": msg.get("subject") or _("No Subject"),
"description": msg.get("body"),
"partner_email": msg.get("from"),
"partner_id": msg.get("author_id"),
}
defaults.update(custom_values)
# Write default values coming from msg
ticket = super().message_new(msg, custom_values=defaults)
# Use mail gateway tools to search for partners to subscribe
email_list = tools.email_split(
(msg.get("to") or "") + "," + (msg.get("cc") or "")
)
partner_ids = [
p.id
for p in self.env["mail.thread"]._mail_find_partner_from_emails(
email_list, records=ticket, force_create=False
)
if p
]
ticket.message_subscribe(partner_ids)
return ticket
def message_update(self, msg, update_vals=None):
"""Override message_update to subscribe partners"""
email_list = tools.email_split(
(msg.get("to") or "") + "," + (msg.get("cc") or "")
)
partner_ids = [
p.id
for p in self.env["mail.thread"]._mail_find_partner_from_emails(
email_list, records=self, force_create=False
)
if p
]
self.message_subscribe(partner_ids)
return super().message_update(msg, update_vals=update_vals)
def _message_get_suggested_recipients(self):
recipients = super()._message_get_suggested_recipients()
try:
for ticket in self:
if ticket.partner_id:
ticket._message_add_suggested_recipient(
recipients, partner=ticket.partner_id, reason=_("Customer")
)
elif ticket.partner_email:
ticket._message_add_suggested_recipient(
recipients,
email=ticket.partner_email,
reason=_("Customer Email"),
)
except AccessError:
# no read access rights -> just ignore suggested recipients because this
# imply modifying followers
return recipients
return recipients
def _notify_get_reply_to(
self, default=None, records=None, company=None, doc_names=None
):
"""Override to set alias of tasks to their team if any."""
aliases = (
self.sudo()
.mapped("team_id")
._notify_get_reply_to(
default=default, records=None, company=company, doc_names=None
)
)
res = {ticket.id: aliases.get(ticket.team_id.id) for ticket in self}
leftover = self.filtered(lambda rec: not rec.team_id)
if leftover:
res.update(
super(HelpdeskTicket, leftover)._notify_get_reply_to(
default=default, records=None, company=company, doc_names=doc_names
)
)
return res
| 35.405109 | 9,701 |
379 |
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class ResUsers(models.Model):
_inherit = "res.users"
# Records come from user_ids field of helpdesk.ticket.team.
helpdesk_team_ids = fields.Many2many(
comodel_name="helpdesk.ticket.team",
relation="helpdesk_ticket_team_res_users_rel",
column1="res_users_id",
column2="helpdesk_ticket_team_id",
)
| 29.153846 | 379 |
380 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
helpdesk_mgmt_portal_select_team = fields.Boolean(
related="company_id.helpdesk_mgmt_portal_select_team",
readonly=False,
)
| 31.5 | 378 |
1,581 |
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
helpdesk_ticket_ids = fields.One2many(
comodel_name="helpdesk.ticket",
inverse_name="partner_id",
string="Related tickets",
)
helpdesk_ticket_count = fields.Integer(
compute="_compute_helpdesk_ticket_count", string="Ticket count"
)
helpdesk_ticket_active_count = fields.Integer(
compute="_compute_helpdesk_ticket_count", string="Ticket active count"
)
helpdesk_ticket_count_string = fields.Char(
compute="_compute_helpdesk_ticket_count", string="Tickets"
)
def _compute_helpdesk_ticket_count(self):
for record in self:
ticket_ids = self.env["helpdesk.ticket"].search(
[("partner_id", "child_of", record.id)]
)
record.helpdesk_ticket_count = len(ticket_ids)
record.helpdesk_ticket_active_count = len(
ticket_ids.filtered(lambda ticket: not ticket.stage_id.closed)
)
count_active = record.helpdesk_ticket_active_count
count = record.helpdesk_ticket_count
record.helpdesk_ticket_count_string = "{} / {}".format(count_active, count)
def action_view_helpdesk_tickets(self):
return {
"name": self.name,
"view_mode": "tree,form",
"res_model": "helpdesk.ticket",
"type": "ir.actions.act_window",
"domain": [("partner_id", "child_of", self.id)],
"context": self.env.context,
}
| 34.369565 | 1,581 |
8,923 |
py
|
PYTHON
|
15.0
|
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from collections import OrderedDict
from operator import itemgetter
from odoo import _, http
from odoo.exceptions import AccessError, MissingError
from odoo.http import request
from odoo.osv.expression import AND, OR
from odoo.tools import groupby as groupbyelem
from odoo.addons.portal.controllers.portal import CustomerPortal, pager as portal_pager
class CustomerPortalHelpdesk(CustomerPortal):
"""Routes called in portal mode to manage tickets.
Very similar to those in the "project" module defined to manage tasks.
"""
def _prepare_home_portal_values(self, counters):
values = super()._prepare_home_portal_values(counters)
if "ticket_count" in counters:
helpdesk_model = request.env["helpdesk.ticket"]
ticket_count = (
helpdesk_model.search_count([])
if helpdesk_model.check_access_rights("read", raise_exception=False)
else 0
)
values["ticket_count"] = ticket_count
return values
@http.route(
["/my/tickets", "/my/tickets/page/<int:page>"],
type="http",
auth="user",
website=True,
)
def portal_my_tickets(
self,
page=1,
date_begin=None,
date_end=None,
sortby=None,
filterby=None,
search=None,
search_in=None,
groupby=None,
**kw
):
HelpdeskTicket = request.env["helpdesk.ticket"]
# Avoid error if the user does not have access.
if not HelpdeskTicket.check_access_rights("read", raise_exception=False):
return request.redirect("/my")
values = self._prepare_portal_layout_values()
searchbar_sortings = self._ticket_get_searchbar_sortings()
searchbar_sortings = dict(
sorted(
self._ticket_get_searchbar_sortings().items(),
key=lambda item: item[1]["sequence"],
)
)
searchbar_filters = {
"all": {"label": _("All"), "domain": []},
}
for stage in request.env["helpdesk.ticket.stage"].search([]):
searchbar_filters[str(stage.id)] = {
"label": stage.name,
"domain": [("stage_id", "=", stage.id)],
}
searchbar_inputs = self._ticket_get_searchbar_inputs()
searchbar_groupby = self._ticket_get_searchbar_groupby()
if not sortby:
sortby = "date"
order = searchbar_sortings[sortby]["order"]
if not filterby:
filterby = "all"
domain = searchbar_filters.get(filterby, searchbar_filters.get("all"))["domain"]
if not groupby:
groupby = "none"
if date_begin and date_end:
domain += [
("create_date", ">", date_begin),
("create_date", "<=", date_end),
]
if not search_in:
search_in = "all"
if search:
domain += self._ticket_get_search_domain(search_in, search)
domain = AND(
[
domain,
request.env["ir.rule"]._compute_domain(HelpdeskTicket._name, "read"),
]
)
# count for pager
ticket_count = HelpdeskTicket.search_count(domain)
# pager
pager = portal_pager(
url="/my/tickets",
url_args={
"date_begin": date_begin,
"date_end": date_end,
"sortby": sortby,
"filterby": filterby,
"groupby": groupby,
"search": search,
"search_in": search_in,
},
total=ticket_count,
page=page,
step=self._items_per_page,
)
order = self._ticket_get_order(order, groupby)
tickets = HelpdeskTicket.search(
domain,
order=order,
limit=self._items_per_page,
offset=pager["offset"],
)
request.session["my_tickets_history"] = tickets.ids[:100]
groupby_mapping = self._ticket_get_groupby_mapping()
group = groupby_mapping.get(groupby)
if group:
grouped_tickets = [
request.env["helpdesk.ticket"].concat(*g)
for k, g in groupbyelem(tickets, itemgetter(group))
]
elif tickets:
grouped_tickets = [tickets]
else:
grouped_tickets = []
values.update(
{
"date": date_begin,
"date_end": date_end,
"grouped_tickets": grouped_tickets,
"page_name": "ticket",
"default_url": "/my/tickets",
"pager": pager,
"searchbar_sortings": searchbar_sortings,
"searchbar_groupby": searchbar_groupby,
"searchbar_inputs": searchbar_inputs,
"search_in": search_in,
"search": search,
"sortby": sortby,
"groupby": groupby,
"searchbar_filters": OrderedDict(sorted(searchbar_filters.items())),
"filterby": filterby,
}
)
return request.render("helpdesk_mgmt.portal_my_tickets", values)
@http.route(
["/my/ticket/<int:ticket_id>"], type="http", auth="public", website=True
)
def portal_my_ticket(self, ticket_id, access_token=None, **kw):
try:
ticket_sudo = self._document_check_access(
"helpdesk.ticket", ticket_id, access_token=access_token
)
except (AccessError, MissingError):
return request.redirect("/my")
# ensure attachments are accessible with access token inside template
for attachment in ticket_sudo.attachment_ids:
attachment.generate_access_token()
values = self._ticket_get_page_view_values(ticket_sudo, access_token, **kw)
return request.render("helpdesk_mgmt.portal_helpdesk_ticket_page", values)
def _ticket_get_page_view_values(self, ticket, access_token, **kwargs):
closed_stages = request.env["helpdesk.ticket.stage"].search(
[("close_from_portal", "=", True)]
)
values = {
"closed_stages": closed_stages, # used to display close buttons
"page_name": "ticket",
"ticket": ticket,
"user": request.env.user,
}
return self._get_page_view_values(
ticket, access_token, values, "my_tickets_history", False, **kwargs
)
def _ticket_get_searchbar_sortings(self):
return {
"date": {
"label": _("Newest"),
"order": "create_date desc",
"sequence": 1,
},
"name": {"label": _("Title"), "order": "name", "sequence": 2},
"stage": {"label": _("Stage"), "order": "stage_id", "sequence": 3},
"update": {
"label": _("Last Stage Update"),
"order": "last_stage_update desc",
"sequence": 4,
},
}
def _ticket_get_searchbar_groupby(self):
values = {
"none": {"input": "none", "label": _("None"), "order": 1},
"category": {
"input": "category",
"label": _("Category"),
"order": 2,
},
"stage": {"input": "stage", "label": _("Stage"), "order": 3},
}
return dict(sorted(values.items(), key=lambda item: item[1]["order"]))
def _ticket_get_searchbar_inputs(self):
values = {
"all": {"input": "all", "label": _("Search in All"), "order": 1},
"number": {
"input": "number",
"label": _("Search in Number"),
"order": 2,
},
"name": {
"input": "name",
"label": _("Search in Title"),
"order": 3,
},
}
return dict(sorted(values.items(), key=lambda item: item[1]["order"]))
def _ticket_get_search_domain(self, search_in, search):
search_domain = []
if search_in in ("number", "all"):
search_domain.append([("number", "ilike", search)])
if search_in in ("name", "all"):
search_domain.append([("name", "ilike", search)])
return OR(search_domain)
def _ticket_get_groupby_mapping(self):
return {
"category": "category_id",
"stage": "stage_id",
}
def _ticket_get_order(self, order, groupby):
groupby_mapping = self._ticket_get_groupby_mapping()
field_name = groupby_mapping.get(groupby, "")
if not field_name:
return order
return "%s, %s" % (field_name, order)
| 34.187739 | 8,923 |
4,086 |
py
|
PYTHON
|
15.0
|
import base64
import logging
import werkzeug
import odoo.http as http
from odoo.http import request
from odoo.tools import plaintext2html
_logger = logging.getLogger(__name__)
class HelpdeskTicketController(http.Controller):
@http.route("/ticket/close", type="http", auth="user")
def support_ticket_close(self, **kw):
"""Close the support ticket"""
values = {}
for field_name, field_value in kw.items():
if field_name.endswith("_id"):
values[field_name] = int(field_value)
else:
values[field_name] = field_value
ticket = (
http.request.env["helpdesk.ticket"]
.sudo()
.search([("id", "=", values["ticket_id"])])
)
stage = http.request.env["helpdesk.ticket.stage"].browse(values.get("stage_id"))
if stage.close_from_portal: # protect against invalid target stage request
ticket.stage_id = values.get("stage_id")
return werkzeug.utils.redirect("/my/ticket/" + str(ticket.id))
def _get_teams(self):
return (
http.request.env["helpdesk.ticket.team"]
.sudo()
.search([("active", "=", True), ("show_in_portal", "=", True)])
if http.request.env.user.company_id.helpdesk_mgmt_portal_select_team
else False
)
@http.route("/new/ticket", type="http", auth="user", website=True)
def create_new_ticket(self, **kw):
categories = http.request.env["helpdesk.ticket.category"].search(
[("active", "=", True)]
)
email = http.request.env.user.email
name = http.request.env.user.name
return http.request.render(
"helpdesk_mgmt.portal_create_ticket",
{
"categories": categories,
"teams": self._get_teams(),
"email": email,
"name": name,
},
)
def _prepare_submit_ticket_vals(self, **kw):
category = http.request.env["helpdesk.ticket.category"].browse(
int(kw.get("category"))
)
company = category.company_id or http.request.env.user.company_id
vals = {
"company_id": company.id,
"category_id": category.id,
"description": plaintext2html(kw.get("description")),
"name": kw.get("subject"),
"attachment_ids": False,
"channel_id": request.env["helpdesk.ticket.channel"]
.sudo()
.search([("name", "=", "Web")])
.id,
"partner_id": request.env.user.partner_id.id,
"partner_name": request.env.user.partner_id.name,
"partner_email": request.env.user.partner_id.email,
}
if company.helpdesk_mgmt_portal_select_team:
team = (
http.request.env["helpdesk.ticket.team"]
.sudo()
.search(
[("id", "=", int(kw.get("team"))), ("show_in_portal", "=", True)]
)
)
vals.update({"team_id": team.id})
return vals
@http.route("/submitted/ticket", type="http", auth="user", website=True, csrf=True)
def submit_ticket(self, **kw):
vals = self._prepare_submit_ticket_vals(**kw)
new_ticket = request.env["helpdesk.ticket"].sudo().create(vals)
new_ticket.message_subscribe(partner_ids=request.env.user.partner_id.ids)
if kw.get("attachment"):
for c_file in request.httprequest.files.getlist("attachment"):
data = c_file.read()
if c_file.filename:
request.env["ir.attachment"].sudo().create(
{
"name": c_file.filename,
"datas": base64.b64encode(data),
"res_model": "helpdesk.ticket",
"res_id": new_ticket.id,
}
)
return werkzeug.utils.redirect("/my/ticket/%s" % new_ticket.id)
| 38.186916 | 4,086 |
693 |
py
|
PYTHON
|
15.0
|
import setuptools
with open('VERSION.txt', 'r') as f:
version = f.read().strip()
setuptools.setup(
name="odoo-addons-oca-helpdesk",
description="Meta package for oca-helpdesk Odoo addons",
version=version,
install_requires=[
'odoo-addon-helpdesk_mgmt>=15.0dev,<15.1dev',
'odoo-addon-helpdesk_mgmt_project>=15.0dev,<15.1dev',
'odoo-addon-helpdesk_mgmt_rating>=15.0dev,<15.1dev',
'odoo-addon-helpdesk_mgmtsystem_nonconformity>=15.0dev,<15.1dev',
'odoo-addon-helpdesk_type>=15.0dev,<15.1dev',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Odoo',
'Framework :: Odoo :: 15.0',
]
)
| 31.5 | 693 |
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 |
630 |
py
|
PYTHON
|
15.0
|
{
"name": "Helpdesk Management Rating",
"summary": """
This module allows customer to rate the assistance received
on a ticket.
""",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"author": "Domatix, Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/helpdesk",
"category": "After-Sales",
"depends": ["helpdesk_mgmt", "rating"],
"data": [
"data/helpdesk_data.xml",
"views/helpdesk_ticket_menu.xml",
"views/helpdesk_ticket_views.xml",
"views/helpdesk_ticket_stage_views.xml",
],
"installable": True,
}
| 31.5 | 630 |
466 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
openupgrade.load_data(
env.cr, "helpdesk_mgmt_rating", "migrations/15.0.1.0.0/noupdate_changes.xml"
)
openupgrade.delete_record_translations(
env.cr,
"helpdesk_mgmt_rating",
["rating_ticket_email_template"],
)
| 29 | 464 |
1,810 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import common, new_test_user
from odoo.tests.common import users
class TestHelpdeskMgmtRating(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner = cls.env["res.partner"].create(
{"name": "Test partner", "email": "[email protected]"}
)
ctx = {
"mail_create_nolog": True,
"mail_create_nosubscribe": True,
"mail_notrack": True,
"no_reset_password": True,
}
new_test_user(
cls.env,
login="test-helpdesk-user",
groups="helpdesk_mgmt.group_helpdesk_user",
context=ctx,
)
cls.stage_done = cls.env.ref("helpdesk_mgmt.helpdesk_ticket_stage_done")
cls.stage_done.rating_mail_template_id = cls.env.ref(
"helpdesk_mgmt_rating.rating_ticket_email_template"
)
@users("admin", "test-helpdesk-user")
def test_ticket_stage_done(self):
ticket = self.env["helpdesk.ticket"].create(
{
"name": "Test 1",
"description": "Ticket test",
"partner_id": self.partner.id,
}
)
old_messages = ticket.message_ids
self.assertEqual(ticket.positive_rate_percentage, -1)
ticket.write({"stage_id": self.stage_done.id})
new_messages = ticket.message_ids - old_messages
self.assertIn(self.partner, new_messages.mapped("partner_ids"))
rating = ticket.rating_ids.filtered(lambda x: x.partner_id == self.partner)
rating.write({"rating": 5, "consumed": True})
self.assertEqual(ticket.positive_rate_percentage, 100)
| 37.666667 | 1,808 |
429 |
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class HelpdeskTicketStage(models.Model):
_inherit = "helpdesk.ticket.stage"
rating_mail_template_id = fields.Many2one(
comodel_name="mail.template",
string="Rating Email Template",
domain=[("model", "=", "helpdesk.ticket")],
help="If set, an email will be sent to the customer "
"with a rating survey when the ticket reaches this stage.",
)
| 33 | 429 |
2,837 |
py
|
PYTHON
|
15.0
|
from odoo import _, api, fields, models
from odoo.tools.safe_eval import safe_eval
class HelpdeskTicket(models.Model):
_name = "helpdesk.ticket"
_inherit = ["helpdesk.ticket", "rating.mixin"]
positive_rate_percentage = fields.Integer(
string="Positive Rates Percentage",
compute="_compute_percentage",
store=True,
default=-1,
)
rating_status = fields.Selection(
selection=[
("stage_change", "Rating when changing stage"),
("no_rate", "No rating"),
],
string="Customer Rating",
default="stage_change",
required=True,
)
@api.depends("rating_ids.rating")
def _compute_percentage(self):
for ticket in self:
activity = ticket.rating_get_grades()
ticket.positive_rate_percentage = (
activity["great"] * 100 / sum(activity.values())
if sum(activity.values())
else -1
)
def write(self, vals):
res = super().write(vals)
if "stage_id" in vals and vals.get("stage_id"):
stage = self.env["helpdesk.ticket.stage"].browse(vals.get("stage_id"))
if stage.rating_mail_template_id:
self._send_ticket_rating_mail(force_send=False)
return res
def _send_ticket_rating_mail(self, force_send=False):
for ticket in self:
if ticket.rating_status == "stage_change":
survey_template = ticket.stage_id.rating_mail_template_id
if survey_template:
ticket.rating_send_request(
survey_template,
lang=ticket.partner_id.lang,
force_send=force_send,
)
def rating_apply(self, rate, token=None, feedback=None, subtype_xmlid=None):
return super().rating_apply(
rate,
token=token,
feedback=feedback,
subtype_xmlid="helpdesk_mgmt_rating.mt_ticket_rating",
)
def rating_get_partner_id(self):
res = super().rating_get_partner_id()
if not res and self.partner_id:
return self.partner_id
return res
def rating_get_parent_model_name(self, vals):
return "helpdesk.ticket"
def rating_get_ticket_id(self):
return self.id
def action_view_ticket_rating(self):
action = self.env["ir.actions.act_window"]._for_xml_id(
"helpdesk_mgmt_rating.helpdesk_ticket_rating_action"
)
action["name"] = _("Ticket Rating")
action_context = safe_eval(action["context"]) if action["context"] else {}
action_context.update(self.env.context)
action_context.pop("group_by", None)
action["context"] = action_context
return action
| 34.180723 | 2,837 |
785 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019 Open Source Integrators
# Copyright (C) 2019 Konos
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Helpdesk Ticket Type",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"summary": "Add a type to your tickets",
"author": "Konos, " "Open Source Integrators, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/helpdesk",
"depends": ["helpdesk_mgmt"],
"data": [
"security/ir.model.access.csv",
"views/helpdesk_ticket_type.xml",
"views/helpdesk_ticket_team.xml",
"views/helpdesk_ticket.xml",
],
"demo": ["demo/helpdesk_type_demo.xml"],
"application": False,
"development_status": "Beta",
"maintainers": ["nelsonramirezs", "max3903"],
}
| 34.130435 | 785 |
1,972 |
py
|
PYTHON
|
15.0
|
from odoo.addons.helpdesk_mgmt.tests import test_helpdesk_ticket
class TestHelpdeskType(test_helpdesk_ticket.TestHelpdeskTicket):
@classmethod
def setUpClass(cls):
super().setUpClass()
Ticket = cls.env["helpdesk.ticket"]
Team = cls.env["helpdesk.ticket.team"]
Type = cls.env["helpdesk.ticket.type"]
cls.ht_team1 = Team.create({"name": "Team 1", "user_ids": [(4, cls.user.id)]})
cls.ht_type1 = Type.create(
{"name": "Type 1", "team_ids": [(4, cls.ht_team1.id)]}
)
cls.ht_type2 = Type.create({"name": "Type 2"})
cls.ht_ticket1 = Ticket.create(
{"name": "Test 1", "description": "Ticket test 1"}
)
def test_helpdesk_onchange_type_id(self):
self.ht_ticket1.write({"team_id": self.ht_team1.id, "user_id": self.user.id})
self.ht_ticket1.type_id = self.ht_type1
self.ht_ticket1._onchange_type_id()
self.assertEqual(
self.ht_ticket1.team_id,
self.ht_team1,
"Helpdesk Ticket: when type is changed, ticket team should be unchanged"
" if current team belongs to the new type",
)
self.assertEqual(
self.ht_ticket1.user_id,
self.user,
"Helpdesk Ticket: when type is changed, ticket user should be unchanged"
" if user belongs to a that belongs to the new type",
)
self.ht_ticket1.type_id = self.ht_type2
self.ht_ticket1._onchange_type_id()
self.assertFalse(
self.ht_ticket1.team_id,
"Helpdesk Ticket: When type is changed, ticket team should be reset if"
" current team does not belong to the new type",
)
self.assertFalse(
self.ht_ticket1.user_id,
"Helpdesk Ticket: When type is changed, ticket user should be reset if"
" current user does not belong to a team assigned to the new type",
)
| 39.44 | 1,972 |
461 |
py
|
PYTHON
|
15.0
|
# Copyright (c) 2019 Open Source Integrators
# Copyright (C) 2019 Konos
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import fields, models
class HelpdeskTeam(models.Model):
_inherit = "helpdesk.ticket.team"
type_ids = fields.Many2many(
"helpdesk.ticket.type",
string="Ticket Type",
help="Ticket Types the team will use. This team's tickets will only "
"be able to use those types.",
)
| 30.733333 | 461 |
476 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019 Konos
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import fields, models
class HelpdeskType(models.Model):
"""Helpdesk Type"""
_name = "helpdesk.ticket.type"
_description = "Helpdesk Ticket Type"
_order = "name asc"
name = fields.Char(required=True)
team_ids = fields.Many2many(
"helpdesk.ticket.team",
string="Teams",
help="Helpdesk teams allowed to use this type.",
)
| 26.444444 | 476 |
531 |
py
|
PYTHON
|
15.0
|
# Copyright (c) 2019 Open Source Integrators
# Copyright (C) 2019 Konos
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class HelpdeskTicket(models.Model):
_inherit = "helpdesk.ticket"
type_id = fields.Many2one("helpdesk.ticket.type", string="Type")
@api.onchange("type_id")
def _onchange_type_id(self):
if self.type_id and self.team_id and self.type_id not in self.team_id.type_ids:
self.team_id = False
self.user_id = False
| 33.1875 | 531 |
618 |
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Helpdesk Project",
"summary": "Add the option to select project in the tickets.",
"version": "15.0.1.1.3",
"license": "AGPL-3",
"category": "After-Sales",
"author": "PuntSistemes S.L.U., " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/helpdesk",
"depends": ["helpdesk_mgmt", "project"],
"data": [
"views/helpdesk_ticket_view.xml",
"views/project_view.xml",
"views/project_task_view.xml",
],
"development_status": "Beta",
"auto_install": True,
}
| 32.526316 | 618 |
2,949 |
py
|
PYTHON
|
15.0
|
from odoo.addons.helpdesk_mgmt.tests import test_helpdesk_ticket
class TestHelpdeskTicketProject(test_helpdesk_ticket.TestHelpdeskTicket):
@classmethod
def setUpClass(cls):
super().setUpClass()
Ticket = cls.env["helpdesk.ticket"]
Project = cls.env["project.project"]
Task = cls.env["project.task"]
cls.ticket2 = Ticket.create({"name": "Test 2", "description": "Ticket test2"})
cls.project1 = Project.create({"name": "Test Helpdesk-Project 1"})
cls.task_project1 = Task.create(
{"name": "Test Task Helpdesk-Project 1", "project_id": cls.project1.id}
)
cls.project2 = Project.create({"name": "Test Helpdesk-Project 2"})
cls.task_project2 = Task.create(
{"name": "Test Task Helpdesk-Project 2", "project_id": cls.project2.id}
)
cls.ticket.write(
{"project_id": cls.project1.id, "task_id": cls.task_project1.id}
)
cls.ticket2.write(
{"project_id": cls.project1.id, "task_id": cls.task_project1.id}
)
def test_helpdesk_ticket_project_task(self):
self.ticket.write({"project_id": self.project2.id})
self.assertFalse(
self.ticket.task_id,
"Helpdesk Ticket: When change the project "
"the ticket task should be reset.",
)
def test_helpdesk_ticket_counts(self):
self.assertEqual(
self.project1.ticket_count,
2,
"Helpdesk Ticket: Project should have two related tickets.",
)
self.assertEqual(
self.project1.todo_ticket_count,
2,
"Helpdesk Ticket: Project should have two related todo tickets.",
)
self.assertEqual(
self.task_project1.ticket_count,
2,
"Helpdesk Ticket: Task have two realted tickets.",
)
self.assertEqual(
self.task_project1.todo_ticket_count,
2,
"Helpdesk Ticket: Task have two realted tickets.",
)
self.assertEqual(
self.project2.ticket_count,
0,
"Helpdesk Ticket: Project should have two related tickets.",
)
self.assertEqual(
self.task_project2.ticket_count,
0,
"Helpdesk Ticket: Task have two realted tickets.",
)
self.ticket.write({"stage_id": self.stage_closed.id})
self.assertEqual(
self.project1.ticket_count,
2,
"Helpdesk Ticket: Project should have two related tickets.",
)
self.assertEqual(
self.project1.todo_ticket_count,
1,
"Helpdesk Ticket: Project should have one related todo tickets.",
)
self.assertEqual(
self.task_project1.todo_ticket_count,
1,
"Helpdesk Ticket: Task have one realted tickets.",
)
| 36.407407 | 2,949 |
564 |
py
|
PYTHON
|
15.0
|
from odoo import api, fields, models
class HelpdeskTicket(models.Model):
_inherit = "helpdesk.ticket"
project_id = fields.Many2one(string="Project", comodel_name="project.project")
task_id = fields.Many2one(
string="Task",
comodel_name="project.task",
compute="_compute_task_id",
readonly=False,
store=True,
)
@api.depends("project_id")
def _compute_task_id(self):
for record in self:
if record.task_id.project_id != record.project_id:
record.task_id = False
| 26.857143 | 564 |
2,646 |
py
|
PYTHON
|
15.0
|
from odoo import _, api, fields, models
class ProjectTask(models.Model):
_inherit = "project.task"
ticket_ids = fields.One2many(
comodel_name="helpdesk.ticket", inverse_name="task_id", string="Tickets"
)
ticket_count = fields.Integer(compute="_compute_ticket_count", store=True)
label_tickets = fields.Char(
string="Use Tickets as",
default=lambda s: _("Tickets"),
translate=True,
help="Gives label to tickets on project's kanban view.",
)
todo_ticket_count = fields.Integer(
string="Number of tickets", compute="_compute_ticket_count", store=True
)
@api.depends("ticket_ids", "ticket_ids.stage_id")
def _compute_ticket_count(self):
HelpdeskTicket = self.env["helpdesk.ticket"]
invname = "task_id"
domain = [(invname, "in", self.ids)]
fields = [invname]
groupby = [invname]
counts = {
pr[invname][0]: pr[f"{invname}_count"]
for pr in HelpdeskTicket.read_group(domain, fields, groupby)
}
domain.append(("closed", "=", False))
counts_todo = {
pr[invname][0]: pr[f"{invname}_count"]
for pr in HelpdeskTicket.read_group(domain, fields, groupby)
}
for record in self:
record.ticket_count = counts.get(record.id, 0)
record.todo_ticket_count = counts_todo.get(record.id, 0)
def action_view_ticket(self):
result = self.env["ir.actions.act_window"]._for_xml_id(
"helpdesk_mgmt.action_helpdesk_ticket_kanban_from_dashboard"
)
# choose the view_mode accordingly
if not self.ticket_ids or self.ticket_count > 1:
result["domain"] = "[('id','in',%s)]" % (self.ticket_ids.ids)
res = self.env.ref("helpdesk_mgmt.ticket_view_tree", False)
tree_view = [(res and res.id or False, "tree")]
if "views" in result:
result["views"] = tree_view + [
(state, view) for state, view in result["views"] if view != "tree"
]
else:
result["views"] = tree_view
elif self.ticket_count == 1:
res = self.env.ref("helpdesk_mgmt.ticket_view_form", False)
form_view = [(res and res.id or False, "form")]
if "views" in result:
result["views"] = form_view + [
(state, view) for state, view in result["views"] if view != "form"
]
else:
result["views"] = form_view
result["res_id"] = self.ticket_ids.id
return result
| 40.090909 | 2,646 |
1,425 |
py
|
PYTHON
|
15.0
|
from odoo import _, api, fields, models
class ProjectProject(models.Model):
_inherit = "project.project"
ticket_ids = fields.One2many(
comodel_name="helpdesk.ticket", inverse_name="project_id", string="Tickets"
)
ticket_count = fields.Integer(compute="_compute_ticket_count", store=True)
label_tickets = fields.Char(
string="Use Tickets as",
default=lambda s: _("Tickets"),
translate=True,
help="Gives label to tickets on project's kanban view.",
)
todo_ticket_count = fields.Integer(
string="Number of tickets", compute="_compute_ticket_count", store=True
)
@api.depends("ticket_ids", "ticket_ids.stage_id")
def _compute_ticket_count(self):
HelpdeskTicket = self.env["helpdesk.ticket"]
domain = [("project_id", "in", self.ids)]
fields = ["project_id"]
groupby = ["project_id"]
counts = {
pr["project_id"][0]: pr["project_id_count"]
for pr in HelpdeskTicket.read_group(domain, fields, groupby)
}
domain.append(("closed", "=", False))
counts_todo = {
pr["project_id"][0]: pr["project_id_count"]
for pr in HelpdeskTicket.read_group(domain, fields, groupby)
}
for record in self:
record.ticket_count = counts.get(record.id, 0)
record.todo_ticket_count = counts_todo.get(record.id, 0)
| 37.5 | 1,425 |
1,438 |
py
|
PYTHON
|
15.0
|
# Copyright (c) 2007 Ferran Pegueroles <[email protected]>
# Copyright (c) 2009 Albert Cervera i Areny <[email protected]>
# Copyright (C) 2011 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2011 Domsense srl (<http://www.domsense.com>)
# Copyright (C) 2013-2014 Camptocamp (<http://www.camptocamp.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Report to printer",
"version": "15.0.1.1.0",
"category": "Generic Modules/Base",
"author": "Agile Business Group & Domsense, Pegueroles SCP, NaN,"
" LasLabs, Camptocamp, Odoo Community Association (OCA),"
" Open for Small Business Ltd",
"website": "https://github.com/OCA/report-print-send",
"license": "AGPL-3",
"depends": ["web"],
"data": [
"data/printing_data.xml",
"security/security.xml",
"views/printing_printer.xml",
"views/printing_server.xml",
"views/printing_job.xml",
"views/printing_report.xml",
"views/res_users.xml",
"views/ir_actions_report.xml",
"wizards/print_attachment_report.xml",
"wizards/printing_printer_update_wizard_view.xml",
],
"assets": {
"web.assets_backend": [
"/base_report_to_printer/static/src/js/qweb_action_manager.esm.js",
],
},
"installable": True,
"application": False,
"external_dependencies": {"python": ["pycups"]},
}
| 37.842105 | 1,438 |
1,983 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
class TestResUsers(common.TransactionCase):
def setUp(self):
super(TestResUsers, self).setUp()
self.user_vals = {"name": "Test", "login": "login"}
def new_record(self):
return self.env["res.users"].create(self.user_vals)
def test_available_action_types_excludes_user_default(self):
"""It should not contain `user_default` in avail actions"""
self.user_vals["printing_action"] = "user_default"
with self.assertRaises(ValueError):
self.new_record()
def test_available_action_types_includes_something_else(self):
"""It should still contain other valid keys"""
self.user_vals["printing_action"] = "server"
self.assertTrue(self.new_record())
def test_onchange_printer_tray_id_empty(self):
user = self.env["res.users"].new({"printer_tray_id": False})
user.onchange_printing_printer_id()
self.assertFalse(user.printer_tray_id)
def test_onchange_printer_tray_id_not_empty(self):
server = self.env["printing.server"].create({})
printer = self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
tray = self.env["printing.tray"].create(
{"name": "Tray", "system_name": "TrayName", "printer_id": printer.id}
)
user = self.env["res.users"].new({"printer_tray_id": tray.id})
self.assertEqual(user.printer_tray_id, tray)
user.onchange_printing_printer_id()
self.assertFalse(user.printer_tray_id)
| 37.415094 | 1,983 |
3,191 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 SYLEAM
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestPrintingReportXmlAction(TransactionCase):
def setUp(self):
super(TestPrintingReportXmlAction, self).setUp()
self.Model = self.env["printing.report.xml.action"]
self.report = self.env["ir.actions.report"].search([], limit=1)
self.server = self.env["printing.server"].create({})
self.report_vals = {
"report_id": self.report.id,
"user_id": self.env.ref("base.user_demo").id,
"action": "server",
}
def new_record(self, vals=None):
values = self.report_vals
if vals is not None:
values.update(vals)
return self.Model.create(values)
def new_printer(self):
return self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
def test_behaviour(self):
"""It should return some action's data, unless called on empty
recordset
"""
xml_action = self.new_record()
self.assertEqual(
xml_action.behaviour(),
{
"action": xml_action.action,
"printer": xml_action.printer_id,
"tray": False,
},
)
xml_action = self.new_record({"printer_id": self.new_printer().id})
self.assertEqual(
xml_action.behaviour(),
{
"action": xml_action.action,
"printer": xml_action.printer_id,
"tray": False,
},
)
self.assertEqual(self.Model.behaviour(), {})
def test_onchange_printer_tray_id_empty(self):
action = self.env["printing.report.xml.action"].new({"printer_tray_id": False})
action.onchange_printer_id()
self.assertFalse(action.printer_tray_id)
def test_onchange_printer_tray_id_not_empty(self):
server = self.env["printing.server"].create({})
printer = self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
tray = self.env["printing.tray"].create(
{"name": "Tray", "system_name": "TrayName", "printer_id": printer.id}
)
action = self.env["printing.report.xml.action"].new(
{"printer_tray_id": tray.id}
)
self.assertEqual(action.printer_tray_id, tray)
action.onchange_printer_id()
self.assertFalse(action.printer_tray_id)
| 32.561224 | 3,191 |
2,129 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from unittest import mock
from odoo import fields
from odoo.tests.common import TransactionCase
model = "odoo.addons.base_report_to_printer.models.printing_server"
class TestPrintingJob(TransactionCase):
def setUp(self):
super(TestPrintingJob, self).setUp()
self.Model = self.env["printing.server"]
self.server = self.Model.create({})
self.printer_vals = {
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
self.job_vals = {
"server_id": self.server.id,
"job_id_cups": 1,
"job_media_progress": 0,
"time_at_creation": fields.Datetime.now(),
}
def new_printer(self):
return self.env["printing.printer"].create(self.printer_vals)
def new_job(self, printer, vals=None):
values = self.job_vals
if vals is not None:
values.update(vals)
values["printer_id"] = printer.id
return self.env["printing.job"].create(values)
@mock.patch("%s.cups" % model)
def test_cancel_job_error(self, cups):
"""It should catch any exception from CUPS and update status"""
cups.Connection.side_effect = Exception
printer = self.new_printer()
job = self.new_job(printer, {"job_id_cups": 2})
job.action_cancel()
cups.Connection.side_effect = None
self.assertEqual(cups.Connection().cancelJob.call_count, 0)
@mock.patch("%s.cups" % model)
def test_cancel_job(self, cups):
"""It should catch any exception from CUPS and update status"""
printer = self.new_printer()
job = self.new_job(printer)
job.cancel()
cups.Connection().cancelJob.assert_called_once_with(
job.job_id_cups, purge_job=False
)
| 33.793651 | 2,129 |
1,787 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
model = "odoo.addons.base_report_to_printer.models.printing_server"
class TestPrintingTray(TransactionCase):
def setUp(self):
super(TestPrintingTray, self).setUp()
self.Model = self.env["printing.tray"]
self.server = self.env["printing.server"].create({})
self.printer = self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
self.tray_vals = {
"name": "Tray",
"system_name": "TrayName",
"printer_id": self.printer.id,
}
def new_tray(self):
return self.env["printing.tray"].create(self.tray_vals)
def test_report_behaviour(self):
"""It should add the selected tray in the report data"""
ir_report = self.env["ir.actions.report"].search([], limit=1)
report = self.env["printing.report.xml.action"].create(
{"user_id": self.env.user.id, "report_id": ir_report.id, "action": "server"}
)
report.printer_tray_id = False
behaviour = report.behaviour()
self.assertEqual(behaviour["tray"], False)
# Check that we have te right value
report.printer_tray_id = self.new_tray()
behaviour = report.behaviour()
self.assertEqual(behaviour["tray"], report.printer_tray_id.system_name)
| 36.469388 | 1,787 |
6,315 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# Copyright 2017 Tecnativa - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from unittest import mock
from odoo import exceptions
from odoo.tests import common
class TestReport(common.HttpCase):
def setUp(self):
super(TestReport, self).setUp()
self.Model = self.env["ir.actions.report"]
self.server = self.env["printing.server"].create({})
self.report_vals = {
"name": "Test Report",
"model": "ir.actions.report",
"report_name": "Test Report",
}
self.report_view = self.env["ir.ui.view"].create(
{
"name": "Test",
"type": "qweb",
"arch": """<t t-name="base_report_to_printer.test">
<div>Test</div>
</t>""",
}
)
self.report_imd = (
self.env["ir.model.data"]
.sudo()
.create(
{
"name": "test",
"module": "base_report_to_printer",
"model": "ir.ui.view",
"res_id": self.report_view.id,
}
)
)
self.report = self.Model.create(
{
"name": "Test",
"report_type": "qweb-pdf",
"model": "res.partner",
"report_name": "base_report_to_printer.test",
}
)
self.report_text = self.Model.create(
{
"name": "Test",
"report_type": "qweb-text",
"model": "res.partner",
"report_name": "base_report_to_printer.test",
}
)
self.partners = self.env["res.partner"]
for n in range(5):
self.partners += self.env["res.partner"].create({"name": "Test %d" % n})
def new_record(self):
return self.Model.create(self.report_vals)
def new_printer(self):
return self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
def test_can_print_report_context_skip(self):
"""It should return False based on context"""
rec_id = self.new_record().with_context(must_skip_send_to_printer=True)
res = rec_id._can_print_report({"action": "server"}, True, True)
self.assertFalse(res)
def test_can_print_report_true(self):
"""It should return True when server print allowed"""
res = self.new_record()._can_print_report({"action": "server"}, True, True)
self.assertTrue(res)
def test_can_print_report_false(self):
"""It should return False when server print not allowed"""
res = self.new_record()._can_print_report({"action": "server"}, True, False)
self.assertFalse(res)
def test_render_qweb_pdf_not_printable(self):
"""It should print the report, only if it is printable"""
with mock.patch(
"odoo.addons.base_report_to_printer.models."
"printing_printer.PrintingPrinter."
"print_document"
) as print_document:
self.report._render_qweb_pdf(self.partners.ids)
print_document.assert_not_called()
def test_render_qweb_pdf_printable(self):
"""It should print the report, only if it is printable"""
with mock.patch(
"odoo.addons.base_report_to_printer.models."
"printing_printer.PrintingPrinter."
"print_document"
) as print_document:
self.report.property_printing_action_id.action_type = "server"
self.report.printing_printer_id = self.new_printer()
document = self.report._render_qweb_pdf(self.partners.ids)
print_document.assert_called_once_with(
self.report,
document[0],
action="server",
doc_format="qweb-pdf",
tray=False,
)
def test_render_qweb_text_printable(self):
"""It should print the report, only if it is printable"""
with mock.patch(
"odoo.addons.base_report_to_printer.models."
"printing_printer.PrintingPrinter."
"print_document"
) as print_document:
self.report_text.property_printing_action_id.action_type = "server"
self.report_text.printing_printer_id = self.new_printer()
document = self.report_text._render_qweb_text(self.partners.ids)
print_document.assert_called_once_with(
self.report_text,
document[0],
action="server",
doc_format="qweb-text",
tray=False,
)
def test_print_document_not_printable(self):
"""It should print the report, regardless of the defined behaviour"""
self.report.printing_printer_id = self.new_printer()
with mock.patch(
"odoo.addons.base_report_to_printer.models."
"printing_printer.PrintingPrinter."
"print_document"
) as print_document:
self.report.print_document(self.partners.ids)
print_document.assert_called_once()
def test_print_document_printable(self):
"""It should print the report, regardless of the defined behaviour"""
self.report.property_printing_action_id.action_type = "server"
self.report.printing_printer_id = self.new_printer()
with mock.patch(
"odoo.addons.base_report_to_printer.models."
"printing_printer.PrintingPrinter."
"print_document"
) as print_document:
self.report.print_document(self.partners.ids)
print_document.assert_called_once()
def test_print_document_no_printer(self):
"""It should raise an error"""
with self.assertRaises(exceptions.UserError):
self.report.print_document(self.partners.ids)
| 37.589286 | 6,315 |
11,443 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# Copyright 2016 SYLEAM
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from unittest import mock
from odoo.tests.common import TransactionCase
model = "odoo.addons.base.models.ir_actions_report.IrActionsReport"
class TestIrActionsReportXml(TransactionCase):
def setUp(self):
super(TestIrActionsReportXml, self).setUp()
self.Model = self.env["ir.actions.report"]
self.vals = {}
self.report = self.env["ir.actions.report"].search([], limit=1)
self.server = self.env["printing.server"].create({})
def new_action(self):
return self.env["printing.action"].create(
{"name": "Printing Action", "action_type": "server"}
)
def new_printing_action(self):
return self.env["printing.report.xml.action"].create(
{
"report_id": self.report.id,
"user_id": self.env.ref("base.user_demo").id,
"action": "server",
}
)
def new_printer(self):
return self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
def new_tray(self, vals=None, defaults=None):
values = dict(defaults)
if vals is not None:
values.update(vals)
return self.env["printing.tray"].create(values)
def test_print_action_for_report_name_gets_report(self):
"""It should get report by name"""
with mock.patch("%s._get_report_from_name" % model) as mk:
expect = "test"
self.Model.print_action_for_report_name(expect)
mk.assert_called_once_with(expect)
def test_print_action_for_report_name_returns_if_no_report(self):
"""It should return empty dict when no matching report"""
with mock.patch("%s._get_report_from_name" % model) as mk:
expect = "test"
mk.return_value = False
res = self.Model.print_action_for_report_name(expect)
self.assertDictEqual({}, res)
def test_print_action_for_report_name_returns_if_report(self):
"""It should return correct serializable result for behaviour"""
with mock.patch("%s._get_report_from_name" % model) as mk:
res = self.Model.print_action_for_report_name("test")
behaviour = mk().behaviour()
expect = {
"action": behaviour["action"],
"printer_name": behaviour["printer"].name,
}
self.assertDictEqual(expect, res, "Expect {}, Got {}".format(expect, res))
def test_behaviour_default_values(self):
"""It should return the default action and printer"""
report = self.Model.search([], limit=1)
self.env.user.printing_action = False
self.env.user.printing_printer_id = False
report.property_printing_action_id = False
report.printing_printer_id = False
self.assertEqual(
report.behaviour(),
{
"action": "client",
"printer": self.env["printing.printer"],
"tray": False,
},
)
def test_behaviour_user_values(self):
"""It should return the action and printer from user"""
report = self.Model.search([], limit=1)
self.env.user.printing_action = "client"
self.env.user.printing_printer_id = self.new_printer()
self.assertEqual(
report.behaviour(),
{
"action": "client",
"printer": self.env.user.printing_printer_id,
"tray": False,
},
)
def test_behaviour_report_values(self):
"""It should return the action and printer from report"""
report = self.Model.search([], limit=1)
self.env.user.printing_action = "client"
report.property_printing_action_id = self.new_action()
report.printing_printer_id = self.new_printer()
self.assertEqual(
report.behaviour(),
{
"action": report.property_printing_action_id.action_type,
"printer": report.printing_printer_id,
"tray": False,
},
)
def test_behaviour_user_action(self):
"""It should return the action and printer from user action"""
report = self.Model.search([], limit=1)
self.env.user.printing_action = "client"
report.property_printing_action_id.action_type = "user_default"
self.assertEqual(
report.behaviour(),
{"action": "client", "printer": report.printing_printer_id, "tray": False},
)
def test_behaviour_printing_action_on_wrong_user(self):
"""It should return the action and printer ignoring printing action"""
report = self.Model.search([], limit=1)
self.env.user.printing_action = "client"
printing_action = self.new_printing_action()
printing_action.user_id = self.env["res.users"].search(
[("id", "!=", self.env.user.id)], limit=1
)
self.assertEqual(
report.behaviour(),
{"action": "client", "printer": report.printing_printer_id, "tray": False},
)
def test_behaviour_printing_action_on_wrong_report(self):
"""It should return the action and printer ignoring printing action"""
report = self.Model.search([], limit=1)
self.env.user.printing_action = "client"
printing_action = self.new_printing_action()
printing_action.user_id = self.env.user
printing_action.report_id = self.env["ir.actions.report"].search(
[("id", "!=", report.id)], limit=1
)
self.assertEqual(
report.behaviour(),
{"action": "client", "printer": report.printing_printer_id, "tray": False},
)
def test_behaviour_printing_action_with_no_printer(self):
"""It should return the action from printing action and printer from
other
"""
report = self.Model.search([], limit=1)
self.env.user.printing_action = "client"
printing_action = self.new_printing_action()
printing_action.user_id = self.env.user
printing_action.report_id = report
self.assertEqual(
report.behaviour(),
{
"action": printing_action.action,
"printer": report.printing_printer_id,
"tray": False,
},
)
def test_behaviour_printing_action_with_printer(self):
"""It should return the action and printer from printing action"""
report = self.Model.search([], limit=1)
self.env.user.printing_action = "client"
printing_action = self.new_printing_action()
printing_action.user_id = self.env.user
printing_action.printer_id = self.new_printer()
self.assertEqual(
report.behaviour(),
{
"action": printing_action.action,
"printer": printing_action.printer_id,
"tray": False,
},
)
def test_behaviour_printing_action_user_defaults(self):
"""It should return the action and printer from user with printing
action
"""
report = self.Model.search([], limit=1)
self.env.user.printing_action = "client"
printing_action = self.new_printing_action()
printing_action.user_id = self.env.user
printing_action.action = "user_default"
self.assertEqual(
report.behaviour(),
{"action": "client", "printer": report.printing_printer_id, "tray": False},
)
def test_print_tray_behaviour(self):
"""
It should return the correct tray
"""
report = self.env["ir.actions.report"].search([], limit=1)
action = self.env["printing.report.xml.action"].create(
{"user_id": self.env.user.id, "report_id": report.id, "action": "server"}
)
printer = self.new_printer()
tray_vals = {"name": "Tray", "system_name": "Tray", "printer_id": printer.id}
user_tray = self.new_tray({"system_name": "User tray"}, tray_vals)
report_tray = self.new_tray({"system_name": "Report tray"}, tray_vals)
action_tray = self.new_tray({"system_name": "Action tray"}, tray_vals)
# No report passed
self.env.user.printer_tray_id = False
options = printer.print_options()
self.assertFalse("InputSlot" in options)
# No tray defined
self.env.user.printer_tray_id = False
report.printer_tray_id = False
action.printer_tray_id = False
options = report.behaviour()
self.assertTrue("tray" in options)
# Only user tray is defined
self.env.user.printer_tray_id = user_tray
report.printer_tray_id = False
action.printer_tray_id = False
self.assertEqual("User tray", report.behaviour()["tray"])
# Only report tray is defined
self.env.user.printer_tray_id = False
report.printer_tray_id = report_tray
action.printer_tray_id = False
self.assertEqual("Report tray", report.behaviour()["tray"])
# Only action tray is defined
self.env.user.printer_tray_id = False
report.printer_tray_id = False
action.printer_tray_id = action_tray
self.assertEqual("Action tray", report.behaviour()["tray"])
# User and report tray defined
self.env.user.printer_tray_id = user_tray
report.printer_tray_id = report_tray
action.printer_tray_id = False
self.assertEqual("Report tray", report.behaviour()["tray"])
# All trays are defined
self.env.user.printer_tray_id = user_tray
report.printer_tray_id = report_tray
action.printer_tray_id = action_tray
self.assertEqual("Action tray", report.behaviour()["tray"])
def test_onchange_printer_tray_id_empty(self):
action = self.env["ir.actions.report"].new({"printer_tray_id": False})
action.onchange_printing_printer_id()
self.assertFalse(action.printer_tray_id)
def test_onchange_printer_tray_id_not_empty(self):
server = self.env["printing.server"].create({})
printer = self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
tray = self.env["printing.tray"].create(
{"name": "Tray", "system_name": "TrayName", "printer_id": printer.id}
)
action = self.env["ir.actions.report"].new({"printer_tray_id": tray.id})
self.assertEqual(action.printer_tray_id, tray)
action.onchange_printing_printer_id()
self.assertFalse(action.printer_tray_id)
| 38.789831 | 11,443 |
3,381 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from unittest import mock
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase
model = "odoo.addons.base_report_to_printer.models.printing_server"
class StopTest(Exception):
pass
class TestPrintingPrinterWizard(TransactionCase):
def setUp(self):
super().setUp()
self.Model = self.env["printing.printer.update.wizard"]
self.server = self.env["printing.server"].create({})
self.printer_vals = {
"printer-info": "Info",
"printer-make-and-model": "Make and Model",
"printer-location": "location",
"device-uri": "URI",
"printer-uri-supported": "uri",
}
def _record_vals(self, sys_name="sys_name"):
return {
"name": self.printer_vals["printer-info"],
"server_id": self.server.id,
"system_name": sys_name,
"model": self.printer_vals["printer-make-and-model"],
"location": self.printer_vals["printer-location"],
"uri": self.printer_vals["device-uri"],
}
@mock.patch("%s.cups" % model)
def test_action_ok_inits_connection(self, cups):
"""It should initialize CUPS connection"""
self.Model.action_ok()
cups.Connection.assert_called_once_with(
host=self.server.address, port=self.server.port
)
@mock.patch("%s.cups" % model)
def test_action_ok_gets_printers(self, cups):
"""It should get printers from CUPS"""
cups.Connection().getPrinters.return_value = {"sys_name": self.printer_vals}
cups.Connection().getPPD3.return_value = (200, 0, "")
self.Model.action_ok()
cups.Connection().getPrinters.assert_called_once_with()
@mock.patch("%s.cups" % model)
def test_action_ok_raises_warning_on_error(self, cups):
"""It should raise Warning on any error"""
cups.Connection.side_effect = StopTest
with self.assertRaises(UserError):
self.Model.action_ok()
@mock.patch("%s.cups" % model)
def test_action_ok_creates_new_printer(self, cups):
"""It should create new printer w/ proper vals"""
cups.Connection().getPrinters.return_value = {"sys_name": self.printer_vals}
cups.Connection().getPPD3.return_value = (200, 0, "")
self.Model.action_ok()
rec_id = self.env["printing.printer"].search(
[("system_name", "=", "sys_name")], limit=1
)
self.assertTrue(rec_id)
for key, val in self._record_vals().items():
if rec_id._fields[key].type == "many2one":
val = self.env[rec_id._fields[key].comodel_name].browse(val)
self.assertEqual(val, rec_id[key])
@mock.patch("%s.cups" % model)
def test_action_ok_skips_existing_printer(self, cups):
"""It should not recreate existing printers"""
cups.Connection().getPrinters.return_value = {"sys_name": self.printer_vals}
cups.Connection().getPPD3.return_value = (200, 0, "")
self.env["printing.printer"].create(self._record_vals())
self.Model.action_ok()
res_ids = self.env["printing.printer"].search(
[("system_name", "=", "sys_name")]
)
self.assertEqual(1, len(res_ids))
| 38.420455 | 3,381 |
7,571 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from unittest import mock
from odoo import fields
from odoo.tests.common import TransactionCase
model = "odoo.addons.base_report_to_printer.models.printing_server"
model_base = "odoo.models.BaseModel"
class TestPrintingServer(TransactionCase):
def setUp(self):
super(TestPrintingServer, self).setUp()
self.Model = self.env["printing.server"]
self.server = self.Model.create({})
self.printer_vals = {
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
self.job_vals = {
"server_id": self.server.id,
"job_id_cups": 1,
"job_media_progress": 0,
"time_at_creation": fields.Datetime.now(),
}
def new_printer(self):
return self.env["printing.printer"].create(self.printer_vals)
def new_job(self, printer, vals=None):
values = self.job_vals
if vals is not None:
values.update(vals)
values["printer_id"] = printer.id
return self.env["printing.job"].create(values)
@mock.patch("%s.cups" % model)
def test_update_printers_error(self, cups):
"""It should catch any exception from CUPS and update status"""
cups.Connection.side_effect = Exception
rec_id = self.new_printer()
self.Model.update_printers()
self.assertEqual("server-error", rec_id.status)
@mock.patch("%s.cups" % model)
def test_update_printers_inits_cups(self, cups):
"""It should init CUPS connection"""
self.new_printer()
self.Model.update_printers()
cups.Connection.assert_called_once_with(
host=self.server.address, port=self.server.port
)
@mock.patch("%s.cups" % model)
def test_update_printers_gets_all_printers(self, cups):
"""It should get all printers from CUPS server"""
self.new_printer()
self.Model.update_printers()
cups.Connection().getPrinters.assert_called_once_with()
@mock.patch("%s.cups" % model)
def test_update_printers_search(self, cups):
"""It should search all when no domain"""
with mock.patch("%s.search" % model_base) as search:
self.Model.update_printers()
search.assert_called_once_with([])
@mock.patch("%s.cups" % model)
def test_update_printers_search_domain(self, cups):
"""It should use specific domain for search"""
with mock.patch("%s.search" % model_base) as search:
expect = [("id", ">", 0)]
self.Model.update_printers(expect)
search.assert_called_once_with(expect)
@mock.patch("%s.cups" % model)
def test_update_printers_update_unavailable(self, cups):
"""It should update status when printer is unavailable"""
rec_id = self.new_printer()
cups.Connection().getPrinters().get.return_value = False
self.Model.action_update_printers()
self.assertEqual("unavailable", rec_id.status)
@mock.patch("%s.cups" % model)
def test_update_archived_printers(self, cups):
"""It should update status even if printer is archived"""
rec_id = self.new_printer()
rec_id.toggle_active()
self.server.refresh()
cups.Connection().getPrinters().get.return_value = False
self.Model.action_update_printers()
self.assertEqual(
"unavailable",
rec_id.status,
)
@mock.patch("%s.cups" % model)
def test_update_jobs_cron(self, cups):
"""It should get all jobs from CUPS server"""
self.new_printer()
self.Model.action_update_jobs()
cups.Connection().getPrinters.assert_called_once_with()
cups.Connection().getJobs.assert_called_once_with(
which_jobs="all",
first_job_id=-1,
requested_attributes=[
"job-name",
"job-id",
"printer-uri",
"job-media-progress",
"time-at-creation",
"job-state",
"job-state-reasons",
"time-at-processing",
"time-at-completed",
],
)
@mock.patch("%s.cups" % model)
def test_update_jobs_button(self, cups):
"""It should get all jobs from CUPS server"""
self.new_printer()
self.server.action_update_jobs()
cups.Connection().getPrinters.assert_called_once_with()
cups.Connection().getJobs.assert_called_once_with(
which_jobs="all",
first_job_id=-1,
requested_attributes=[
"job-name",
"job-id",
"printer-uri",
"job-media-progress",
"time-at-creation",
"job-state",
"job-state-reasons",
"time-at-processing",
"time-at-completed",
],
)
@mock.patch("%s.cups" % model)
def test_update_jobs_error(self, cups):
"""It should catch any exception from CUPS and update status"""
cups.Connection.side_effect = Exception
self.new_printer()
self.server.update_jobs()
cups.Connection.assert_called_with(
host=self.server.address, port=self.server.port
)
@mock.patch("%s.cups" % model)
def test_update_jobs_uncompleted(self, cups):
"""
It should search which jobs have been completed since last update
"""
printer = self.new_printer()
self.new_job(printer, vals={"job_state": "completed"})
self.new_job(printer, vals={"job_id_cups": 2, "job_state": "processing"})
self.server.update_jobs(which="not-completed")
cups.Connection().getJobs.assert_any_call(
which_jobs="completed",
first_job_id=2,
requested_attributes=[
"job-name",
"job-id",
"printer-uri",
"job-media-progress",
"time-at-creation",
"job-state",
"job-state-reasons",
"time-at-processing",
"time-at-completed",
],
)
@mock.patch("%s.cups" % model)
def test_update_jobs(self, cups):
"""
It should update all jobs, known or not
"""
printer = self.new_printer()
printer_uri = "hostname:port/" + printer.system_name
cups.Connection().getJobs.return_value = {
1: {"printer-uri": printer_uri},
2: {"printer-uri": printer_uri, "job-state": 9},
4: {"printer-uri": printer_uri, "job-state": 5},
}
self.new_job(printer, vals={"job_state": "completed"})
completed_job = self.new_job(
printer, vals={"job_id_cups": 2, "job_state": "processing"}
)
purged_job = self.new_job(
printer, vals={"job_id_cups": 3, "job_state": "processing"}
)
self.server.update_jobs()
new_job = self.env["printing.job"].search([("job_id_cups", "=", 4)])
self.assertEqual(completed_job.job_state, "completed")
self.assertEqual(purged_job.active, False)
self.assertEqual(new_job.job_state, "processing")
| 36.399038 | 7,571 |
8,917 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import errno
import tempfile
from unittest import mock
from odoo.tests.common import TransactionCase
model = "odoo.addons.base_report_to_printer.models.printing_printer"
server_model = "odoo.addons.base_report_to_printer.models.printing_server"
ppd_header = '*PPD-Adobe: "4.3"'
ppd_input_slot_header = """
*OpenUI *InputSlot: PickOne
*DefaultInputSlot: Auto
*InputSlot Auto/Auto (Default): "
<< /DeferredMediaSelection true /ManualFeed false
/MediaPosition null /MediaType null >> setpagedevice
userdict /TSBMediaType 0 put"
*End
"""
ppd_input_slot_body = """
*InputSlot {name}/{text}: "
<< /DeferredMediaSelection true /ManualFeed false
/MediaPosition null /MediaType null >> setpagedevice
userdict /TSBMediaType 0 put"
*End
"""
ppd_input_slot_footer = """
*CloseUI: *InputSlot
"""
class TestPrintingPrinter(TransactionCase):
def setUp(self):
super(TestPrintingPrinter, self).setUp()
self.Model = self.env["printing.printer"]
self.ServerModel = self.env["printing.server"]
self.server = self.env["printing.server"].create({})
self.printer = self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
self.tray_vals = {
"name": "Tray",
"system_name": "TrayName",
"printer_id": self.printer.id,
}
def new_tray(self, vals=None):
values = self.tray_vals
if vals is not None:
values.update(vals)
return self.env["printing.tray"].create(values)
def build_ppd(self, input_slots=None):
"""
Builds a fake PPD file declaring defined input slots
"""
ppd_contents = ppd_header
ppd_contents += ppd_input_slot_header
if input_slots is not None:
for input_slot in input_slots:
ppd_contents += ppd_input_slot_body.format(
name=input_slot["name"], text=input_slot["text"]
)
ppd_contents += ppd_input_slot_footer
return ppd_contents
def mock_cups_ppd(self, cups, file_name=None, input_slots=None):
"""
Create a fake PPD file (if needed), then mock the getPPD3 method
return value to give that file
"""
if file_name is None:
fd, file_name = tempfile.mkstemp()
if file_name:
ppd_contents = self.build_ppd(input_slots=input_slots)
with open(file_name, "w") as fp:
fp.write(ppd_contents)
cups.Connection().getPPD3.return_value = (200, 0, file_name)
cups.Connection().getPrinters.return_value = {
self.printer.system_name: {
"printer-info": "info",
"printer-uri-supported": "uri",
}
}
@mock.patch("%s.cups" % server_model)
def test_update_printers(self, cups):
"""
Check that the update_printers method calls _prepare_update_from_cups
"""
self.mock_cups_ppd(cups, file_name=False)
self.assertEqual(self.printer.name, "Printer")
self.ServerModel.update_printers()
self.assertEqual(self.printer.name, "info")
@mock.patch("%s.cups" % server_model)
def test_prepare_update_from_cups_no_ppd(self, cups):
"""
Check that the tray_ids field has no value when no PPD is available
"""
self.mock_cups_ppd(cups, file_name=False)
connection = cups.Connection()
cups_printer = connection.getPrinters()[self.printer.system_name]
vals = self.printer._prepare_update_from_cups(connection, cups_printer)
self.assertFalse("tray_ids" in vals)
@mock.patch("%s.cups" % server_model)
def test_prepare_update_from_cups_empty_ppd(self, cups):
"""
Check that the tray_ids field has no value when the PPD file has
no input slot declared
"""
fd, file_name = tempfile.mkstemp()
self.mock_cups_ppd(cups, file_name=file_name)
# Replace the ppd file's contents by an empty file
with open(file_name, "w") as fp:
fp.write(ppd_header)
connection = cups.Connection()
cups_printer = connection.getPrinters()[self.printer.system_name]
vals = self.printer._prepare_update_from_cups(connection, cups_printer)
self.assertFalse("tray_ids" in vals)
@mock.patch("%s.cups" % server_model)
@mock.patch("os.unlink")
def test_prepare_update_from_cups_unlink_error(self, os_unlink, cups):
"""
When OSError other than ENOENT is encountered, the exception is raised
"""
# Break os.unlink
os_unlink.side_effect = OSError(errno.EIO, "Error")
self.mock_cups_ppd(cups)
connection = cups.Connection()
cups_printer = connection.getPrinters()[self.printer.system_name]
with self.assertRaises(OSError):
self.printer._prepare_update_from_cups(connection, cups_printer)
@mock.patch("%s.cups" % server_model)
@mock.patch("os.unlink")
def test_prepare_update_from_cups_unlink_error_enoent(self, os_unlink, cups):
"""
When a ENOENT error is encountered, the file has already been unlinked
This is not an issue, as we were trying to delete the file.
The update can continue.
"""
# Break os.unlink
os_unlink.side_effect = OSError(errno.ENOENT, "Error")
self.mock_cups_ppd(cups)
connection = cups.Connection()
cups_printer = connection.getPrinters()[self.printer.system_name]
vals = self.printer._prepare_update_from_cups(connection, cups_printer)
self.assertEqual(
vals["tray_ids"],
[(0, 0, {"name": "Auto (Default)", "system_name": "Auto"})],
)
@mock.patch("%s.cups" % server_model)
def test_prepare_update_from_cups(self, cups):
"""
Check the return value when adding a single tray
"""
self.mock_cups_ppd(cups)
connection = cups.Connection()
cups_printer = connection.getPrinters()[self.printer.system_name]
vals = self.printer._prepare_update_from_cups(connection, cups_printer)
self.assertEqual(
vals["tray_ids"],
[(0, 0, {"name": "Auto (Default)", "system_name": "Auto"})],
)
@mock.patch("%s.cups" % server_model)
def test_prepare_update_from_cups_with_multiple_trays(self, cups):
"""
Check the return value when adding multiple trays at once
"""
self.mock_cups_ppd(cups, input_slots=[{"name": "Tray1", "text": "Tray 1"}])
connection = cups.Connection()
cups_printer = connection.getPrinters()[self.printer.system_name]
vals = self.printer._prepare_update_from_cups(connection, cups_printer)
self.assertItemsEqual(
vals["tray_ids"],
[
(0, 0, {"name": "Auto (Default)", "system_name": "Auto"}),
(0, 0, {"name": "Tray 1", "system_name": "Tray1"}),
],
)
@mock.patch("%s.cups" % server_model)
def test_prepare_update_from_cups_already_known_trays(self, cups):
"""
Check that calling the method twice doesn't create the trays multiple
times
"""
self.mock_cups_ppd(cups, input_slots=[{"name": "Tray1", "text": "Tray 1"}])
connection = cups.Connection()
cups_printer = connection.getPrinters()[self.printer.system_name]
# Create a tray which is in the PPD file
self.new_tray({"system_name": "Tray1"})
vals = self.printer._prepare_update_from_cups(connection, cups_printer)
self.assertEqual(
vals["tray_ids"],
[(0, 0, {"name": "Auto (Default)", "system_name": "Auto"})],
)
@mock.patch("%s.cups" % server_model)
def test_prepare_update_from_cups_unknown_trays(self, cups):
"""
Check that trays which are not in the PPD file are removed from Odoo
"""
self.mock_cups_ppd(cups)
connection = cups.Connection()
cups_printer = connection.getPrinters()[self.printer.system_name]
# Create a tray which is absent from the PPD file
tray = self.new_tray()
vals = self.printer._prepare_update_from_cups(connection, cups_printer)
self.assertEqual(
vals["tray_ids"],
[(0, 0, {"name": "Auto (Default)", "system_name": "Auto"}), (2, tray.id)],
)
| 34.968627 | 8,917 |
7,131 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import tempfile
from unittest import mock
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase
model = "odoo.addons.base_report_to_printer.models.printing_printer"
server_model = "odoo.addons.base_report_to_printer.models.printing_server"
class TestPrintingPrinter(TransactionCase):
def setUp(self):
super(TestPrintingPrinter, self).setUp()
self.Model = self.env["printing.printer"]
self.ServerModel = self.env["printing.server"]
self.server = self.env["printing.server"].create({})
self.printer_vals = {
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
self.report = self.env["ir.actions.report"].search([], limit=1)
def new_record(self):
return self.Model.create(self.printer_vals)
def test_option_tray(self):
"""
It should put the value in InputSlot
"""
self.assertEqual(
self.Model._set_option_tray(None, "Test Tray"), {"InputSlot": "Test Tray"}
)
self.assertEqual(self.Model._set_option_tray(None, False), {})
def test_option_noops(self):
"""
Noops should return an empty dict
"""
self.assertEqual(self.Model._set_option_action(None, "printer"), {})
self.assertEqual(self.Model._set_option_printer(None, self.Model), {})
def test_option_doc_format(self):
"""
Raw documents should set raw boolean.
"""
self.assertEqual(
self.Model._set_option_doc_format(None, "raw"), {"raw": "True"}
)
# Deprecate _set_option_format in v12.
self.assertEqual(self.Model._set_option_format(None, "raw"), {"raw": "True"})
self.assertEqual(self.Model._set_option_doc_format(None, "pdf"), {})
# Deprecate _set_option_format in v12.
self.assertEqual(self.Model._set_option_format(None, "pdf"), {})
def test_print_options(self):
"""It should generate the right options dictionnary"""
# TODO: None here used as report - tests here should be merged
# with tests in test_printing_printer_tray from when modules merged
report = self.env["ir.actions.report"].search([], limit=1)
self.assertEqual(self.Model.print_options(doc_format="raw"), {"raw": "True"})
self.assertEqual(
self.Model.print_options(report, doc_format="pdf", copies=2),
{"copies": "2"},
)
self.assertEqual(
self.Model.print_options(report, doc_format="raw", copies=2),
{"raw": "True", "copies": "2"},
)
self.assertTrue("InputSlot" in self.Model.print_options(report, tray="Test"))
@mock.patch("%s.cups" % server_model)
def test_print_report(self, cups):
"""It should print a report through CUPS"""
fd, file_name = tempfile.mkstemp()
with mock.patch("%s.mkstemp" % model) as mkstemp:
mkstemp.return_value = fd, file_name
printer = self.new_record()
printer.print_document(self.report, b"content to print", doc_format="pdf")
cups.Connection().printFile.assert_called_once_with(
printer.system_name, file_name, file_name, options={}
)
@mock.patch("%s.cups" % server_model)
def test_print_report_error(self, cups):
"""It should print a report through CUPS"""
cups.Connection.side_effect = Exception
fd, file_name = tempfile.mkstemp()
with mock.patch("%s.mkstemp" % model) as mkstemp:
mkstemp.return_value = fd, file_name
printer = self.new_record()
with self.assertRaises(UserError):
printer.print_document(
self.report, b"content to print", doc_format="pdf"
)
@mock.patch("%s.cups" % server_model)
def test_print_file(self, cups):
"""It should print a file through CUPS"""
file_name = "file_name"
printer = self.new_record()
printer.print_file(file_name, "pdf")
cups.Connection().printFile.assert_called_once_with(
printer.system_name, file_name, file_name, options={}
)
@mock.patch("%s.cups" % server_model)
def test_print_file_error(self, cups):
"""It should print a file through CUPS"""
cups.Connection.side_effect = Exception
file_name = "file_name"
printer = self.new_record()
with self.assertRaises(UserError):
printer.print_file(file_name)
def test_set_default(self):
"""It should set a single record as default"""
printer = self.new_record()
self.assertTrue(printer.default)
other_printer = self.new_record()
other_printer.set_default()
self.assertFalse(printer.default)
self.assertTrue(other_printer.default)
# Check that calling the method on an empty recordset does nothing
self.Model.set_default()
self.assertEqual(other_printer, self.Model.get_default())
def test_unset_default(self):
"""It should unset the default state of the printer"""
printer = self.new_record()
self.assertTrue(printer.default)
printer.unset_default()
self.assertFalse(printer.default)
@mock.patch("%s.cups" % server_model)
def test_cancel_all_jobs(self, cups):
"""It should cancel all jobs"""
printer = self.new_record()
printer.action_cancel_all_jobs()
cups.Connection().cancelAllJobs.assert_called_once_with(
name=printer.system_name, purge_jobs=False
)
@mock.patch("%s.cups" % server_model)
def test_cancel_and_purge_all_jobs(self, cups):
"""It should cancel all jobs"""
printer = self.new_record()
printer.cancel_all_jobs(purge_jobs=True)
cups.Connection().cancelAllJobs.assert_called_once_with(
name=printer.system_name, purge_jobs=True
)
@mock.patch("%s.cups" % server_model)
def test_enable_printer(self, cups):
"""It should enable the printer"""
printer = self.new_record()
printer.enable()
cups.Connection().enablePrinter.assert_called_once_with(printer.system_name)
@mock.patch("%s.cups" % server_model)
def test_disable_printer(self, cups):
"""It should disable the printer"""
printer = self.new_record()
printer.disable()
cups.Connection().disablePrinter.assert_called_once_with(printer.system_name)
@mock.patch("%s.cups" % server_model)
def test_print_test_page(self, cups):
"""It should print a test page"""
printer = self.new_record()
printer.print_test_page()
cups.Connection().printTestPage.assert_called_once_with(printer.system_name)
| 39.181319 | 7,131 |
912 |
py
|
PYTHON
|
15.0
|
# Copyright (c) 2007 Ferran Pegueroles <[email protected]>
# Copyright (c) 2009 Albert Cervera i Areny <[email protected]>
# Copyright (C) 2011 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2011 Domsense srl (<http://www.domsense.com>)
# Copyright (C) 2013-2014 Camptocamp (<http://www.camptocamp.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class PrintingAction(models.Model):
_name = "printing.action"
_description = "Print Job Action"
@api.model
def _available_action_types(self):
return [
("server", "Send to Printer"),
("client", "Send to Client"),
("user_default", "Use user's defaults"),
]
name = fields.Char(required=True)
action_type = fields.Selection(
selection=_available_action_types, string="Type", required=True
)
| 35.076923 | 912 |
7,090 |
py
|
PYTHON
|
15.0
|
# Copyright (c) 2007 Ferran Pegueroles <[email protected]>
# Copyright (c) 2009 Albert Cervera i Areny <[email protected]>
# Copyright (C) 2011 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2011 Domsense srl (<http://www.domsense.com>)
# Copyright (C) 2013-2014 Camptocamp (<http://www.camptocamp.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
from odoo.tools.safe_eval import safe_eval, time
REPORT_TYPES = {"qweb-pdf": "pdf", "qweb-text": "text"}
class IrActionsReport(models.Model):
_inherit = "ir.actions.report"
property_printing_action_id = fields.Many2one(
comodel_name="printing.action",
string="Default Behaviour",
company_dependent=True,
)
printing_printer_id = fields.Many2one(
comodel_name="printing.printer", string="Default Printer"
)
printer_tray_id = fields.Many2one(
comodel_name="printing.tray",
string="Paper Source",
domain="[('printer_id', '=', printing_printer_id)]",
)
printing_action_ids = fields.One2many(
comodel_name="printing.report.xml.action",
inverse_name="report_id",
string="Actions",
help="This field allows configuring action and printer on a per " "user basis",
)
@api.onchange("printing_printer_id")
def onchange_printing_printer_id(self):
"""Reset the tray when the printer is changed"""
self.printer_tray_id = False
@api.model
def print_action_for_report_name(self, report_name):
"""Returns if the action is a direct print or pdf
Called from js
"""
report = self._get_report_from_name(report_name)
if not report:
return {}
result = report.behaviour()
serializable_result = {
"action": result["action"],
"printer_name": result["printer"].name,
}
return serializable_result
def _get_user_default_print_behaviour(self):
printer_obj = self.env["printing.printer"]
user = self.env.user
return dict(
action=user.printing_action or "client",
printer=user.printing_printer_id or printer_obj.get_default(),
tray=str(user.printer_tray_id.system_name)
if user.printer_tray_id
else False,
)
def _get_report_default_print_behaviour(self):
result = {}
report_action = self.property_printing_action_id
if report_action and report_action.action_type != "user_default":
result["action"] = report_action.action_type
if self.printing_printer_id:
result["printer"] = self.printing_printer_id
if self.printer_tray_id:
result["tray"] = self.printer_tray_id.system_name
return result
def behaviour(self):
self.ensure_one()
printing_act_obj = self.env["printing.report.xml.action"]
result = self._get_user_default_print_behaviour()
result.update(self._get_report_default_print_behaviour())
# Retrieve report-user specific values
print_action = printing_act_obj.search(
[
("report_id", "=", self.id),
("user_id", "=", self.env.uid),
("action", "!=", "user_default"),
],
limit=1,
)
if print_action:
# For some reason design takes report defaults over
# False action entries so we must allow for that here
result.update({k: v for k, v in print_action.behaviour().items() if v})
return result
def print_document(self, record_ids, data=None):
"""Print a document, do not return the document file"""
report_type = REPORT_TYPES.get(self.report_type)
if not report_type:
raise exceptions.UserError(
_("This report type (%s) is not supported by direct printing!")
% str(self.report_type)
)
method_name = "_render_qweb_%s" % (report_type)
document, doc_format = getattr(
self.with_context(must_skip_send_to_printer=True), method_name
)(record_ids, data=data)
behaviour = self.behaviour()
printer = behaviour.pop("printer", None)
if not printer:
raise exceptions.UserError(_("No printer configured to print this report."))
if self.print_report_name:
report_file_names = [
safe_eval(self.print_report_name, {"object": obj, "time": time})
for obj in self.env[self.model].browse(record_ids)
]
title = " ".join(report_file_names)
if len(title) > 80:
title = title[:80] + "…"
else:
title = self.report_name
behaviour["title"] = title
# TODO should we use doc_format instead of report_type
return printer.print_document(
self, document, doc_format=self.report_type, **behaviour
)
def _can_print_report(self, behaviour, printer, document):
"""Predicate that decide if report can be sent to printer
If you want to prevent `render_qweb_pdf` to send report you can set
the `must_skip_send_to_printer` key to True in the context
"""
if self.env.context.get("must_skip_send_to_printer"):
return False
if behaviour["action"] == "server" and printer and document:
return True
return False
def report_action(self, docids, data=None, config=True):
res = super().report_action(docids, data=data, config=config)
if not res.get("id"):
res["id"] = self.id
return res
def _render_qweb_pdf(self, res_ids=None, data=None):
"""Generate a PDF and returns it.
If the action configured on the report is server, it prints the
generated document as well.
"""
document, doc_format = super()._render_qweb_pdf(res_ids=res_ids, data=data)
behaviour = self.behaviour()
printer = behaviour.pop("printer", None)
can_print_report = self._can_print_report(behaviour, printer, document)
if can_print_report:
printer.print_document(
self, document, doc_format=self.report_type, **behaviour
)
return document, doc_format
def _render_qweb_text(self, docids, data=None):
"""Generate a TEXT file and returns it.
If the action configured on the report is server, it prints the
generated document as well.
"""
document, doc_format = super()._render_qweb_text(docids=docids, data=data)
behaviour = self.behaviour()
printer = behaviour.pop("printer", None)
can_print_report = self._can_print_report(behaviour, printer, document)
if can_print_report:
printer.print_document(
self, document, doc_format=self.report_type, **behaviour
)
return document, doc_format
| 37.502646 | 7,088 |
8,537 |
py
|
PYTHON
|
15.0
|
# Copyright (c) 2007 Ferran Pegueroles <[email protected]>
# Copyright (c) 2009 Albert Cervera i Areny <[email protected]>
# Copyright (C) 2011 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2011 Domsense srl (<http://www.domsense.com>)
# Copyright (C) 2013-2014 Camptocamp (<http://www.camptocamp.com>)
# Copyright (C) 2016 SYLEAM (<http://www.syleam.fr>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import errno
import logging
import os
from tempfile import mkstemp
from odoo import fields, models
_logger = logging.getLogger(__name__)
try:
import cups
except ImportError:
_logger.debug("Cannot `import cups`.")
class PrintingPrinter(models.Model):
"""
Printers
"""
_name = "printing.printer"
_description = "Printer"
_order = "name"
name = fields.Char(required=True, index=True)
active = fields.Boolean(default=True)
server_id = fields.Many2one(
comodel_name="printing.server",
string="Server",
required=True,
help="Server used to access this printer.",
)
job_ids = fields.One2many(
comodel_name="printing.job",
inverse_name="printer_id",
string="Jobs",
help="Jobs printed on this printer.",
)
system_name = fields.Char(required=True, index=True)
default = fields.Boolean(readonly=True)
status = fields.Selection(
selection=[
("unavailable", "Unavailable"),
("printing", "Printing"),
("unknown", "Unknown"),
("available", "Available"),
("error", "Error"),
("server-error", "Server Error"),
],
required=True,
readonly=True,
default="unknown",
)
status_message = fields.Char(readonly=True)
model = fields.Char(readonly=True)
location = fields.Char(readonly=True)
uri = fields.Char(string="URI", readonly=True)
tray_ids = fields.One2many(
comodel_name="printing.tray", inverse_name="printer_id", string="Paper Sources"
)
def _prepare_update_from_cups(self, cups_connection, cups_printer):
mapping = {3: "available", 4: "printing", 5: "error"}
cups_vals = {
"name": cups_printer["printer-info"],
"model": cups_printer.get("printer-make-and-model", False),
"location": cups_printer.get("printer-location", False),
"uri": cups_printer.get("device-uri", False),
"status": mapping.get(cups_printer.get("printer-state"), "unknown"),
"status_message": cups_printer.get("printer-state-message", ""),
}
# prevent write if the field didn't change
vals = {
fieldname: value
for fieldname, value in cups_vals.items()
if not self or value != self[fieldname]
}
printer_uri = cups_printer["printer-uri-supported"]
printer_system_name = printer_uri[printer_uri.rfind("/") + 1 :]
ppd_info = cups_connection.getPPD3(printer_system_name)
ppd_path = ppd_info[2]
if not ppd_path:
return vals
ppd = cups.PPD(ppd_path)
option = ppd.findOption("InputSlot")
try:
os.unlink(ppd_path)
except OSError as err:
# ENOENT means No such file or directory
# The file has already been deleted, we can continue the update
if err.errno != errno.ENOENT:
raise
if not option:
return vals
tray_commands = []
cups_trays = {
tray_option["choice"]: tray_option["text"] for tray_option in option.choices
}
# Add new trays
tray_commands.extend(
[
(0, 0, {"name": text, "system_name": choice})
for choice, text in cups_trays.items()
if choice not in self.tray_ids.mapped("system_name")
]
)
# Remove deleted trays
tray_commands.extend(
[
(2, tray.id)
for tray in self.tray_ids.filtered(
lambda record: record.system_name not in cups_trays.keys()
)
]
)
if tray_commands:
vals["tray_ids"] = tray_commands
return vals
def print_document(self, report, content, **print_opts):
"""Print a file
Format could be pdf, qweb-pdf, raw, ...
"""
self.ensure_one()
fd, file_name = mkstemp()
try:
os.write(fd, content)
finally:
os.close(fd)
return self.print_file(file_name, report=report, **print_opts)
@staticmethod
def _set_option_doc_format(report, value):
return {"raw": "True"} if value == "raw" else {}
# Backwards compatibility of builtin used as kwarg
_set_option_format = _set_option_doc_format
def _set_option_tray(self, report, value):
"""Note we use self here as some older PPD use tray
rather than InputSlot so we may need to query printer in override"""
return {"InputSlot": str(value)} if value else {}
@staticmethod
def _set_option_noop(report, value):
return {}
_set_option_action = _set_option_noop
_set_option_printer = _set_option_noop
def print_options(self, report=None, **print_opts):
options = {}
for option, value in print_opts.items():
try:
options.update(getattr(self, "_set_option_%s" % option)(report, value))
except AttributeError:
options[option] = str(value)
return options
def print_file(self, file_name, report=None, **print_opts):
"""Print a file"""
self.ensure_one()
title = print_opts.pop("title", file_name)
connection = self.server_id._open_connection(raise_on_error=True)
options = self.print_options(report=report, **print_opts)
_logger.debug(
"Sending job to CUPS printer %s on %s with options %s"
% (self.system_name, self.server_id.address, options)
)
connection.printFile(self.system_name, file_name, title, options=options)
_logger.info(
"Printing job: '{}' on {}".format(file_name, self.server_id.address)
)
try:
os.remove(file_name)
except OSError as exc:
_logger.warning("Unable to remove temporary file %s: %s", file_name, exc)
return True
def set_default(self):
if not self:
return
self.ensure_one()
default_printers = self.search([("default", "=", True)])
default_printers.unset_default()
self.write({"default": True})
return True
def unset_default(self):
self.write({"default": False})
return True
def get_default(self):
return self.search([("default", "=", True)], limit=1)
def action_cancel_all_jobs(self):
self.ensure_one()
return self.cancel_all_jobs()
def cancel_all_jobs(self, purge_jobs=False):
for printer in self:
connection = printer.server_id._open_connection()
connection.cancelAllJobs(name=printer.system_name, purge_jobs=purge_jobs)
# Update jobs' states into Odoo
self.mapped("server_id").update_jobs(which="completed")
return True
def enable(self):
for printer in self:
connection = printer.server_id._open_connection()
connection.enablePrinter(printer.system_name)
# Update printers' stats into Odoo
self.mapped("server_id").update_printers()
return True
def disable(self):
for printer in self:
connection = printer.server_id._open_connection()
connection.disablePrinter(printer.system_name)
# Update printers' stats into Odoo
self.mapped("server_id").update_printers()
return True
def print_test_page(self):
for printer in self:
connection = printer.server_id._open_connection()
if printer.model == "Local Raw Printer":
fd, file_name = mkstemp()
try:
os.write(fd, b"TEST")
finally:
os.close(fd)
connection.printTestPage(printer.system_name, file=file_name)
else:
connection.printTestPage(printer.system_name)
self.mapped("server_id").update_jobs(which="completed")
| 32.96139 | 8,537 |
566 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2013-2014 Camptocamp (<http://www.camptocamp.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PrinterTray(models.Model):
_name = "printing.tray"
_description = "Printer Tray"
_order = "name asc"
name = fields.Char(required=True)
system_name = fields.Char(required=True, readonly=True)
printer_id = fields.Many2one(
comodel_name="printing.printer",
string="Printer",
required=True,
readonly=True,
ondelete="cascade",
)
| 26.952381 | 566 |
10,197 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2016 SYLEAM (<http://www.syleam.fr>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from datetime import datetime
from odoo import _, exceptions, fields, models
_logger = logging.getLogger(__name__)
try:
import cups
except ImportError:
_logger.debug("Cannot `import cups`.")
class PrintingServer(models.Model):
_name = "printing.server"
_description = "Printing server"
name = fields.Char(default="Localhost", required=True, help="Name of the server.")
address = fields.Char(
default="localhost", required=True, help="IP address or hostname of the server"
)
port = fields.Integer(default=631, required=True, help="Port of the server.")
user = fields.Char(help="User name to connect to the server. Empty by default.")
password = fields.Char(help="Password to connect to the server. Empty by default.")
encryption_policy = fields.Selection(
[
("0", "HTTP_ENCRYPT_IF_REQUESTED"),
("1", "HTTP_ENCRYPT_NEVER"),
("2", "HTTP_ENCRYPT_REQUIRED"),
("3", "HTTP_ENCRYPT_ALWAYS"),
],
help="Encryption Policy to connect to the server. Empty by default.",
)
active = fields.Boolean(default=True, help="If checked, this server is useable.")
printer_ids = fields.One2many(
comodel_name="printing.printer",
inverse_name="server_id",
string="Printers List",
help="List of printers available on this server.",
)
def _open_connection(self, raise_on_error=False):
self.ensure_one()
connection = False
# Password callback
password = self.password
def pw_callback(prompt):
return password
try:
# Sometimes connecting to printer servers outside of the local network
# can result in a weird error "cups.IPPError: (1030, 'The printer
# or class does not exist.')".
# An explicit call to `setServer` and `setPort` fixed the issue.
# (see https://github.com/OpenPrinting/pycups/issues/30)
cups.setServer(self.address)
cups.setPort(self.port)
if self.user:
cups.setUser(self.user)
if self.encryption_policy:
cups.setEncryption(int(self.encryption_policy))
if self.password:
cups.setPasswordCB(pw_callback)
connection = cups.Connection(host=self.address, port=self.port)
except Exception:
message = _(
"Failed to connect to the CUPS server on %(address)s:%(port)s. "
"Check that the CUPS server is running and that "
"you can reach it from the Odoo server."
) % {
"address": self.address,
"port": self.port,
}
_logger.warning(message)
if raise_on_error:
raise exceptions.UserError(message) from Exception
return connection
def action_update_printers(self):
return self.update_printers(raise_on_error=True)
def update_printers(self, domain=None, raise_on_error=False):
if domain is None:
domain = []
servers = self
if not self:
servers = self.search(domain)
res = True
for server in servers.with_context(active_test=False):
connection = server._open_connection(raise_on_error=raise_on_error)
if not connection:
server.printer_ids.write({"status": "server-error"})
res = False
continue
# Update Printers
printers = connection.getPrinters()
existing_printers = {
printer.system_name: printer for printer in server.printer_ids
}
updated_printers = []
for name, printer_info in printers.items():
printer = self.env["printing.printer"]
if name in existing_printers:
printer = existing_printers[name]
printer_values = printer._prepare_update_from_cups(
connection, printer_info
)
if server != printer.server_id:
printer_values["server_id"] = server.id
updated_printers.append(name)
if not printer:
printer_values["system_name"] = name
printer.create(printer_values)
elif printer_values:
printer.write(printer_values)
# Set printers not found as unavailable
server.printer_ids.filtered(
lambda record: record.system_name not in updated_printers
).write({"status": "unavailable"})
return res
def action_update_jobs(self):
if not self:
self = self.search([])
return self.update_jobs()
def update_jobs(self, which="all", first_job_id=-1):
job_obj = self.env["printing.job"]
printer_obj = self.env["printing.printer"]
mapping = {
3: "pending",
4: "pending held",
5: "processing",
6: "processing stopped",
7: "canceled",
8: "aborted",
9: "completed",
}
# Update printers list, to ensure that jobs printers will be in Odoo
self.update_printers()
for server in self:
connection = server._open_connection()
if not connection:
continue
# Retrieve asked job data
jobs_data = connection.getJobs(
which_jobs=which,
first_job_id=first_job_id,
requested_attributes=[
"job-name",
"job-id",
"printer-uri",
"job-media-progress",
"time-at-creation",
"job-state",
"job-state-reasons",
"time-at-processing",
"time-at-completed",
],
)
# Retrieve known uncompleted jobs data to update them
if which == "not-completed":
oldest_uncompleted_job = job_obj.search(
[("job_state", "not in", ("canceled", "aborted", "completed"))],
limit=1,
order="job_id_cups",
)
if oldest_uncompleted_job:
jobs_data.update(
connection.getJobs(
which_jobs="completed",
first_job_id=oldest_uncompleted_job.job_id_cups,
requested_attributes=[
"job-name",
"job-id",
"printer-uri",
"job-media-progress",
"time-at-creation",
"job-state",
"job-state-reasons",
"time-at-processing",
"time-at-completed",
],
)
)
all_cups_job_ids = set()
for cups_job_id, job_data in jobs_data.items():
all_cups_job_ids.add(cups_job_id)
jobs = job_obj.with_context(active_test=False).search(
[("job_id_cups", "=", cups_job_id), ("server_id", "=", server.id)]
)
cups_job_values = {
"name": job_data.get("job-name", ""),
"active": True,
"job_media_progress": job_data.get("job-media-progress", 0),
"job_state": mapping.get(job_data.get("job-state"), "unknown"),
"job_state_reason": job_data.get("job-state-reasons", ""),
"time_at_creation": datetime.fromtimestamp(
job_data.get("time-at-creation", 0)
),
}
if job_data.get("time-at-processing"):
cups_job_values["time_at_processing"] = datetime.fromtimestamp(
job_data["time-at-processing"]
)
if job_data.get("time-at-completed"):
cups_job_values["time_at_completed"] = datetime.fromtimestamp(
job_data["time-at-completed"]
)
job_values = {
fieldname: value
for fieldname, value in cups_job_values.items()
if not jobs or value != jobs[fieldname]
}
# Search for the printer in Odoo
printer_uri = job_data["printer-uri"]
printer_system_name = printer_uri[printer_uri.rfind("/") + 1 :]
printer = printer_obj.search(
[
("server_id", "=", server.id),
("system_name", "=", printer_system_name),
],
limit=1,
)
# CUPS retains jobs for disconnected printers and also may
# leak jobs data for unshared printers, therefore we just
# discard here if not printer found
if not printer:
continue
if jobs.printer_id != printer:
job_values["printer_id"] = printer.id
if not jobs:
job_values["job_id_cups"] = cups_job_id
job_obj.create(job_values)
elif job_values:
jobs.write(job_values)
# Deactive purged jobs
if which == "all" and first_job_id == -1:
purged_jobs = job_obj.search(
[("job_id_cups", "not in", list(all_cups_job_ids))]
)
purged_jobs.write({"active": False})
return True
| 37.907063 | 10,197 |
4,923 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2016 SYLEAM (<http://www.syleam.fr>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo import fields, models
_logger = logging.getLogger(__name__)
class PrintingJob(models.Model):
_name = "printing.job"
_description = "Printing Job"
_order = "job_id_cups DESC"
name = fields.Char(help="Job name.")
active = fields.Boolean(
default=True, help="Unchecked if the job is purged from cups."
)
job_id_cups = fields.Integer(
string="Job ID", required=True, help="CUPS id for this job."
)
server_id = fields.Many2one(
comodel_name="printing.server",
string="Server",
related="printer_id.server_id",
store=True,
help="Server which hosts this job.",
)
printer_id = fields.Many2one(
comodel_name="printing.printer",
string="Printer",
required=True,
ondelete="cascade",
help="Printer used for this job.",
)
job_media_progress = fields.Integer(
string="Media Progress",
required=True,
help="Percentage of progress for this job.",
)
time_at_creation = fields.Datetime(
required=True, help="Date and time of creation for this job."
)
time_at_processing = fields.Datetime(help="Date and time of process for this job.")
time_at_completed = fields.Datetime(
help="Date and time of completion for this job."
)
job_state = fields.Selection(
selection=[
("pending", "Pending"),
("pending held", "Pending Held"),
("processing", "Processing"),
("processing stopped", "Processing Stopped"),
("canceled", "Canceled"),
("aborted", "Aborted"),
("completed", "Completed"),
("unknown", "Unknown"),
],
string="State",
help="Current state of the job.",
)
job_state_reason = fields.Selection(
selection=[
("none", "No reason"),
("aborted-by-system", "Aborted by the system"),
("compression-error", "Error in the compressed data"),
("cups-filter-crashed", "CUPS filter crashed"),
("document-access-error", "The URI cannot be accessed"),
("document-format-error", "Error in the document"),
("job-canceled-at-device", "Cancelled at the device"),
("job-canceled-by-operator", "Cancelled by the printer operator"),
("job-canceled-by-user", "Cancelled by the user"),
("job-completed-successfully", "Completed successfully"),
("job-completed-with-errors", "Completed with some errors"),
("job-completed-with-warnings", "Completed with some warnings"),
("job-data-insufficient", "No data has been received"),
("job-hold-until-specified", "Currently held"),
("job-incoming", "Files are currently being received"),
("job-interpreting", "Currently being interpreted"),
("job-outgoing", "Currently being sent to the printer"),
("job-printing", "Currently printing"),
("job-queued", "Queued for printing"),
("job-queued-for-marker", "Printer needs ink/marker/toner"),
("job-restartable", "Can be restarted"),
("job-transforming", "Being transformed into a different format"),
("printer-stopped", "Printer is stopped"),
("printer-stopped-partly", "Printer state reason set to 'stopped-partly'"),
(
"processing-to-stop-point",
"Cancelled, but printing already processed pages",
),
("queued-in-device", "Queued at the output device"),
("resources-are-not-ready", "Resources not available to print the job"),
("service-off-line", "Held because the printer is offline"),
("submission-interrupted", "Files were not received in full"),
("unsupported-compression", "Compressed using an unknown algorithm"),
("unsupported-document-format", "Unsupported format"),
],
string="State Reason",
help="Reason for the current job state.",
)
_sql_constraints = [
(
"job_id_cups_unique",
"UNIQUE(job_id_cups, server_id)",
"The id of the job must be unique per server !",
)
]
def action_cancel(self):
self.ensure_one()
return self.cancel()
def cancel(self, purge_job=False):
for job in self:
connection = job.server_id._open_connection()
if not connection:
continue
connection.cancelJob(job.job_id_cups, purge_job=purge_job)
# Update jobs' states info Odoo
self.mapped("server_id").update_jobs(which="all", first_job_id=job.job_id_cups)
return True
| 38.76378 | 4,923 |
1,631 |
py
|
PYTHON
|
15.0
|
# Copyright (c) 2007 Ferran Pegueroles <[email protected]>
# Copyright (c) 2009 Albert Cervera i Areny <[email protected]>
# Copyright (C) 2011 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2011 Domsense srl (<http://www.domsense.com>)
# Copyright (C) 2013-2014 Camptocamp (<http://www.camptocamp.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class PrintingReportXmlAction(models.Model):
_name = "printing.report.xml.action"
_description = "Printing Report Printing Actions"
report_id = fields.Many2one(
comodel_name="ir.actions.report",
string="Report",
required=True,
ondelete="cascade",
)
user_id = fields.Many2one(
comodel_name="res.users", string="User", required=True, ondelete="cascade"
)
action = fields.Selection(
selection=lambda s: s.env["printing.action"]._available_action_types(),
required=True,
)
printer_id = fields.Many2one(comodel_name="printing.printer", string="Printer")
printer_tray_id = fields.Many2one(
comodel_name="printing.tray",
string="Paper Source",
domain="[('printer_id', '=', printer_id)]",
)
@api.onchange("printer_id")
def onchange_printer_id(self):
"""Reset the tray when the printer is changed"""
self.printer_tray_id = False
def behaviour(self):
if not self:
return {}
return {
"action": self.action,
"printer": self.printer_id,
"tray": self.printer_tray_id.system_name,
}
| 33.979167 | 1,631 |
1,614 |
py
|
PYTHON
|
15.0
|
# Copyright (c) 2007 Ferran Pegueroles <[email protected]>
# Copyright (c) 2009 Albert Cervera i Areny <[email protected]>
# Copyright (C) 2011 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2011 Domsense srl (<http://www.domsense.com>)
# Copyright (C) 2013-2014 Camptocamp (<http://www.camptocamp.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ResUsers(models.Model):
_inherit = "res.users"
@api.model
def _user_available_action_types(self):
return [
(code, string)
for code, string in self.env["printing.action"]._available_action_types()
if code != "user_default"
]
printing_action = fields.Selection(selection=_user_available_action_types)
printing_printer_id = fields.Many2one(
comodel_name="printing.printer", string="Default Printer"
)
@property
def SELF_READABLE_FIELDS(self):
return super().SELF_READABLE_FIELDS + ["printing_action", "printing_printer_id"]
@property
def SELF_WRITEABLE_FIELDS(self):
return super().SELF_WRITEABLE_FIELDS + [
"printing_action",
"printing_printer_id",
]
printer_tray_id = fields.Many2one(
comodel_name="printing.tray",
string="Default Printer Paper Source",
domain="[('printer_id', '=', printing_printer_id)]",
)
@api.onchange("printing_printer_id")
def onchange_printing_printer_id(self):
"""Reset the tray when the printer is changed"""
self.printer_tray_id = False
| 34.340426 | 1,614 |
2,472 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
import base64
from odoo import _, fields, models
class PrintAttachment(models.TransientModel):
_name = "wizard.print.attachment"
_description = "Print Attachment"
printer_id = fields.Many2one(
comodel_name="printing.printer",
string="Printer",
required=True,
help="Printer used to print the attachments.",
)
attachment_line_ids = fields.One2many(
"wizard.print.attachment.line",
"wizard_id",
string="Attachments to print",
)
def print_attachments(self):
"""Prints a label per selected record"""
self.ensure_one()
errors = []
for att_line in self.attachment_line_ids:
data = att_line.attachment_id.datas
title = att_line.attachment_id.name
if not data:
errors.append(att_line)
continue
content = base64.b64decode(data)
content_format = att_line.get_format()
self.printer_id.print_document(
None,
content=content,
format=content_format,
copies=att_line.copies,
title=title,
)
if errors:
return {
"warning": _("Following attachments could not be printed:\n\n%s")
% "\n".join(
[
_("{name} ({copies} copies)").format(
name=err.record_name, copies=err.copies
)
for err in errors
]
)
}
class PrintAttachmentLine(models.TransientModel):
_name = "wizard.print.attachment.line"
_description = "Print Attachment line"
wizard_id = fields.Many2one("wizard.print.attachment")
attachment_id = fields.Many2one(
"ir.attachment",
required=True,
domain=(
"['|', ('mimetype', '=', 'application/pdf'), "
"('mimetype', '=', 'application/octet-stream')]"
),
)
record_name = fields.Char(related="attachment_id.res_name", readonly=True)
copies = fields.Integer(default=1)
def get_format(self):
self.ensure_one()
mimetype = self.attachment_id.mimetype
if mimetype == "application/pdf":
return "pdf"
else:
return "raw"
| 31.291139 | 2,472 |
895 |
py
|
PYTHON
|
15.0
|
# Copyright (c) 2009 Albert Cervera i Areny <[email protected]>
# Copyright (C) 2011 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2011 Domsense srl (<http://www.domsense.com>)
# Copyright (C) 2014 Camptocamp (<http://www.camptocamp.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo import models
_logger = logging.getLogger(__name__)
class PrintingPrinterUpdateWizard(models.TransientModel):
_name = "printing.printer.update.wizard"
_description = "Printing Printer Update Wizard"
def action_ok(self):
self.env["printing.server"].search([]).update_printers(raise_on_error=True)
return {
"name": "Printers",
"view_mode": "tree,form",
"res_model": "printing.printer",
"type": "ir.actions.act_window",
"target": "current",
}
| 33.148148 | 895 |
710 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2016-2022 SUBTENO-IT (<https://subteno-it.fr>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Printer ZPL II",
"version": "15.0.1.0.0",
"category": "Printer",
"summary": "Add a ZPL II label printing feature",
"author": "SUBTENO-IT, FLorent de Labarre, "
"Apertoso NV, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/report-print-send",
"license": "AGPL-3",
"depends": ["base_report_to_printer"],
"data": [
"security/ir.model.access.csv",
"views/printing_label_zpl2.xml",
"wizard/print_record_label.xml",
"wizard/wizard_import_zpl2.xml",
],
"installable": True,
}
| 33.809524 | 710 |
3,580 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2018 Florent de Labarre (<https://github.com/fmdl>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from unittest.mock import patch
from odoo.tests.common import TransactionCase
model = "odoo.addons.base_report_to_printer.models.printing_server"
class TestWizardPrintRecordLabel(TransactionCase):
def setUp(self):
super(TestWizardPrintRecordLabel, self).setUp()
self.Model = self.env["wizard.print.record.label"]
self.server = self.env["printing.server"].create({})
self.printer = self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
self.label = self.env["printing.label.zpl2"].create(
{
"name": "ZPL II Label",
"model_id": self.env.ref(
"base_report_to_printer.model_printing_printer"
).id,
}
)
def test_get_record(self):
"""Check if return a record"""
self.label.record_id = 10
res = self.label._get_record()
Obj = self.env[self.label.model_id.model]
record = Obj.search([("id", "=", self.label.record_id)], limit=1)
if not record:
record = Obj.search([], limit=1, order="id desc")
self.assertEqual(res, record)
@patch("%s.cups" % model)
def test_print_label_test(self, cups):
"""Check if print test"""
self.label.test_print_mode = True
self.label.printer_id = self.printer
self.label.record_id = 10
self.label.print_test_label()
cups.Connection().printFile.assert_called_once()
def test_emulation_without_params(self):
"""Check if not execute next if not in this mode"""
self.label.test_labelary_mode = False
self.assertIs(self.label.labelary_image, False)
def test_emulation_with_bad_header(self):
"""Check if bad header"""
self.label.test_labelary_mode = True
self.label.labelary_width = 80
self.label.labelary_dpmm = "8dpmm"
self.label.labelary_height = 10000000
self.env["printing.label.zpl2.component"].create(
{"name": "ZPL II Label", "label_id": self.label.id, "data": '"Test"'}
)
self.assertFalse(self.label.labelary_image)
def test_emulation_with_bad_data_compute(self):
"""Check if bad data compute"""
self.label.test_labelary_mode = True
self.label.labelary_width = 80
self.label.labelary_height = 30
self.label.labelary_dpmm = "8dpmm"
component = self.env["printing.label.zpl2.component"].create(
{"name": "ZPL II Label", "label_id": self.label.id, "data": "wrong_data"}
)
component.unlink()
self.assertIs(self.label.labelary_image, False)
def test_emulation_with_good_data(self):
"""Check if ok"""
self.label.test_labelary_mode = True
self.label.labelary_width = 80
self.label.labelary_height = 30
self.label.labelary_dpmm = "8dpmm"
self.env["printing.label.zpl2.component"].create(
{"name": "ZPL II Label", "label_id": self.label.id, "data": '"good_data"'}
)
self.assertTrue(self.label.labelary_image)
| 38.085106 | 3,580 |
3,714 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2018 Florent de Labarre (<https://github.com/fmdl>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestWizardImportZpl2(TransactionCase):
def setUp(self):
super(TestWizardImportZpl2, self).setUp()
self.Model = self.env["wizard.print.record.label"]
self.server = self.env["printing.server"].create({})
self.printer = self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
self.label = self.env["printing.label.zpl2"].create(
{
"name": "ZPL II Label",
"model_id": self.env.ref(
"base_report_to_printer.model_printing_printer"
).id,
}
)
def test_open_wizard(self):
"""open wizard from label"""
res = self.label.import_zpl2()
self.assertEqual(res.get("context").get("default_label_id"), self.label.id)
def test_wizard_import_zpl2(self):
"""Import ZPL2 from wizard"""
zpl_data = (
"^XA\n"
"^CI28\n"
"^LH0,0\n"
"^CF0\n"
"^CFA,10\n"
"^CFB,10,10\n"
"^FO10,10^A0N,30,30^FDTEXT^FS\n"
"^BY2,3.0^FO600,60^BCN,30,N,N,N"
"^FDAJFGJAGJVJVHK^FS\n"
"^FO10,40^A0N,20,40^FB150,2,1,J,0^FDTEXT BLOCK^FS\n"
"^FO300,10^GC100,3,B^FS\n"
"^FO10,200^GB200,200,100,B,0^FS\n"
"^FO10,60^GFA,16.0,16.0,2.0,"
"b'FFC0FFC0FFC0FFC0FFC0FFC0FFC0FFC0'^FS\n"
"^FO10,200^GB300,100,6,W,0^FS\n"
"^BY2,3.0^FO300,10^B1N,N,30,N,N^FD678987656789^FS\n"
"^BY2,3.0^FO300,70^B2N,30,Y,Y,N^FD567890987768^FS\n"
"^BY2,3.0^FO300,120^B3N,N,30,N,N^FD98765456787656^FS\n"
"^BY2,3.0^FO300,200^BQN,2,5,Q,7"
"^FDMM,A876567897656787658654645678^FS\n"
"^BY2,3.0^FO400,250^BER,40,Y,Y^FD9876789987654567^FS\n"
"^BY2,3.0^FO350,250^B7N,20,0,0,0,N^FD8765678987656789^FS\n"
"^BY2,3.0^FO700,10^B9N,20,N,N,N^FD87657890987654^FS\n"
"^BY2,3.0^FO600,200^B4N,50,N^FD7654567898765678^FS\n"
"^BY2,3.0^FO600,300^BEN,50,Y,Y^FD987654567890876567^FS\n"
"^FO300,300^AGI,50,50^FR^FDINVERTED^FS\n"
"^BY2,3.0^FO700,200^B8,50,N,N^FD987609876567^FS\n"
"^JUR\n"
"^XZ"
)
vals = {"label_id": self.label.id, "delete_component": True, "data": zpl_data}
wizard = self.env["wizard.import.zpl2"].create(vals)
wizard.import_zpl2()
self.assertEqual(18, len(self.label.component_ids))
def test_wizard_import_zpl2_add(self):
"""Import ZPL2 from wizard ADD"""
self.env["printing.label.zpl2.component"].create(
{
"name": "ZPL II Label",
"label_id": self.label.id,
"data": '"data"',
"sequence": 10,
}
)
zpl_data = (
"^XA\n" "^CI28\n" "^LH0,0\n" "^FO10,10^A0N,30,30^FDTEXT^FS\n" "^JUR\n" "^XZ"
)
vals = {"label_id": self.label.id, "delete_component": False, "data": zpl_data}
wizard = self.env["wizard.import.zpl2"].create(vals)
wizard.import_zpl2()
self.assertEqual(2, len(self.label.component_ids))
| 39.094737 | 3,714 |
3,815 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from unittest.mock import patch
from odoo.tests.common import TransactionCase
model = "odoo.addons.base_report_to_printer.models.printing_server"
class TestWizardPrintRecordLabel(TransactionCase):
def setUp(self):
super(TestWizardPrintRecordLabel, self).setUp()
self.Model = self.env["wizard.print.record.label"]
self.server = self.env["printing.server"].create({})
self.printer = self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
self.label = self.env["printing.label.zpl2"].create(
{
"name": "ZPL II Label",
"model_id": self.env.ref(
"base_report_to_printer.model_printing_printer"
).id,
}
)
@patch("%s.cups" % model)
def test_print_record_label(self, cups):
"""Check that printing a label using the generic wizard works"""
wizard_obj = self.Model.with_context(
active_model="printing.printer",
active_id=self.printer.id,
active_ids=[self.printer.id],
printer_zpl2_id=self.printer.id,
)
wizard = wizard_obj.create({})
self.assertEqual(wizard.printer_id, self.printer)
self.assertEqual(wizard.label_id, self.label)
wizard.print_label()
cups.Connection().printFile.assert_called_once()
def test_wizard_multiple_printers_and_labels(self):
"""Check that printer_id and label_id are not automatically filled
when there are multiple possible values
"""
self.env["printing.printer"].create(
{
"name": "Other_Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
self.env["printing.label.zpl2"].create(
{
"name": "Other ZPL II Label",
"model_id": self.env.ref(
"base_report_to_printer.model_printing_printer"
).id,
}
)
wizard_obj = self.Model.with_context(
active_model="printing.printer",
active_id=self.printer.id,
active_ids=[self.printer.id],
)
values = wizard_obj.default_get(["printer_id", "label_id"])
self.assertEqual(values.get("printer_id", False), False)
self.assertEqual(values.get("label_id", False), False)
def test_wizard_multiple_labels_but_on_different_models(self):
"""Check that label_id is automatically filled when there are multiple
labels, but only one on the right model
"""
self.env["printing.label.zpl2"].create(
{
"name": "Other ZPL II Label",
"model_id": self.env.ref("base.model_res_users").id,
}
)
wizard_obj = self.Model.with_context(
active_model="printing.printer",
active_id=self.printer.id,
active_ids=[self.printer.id],
printer_zpl2_id=self.printer.id,
)
wizard = wizard_obj.create({})
self.assertEqual(wizard.label_id, self.label)
| 36.682692 | 3,815 |
36,901 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from unittest.mock import patch
from odoo import exceptions
from odoo.tests.common import TransactionCase
from ..models import zpl2
model = "odoo.addons.base_report_to_printer.models.printing_server"
class TestPrintingLabelZpl2(TransactionCase):
def setUp(self):
super(TestPrintingLabelZpl2, self).setUp()
self.Model = self.env["printing.label.zpl2"]
self.ComponentModel = self.env["printing.label.zpl2.component"]
self.server = self.env["printing.server"].create({})
self.printer = self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
self.label_vals = {
"name": "ZPL II Label",
"model_id": self.env.ref(
"base_report_to_printer.model_printing_printer"
).id,
}
self.component_vals = {"name": "ZPL II Label Component"}
def new_label(self, vals=None):
values = self.label_vals.copy()
if vals:
values.update(vals)
return self.Model.create(values)
def new_component(self, vals=None):
values = self.component_vals.copy()
if vals:
values.update(vals)
return self.ComponentModel.create(values)
def test_print_on_bad_model(self):
"""Check that printing on the bad model raises an exception"""
label = self.new_label()
with self.assertRaises(exceptions.UserError):
label.print_label(self.printer, label)
@patch("%s.cups" % model)
def test_print_empty_label(self, cups):
"""Check that printing an empty label works"""
label = self.new_label()
label.print_label(self.printer, self.printer)
cups.Connection().printFile.assert_called_once()
def test_empty_label_contents(self):
"""Check contents of an empty label"""
label = self.new_label()
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ",
)
def test_sublabel_label_contents(self):
"""Check contents of a sublabel label component"""
sublabel = self.new_label({"name": "Sublabel"})
data = "Some text"
self.new_component({"label_id": sublabel.id, "data": '"' + data + '"'})
label = self.new_label()
self.new_component(
{
"label_id": label.id,
"name": "Sublabel contents",
"component_type": "sublabel",
"sublabel_id": sublabel.id,
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Sublabel component position
# Position 30x30 because the default values are :
# - 10x10 for the sublabel component in the main label
# - 10x10 for the sublabel in the sublabel component
# - 10x10 for the component in the sublabel
"^FO30,30"
# Sublabel component format
"^A0N,10,10"
# Sublabel component contents
"^FD{contents}"
# Sublabel component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_repeatable_component_label_fixed_contents(self):
"""Check contents of a repeatable label component
Check that a fixed value is repeated each time
"""
label = self.new_label(
{"model_id": self.env.ref("printer_zpl2.model_printing_label_zpl2").id}
)
data = "Some text"
self.new_component(
{
"label_id": label.id,
"data": '"' + data + '"',
"repeat": True,
"repeat_count": 3,
"repeat_offset_y": 15,
}
)
contents = label._generate_zpl2_data(label).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# First component position
"^FO10,10"
# First component format
"^A0N,10,10"
# First component contents
"^FD{contents}"
# First component end
"^FS\n"
# Second component position
"^FO10,25"
# Second component format
"^A0N,10,10"
# Second component contents
"^FD{contents}"
# Second component end
"^FS\n"
# Third component position
"^FO10,40"
# Third component format
"^A0N,10,10"
# Third component contents
"^FD{contents}"
# Third component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_repeatable_component_label_iterable_contents(self):
"""Check contents of a repeatable label component
Check that an iterable contents (list, tuple, etc.) is browsed
If the repeat_count is higher than the value length, all values are
displayed
"""
label = self.new_label(
{"model_id": self.env.ref("printer_zpl2.model_printing_label_zpl2").id}
)
data = ["First text", "Second text", "Third text"]
self.new_component(
{
"label_id": label.id,
"data": str(data),
"repeat": True,
"repeat_offset": 1,
"repeat_count": 3,
"repeat_offset_y": 15,
}
)
contents = label._generate_zpl2_data(label).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# First component position
"^FO10,10"
# First component format
"^A0N,10,10"
# First component contents
"^FD{contents[1]}"
# First component end
"^FS\n"
# Second component position
"^FO10,25"
# Second component format
"^A0N,10,10"
# Second component contents
"^FD{contents[2]}"
# Second component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_repeatable_component_label_iterable_offset(self):
"""Check contents of a repeatable label component with an offset
Check that an iterable contents (list, tuple, etc.) is browsed
If the repeat_count is higher than the value length, all values are
displayed
"""
label = self.new_label(
{"model_id": self.env.ref("printer_zpl2.model_printing_label_zpl2").id}
)
data = ["Text {value}".format(value=ind) for ind in range(20)]
self.new_component(
{
"label_id": label.id,
"data": str(data),
"repeat": True,
"repeat_offset": 10,
"repeat_count": 3,
"repeat_offset_y": 15,
}
)
contents = label._generate_zpl2_data(label).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# First component position
"^FO10,10"
# First component format
"^A0N,10,10"
# First component contents
"^FD{contents[10]}"
# First component end
"^FS\n"
# Second component position
"^FO10,25"
# Second component format
"^A0N,10,10"
# Second component contents
"^FD{contents[11]}"
# Second component end
"^FS\n"
# Third component position
"^FO10,40"
# Third component format
"^A0N,10,10"
# Third component contents
"^FD{contents[12]}"
# Third component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_repeatable_sublabel_contents(self):
"""Check contents of a repeatable sublabel label component"""
sublabel = self.new_label(
{
"name": "Sublabel",
"model_id": self.env.ref(
"printer_zpl2.model_printing_label_zpl2_component"
).id,
}
)
self.new_component(
{"label_id": sublabel.id, "name": "Components name", "data": "object.name"}
)
self.new_component(
{
"label_id": sublabel.id,
"name": "Components data",
"data": "object.data",
"origin_x": 50,
}
)
label = self.new_label(
{"model_id": self.env.ref("printer_zpl2.model_printing_label_zpl2").id}
)
self.new_component(
{"label_id": label.id, "name": "Label name", "data": "object.name"}
)
self.new_component(
{
"label_id": label.id,
"name": "Label components",
"component_type": "sublabel",
"origin_x": 15,
"origin_y": 30,
"data": "object.component_ids",
"sublabel_id": sublabel.id,
"repeat": True,
"repeat_count": 3,
"repeat_offset_y": 15,
}
)
contents = label._generate_zpl2_data(label).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Label name component position
"^FO10,10"
# Label name component format
"^A0N,10,10"
# Label name component contents
"^FD{label.name}"
# Label name component end
"^FS\n"
# First component name component position
"^FO35,50"
# First component name component format
"^A0N,10,10"
# First component name component contents
"^FD{label.component_ids[0].name}"
# First component name component end
"^FS\n"
# First component data component position
"^FO75,50"
# First component data component format
"^A0N,10,10"
# First component data component contents
"^FD{label.component_ids[0].data}"
# First component data component end
"^FS\n"
# Second component name component position
"^FO35,65"
# Second component name component format
"^A0N,10,10"
# Second component name component contents
"^FD{label.component_ids[1].name}"
# Second component name component end
"^FS\n"
# Second component data component position
"^FO75,65"
# Second component data component format
"^A0N,10,10"
# Second component data component contents
"^FD{label.component_ids[1].data}"
# Second component data component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(label=label),
)
def test_text_label_contents(self):
"""Check contents of a text label"""
label = self.new_label()
data = "Some text"
self.new_component({"label_id": label.id, "data": '"%s"' % data})
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Component position
"^FO10,10"
# Component format
"^A0N,10,10"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_reversed_text_label_contents(self):
"""Check contents of a text label"""
label = self.new_label()
data = "Some text"
self.new_component(
{"label_id": label.id, "data": '"' + data + '"', "reverse_print": True}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Component position
"^FO10,10"
# Component format
"^A0N,10,10"
# Reverse print argument
"^FR"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_block_text_label_contents(self):
"""Check contents of a text label"""
label = self.new_label()
data = "Some text"
self.new_component(
{"label_id": label.id, "data": '"' + data + '"', "in_block": True}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Component position
"^FO10,10"
# Component format
"^A0N,10,10"
# Block definition
"^FB0,1,0,L,0"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_rectangle_label_contents(self):
"""Check contents of a rectangle label"""
label = self.new_label()
self.new_component({"label_id": label.id, "component_type": "rectangle"})
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Component position
"^FO10,10"
# Component format
"^GB1,1,1,B,0"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ",
)
def test_diagonal_line_label_contents(self):
"""Check contents of a diagonal line label"""
label = self.new_label()
self.new_component({"label_id": label.id, "component_type": "diagonal"})
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Component position
"^FO10,10"
# Component format
"^GD3,3,1,B,L"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ",
)
def test_circle_label_contents(self):
"""Check contents of a circle label"""
label = self.new_label()
self.new_component({"label_id": label.id, "component_type": "circle"})
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Component position
"^FO10,10"
# Component format
"^GC3,2,B"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ",
)
def test_code11_barcode_label_contents(self):
"""Check contents of a code 11 barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{
"label_id": label.id,
"component_type": "code_11",
"data": '"' + data + '"',
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^B1N,N,0,N,N"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_2of5_barcode_label_contents(self):
"""Check contents of a interleaved 2 of 5 barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{
"label_id": label.id,
"component_type": "interleaved_2_of_5",
"data": '"' + data + '"',
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^B2N,0,N,N,N"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_code39_barcode_label_contents(self):
"""Check contents of a code 39 barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{
"label_id": label.id,
"component_type": "code_39",
"data": '"' + data + '"',
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^B3N,N,0,N,N"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_code49_barcode_label_contents(self):
"""Check contents of a code 49 barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{
"label_id": label.id,
"component_type": "code_49",
"data": '"' + data + '"',
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^B4N,0,N"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_code49_barcode_label_contents_line(self):
"""Check contents of a code 49 barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{
"label_id": label.id,
"component_type": "code_49",
"data": '"' + data + '"',
"interpretation_line": True,
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^B4N,0,B"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_code49_barcode_label_contents_with_above(self):
"""Check contents of a code 49 barconde label
with interpretation line above
"""
label = self.new_label()
data = "Some text"
self.new_component(
{
"label_id": label.id,
"component_type": "code_49",
"data": '"' + data + '"',
"interpretation_line": True,
"interpretation_line_above": True,
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^B4N,0,A"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_pdf417_barcode_label_contents(self):
"""Check contents of a pdf417 barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{"label_id": label.id, "component_type": "pdf417", "data": '"' + data + '"'}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^B7N,0,0,0,0,N"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_ean8_barcode_label_contents(self):
"""Check contents of a ean-8 barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{"label_id": label.id, "component_type": "ean-8", "data": '"' + data + '"'}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^B8N,0,N,N"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_upce_barcode_label_contents(self):
"""Check contents of a upc-e barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{"label_id": label.id, "component_type": "upc-e", "data": '"' + data + '"'}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^B9N,0,N,N,N"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_code128_barcode_label_contents(self):
"""Check contents of a code 128 barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{
"label_id": label.id,
"component_type": "code_128",
"data": '"' + data + '"',
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^BCN,0,N,N,N"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_ean13_barcode_label_contents(self):
"""Check contents of a ean-13 barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{"label_id": label.id, "component_type": "ean-13", "data": '"' + data + '"'}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^BEN,0,N,N"
# Component contents
"^FD{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_qrcode_barcode_label_contents(self):
"""Check contents of a qr code barcode label"""
label = self.new_label()
data = "Some text"
self.new_component(
{
"label_id": label.id,
"component_type": "qr_code",
"data": '"' + data + '"',
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
# Label start
"^XA\n"
# Print width
"^PW480\n"
# UTF-8 encoding
"^CI28\n"
# Label position
"^LH10,10\n"
# Barcode default format
"^BY2,3.0"
# Component position
"^FO10,10"
# Component format
"^BQN,2,1,Q,7"
# Component contents
"^FDQA,{contents}"
# Component end
"^FS\n"
# Recall last saved parameters
"^JUR\n"
# Label end
"^XZ".format(contents=data),
)
def test_graphic_label_contents_blank(self):
"""Check contents of a image label"""
label = self.new_label()
data = "R0lGODlhAQABAIAAAP7//wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="
self.new_component(
{
"label_id": label.id,
"component_type": "graphic",
"data": '"' + data + '"',
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
"^XA\n"
"^PW480\n"
"^CI28\n"
"^LH10,10\n"
"^FO10,10^GFA,1.0,1.0,1.0,b'00'^FS\n"
"^JUR\n"
"^XZ",
)
def test_graphic_label_contents_blank_rotated(self):
"""Check contents of image rotated label"""
label = self.new_label()
data = "R0lGODlhAQABAIAAAP7//wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="
self.new_component(
{
"label_id": label.id,
"component_type": "graphic",
"data": '"' + data + '"',
"height": 10,
"width": 10,
"reverse_print": 1,
"orientation": zpl2.ORIENTATION_ROTATED,
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
"^XA\n"
"^PW480\n"
"^CI28\n"
"^LH10,10\n"
"^FO10,10^GFA,20.0,20.0,2.0,"
"b'FFC0FFC0FFC0FFC0FFC0FFC0FFC0FFC0FFC0FFC0'^FS\n"
"^JUR\n"
"^XZ",
)
def test_graphic_label_contents_blank_inverted(self):
"""Check contents of a image inverted label"""
label = self.new_label()
data = "R0lGODlhAQABAIAAAP7//wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="
self.new_component(
{
"label_id": label.id,
"component_type": "graphic",
"data": '"' + data + '"',
"orientation": zpl2.ORIENTATION_INVERTED,
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
"^XA\n"
"^PW480\n"
"^CI28\n"
"^LH10,10\n"
"^FO10,10^GFA,1.0,1.0,1.0,b'00'^FS\n"
"^JUR\n"
"^XZ",
)
def test_graphic_label_contents_blank_bottom(self):
"""Check contents of a image bottom label"""
label = self.new_label()
data = "R0lGODlhAQABAIAAAP7//wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="
self.new_component(
{
"label_id": label.id,
"component_type": "graphic",
"data": '"' + data + '"',
"orientation": zpl2.ORIENTATION_BOTTOM_UP,
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
"^XA\n"
"^PW480\n"
"^CI28\n"
"^LH10,10\n"
"^FO10,10^GFA,1.0,1.0,1.0,b'00'^FS\n"
"^JUR\n"
"^XZ",
)
def test_zpl2_raw_contents_blank(self):
"""Check contents of a image label"""
label = self.new_label()
data = "^FO50,50^GB100,100,100^FS"
self.new_component(
{
"label_id": label.id,
"component_type": "zpl2_raw",
"data": '"' + data + '"',
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents,
"^XA\n"
"^PW480\n"
"^CI28\n"
"^LH10,10\n"
"^FO50,50^GB100,100,100^FS\n"
"^JUR\n"
"^XZ",
)
def test_zpl2_component_not_show(self):
"""Check to don't show no things"""
label = self.new_label()
data = "component_not_show"
self.new_component(
{
"label_id": label.id,
"component_type": "zpl2_raw",
"data": '"' + data + '"',
}
)
contents = label._generate_zpl2_data(self.printer).decode("utf-8")
self.assertEqual(
contents, "^XA\n" "^PW480\n" "^CI28\n" "^LH10,10\n" "^JUR\n" "^XZ"
)
def test_zpl2_component_quick_move(self):
"""Check component quick move"""
label = self.new_label()
component = self.new_component(
{
"label_id": label.id,
"component_type": "zpl2_raw",
"data": '""',
"origin_x": 20,
"origin_y": 30,
}
)
component.action_plus_origin_x()
self.assertEqual(30, component.origin_x)
component.action_minus_origin_x()
self.assertEqual(20, component.origin_x)
component.action_plus_origin_y()
self.assertEqual(40, component.origin_y)
component.action_minus_origin_y()
self.assertEqual(30, component.origin_y)
| 31.19273 | 36,901 |
1,545 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2018 Florent de Labarre (<https://github.com/fmdl>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
model = "odoo.addons.base_report_to_printer.models.printing_server"
class TestWizardPrintRecordLabel(TransactionCase):
def setUp(self):
super(TestWizardPrintRecordLabel, self).setUp()
self.Model = self.env["wizard.print.record.label"]
self.server = self.env["printing.server"].create({})
self.printer = self.env["printing.printer"].create(
{
"name": "Printer",
"server_id": self.server.id,
"system_name": "Sys Name",
"default": True,
"status": "unknown",
"status_message": "Msg",
"model": "res.users",
"location": "Location",
"uri": "URI",
}
)
self.label = self.env["printing.label.zpl2"].create(
{
"name": "ZPL II Label",
"model_id": self.env.ref(
"base_report_to_printer.model_printing_printer"
).id,
}
)
def test_create_action(self):
"""Check the creation of action"""
self.label.create_action()
self.assertTrue(self.label.action_window_id)
def test_unlink_action(self):
"""Check the unlink of action"""
self.label.unlink_action()
self.assertFalse(self.label.action_window_id)
| 35.113636 | 1,545 |
12,028 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2018 Florent de Labarre (<https://github.com/fmdl>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import base64
import binascii
import io
import logging
import re
from PIL import Image, ImageOps
from odoo import _, fields, models
from ..models import zpl2
_logger = logging.getLogger(__name__)
def _compute_arg(data, arg):
vals = {}
for i, d in enumerate(data.split(",")):
vals[arg[i]] = d
return vals
def _field_origin(data):
if data[:2] == "FO":
position = data[2:]
vals = _compute_arg(position, ["origin_x", "origin_y"])
return vals
return {}
def _font_format(data):
if data[:1] == "A":
data = data.split(",")
vals = {}
if len(data[0]) > 1:
vals[zpl2.ARG_FONT] = data[0][1]
if len(data[0]) > 2:
vals[zpl2.ARG_ORIENTATION] = data[0][2]
if len(data) > 1:
vals[zpl2.ARG_HEIGHT] = data[1]
if len(data) > 2:
vals[zpl2.ARG_WIDTH] = data[2]
return vals
return {}
def _default_font_format(data):
if data[:2] == "CF":
args = [zpl2.ARG_FONT, zpl2.ARG_HEIGHT, zpl2.ARG_WIDTH]
vals = _compute_arg(data[2:], args)
if vals.get(zpl2.ARG_HEIGHT, False) and not vals.get(zpl2.ARG_WIDTH, False):
vals.update({zpl2.ARG_WIDTH: vals.get(zpl2.ARG_HEIGHT)})
else:
vals.update({zpl2.ARG_HEIGHT: 10})
return vals
return {}
def _field_block(data):
if data[:2] == "FB":
vals = {zpl2.ARG_IN_BLOCK: True}
args = [
zpl2.ARG_BLOCK_WIDTH,
zpl2.ARG_BLOCK_LINES,
zpl2.ARG_BLOCK_SPACES,
zpl2.ARG_BLOCK_JUSTIFY,
zpl2.ARG_BLOCK_LEFT_MARGIN,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _code11(data):
if data[:2] == "B1":
vals = {"component_type": zpl2.BARCODE_CODE_11}
args = [
zpl2.ARG_ORIENTATION,
zpl2.ARG_CHECK_DIGITS,
zpl2.ARG_HEIGHT,
zpl2.ARG_INTERPRETATION_LINE,
zpl2.ARG_INTERPRETATION_LINE_ABOVE,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _interleaved2of5(data):
if data[:2] == "B2":
vals = {"component_type": zpl2.BARCODE_INTERLEAVED_2_OF_5}
args = [
zpl2.ARG_ORIENTATION,
zpl2.ARG_HEIGHT,
zpl2.ARG_INTERPRETATION_LINE,
zpl2.ARG_INTERPRETATION_LINE_ABOVE,
zpl2.ARG_CHECK_DIGITS,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _code39(data):
if data[:2] == "B3":
vals = {"component_type": zpl2.BARCODE_CODE_39}
args = [
zpl2.ARG_ORIENTATION,
zpl2.ARG_CHECK_DIGITS,
zpl2.ARG_HEIGHT,
zpl2.ARG_INTERPRETATION_LINE,
zpl2.ARG_INTERPRETATION_LINE_ABOVE,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _code49(data):
if data[:2] == "B4":
vals = {"component_type": zpl2.BARCODE_CODE_49}
args = [
zpl2.ARG_ORIENTATION,
zpl2.ARG_HEIGHT,
zpl2.ARG_INTERPRETATION_LINE,
zpl2.ARG_STARTING_MODE,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _pdf417(data):
if data[:2] == "B7":
vals = {"component_type": zpl2.BARCODE_PDF417}
args = [
zpl2.ARG_ORIENTATION,
zpl2.ARG_HEIGHT,
zpl2.ARG_SECURITY_LEVEL,
zpl2.ARG_COLUMNS_COUNT,
zpl2.ARG_ROWS_COUNT,
zpl2.ARG_TRUNCATE,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _ean8(data):
if data[:2] == "B8":
vals = {"component_type": zpl2.BARCODE_EAN_8}
args = [
zpl2.ARG_ORIENTATION,
zpl2.ARG_HEIGHT,
zpl2.ARG_INTERPRETATION_LINE,
zpl2.ARG_INTERPRETATION_LINE_ABOVE,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _upce(data):
if data[:2] == "B9":
vals = {"component_type": zpl2.BARCODE_UPC_E}
args = [
zpl2.ARG_ORIENTATION,
zpl2.ARG_HEIGHT,
zpl2.ARG_INTERPRETATION_LINE,
zpl2.ARG_INTERPRETATION_LINE_ABOVE,
zpl2.ARG_CHECK_DIGITS,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _code128(data):
if data[:2] == "BC":
vals = {"component_type": zpl2.BARCODE_CODE_128}
args = [
zpl2.ARG_ORIENTATION,
zpl2.ARG_HEIGHT,
zpl2.ARG_INTERPRETATION_LINE,
zpl2.ARG_INTERPRETATION_LINE_ABOVE,
zpl2.ARG_CHECK_DIGITS,
zpl2.ARG_MODE,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _ean13(data):
if data[:2] == "BE":
vals = {"component_type": zpl2.BARCODE_EAN_13}
args = [
zpl2.ARG_ORIENTATION,
zpl2.ARG_HEIGHT,
zpl2.ARG_INTERPRETATION_LINE,
zpl2.ARG_INTERPRETATION_LINE_ABOVE,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _qrcode(data):
if data[:2] == "BQ":
vals = {"component_type": zpl2.BARCODE_QR_CODE}
args = [
zpl2.ARG_ORIENTATION,
zpl2.ARG_MODEL,
zpl2.ARG_MAGNIFICATION_FACTOR,
zpl2.ARG_ERROR_CORRECTION,
zpl2.ARG_MASK_VALUE,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _default_barcode_field(data):
if data[:2] == "BY":
args = [zpl2.ARG_MODULE_WIDTH, zpl2.ARG_BAR_WIDTH_RATIO, zpl2.ARG_HEIGHT]
return _compute_arg(data[2:], args)
return {}
def _field_reverse_print(data):
if data[:2] == "FR":
return {zpl2.ARG_REVERSE_PRINT: True}
return {}
def _graphic_box(data):
if data[:2] == "GB":
vals = {"component_type": "rectangle"}
args = [
zpl2.ARG_WIDTH,
zpl2.ARG_HEIGHT,
zpl2.ARG_THICKNESS,
zpl2.ARG_COLOR,
zpl2.ARG_ROUNDING,
]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _graphic_circle(data):
if data[:2] == "GC":
vals = {"component_type": "circle"}
args = [zpl2.ARG_WIDTH, zpl2.ARG_THICKNESS, zpl2.ARG_COLOR]
vals.update(_compute_arg(data[2:], args))
return vals
return {}
def _graphic_field(data):
if data[:3] == "GFA":
vals = {}
args = [
"compression",
"total_bytes",
"total_bytes",
"bytes_per_row",
"ascii_data",
]
vals.update(_compute_arg(data[3:], args))
# Image
rawData = re.sub("[^A-F0-9]+", "", vals["ascii_data"])
rawData = binascii.unhexlify(rawData)
width = int(float(vals["bytes_per_row"]) * 8)
height = int(float(vals["total_bytes"]) / width) * 8
img = Image.frombytes("1", (width, height), rawData, "raw").convert("L")
img = ImageOps.invert(img)
imgByteArr = io.BytesIO()
img.save(imgByteArr, format="PNG")
image = base64.b64encode(imgByteArr.getvalue())
return {
"component_type": "graphic",
"graphic_image": image,
zpl2.ARG_WIDTH: width,
zpl2.ARG_HEIGHT: height,
}
return {}
def _get_data(data):
if data[:2] == "FD":
return {"data": '"%s"' % data[2:]}
return {}
SUPPORTED_CODE = {
"FO": {"method": _field_origin},
"FD": {"method": _get_data},
"A": {"method": _font_format},
"FB": {"method": _field_block},
"B1": {"method": _code11},
"B2": {"method": _interleaved2of5},
"B3": {"method": _code39},
"B4": {"method": _code49},
"B7": {"method": _pdf417},
"B8": {"method": _ean8},
"B9": {"method": _upce},
"BC": {"method": _code128},
"BE": {"method": _ean13},
"BQ": {"method": _qrcode},
"BY": {
"method": _default_barcode_field,
"default": [
zpl2.BARCODE_CODE_11,
zpl2.BARCODE_INTERLEAVED_2_OF_5,
zpl2.BARCODE_CODE_39,
zpl2.BARCODE_CODE_49,
zpl2.BARCODE_PDF417,
zpl2.BARCODE_EAN_8,
zpl2.BARCODE_UPC_E,
zpl2.BARCODE_CODE_128,
zpl2.BARCODE_EAN_13,
zpl2.BARCODE_QR_CODE,
],
},
"CF": {"method": _default_font_format, "default": ["text"]},
"FR": {"method": _field_reverse_print},
"GB": {"method": _graphic_box},
"GC": {"method": _graphic_circle},
"GFA": {"method": _graphic_field},
}
class WizardImportZPl2(models.TransientModel):
_name = "wizard.import.zpl2"
_description = "Import ZPL2"
label_id = fields.Many2one(
comodel_name="printing.label.zpl2", string="Label", required=True, readonly=True
)
data = fields.Text(required=True, help="Printer used to print the labels.")
delete_component = fields.Boolean(
string="Delete existing components", default=False
)
def _start_sequence(self):
sequences = self.mapped("label_id.component_ids.sequence")
if sequences:
return max(sequences) + 1
return 0
def import_zpl2(self):
self.ensure_one()
Zpl2Component = self.env["printing.label.zpl2.component"]
if self.delete_component:
self.mapped("label_id.component_ids").unlink()
sequence = self._start_sequence()
default = {}
for i, line in enumerate(self.data.split("\n")):
vals = {}
args = line.split("^")
for arg in args:
for _key, code in SUPPORTED_CODE.items():
component_arg = code["method"](arg)
if component_arg:
if code.get("default", False):
for deft in code.get("default"):
default.update({deft: component_arg})
else:
vals.update(component_arg)
break
if vals:
if "component_type" not in vals.keys():
vals.update({"component_type": "text"})
if vals["component_type"] in default.keys():
vals.update(default[vals["component_type"]])
vals = self._update_vals(vals)
seq = sequence + i * 10
vals.update(
{
"name": _("Import %s") % seq,
"sequence": seq,
"model": str(zpl2.MODEL_ENHANCED),
"label_id": self.label_id.id,
}
)
Zpl2Component.create(vals)
def _update_vals(self, vals):
if "orientation" in vals.keys() and vals["orientation"] == "":
vals["orientation"] = "N"
# Field
Zpl2Component = self.env["printing.label.zpl2.component"]
model_fields = Zpl2Component.fields_get()
component = {}
for field, value in vals.items():
if field in model_fields.keys():
field_type = model_fields[field].get("type", False)
if field_type == "boolean":
if not value or value == zpl2.BOOL_NO:
value = False
else:
value = True
if field_type in ("integer", "float"):
value = float(value)
if field == "model":
value = int(float(value))
component.update({field: value})
return component
| 28.168618 | 12,028 |
2,424 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2016 SYLEAM (<http://www.syleam.fr>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class PrintRecordLabel(models.TransientModel):
_name = "wizard.print.record.label"
_description = "Print Record Label"
printer_id = fields.Many2one(
comodel_name="printing.printer",
string="Printer",
required=True,
help="Printer used to print the labels.",
)
label_id = fields.Many2one(
comodel_name="printing.label.zpl2",
string="Label",
required=True,
domain=lambda self: [
("model_id.model", "=", self.env.context.get("active_model"))
],
help="Label to print.",
)
active_model_id = fields.Many2one(
comodel_name="ir.model",
string="Model",
domain=lambda self: [("model", "=", self.env.context.get("active_model"))],
)
model = fields.Char(related="active_model_id.model", string="Model Name")
line_ids = fields.One2many("wizard.print.record.label.line", "label_header_id")
@api.model
def default_get(self, fields_list):
values = super(PrintRecordLabel, self).default_get(fields_list)
# Automatically select the printer and label, if only one is available
printers = self.env["printing.printer"].search(
[("id", "=", self.env.context.get("printer_zpl2_id"))]
)
if not printers:
printers = self.env["printing.printer"].search([])
if len(printers) == 1:
values["printer_id"] = printers.id
labels = self.env["printing.label.zpl2"].search(
[("model_id.model", "=", self.env.context.get("active_model"))]
)
if len(labels) == 1:
values["label_id"] = labels.id
return values
def print_label(self):
"""Prints a label per selected record"""
record_model = self.env.context["active_model"]
for record_id in self.env.context["active_ids"]:
record = self.env[record_model].browse(record_id)
self.label_id.print_label(self.printer_id, record)
class PrintRecordLabelLines(models.TransientModel):
_name = "wizard.print.record.label.line"
_description = "Print Record Label Line"
label_no = fields.Integer(string="# labels")
label_header_id = fields.Many2one(comodel_name="wizard.print.record.label")
| 35.647059 | 2,424 |
10,717 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2016 SYLEAM (<http://www.syleam.fr>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo import api, fields, models
from . import zpl2
_logger = logging.getLogger(__name__)
DEFAULT_PYTHON_CODE = """# Python One-Liners
# - object: %s record on which the action is triggered; may be void
# - page_number: Current Page
# - page_count: Total Page
# - time, datetime: Python libraries
# - write instead 'component_not_show' to don't show this component
# Example: object.name
""
"""
class PrintingLabelZpl2Component(models.Model):
_name = "printing.label.zpl2.component"
_description = "ZPL II Label Component"
_order = "sequence, id"
label_id = fields.Many2one(
comodel_name="printing.label.zpl2",
string="Label",
required=True,
ondelete="cascade",
help="Label using this component.",
)
sequence = fields.Integer(help="Order used to print the elements.")
name = fields.Char(required=True, help="Name of the component.")
origin_x = fields.Integer(
required=True,
default=10,
help="Origin point of the component in the label, X coordinate.",
)
origin_y = fields.Integer(
required=True,
default=10,
help="Origin point of the component in the label, Y coordinate.",
)
component_type = fields.Selection(
selection=[
("text", "Text"),
("rectangle", "Rectangle / Line"),
("diagonal", "Diagonal Line"),
("circle", "Circle"),
("graphic", "Graphic"),
(str(zpl2.BARCODE_CODE_11), "Code 11"),
(str(zpl2.BARCODE_INTERLEAVED_2_OF_5), "Interleaved 2 of 5"),
(str(zpl2.BARCODE_CODE_39), "Code 39"),
(str(zpl2.BARCODE_CODE_49), "Code 49"),
(str(zpl2.BARCODE_PDF417), "PDF417"),
(str(zpl2.BARCODE_EAN_8), "EAN-8"),
(str(zpl2.BARCODE_UPC_E), "UPC-E"),
(str(zpl2.BARCODE_CODE_128), "Code 128"),
(str(zpl2.BARCODE_EAN_13), "EAN-13"),
(str(zpl2.BARCODE_QR_CODE), "QR Code"),
("sublabel", "Sublabel"),
("zpl2_raw", "ZPL2"),
],
string="Type",
required=True,
default="text",
help="Type of content, simple text or barcode.",
)
font = fields.Selection(
selection=[
(str(zpl2.FONT_DEFAULT), "Default"),
(str(zpl2.FONT_9X5), "9x5"),
(str(zpl2.FONT_11X7), "11x7"),
(str(zpl2.FONT_18X10), "18x10"),
(str(zpl2.FONT_28X15), "28x15"),
(str(zpl2.FONT_26X13), "26x13"),
(str(zpl2.FONT_60X40), "60x40"),
(str(zpl2.FONT_21X13), "21x13"),
],
required=True,
default=str(zpl2.FONT_DEFAULT),
help="Font to use, for text only.",
)
thickness = fields.Integer(help="Thickness of the line to draw.")
color = fields.Selection(
selection=[(str(zpl2.COLOR_BLACK), "Black"), (str(zpl2.COLOR_WHITE), "White")],
default=str(zpl2.COLOR_BLACK),
help="Color of the line to draw.",
)
orientation = fields.Selection(
selection=[
(str(zpl2.ORIENTATION_NORMAL), "Normal"),
(str(zpl2.ORIENTATION_ROTATED), "Rotated"),
(str(zpl2.ORIENTATION_INVERTED), "Inverted"),
(str(zpl2.ORIENTATION_BOTTOM_UP), "Read from Bottom up"),
],
required=True,
default=str(zpl2.ORIENTATION_NORMAL),
help="Orientation of the barcode.",
)
diagonal_orientation = fields.Selection(
selection=[
(str(zpl2.DIAGONAL_ORIENTATION_LEFT), "Left (\\)"),
(str(zpl2.DIAGONAL_ORIENTATION_RIGHT), "Right (/)"),
],
default=str(zpl2.DIAGONAL_ORIENTATION_LEFT),
help="Orientation of the diagonal line.",
)
data_autofill = fields.Boolean(
string="Autofill Data",
help="Change 'data' with dictionary of the object information.",
)
check_digits = fields.Boolean(
help="Check if you want to compute and print the check digit."
)
height = fields.Integer(
help="Height of the printed component. For a text component, height "
"of a single character."
)
width = fields.Integer(
help="Width of the printed component. For a text component, width of "
"a single character."
)
rounding = fields.Integer(help="Rounding of the printed rectangle corners.")
interpretation_line = fields.Boolean(
help="Check if you want the interpretation line to be printed."
)
interpretation_line_above = fields.Boolean(
help="Check if you want the interpretation line to be printed above "
"the barcode."
)
module_width = fields.Integer(default=2, help="Module width for the barcode.")
bar_width_ratio = fields.Float(
default=3.0, help="Ratio between wide bar and narrow bar."
)
security_level = fields.Integer(help="Security level for error detection.")
columns_count = fields.Integer(help="Number of data columns to encode.")
rows_count = fields.Integer(help="Number of rows to encode.")
truncate = fields.Boolean(help="Check if you want to truncate the barcode.")
model = fields.Selection(
selection=[
(str(zpl2.MODEL_ORIGINAL), "Original"),
(str(zpl2.MODEL_ENHANCED), "Enhanced"),
],
default=str(zpl2.MODEL_ENHANCED),
help="Barcode model, used by some barcode types like QR Code.",
)
magnification_factor = fields.Integer(
default=1, help="Magnification Factor, from 1 to 10."
)
only_product_barcode = fields.Boolean("Only product barcode data")
error_correction = fields.Selection(
selection=[
(str(zpl2.ERROR_CORRECTION_ULTRA_HIGH), "Ultra-high Reliability Level"),
(str(zpl2.ERROR_CORRECTION_HIGH), "High Reliability Level"),
(str(zpl2.ERROR_CORRECTION_STANDARD), "Standard Level"),
(str(zpl2.ERROR_CORRECTION_HIGH_DENSITY), "High Density Level"),
],
required=True,
default=str(zpl2.ERROR_CORRECTION_HIGH),
help="Error correction for some barcode types like QR Code.",
)
mask_value = fields.Integer(default=7, help="Mask Value, from 0 to 7.")
model_id = fields.Many2one(
comodel_name="ir.model", compute="_compute_model_id", string="Record's model"
)
data = fields.Text(
default=lambda self: self._compute_default_data(),
required=True,
help="Data to print on this component. Resource values can be "
"inserted with %(object.field_name)s.",
)
sublabel_id = fields.Many2one(
comodel_name="printing.label.zpl2",
string="Sublabel",
help="Another label to include into this one as a component. "
"This allows to define reusable labels parts.",
)
repeat = fields.Boolean(
string="Repeatable",
help="Check this box to repeat this component on the label.",
)
repeat_offset = fields.Integer(
default=0, help="Number of elements to skip when reading a list of elements."
)
repeat_count = fields.Integer(
default=1, help="Maximum count of repeats of the component."
)
repeat_offset_x = fields.Integer(
help="X coordinate offset between each occurence of this component on "
"the label."
)
repeat_offset_y = fields.Integer(
help="Y coordinate offset between each occurence of this component on "
"the label."
)
reverse_print = fields.Boolean(
help="If checked, the data will be printed in the inverse color of "
"the background."
)
in_block = fields.Boolean(
help="If checked, the data will be restrected in a "
"defined block on the label."
)
block_width = fields.Integer(help="Width of the block.")
block_lines = fields.Integer(
default=1, help="Maximum number of lines to print in the block."
)
block_spaces = fields.Integer(
help="Number of spaces added between lines in the block."
)
block_justify = fields.Selection(
selection=[
(str(zpl2.JUSTIFY_LEFT), "Left"),
(str(zpl2.JUSTIFY_CENTER), "Center"),
(str(zpl2.JUSTIFY_JUSTIFIED), "Justified"),
(str(zpl2.JUSTIFY_RIGHT), "Right"),
],
string="Justify",
required=True,
default="L",
help="Choose how the text will be justified in the block.",
)
block_left_margin = fields.Integer(
string="Left Margin",
help="Left margin for the second and other lines in the block.",
)
graphic_image = fields.Binary(
string="Image",
attachment=True,
help="This field holds a static image to print. "
"If not set, the data field is evaluated.",
)
def process_model(self, model):
# Used for expansions of this module
return model
@api.depends("label_id.model_id")
def _compute_model_id(self):
# it's 'compute' instead of 'related' because is easier to expand it
for component in self:
component.model_id = self.process_model(component.label_id.model_id)
def _compute_default_data(self):
model_id = self.env.context.get("default_model_id") or self.model_id.id
model = self.env["ir.model"].browse(model_id)
model = self.process_model(model)
return DEFAULT_PYTHON_CODE % (model.model or "")
@api.onchange("model_id", "data")
def _onchange_data(self):
for component in self.filtered(lambda c: not c.data):
component.data = component._compute_default_data()
@api.onchange("component_type")
def _onchange_component_type(self):
for component in self:
if component.component_type == "qr_code":
component.data_autofill = True
else:
component.data_autofill = False
@api.model
def autofill_data(self, record, eval_args):
data = {}
usual_fields = ["id", "create_date", record.display_name]
for field in usual_fields:
if hasattr(record, field):
data[field] = getattr(record, field)
return data
def action_plus_origin_x(self):
self.ensure_one()
self.origin_x += 10
def action_minus_origin_x(self):
self.ensure_one()
self.origin_x -= 10
def action_plus_origin_y(self):
self.ensure_one()
self.origin_y += 10
def action_minus_origin_y(self):
self.ensure_one()
self.origin_y -= 10
| 36.576792 | 10,717 |
19,978 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2016 SYLEAM (<http://www.syleam.fr>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import base64
import io
import itertools
import logging
from collections import defaultdict
import requests
from PIL import Image, ImageOps
from odoo import _, api, exceptions, fields, models
from odoo.exceptions import ValidationError
from odoo.tools.safe_eval import safe_eval, wrap_module
from . import zpl2
_logger = logging.getLogger(__name__)
class PrintingLabelZpl2(models.Model):
_name = "printing.label.zpl2"
_description = "ZPL II Label"
_order = "model_id, name, id"
name = fields.Char(required=True, help="Label Name.")
active = fields.Boolean(default=True)
description = fields.Char(help="Long description for this label.")
model_id = fields.Many2one(
comodel_name="ir.model",
string="Model",
required=True,
ondelete="cascade",
help="Model used to print this label.",
)
origin_x = fields.Integer(
required=True,
default=10,
help="Origin point of the contents in the label, X coordinate.",
)
origin_y = fields.Integer(
required=True,
default=10,
help="Origin point of the contents in the label, Y coordinate.",
)
width = fields.Integer(
required=True,
default=480,
help="Width of the label, will be set on the printer before printing.",
)
component_ids = fields.One2many(
comodel_name="printing.label.zpl2.component",
inverse_name="label_id",
string="Label Components",
help="Components which will be printed on the label.",
copy=True,
)
restore_saved_config = fields.Boolean(
string="Restore printer's configuration",
help="Restore printer's saved configuration and end of each label ",
default=True,
)
action_window_id = fields.Many2one(
comodel_name="ir.actions.act_window",
string="Action",
readonly=True,
)
test_print_mode = fields.Boolean(string="Mode Print")
test_labelary_mode = fields.Boolean(string="Mode Labelary")
record_id = fields.Integer(string="Record ID", default=1)
extra = fields.Text(default="{}")
printer_id = fields.Many2one(comodel_name="printing.printer", string="Printer")
labelary_image = fields.Binary(
string="Image from Labelary", compute="_compute_labelary_image"
)
labelary_dpmm = fields.Selection(
selection=[
("6dpmm", "6dpmm (152 pdi)"),
("8dpmm", "8dpmm (203 dpi)"),
("12dpmm", "12dpmm (300 pdi)"),
("24dpmm", "24dpmm (600 dpi)"),
],
string="Print density",
required=True,
default="8dpmm",
)
labelary_width = fields.Float(string="Width in mm", default=140)
labelary_height = fields.Float(string="Height in mm", default=70)
@api.constrains("component_ids")
def check_recursion(self):
cr = self._cr
self.flush(["component_ids"])
query = (
'SELECT "{}", "{}" FROM "{}" '
'WHERE "{}" IN %s AND "{}" IS NOT NULL'.format(
"label_id",
"sublabel_id",
"printing_label_zpl2_component",
"label_id",
"sublabel_id",
)
)
succs = defaultdict(set) # transitive closure of successors
preds = defaultdict(set) # transitive closure of predecessors
todo, done = set(self.ids), set()
while todo:
cr.execute(query, [tuple(todo)]) # pylint: disable=E8103
done.update(todo)
todo.clear()
for id1, id2 in cr.fetchall():
for x, y in itertools.product(
[id1] + list(preds[id1]), [id2] + list(succs[id2])
):
if x == y:
raise ValidationError(_("You can not create recursive labels."))
succs[x].add(y)
preds[y].add(x)
if id2 not in done:
todo.add(id2)
def _get_component_data(self, record, component, eval_args):
if component.data_autofill:
return component.autofill_data(record, eval_args)
return safe_eval(str(component.data), eval_args) or ""
def _get_to_data_to_print(
self,
record,
page_number=1,
page_count=1,
label_offset_x=0,
label_offset_y=0,
**extra
):
to_print = []
for component in self.component_ids:
eval_args = extra
eval_args.update(
{
"object": record,
"page_number": str(page_number + 1),
"page_count": str(page_count),
"time": wrap_module(
__import__("time"), ["time", "strptime", "strftime"]
),
"datetime": wrap_module(
__import__("datetime"),
[
"date",
"datetime",
"time",
"timedelta",
"timezone",
"tzinfo",
"MAXYEAR",
"MINYEAR",
],
),
}
)
data = self._get_component_data(record, component, eval_args)
if isinstance(data, str) and data == "component_not_show":
continue
# Generate a list of elements if the component is repeatable
for idx in range(
component.repeat_offset,
component.repeat_offset + component.repeat_count,
):
printed_data = data
# Pick the right value if data is a collection
if isinstance(data, (list, tuple, set, models.BaseModel)):
# If we reached the end of data, quit the loop
if idx >= len(data):
break
# Set the real data to display
printed_data = data[idx]
position = idx - component.repeat_offset
to_print.append(
(
component,
printed_data,
label_offset_x + component.repeat_offset_x * position,
label_offset_y + component.repeat_offset_y * position,
)
)
return to_print
# flake8: noqa: C901
def _generate_zpl2_components_data(
self,
label_data,
record,
page_number=1,
page_count=1,
label_offset_x=0,
label_offset_y=0,
**extra
):
to_print = self._get_to_data_to_print(
record, page_number, page_count, label_offset_x, label_offset_y, **extra
)
for (component, data, offset_x, offset_y) in to_print:
component_offset_x = component.origin_x + offset_x
component_offset_y = component.origin_y + offset_y
if component.component_type == "text":
barcode_arguments = {
field_name: component[field_name]
for field_name in [
zpl2.ARG_FONT,
zpl2.ARG_ORIENTATION,
zpl2.ARG_HEIGHT,
zpl2.ARG_WIDTH,
zpl2.ARG_REVERSE_PRINT,
zpl2.ARG_IN_BLOCK,
zpl2.ARG_BLOCK_WIDTH,
zpl2.ARG_BLOCK_LINES,
zpl2.ARG_BLOCK_SPACES,
zpl2.ARG_BLOCK_JUSTIFY,
zpl2.ARG_BLOCK_LEFT_MARGIN,
]
}
label_data.font_data(
component_offset_x, component_offset_y, barcode_arguments, data
)
elif component.component_type == "zpl2_raw":
label_data._write_command(data)
elif component.component_type == "rectangle":
label_data.graphic_box(
component_offset_x,
component_offset_y,
{
zpl2.ARG_WIDTH: component.width,
zpl2.ARG_HEIGHT: component.height,
zpl2.ARG_THICKNESS: component.thickness,
zpl2.ARG_COLOR: component.color,
zpl2.ARG_ROUNDING: component.rounding,
},
)
elif component.component_type == "diagonal":
label_data.graphic_diagonal_line(
component_offset_x,
component_offset_y,
{
zpl2.ARG_WIDTH: component.width,
zpl2.ARG_HEIGHT: component.height,
zpl2.ARG_THICKNESS: component.thickness,
zpl2.ARG_COLOR: component.color,
zpl2.ARG_DIAGONAL_ORIENTATION: component.diagonal_orientation,
},
)
elif component.component_type == "graphic":
# During the on_change don't take the bin_size
image = (
component.with_context(bin_size_graphic_image=False).graphic_image
or data
)
try:
pil_image = Image.open(io.BytesIO(base64.b64decode(image))).convert(
"RGB"
)
except Exception:
continue
if component.width and component.height:
pil_image = pil_image.resize((component.width, component.height))
# Invert the colors
if component.reverse_print:
pil_image = ImageOps.invert(pil_image)
# Rotation (PIL rotates counter clockwise)
if component.orientation == zpl2.ORIENTATION_ROTATED:
pil_image = pil_image.transpose(Image.ROTATE_270)
elif component.orientation == zpl2.ORIENTATION_INVERTED:
pil_image = pil_image.transpose(Image.ROTATE_180)
elif component.orientation == zpl2.ORIENTATION_BOTTOM_UP:
pil_image = pil_image.transpose(Image.ROTATE_90)
label_data.graphic_field(
component_offset_x, component_offset_y, pil_image
)
elif component.component_type == "circle":
label_data.graphic_circle(
component_offset_x,
component_offset_y,
{
zpl2.ARG_DIAMETER: component.width,
zpl2.ARG_THICKNESS: component.thickness,
zpl2.ARG_COLOR: component.color,
},
)
elif component.component_type == "sublabel":
component_offset_x += component.sublabel_id.origin_x
component_offset_y += component.sublabel_id.origin_y
component.sublabel_id._generate_zpl2_components_data(
label_data,
data if isinstance(data, models.BaseModel) else record,
label_offset_x=component_offset_x,
label_offset_y=component_offset_y,
)
else:
if component.component_type == zpl2.BARCODE_QR_CODE:
# Adding Control Arguments to QRCode data Label
data = "{}A,{}".format(component.error_correction, data)
barcode_arguments = {
field_name: component[field_name]
for field_name in [
zpl2.ARG_ORIENTATION,
zpl2.ARG_CHECK_DIGITS,
zpl2.ARG_HEIGHT,
zpl2.ARG_INTERPRETATION_LINE,
zpl2.ARG_INTERPRETATION_LINE_ABOVE,
zpl2.ARG_SECURITY_LEVEL,
zpl2.ARG_COLUMNS_COUNT,
zpl2.ARG_ROWS_COUNT,
zpl2.ARG_TRUNCATE,
zpl2.ARG_MODULE_WIDTH,
zpl2.ARG_BAR_WIDTH_RATIO,
zpl2.ARG_MODEL,
zpl2.ARG_MAGNIFICATION_FACTOR,
zpl2.ARG_ERROR_CORRECTION,
zpl2.ARG_MASK_VALUE,
]
}
label_data.barcode_data(
component.origin_x + offset_x,
component.origin_y + offset_y,
component.component_type,
barcode_arguments,
data,
)
def _generate_zpl2_data(self, record, page_count=1, **extra):
self.ensure_one()
label_data = zpl2.Zpl2()
labelary_emul = extra.get("labelary_emul", False)
for page_number in range(page_count):
# Initialize printer's configuration
label_data.label_start()
if not labelary_emul:
label_data.print_width(self.width)
label_data.label_encoding()
label_data.label_home(self.origin_x, self.origin_y)
self._generate_zpl2_components_data(
label_data,
record,
page_number=page_number,
page_count=page_count,
**extra
)
# Restore printer's configuration and end the label
if self.restore_saved_config:
label_data.configuration_update(zpl2.CONF_RECALL_LAST_SAVED)
label_data.label_end()
return label_data.output()
def print_label(self, printer, record, page_count=1, **extra):
for label in self:
if record._name != label.model_id.model:
raise exceptions.UserError(
_("This label cannot be used on {model}").format(model=record._name)
)
# Send the label to printer
label_contents = label._generate_zpl2_data(
record, page_count=page_count, **extra
)
printer.print_document(
report=None, content=label_contents, doc_format="raw"
)
return True
@api.model
def new_action(self, model_id):
return self.env["ir.actions.act_window"].create(
{
"name": _("Print Label"),
"binding_model_id": model_id,
"res_model": "wizard.print.record.label",
"view_mode": "form",
"target": "new",
"binding_type": "action",
"context": "{'default_active_model_id': %s}" % model_id,
}
)
@api.model
def add_action(self, model_id):
action = self.env["ir.actions.act_window"].search(
[
("binding_model_id", "=", model_id),
("res_model", "=", "wizard.print.record.label"),
("view_mode", "=", "form"),
("binding_type", "=", "action"),
]
)
if not action:
action = self.new_action(model_id)
return action
def create_action(self):
models = self.filtered(lambda record: not record.action_window_id).mapped(
"model_id"
)
labels = self.with_context(active_test=False).search(
[("model_id", "in", models.ids), ("action_window_id", "=", False)]
)
actions = self.env["ir.actions.act_window"].search(
[
("binding_model_id", "in", models.ids),
("res_model", "=", "wizard.print.record.label"),
("view_mode", "=", "form"),
("binding_type", "=", "action"),
]
)
for model in models:
action = actions.filtered(lambda a: a.binding_model_id == model)
if not action:
action = self.new_action(model.id)
for label in labels.filtered(lambda l: l.model_id == model):
label.action_window_id = action
return True
def unlink_action(self):
self.mapped("action_window_id").unlink()
def import_zpl2(self):
self.ensure_one()
return {
"view_mode": "form",
"res_model": "wizard.import.zpl2",
"type": "ir.actions.act_window",
"target": "new",
"context": {"default_label_id": self.id},
}
def _get_record(self):
self.ensure_one()
Obj = self.env[self.model_id.model]
record = Obj.search([("id", "=", self.record_id)], limit=1)
if not record:
record = Obj.search([], limit=1, order="id desc")
self.record_id = record.id
return record
def print_test_label(self):
for label in self:
if label.test_print_mode and label.record_id and label.printer_id:
record = label._get_record()
extra = safe_eval(label.extra, {"env": self.env})
if record:
label.print_label(label.printer_id, record, **extra)
@api.depends(
"record_id",
"labelary_dpmm",
"labelary_width",
"labelary_height",
"component_ids",
"origin_x",
"origin_y",
"test_labelary_mode",
)
def _compute_labelary_image(self):
for label in self:
label.labelary_image = label._generate_labelary_image()
def _generate_labelary_image(self):
self.ensure_one()
if not (
self.test_labelary_mode
and self.record_id
and self.labelary_width
and self.labelary_height
and self.labelary_dpmm
and self.component_ids
):
return False
record = self._get_record()
if record:
# If case there an error (in the data field with the safe_eval
# for exemple) the new component or the update is not lost.
try:
url = (
"http://api.labelary.com/v1/printers/"
"{dpmm}/labels/{width}x{height}/0/"
)
width = round(self.labelary_width / 25.4, 2)
height = round(self.labelary_height / 25.4, 2)
url = url.format(dpmm=self.labelary_dpmm, width=width, height=height)
extra = safe_eval(self.extra, {"env": self.env})
zpl_file = self._generate_zpl2_data(record, labelary_emul=True, **extra)
files = {"file": zpl_file}
headers = {"Accept": "image/png"}
response = requests.post(url, headers=headers, files=files, stream=True)
if response.status_code == 200:
# Add a padd
im = Image.open(io.BytesIO(response.content))
im_size = im.size
new_im = Image.new(
"RGB", (im_size[0] + 2, im_size[1] + 2), (164, 164, 164)
)
new_im.paste(im, (1, 1))
imgByteArr = io.BytesIO()
new_im.save(imgByteArr, format="PNG")
return base64.b64encode(imgByteArr.getvalue())
else:
_logger.warning(
_("Error with Labelary API. %s") % response.status_code
)
except Exception as e:
_logger.warning(_("Error with Labelary API. %s") % e)
return False
| 37.980989 | 19,978 |
18,868 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2016 SYLEAM (<http://www.syleam.fr>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# Copied from https://github.com/subteno-it/python-zpl2, as there has been new releases
# that breaks current code without clear source (no commit on the repo). As the amount
# of code is not too much, we put it on the module itself, being able to control the
# whole chain, and to reduce the code with the considerations of current Odoo version
import binascii
import math
from PIL import ImageOps
# Constants for the printer configuration management
CONF_RELOAD_FACTORY = "F"
CONF_RELOAD_NETWORK_FACTORY = "N"
CONF_RECALL_LAST_SAVED = "R"
CONF_SAVE_CURRENT = "S"
# Command arguments names
ARG_FONT = "font"
ARG_HEIGHT = "height"
ARG_WIDTH = "width"
ARG_ORIENTATION = "orientation"
ARG_THICKNESS = "thickness"
ARG_BLOCK_WIDTH = "block_width"
ARG_BLOCK_LINES = "block_lines"
ARG_BLOCK_SPACES = "block_spaces"
ARG_BLOCK_JUSTIFY = "block_justify"
ARG_BLOCK_LEFT_MARGIN = "block_left_margin"
ARG_CHECK_DIGITS = "check_digits"
ARG_INTERPRETATION_LINE = "interpretation_line"
ARG_INTERPRETATION_LINE_ABOVE = "interpretation_line_above"
ARG_STARTING_MODE = "starting_mode"
ARG_SECURITY_LEVEL = "security_level"
ARG_COLUMNS_COUNT = "columns_count"
ARG_ROWS_COUNT = "rows_count"
ARG_TRUNCATE = "truncate"
ARG_MODE = "mode"
ARG_MODULE_WIDTH = "module_width"
ARG_BAR_WIDTH_RATIO = "bar_width_ratio"
ARG_REVERSE_PRINT = "reverse_print"
ARG_IN_BLOCK = "in_block"
ARG_COLOR = "color"
ARG_ROUNDING = "rounding"
ARG_DIAMETER = "diameter"
ARG_DIAGONAL_ORIENTATION = "diagonal_orientation"
ARG_MODEL = "model"
ARG_MAGNIFICATION_FACTOR = "magnification_factor"
ARG_ERROR_CORRECTION = "error_correction"
ARG_MASK_VALUE = "mask_value"
# Model values
MODEL_ORIGINAL = 1
MODEL_ENHANCED = 2
# Error Correction
ERROR_CORRECTION_ULTRA_HIGH = "H"
ERROR_CORRECTION_HIGH = "Q"
ERROR_CORRECTION_STANDARD = "M"
ERROR_CORRECTION_HIGH_DENSITY = "L"
# Boolean values
BOOL_YES = "Y"
BOOL_NO = "N"
# Orientation values
ORIENTATION_NORMAL = "N"
ORIENTATION_ROTATED = "R"
ORIENTATION_INVERTED = "I"
ORIENTATION_BOTTOM_UP = "B"
# Diagonal lines orientation values
DIAGONAL_ORIENTATION_LEFT = "L"
DIAGONAL_ORIENTATION_RIGHT = "R"
# Justify values
JUSTIFY_LEFT = "L"
JUSTIFY_CENTER = "C"
JUSTIFY_JUSTIFIED = "J"
JUSTIFY_RIGHT = "R"
# Font values
FONT_DEFAULT = "0"
FONT_9X5 = "A"
FONT_11X7 = "B"
FONT_18X10 = "D"
FONT_28X15 = "E"
FONT_26X13 = "F"
FONT_60X40 = "G"
FONT_21X13 = "H"
# Color values
COLOR_BLACK = "B"
COLOR_WHITE = "W"
# Barcode types
BARCODE_CODE_11 = "code_11"
BARCODE_INTERLEAVED_2_OF_5 = "interleaved_2_of_5"
BARCODE_CODE_39 = "code_39"
BARCODE_CODE_49 = "code_49"
BARCODE_PDF417 = "pdf417"
BARCODE_EAN_8 = "ean-8"
BARCODE_UPC_E = "upc-e"
BARCODE_CODE_128 = "code_128"
BARCODE_EAN_13 = "ean-13"
BARCODE_QR_CODE = "qr_code"
class Zpl2(object):
"""ZPL II management class
Allows to generate data for Zebra printers
"""
def __init__(self):
self.encoding = "utf-8"
self.initialize()
def initialize(self):
self._buffer = []
def output(self):
"""Return the full contents to send to the printer"""
return "\n".encode(self.encoding).join(self._buffer)
def _enforce(self, value, minimum=1, maximum=32000):
"""Returns the value, forced between minimum and maximum"""
return min(max(minimum, value), maximum)
def _write_command(self, data):
"""Adds a complete command to buffer"""
self._buffer.append(str(data).encode(self.encoding))
def _generate_arguments(self, arguments, kwargs):
"""Generate a zebra arguments from an argument names list and a dict of
values for these arguments
@param arguments : list of argument names, ORDER MATTERS
@param kwargs : list of arguments values
"""
command_arguments = []
# Add all arguments in the list, if they exist
for argument in arguments:
if kwargs.get(argument, None) is not None:
if isinstance(kwargs[argument], bool):
kwargs[argument] = kwargs[argument] and BOOL_YES or BOOL_NO
command_arguments.append(kwargs[argument])
# Return a zebra formatted string, with a comma between each argument
return ",".join(map(str, command_arguments))
def print_width(self, label_width):
"""Defines the print width setting on the printer"""
self._write_command("^PW%d" % label_width)
def configuration_update(self, active_configuration):
"""Set the active configuration on the printer"""
self._write_command("^JU%s" % active_configuration)
def label_start(self):
"""Adds the label start command to the buffer"""
self._write_command("^XA")
def label_encoding(self):
"""Adds the label encoding command to the buffer
Fixed value defined to UTF-8
"""
self._write_command("^CI28")
def label_end(self):
"""Adds the label start command to the buffer"""
self._write_command("^XZ")
def label_home(self, left, top):
"""Define the label top left corner"""
self._write_command("^LH%d,%d" % (left, top))
def _field_origin(self, right, down):
"""Define the top left corner of the data, from the top left corner of
the label
"""
return "^FO%d,%d" % (right, down)
def _font_format(self, font_format):
"""Send the commands which define the font to use for the current data"""
arguments = [ARG_FONT, ARG_HEIGHT, ARG_WIDTH]
# Add orientation in the font name (only place where there is
# no comma between values)
font_format[ARG_FONT] += font_format.get(ARG_ORIENTATION, ORIENTATION_NORMAL)
# Check that the height value fits in the allowed values
if font_format.get(ARG_HEIGHT) is not None:
font_format[ARG_HEIGHT] = self._enforce(font_format[ARG_HEIGHT], minimum=10)
# Check that the width value fits in the allowed values
if font_format.get(ARG_WIDTH) is not None:
font_format[ARG_WIDTH] = self._enforce(font_format[ARG_WIDTH], minimum=10)
# Generate the ZPL II command
return "^A" + self._generate_arguments(arguments, font_format)
def _field_block(self, block_format):
"""Define a maximum width to print some data"""
arguments = [
ARG_BLOCK_WIDTH,
ARG_BLOCK_LINES,
ARG_BLOCK_SPACES,
ARG_BLOCK_JUSTIFY,
ARG_BLOCK_LEFT_MARGIN,
]
return "^FB" + self._generate_arguments(arguments, block_format)
def _barcode_format(self, barcodeType, barcode_format):
"""Generate the commands to print a barcode
Each barcode type needs a specific function
"""
def _code11(**kwargs):
arguments = [
ARG_ORIENTATION,
ARG_CHECK_DIGITS,
ARG_HEIGHT,
ARG_INTERPRETATION_LINE,
ARG_INTERPRETATION_LINE_ABOVE,
]
return "1" + self._generate_arguments(arguments, kwargs)
def _interleaved2of5(**kwargs):
arguments = [
ARG_ORIENTATION,
ARG_HEIGHT,
ARG_INTERPRETATION_LINE,
ARG_INTERPRETATION_LINE_ABOVE,
ARG_CHECK_DIGITS,
]
return "2" + self._generate_arguments(arguments, kwargs)
def _code39(**kwargs):
arguments = [
ARG_ORIENTATION,
ARG_CHECK_DIGITS,
ARG_HEIGHT,
ARG_INTERPRETATION_LINE,
ARG_INTERPRETATION_LINE_ABOVE,
]
return "3" + self._generate_arguments(arguments, kwargs)
def _code49(**kwargs):
arguments = [
ARG_ORIENTATION,
ARG_HEIGHT,
ARG_INTERPRETATION_LINE,
ARG_STARTING_MODE,
]
# Use interpretation_line and interpretation_line_above to generate
# a specific interpretation_line value
if kwargs.get(ARG_INTERPRETATION_LINE) is not None:
if kwargs[ARG_INTERPRETATION_LINE]:
if kwargs[ARG_INTERPRETATION_LINE_ABOVE]:
# Interpretation line after
kwargs[ARG_INTERPRETATION_LINE] = "A"
else:
# Interpretation line before
kwargs[ARG_INTERPRETATION_LINE] = "B"
else:
# No interpretation line
kwargs[ARG_INTERPRETATION_LINE] = "N"
return "4" + self._generate_arguments(arguments, kwargs)
def _pdf417(**kwargs):
arguments = [
ARG_ORIENTATION,
ARG_HEIGHT,
ARG_SECURITY_LEVEL,
ARG_COLUMNS_COUNT,
ARG_ROWS_COUNT,
ARG_TRUNCATE,
]
return "7" + self._generate_arguments(arguments, kwargs)
def _ean8(**kwargs):
arguments = [
ARG_ORIENTATION,
ARG_HEIGHT,
ARG_INTERPRETATION_LINE,
ARG_INTERPRETATION_LINE_ABOVE,
]
return "8" + self._generate_arguments(arguments, kwargs)
def _upce(**kwargs):
arguments = [
ARG_ORIENTATION,
ARG_HEIGHT,
ARG_INTERPRETATION_LINE,
ARG_INTERPRETATION_LINE_ABOVE,
ARG_CHECK_DIGITS,
]
return "9" + self._generate_arguments(arguments, kwargs)
def _code128(**kwargs):
arguments = [
ARG_ORIENTATION,
ARG_HEIGHT,
ARG_INTERPRETATION_LINE,
ARG_INTERPRETATION_LINE_ABOVE,
ARG_CHECK_DIGITS,
ARG_MODE,
]
return "C" + self._generate_arguments(arguments, kwargs)
def _ean13(**kwargs):
arguments = [
ARG_ORIENTATION,
ARG_HEIGHT,
ARG_INTERPRETATION_LINE,
ARG_INTERPRETATION_LINE_ABOVE,
]
return "E" + self._generate_arguments(arguments, kwargs)
def _qrcode(**kwargs):
arguments = [
ARG_ORIENTATION,
ARG_MODEL,
ARG_MAGNIFICATION_FACTOR,
ARG_ERROR_CORRECTION,
ARG_MASK_VALUE,
]
return "Q" + self._generate_arguments(arguments, kwargs)
barcodeTypes = {
BARCODE_CODE_11: _code11,
BARCODE_INTERLEAVED_2_OF_5: _interleaved2of5,
BARCODE_CODE_39: _code39,
BARCODE_CODE_49: _code49,
BARCODE_PDF417: _pdf417,
BARCODE_EAN_8: _ean8,
BARCODE_UPC_E: _upce,
BARCODE_CODE_128: _code128,
BARCODE_EAN_13: _ean13,
BARCODE_QR_CODE: _qrcode,
}
return "^B" + barcodeTypes[barcodeType](**barcode_format)
def _barcode_field_default(self, barcode_format):
"""Add the data start command to the buffer"""
arguments = [
ARG_MODULE_WIDTH,
ARG_BAR_WIDTH_RATIO,
]
return "^BY" + self._generate_arguments(arguments, barcode_format)
def _field_data_start(self):
"""Add the data start command to the buffer"""
return "^FD"
def _field_reverse_print(self):
"""Allows the printed data to appear white over black, or black over white"""
return "^FR"
def _field_data_stop(self):
"""Add the data stop command to the buffer"""
return "^FS"
def _field_data(self, data):
"""Add data to the buffer, between start and stop commands"""
command = "{start}{data}{stop}".format(
start=self._field_data_start(),
data=data,
stop=self._field_data_stop(),
)
return command
def font_data(self, right, down, field_format, data):
"""Add a full text in the buffer, with needed formatting commands"""
reverse = ""
if field_format.get(ARG_REVERSE_PRINT, False):
reverse = self._field_reverse_print()
block = ""
if field_format.get(ARG_IN_BLOCK, False):
block = self._field_block(field_format)
command = "{origin}{font_format}{reverse}{block}{data}".format(
origin=self._field_origin(right, down),
font_format=self._font_format(field_format),
reverse=reverse,
block=block,
data=self._field_data(data),
)
self._write_command(command)
def barcode_data(self, right, down, barcodeType, barcode_format, data):
"""Add a full barcode in the buffer, with needed formatting commands"""
command = "{default}{origin}{barcode_format}{data}".format(
default=self._barcode_field_default(barcode_format),
origin=self._field_origin(right, down),
barcode_format=self._barcode_format(barcodeType, barcode_format),
data=self._field_data(data),
)
self._write_command(command)
def graphic_box(self, right, down, graphic_format):
"""Send the commands to draw a rectangle"""
arguments = [
ARG_WIDTH,
ARG_HEIGHT,
ARG_THICKNESS,
ARG_COLOR,
ARG_ROUNDING,
]
# Check that the thickness value fits in the allowed values
if graphic_format.get(ARG_THICKNESS) is not None:
graphic_format[ARG_THICKNESS] = self._enforce(graphic_format[ARG_THICKNESS])
# Check that the width value fits in the allowed values
if graphic_format.get(ARG_WIDTH) is not None:
graphic_format[ARG_WIDTH] = self._enforce(
graphic_format[ARG_WIDTH], minimum=graphic_format[ARG_THICKNESS]
)
# Check that the height value fits in the allowed values
if graphic_format.get(ARG_HEIGHT) is not None:
graphic_format[ARG_HEIGHT] = self._enforce(
graphic_format[ARG_HEIGHT], minimum=graphic_format[ARG_THICKNESS]
)
# Check that the rounding value fits in the allowed values
if graphic_format.get(ARG_ROUNDING) is not None:
graphic_format[ARG_ROUNDING] = self._enforce(
graphic_format[ARG_ROUNDING], minimum=0, maximum=8
)
# Generate the ZPL II command
command = "{origin}{data}{stop}".format(
origin=self._field_origin(right, down),
data="^GB" + self._generate_arguments(arguments, graphic_format),
stop=self._field_data_stop(),
)
self._write_command(command)
def graphic_diagonal_line(self, right, down, graphic_format):
"""Send the commands to draw a rectangle"""
arguments = [
ARG_WIDTH,
ARG_HEIGHT,
ARG_THICKNESS,
ARG_COLOR,
ARG_DIAGONAL_ORIENTATION,
]
# Check that the thickness value fits in the allowed values
if graphic_format.get(ARG_THICKNESS) is not None:
graphic_format[ARG_THICKNESS] = self._enforce(graphic_format[ARG_THICKNESS])
# Check that the width value fits in the allowed values
if graphic_format.get(ARG_WIDTH) is not None:
graphic_format[ARG_WIDTH] = self._enforce(
graphic_format[ARG_WIDTH], minimum=3
)
# Check that the height value fits in the allowed values
if graphic_format.get(ARG_HEIGHT) is not None:
graphic_format[ARG_HEIGHT] = self._enforce(
graphic_format[ARG_HEIGHT], minimum=3
)
# Check the given orientation
graphic_format[ARG_DIAGONAL_ORIENTATION] = graphic_format.get(
ARG_DIAGONAL_ORIENTATION, DIAGONAL_ORIENTATION_LEFT
)
# Generate the ZPL II command
command = "{origin}{data}{stop}".format(
origin=self._field_origin(right, down),
data="^GD" + self._generate_arguments(arguments, graphic_format),
stop=self._field_data_stop(),
)
self._write_command(command)
def graphic_circle(self, right, down, graphic_format):
"""Send the commands to draw a circle"""
arguments = [ARG_DIAMETER, ARG_THICKNESS, ARG_COLOR]
# Check that the diameter value fits in the allowed values
if graphic_format.get(ARG_DIAMETER) is not None:
graphic_format[ARG_DIAMETER] = self._enforce(
graphic_format[ARG_DIAMETER], minimum=3, maximum=4095
)
# Check that the thickness value fits in the allowed values
if graphic_format.get(ARG_THICKNESS) is not None:
graphic_format[ARG_THICKNESS] = self._enforce(
graphic_format[ARG_THICKNESS], minimum=2, maximum=4095
)
# Generate the ZPL II command
command = "{origin}{data}{stop}".format(
origin=self._field_origin(right, down),
data="^GC" + self._generate_arguments(arguments, graphic_format),
stop=self._field_data_stop(),
)
self._write_command(command)
def graphic_field(self, right, down, pil_image):
"""Encode a PIL image into an ASCII string suitable for ZPL printers"""
width, height = pil_image.size
rounded_width = int(math.ceil(width / 8.0) * 8)
# Transform the image :
# - Invert the colors (PIL uses 0 for black, ZPL uses 0 for white)
# - Convert to monochrome in case it is not already
# - Round the width to a multiple of 8 because ZPL needs an integer
# count of bytes per line (each pixel is a bit)
pil_image = (
ImageOps.invert(pil_image).convert("1").crop((0, 0, rounded_width, height))
)
# Convert the image to a two-character hexadecimal values string
ascii_data = binascii.hexlify(pil_image.tobytes()).upper()
# Each byte is composed of two characters
bytes_per_row = rounded_width / 8
total_bytes = bytes_per_row * height
graphic_image_command = (
"^GFA,{total_bytes},{total_bytes},{bytes_per_row},{ascii_data}".format(
total_bytes=total_bytes,
bytes_per_row=bytes_per_row,
ascii_data=ascii_data,
)
)
# Generate the ZPL II command
command = "{origin}{data}{stop}".format(
origin=self._field_origin(right, down),
data=graphic_image_command,
stop=self._field_data_stop(),
)
self._write_command(command)
| 36.636893 | 18,868 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
522 |
py
|
PYTHON
|
15.0
|
import setuptools
with open('VERSION.txt', 'r') as f:
version = f.read().strip()
setuptools.setup(
name="odoo-addons-oca-report-print-send",
description="Meta package for oca-report-print-send Odoo addons",
version=version,
install_requires=[
'odoo-addon-base_report_to_printer>=15.0dev,<15.1dev',
'odoo-addon-printer_zpl2>=15.0dev,<15.1dev',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Odoo',
'Framework :: Odoo :: 15.0',
]
)
| 27.473684 | 522 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
1,083 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Voxel",
"summary": "Base module for connecting with Voxel",
"version": "15.0.1.0.0",
"development_status": "Production/Stable",
"category": "Hidden",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/edi",
"license": "AGPL-3",
"depends": [
"account",
"product",
"report_xml",
"base_iso3166",
"queue_job",
"product_supplierinfo_for_customer",
],
"data": [
"security/voxel_security.xml",
"security/ir.model.access.csv",
"data/data_voxel_uom.xml",
"data/queue_job_channel_data.xml",
"views/res_company_view.xml",
"views/account_tax_views.xml",
"views/product_uom_views.xml",
"views/res_config_settings_views.xml",
"views/res_partner_views.xml",
"views/template_voxel_report.xml",
"views/voxel_login_views.xml",
],
"installable": True,
}
| 31.852941 | 1,083 |
939 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
mapping_channel_record_data = {
"voxel_export": "channel_voxel_export",
"voxel_import": "channel_voxel_import",
"voxel_status": "channel_voxel_status",
}
@openupgrade.migrate()
def migrate(env, version):
vals_list = []
domain = [
("name", "in", list(mapping_channel_record_data.keys())),
("parent_id", "=", env.ref("queue_job.channel_root").id),
]
for channel in env["queue.job.channel"].search(domain):
vals_list.append(
{
"noupdate": True,
"name": mapping_channel_record_data[channel.name],
"module": "edi_voxel_oca",
"model": "queue.job.channel",
"res_id": channel.id,
}
)
env["ir.model.data"].create(vals_list)
| 31.3 | 939 |
12,063 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from datetime import datetime
from urllib.parse import urljoin
import requests
from lxml import etree
from odoo import _, api, exceptions, fields, models
from odoo.modules.registry import Registry
_logger = logging.getLogger(__name__)
try:
from odoo.addons.queue_job.job import job
except ImportError:
_logger.debug("Can not `import queue_job`.")
import functools
def empty_decorator_factory(*argv, **kwargs):
return functools.partial
job = empty_decorator_factory
class VoxelMixin(models.AbstractModel):
_name = "voxel.mixin"
_description = "Voxel mixin"
voxel_state = fields.Selection(
selection=[
("not_sent", "Not sent"),
("sent", "Sent not verified"),
("sent_errors", "Sending error"),
("accepted", "Sent and accepted"),
("processing_error", "Processing error"),
("cancelled", "Cancelled"),
],
string="Voxel send state",
default="not_sent",
readonly=True,
copy=False,
help="Indicates the status of sending report to Voxel",
)
voxel_xml_report = fields.Text(string="XML Report", readonly=True)
voxel_filename = fields.Char(readonly=True)
processing_error = fields.Text(readonly=True)
# Export methods
# --------------
def enqueue_voxel_report(self, report_name):
eta = self.company_id._get_voxel_report_eta()
queue_obj = self.env["queue.job"].sudo()
for record in self.sudo():
# Look first if there's a failing job. If so, retry that one
failing_job = record.voxel_job_ids.filtered(lambda x: x.state == "failed")[
:1
]
if failing_job:
failing_job.voxel_requeue_sudo()
continue
# If not, create a new one
new_delay = (
record.with_context(company_id=self.company_id.id)
.with_delay(eta=eta)
._get_and_send_voxel_report(report_name)
)
job = queue_obj.search([("uuid", "=", new_delay.uuid)], limit=1)
record.voxel_job_ids |= job
def _get_and_send_voxel_report(self, report_name):
self.ensure_one()
report = self.env.ref(report_name)
report_xml = report._render_qweb_xml(self.ids, {})[0]
# Remove blank spaces
tree = etree.fromstring(report_xml, etree.XMLParser(remove_blank_text=True))
clean_report_xml = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
file_name = self._get_voxel_filename()
self._send_voxel_report("Outbox", file_name, clean_report_xml)
self.write(
{
"voxel_state": "sent",
"voxel_filename": file_name,
"voxel_xml_report": report_xml,
}
)
# export error detection methods
# ------------------------------
def _cron_update_voxel_export_status(self):
for company in self.env["res.company"].search([]):
if company.voxel_enabled and self.get_voxel_login(company):
self._update_voxel_export_status(company)
def _update_voxel_export_status(self, company):
sent_docs = self.search([("voxel_state", "=", "sent")])
if not sent_docs:
return
queue_obj = self.env["queue.job"].sudo()
# Determine processed documents
filenames = self._list_voxel_document_filenames("Outbox", company)
processed = sent_docs.filtered(lambda r: r.voxel_filename not in filenames)
# Determine documents with errors
filenames = self._list_voxel_document_filenames("Error", company)
with_errors = processed.filtered(lambda r: r.voxel_filename in filenames)
doc_dict = {}
for doc in with_errors:
if doc.voxel_filename:
doc_dict[doc.voxel_filename] = doc
for filename in filenames:
if filename.endswith(".log"):
xml_file_name = filename[:-4] + ".xml"
if xml_file_name in doc_dict:
document = doc_dict[xml_file_name]
# Look first if there's a job for the current filename.
# If not, create it
file_job = queue_obj.search(
[("channel", "=", "root.voxel_status")]
).filtered(lambda r: r.args == [filename, company])[:1]
if not file_job:
error_msg = (
document.with_context(company_id=company.id)
.with_delay()
._update_error_status(company, filename)
)
# search queue job to add it to voxel job list
document.voxel_job_ids |= queue_obj.search(
[("uuid", "=", error_msg.uuid)], limit=1
)
# Update state of accepted documents
(processed - with_errors).write({"voxel_state": "accepted"})
def _update_error_status(self, company, filename):
processing_error_log = self._read_voxel_document(
"Error", company, filename, "ISO-8859-1"
)
# Update state of documents with errors
self.write(
{
"processing_error": processing_error_log,
"voxel_state": "processing_error",
}
)
# Delete error files from Voxel
self._delete_voxel_document("Error", filename, company)
self._delete_voxel_document("Error", filename[:-4] + ".xml", company)
self._delete_voxel_document("Error", filename[:-4] + ".utlog", company)
# Import methods
# --------------
def enqueue_import_voxel_documents(self, company):
queue_job_obj = self.env["queue.job"]
# list document names
voxel_filenames = self._list_voxel_document_filenames("Inbox", company)
# iterate the list to import documents one by one
for voxel_filename in voxel_filenames:
# Look first if there's a job for the current filename.
# If not, create it
file_job = queue_job_obj.search(
[("channel", "=", "root.voxel_import")]
).filtered(lambda r: r.args == [voxel_filename, company])[:1]
if not file_job:
self.with_context(
company_id=company.id
).with_delay()._import_voxel_document(voxel_filename, company)
def _import_voxel_document(self, voxel_filename, company):
content = self._read_voxel_document("Inbox", company, voxel_filename)
# call method that parse and create the document from the content
doc = self.create_document_from_xml(content, voxel_filename, company)
if doc:
# write file content in the created object
doc.write({"voxel_xml_report": content, "voxel_filename": voxel_filename})
# Delete file from Voxel
self._delete_voxel_document("Inbox", voxel_filename, company)
def create_document_from_xml(self, xml_content, voxel_filename, company):
"""This method must be overwritten by the model that use
`enqueue_import_voxel_documents` method"""
return False
# API request methods
# --------------------
def _request_to_voxel(
self, request_method, folder, company=None, voxel_filename=None, data=None
):
login = self.get_voxel_login(company)
if not login:
raise Exception
url = urljoin(login.url, folder)
url += url.endswith("/") and "" or "/"
response = request_method(
url=urljoin(url, voxel_filename),
auth=(login.user, login.password),
data=data,
)
_logger.debug("Voxel request response: %s", str(response))
if response.status_code != 200:
response.raise_for_status()
return response
def _send_voxel_report(self, folder, file_name, file_data):
try:
self._request_to_voxel(
requests.put, folder, voxel_filename=file_name, data=file_data
)
except Exception:
new_cr = Registry(self.env.cr.dbname).cursor()
env = api.Environment(new_cr, self.env.uid, self.env.context)
record = env[self._name].browse(self.id)
record.voxel_state = "sent_errors"
new_cr.commit()
new_cr.close()
raise
def _list_voxel_document_filenames(self, folder, company):
try:
response = self._request_to_voxel(requests.get, folder, company)
except Exception as exc:
raise Exception(
"Error reading '{}' folder from Voxel".format(folder)
) from exc
# if no error, return list of documents file names
content = response.content
return content and content.decode("utf-8").split("\n") or []
def _read_voxel_document(self, folder, company, filename, encoding="utf-8"):
try:
response = self._request_to_voxel(requests.get, folder, company, filename)
except Exception as exc:
raise Exception(
"Error reading document {} from folder {}".format(filename, folder)
) from exc
# Getting xml content with utf8 there are characters that can not
# be decoded, so 'ISO-8859-1' is used
return response.content.decode(encoding)
def _delete_voxel_document(self, folder, voxel_filename, company):
try:
self._request_to_voxel(requests.delete, folder, company, voxel_filename)
except Exception as exc:
raise Exception(
"Error deleting document {} from folder {}".format(
voxel_filename, folder
)
) from exc
# auxiliary methods
# -----------------
def _get_voxel_filename(self):
self.ensure_one()
document_type = self.get_document_type()
date_time_seq = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]
return "{}_{}.xml".format(document_type, date_time_seq)
def _cancel_voxel_jobs(self):
# Remove not started jobs
not_started_jobs = self.env["queue.job"]
for queue in self.mapped("voxel_job_ids"):
if queue.state == "started":
raise exceptions.Warning(
_(
"This operation cannot be performed because there are "
"jobs running therefore cannot be unlinked."
)
)
else:
not_started_jobs |= queue
not_started_jobs.unlink()
# set voxel state to cancelled
self.write({"voxel_state": "cancelled"})
def get_voxel_login(self, company=None):
"""This method must be overwritten by the model that inherit from
voxel.mixin"""
return self.env["voxel.login"]
def _get_customer_product_sku(self, product, partner):
"""Look for an entry for specific contact (sending/invoicing contact),
and if not found, look for the commercial partner.
"""
domain = [
"|",
("product_id", "=", product.id),
"&",
("product_tmpl_id", "=", product.product_tmpl_id.id),
("product_id", "=", False),
]
customerinfo = self.env["product.customerinfo"].search(
[("name", "=", partner.id)] + domain,
order="product_id, sequence",
)
if not customerinfo:
customerinfo = self.env["product.customerinfo"].search(
[("name", "=", partner.commercial_partner_id.id)] + domain,
order="product_id, sequence",
)
return customerinfo[:1].product_code
| 40.21 | 12,063 |
478 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class QueueJob(models.Model):
_inherit = "queue.job"
def voxel_do_now(self):
self.sudo().write({"eta": False})
def voxel_cancel_now(self):
self.sudo().filtered(
lambda x: x.state in ["pending", "enqueued", "failed"]
).unlink()
def voxel_requeue_sudo(self):
self.sudo().requeue()
| 23.9 | 478 |
1,630 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import datetime, timedelta
import pytz
from odoo import fields, models
class Company(models.Model):
_inherit = "res.company"
voxel_enabled = fields.Boolean(string="Enable Voxel")
voxel_send_mode = fields.Selection(
string="Send mode",
selection=[
("auto", "On validate"),
("fixed", "At fixed time"),
("delayed", "With delay"),
],
default="auto",
)
voxel_sent_time = fields.Float(string="Sent time")
voxel_delay_time = fields.Float(string="Delay time")
voxel_login_ids = fields.One2many(
comodel_name="voxel.login",
inverse_name="company_id",
string="Voxel logins",
)
def _get_voxel_report_eta(self):
if self.voxel_send_mode == "fixed":
tz = self.env.context.get("tz", self.env.user.partner_id.tz)
offset = datetime.now(pytz.timezone(tz)).strftime("%z") if tz else "+00"
hour_diff = int(offset[:3])
hour, minute = divmod(self.voxel_sent_time * 60, 60)
hour = int(hour - hour_diff)
minute = int(minute)
now = datetime.now()
if now.hour > hour or (now.hour == hour and now.minute > minute):
now += timedelta(days=1)
now = now.replace(hour=hour, minute=minute)
return now
elif self.voxel_send_mode == "delayed":
return datetime.now() + timedelta(hours=self.voxel_delay_time)
else:
return None
| 33.958333 | 1,630 |
590 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
VOXEL_CODE = [
("Unidades", "Units"),
("Kgs", "Kgs"),
("Lts", "Liters"),
("Lbs", "Lbs"),
("Cajas", "Boxes"),
("Bultos", "Packages"),
("Palets", "Pallets"),
("Horas", "Hours"),
("Metros", "Meters"),
("MetrosCuadrados", "Square meters"),
("Contenedores", "Containers"),
("Otros", "Others"),
]
class UoM(models.Model):
_inherit = "uom.uom"
voxel_code = fields.Selection(selection=VOXEL_CODE)
| 23.6 | 590 |
530 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
voxel_send_mode = fields.Selection(
related="company_id.voxel_send_mode", readonly=False
)
voxel_sent_time = fields.Float(related="company_id.voxel_sent_time", readonly=False)
voxel_delay_time = fields.Float(
related="company_id.voxel_delay_time", readonly=False
)
| 33.125 | 530 |
483 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class VoxelLogin(models.Model):
_name = "voxel.login"
_description = "Voxel login"
name = fields.Char(required=True)
url = fields.Char(string="URL", required=True)
user = fields.Char(required=True)
password = fields.Char(required=True)
company_id = fields.Many2one(comodel_name="res.company", string="Company")
| 32.2 | 483 |
574 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
voxel_enabled = fields.Boolean(string="Enable Voxel")
def _commercial_fields(self):
return super()._commercial_fields() + ["voxel_enabled"]
def _get_voxel_vat(self):
"""Rip initial ES prefix if exists."""
self.ensure_one()
vat = self.vat or ""
if vat.startswith("ES"):
return vat[2:]
return vat
| 27.333333 | 574 |
2,105 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountTax(models.Model):
_inherit = "account.tax"
voxel_tax_code = fields.Selection(
selection=[
("IVA", "(IVA) IVA"),
("IGIC", "(IGIC) IGIC"),
("IRPF", "(IRPF) IRPF"),
("RE", "(RE) Recargo de equivalencia"),
(
"ITPAJD",
"(ITPAJD) Impuesto sobre transmisiones patrimoniales y "
"actos jurídicos documentados",
),
("IE", "(IE) Impuestos especiales"),
("RA", "(RA) Renta aduanas"),
(
"IGTECM",
"(IGTECM) Impuesto general sobre el tráfico de "
"empresas que se aplica en Ceuta y Melilla",
),
(
"IECDPCAC",
"(IECDPCAC) Impuesto especial sobre los combustibles "
"derivados del petróleo en la comunidad Autónoma "
"Canaria",
),
(
"IIIMAB",
"(IIIMAB) Impuesto sobre las instalaciones que inciden "
"sobre le medio ambiente en las Baleares",
),
(
"ICIO",
"(ICIO) Impuesto sobre las construcciones, instalaciones " "y obras",
),
(
"IMVDN",
"(IMVDN) Impuesto municipal sobre las viviendas "
"desocupadas en Navarra",
),
("IMSN", "(IMSN) Impuesto municipal sobre solares en Navarra"),
(
"IMGSN",
"(IMGSN) Impuesto municipal sobre gastos " "suntuarios en Navarra",
),
("IMPN", "(IMPN) Impuesto municipal sobre publicidad en Navarra"),
("IBA", "(IBA) Impuesto sobre bebidas alcohólicas"),
("IHC", "(IHC) Impuesto sobre harinas cárnicas"),
("EXENTO", "(EXENTO) Exento"),
("OTRO", "(OTRO) Otro"),
],
)
| 35.576271 | 2,099 |
592 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE
# @author: Simone Orsi <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Base EDI",
"summary": """Base module to aggregate EDI features.""",
"version": "15.0.1.0.0",
"development_status": "Beta",
"website": "https://github.com/OCA/edi",
"license": "LGPL-3",
"author": "ACSONE,Odoo Community Association (OCA)",
"maintainers": ["simahawk"],
"depends": ["base"],
"data": [
"data/module_category.xml",
"security/edi_groups.xml",
"views/edi_menu.xml",
],
}
| 29.6 | 592 |
715 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Voxel stock picking",
"summary": "Sends stock picking report to Voxel.",
"version": "15.0.1.0.0",
"category": "Warehouse Management",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/edi",
"license": "AGPL-3",
"depends": ["edi_voxel_oca", "product_expiry", "sale_stock"],
"data": [
"data/ir_cron_data.xml",
"views/report_voxel_picking.xml",
"views/stock_picking_views.xml",
"views/res_company_view.xml",
"views/res_config_settings_views.xml",
],
"installable": True,
}
| 35.75 | 715 |
9,247 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import datetime
from odoo.tests import Form
from odoo.tests.common import TransactionCase
class TestVoxelStockPickingCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
# Sale order company
country = cls.env["res.country"].create({"name": "Country", "code": "CT"})
state = cls.env["res.country.state"].create(
{"name": "Province", "code": "PRC", "country_id": country.id}
)
cls.main_company = cls.env.ref("base.main_company")
cls.main_company.write(
{
"vat": "US1234567890",
"street": "Street 1",
"street2": "Street 2",
"name": "YourCompany",
"city": "City",
"zip": "99999",
"state_id": state.id,
"country_id": country.id,
"email": "[email protected]",
}
)
# Sale order client
cls.partner = cls.env["res.partner"].create(
{
"ref": "C01",
"vat": "BE0123456789",
"name": "Client (test)",
"email": "[email protected]",
"street": "Street 1",
"street2": "Street 2",
"city": "City (test)",
"zip": "10000",
"state_id": cls.env.ref("base.state_us_49").id,
"country_id": cls.env.ref("base.us").id,
}
)
cls.product = cls.env["product.product"].create(
{"default_code": "DC_001", "name": "Product 1 (test)", "type": "product"}
)
cls.env["product.customerinfo"].create(
{
"name": cls.partner.id,
"product_tmpl_id": cls.product.product_tmpl_id.id,
"product_id": cls.product.id,
"product_code": "1234567891234",
}
)
cls.product2 = cls.env["product.product"].create(
{
"default_code": "DC_002",
"name": "Product 2 (test)",
"type": "product",
"tracking": "lot",
}
)
cls.lot = cls.env["stock.production.lot"].create(
{
"name": "LOT01",
"product_id": cls.product2.id,
"expiration_date": "2020-01-01 12:05:23",
"company_id": cls.main_company.id,
}
)
# Create Sales Order
cls.sale_order = cls._create_sale_order()
# Confirm quotation
cls.sale_order.action_confirm()
# Validate picking
cls.picking = cls.sale_order.picking_ids
cls.picking.write(
{
"name": "Picking name (test)",
"date": datetime(2020, 1, 7),
"company_id": cls.main_company.id,
"note": "Picking note (test)",
}
)
sm = cls.picking.move_lines[0]
sm.write({"quantity_done": sm.product_uom_qty})
sm = cls.picking.move_lines[1]
sm.write({"quantity_done": sm.product_uom_qty})
sm.move_line_ids.lot_id = cls.lot.id
backorder_wizard_dict = cls.picking.button_validate()
# pylint: disable=W8121
backorder_wizard = Form(
cls.env[backorder_wizard_dict["res_model"]].with_context(
backorder_wizard_dict["context"]
)
).save()
backorder_wizard.process()
@classmethod
def _create_sale_order(cls):
sale_order = cls.env["sale.order"].create(
{
"name": "Sale order name (test)",
"partner_id": cls.partner.id,
"company_id": cls.main_company.id,
"order_line": [
(
0,
0,
{
"product_id": cls.product.id,
"product_uom_qty": 2,
"product_uom": cls.product.uom_id.id,
"price_unit": 750,
},
),
(
0,
0,
{
"product_id": cls.product2.id,
"product_uom_qty": 1,
"product_uom": cls.product2.uom_id.id,
"price_unit": 50,
},
),
],
}
)
return sale_order
class TestVoxelStockPicking(TestVoxelStockPickingCommon):
def test_get_voxel_filename(self):
bef = datetime.now()
bef = datetime(
bef.year,
bef.month,
bef.day,
bef.hour,
bef.minute,
bef.second,
(bef.microsecond // 1000) * 1000,
)
filename = self.picking._get_voxel_filename()
document_type, date_time = filename[:-4].split("_", 1)
date_time = datetime.strptime(date_time, "%Y%m%d_%H%M%S_%f")
self.assertEqual(document_type, "Albaran")
self.assertGreaterEqual(date_time, bef)
def test_get_report_values(self):
# Get report data
model_name = "report.edi_voxel_stock_picking_oca.template_voxel_picking"
report_edi_obj = self.env[model_name]
report_data = report_edi_obj._get_report_values(self.picking.ids)
# Get expected data
expected = self._get_picking_data()
# Check data
self.assertDictEqual(report_data["general"], expected["general"])
self.assertDictEqual(report_data["supplier"], expected["supplier"])
self.assertDictEqual(report_data["client"], expected["client"])
self.assertListEqual(report_data["customers"], expected["customers"])
self.assertListEqual(report_data["comments"], expected["comments"])
self.assertListEqual(report_data["references"], expected["references"])
self.assertListEqual(report_data["products"], expected["products"])
def _get_picking_data(self):
return {
"general": self._get_general_data(),
"supplier": self._get_suplier_data(),
"client": self._get_client_data(),
"customers": self._get_customers_data(),
"comments": self._get_comments_data(),
"references": self._get_references_data(),
"products": self._get_products_data(),
}
# report data. Auxiliary methods
# ------------------------------
def _get_general_data(self):
return {
"Type": "AlbaranComercial",
"Ref": "Picking name (test)",
"Date": "2020-01-07",
}
def _get_suplier_data(self):
return {
"CIF": "US1234567890",
"Company": "YourCompany",
"Address": "Street 1, Street 2",
"City": "City",
"PC": "99999",
"Province": "Province",
"Country": "CT",
"Email": "[email protected]",
}
def _get_client_data(self):
return {
"SupplierClientID": "C01",
"CIF": "BE0123456789",
"Company": "Client (test)",
"Address": "Street 1, Street 2",
"City": "City (test)",
"PC": "10000",
"Province": "West Virginia",
"Country": "USA",
"Email": "[email protected]",
}
def _get_customers_data(self):
return [
{
"SupplierClientID": "C01",
"SupplierCustomerID": "C01",
"Customer": "Client (test)",
"Address": "Street 1, Street 2",
"City": "City (test)",
"PC": "10000",
"Province": "West Virginia",
"Country": "USA",
"Email": "[email protected]",
}
]
def _get_comments_data(self):
return [{"Msg": "<p>Picking note (test)</p>"}]
def _get_references_data(self):
return [{"PORef": "Sale order name (test)"}]
def _get_products_data(self):
return [
{
"product": {
"SupplierSKU": "DC_001",
"CustomerSKU": "1234567891234",
"Item": "Product 1 (test)",
"Qty": "2.0",
"MU": "Unidades",
},
},
{
"product": {
"SupplierSKU": "DC_002",
"CustomerSKU": False,
"Item": "Product 2 (test)",
"Qty": "1.0",
"MU": "Unidades",
"TraceabilityList": [
{
"BatchNumber": "LOT01",
"ExpirationDate": "2020-01-01",
"Quantity": 1.0,
}
],
},
},
]
| 35.026515 | 9,247 |
319 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class Company(models.Model):
_inherit = "res.company"
voxel_picking_login_id = fields.Many2one(
string="Stock picking login", comodel_name="voxel.login"
)
| 26.583333 | 319 |
2,929 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class Picking(models.Model):
_name = "stock.picking"
_inherit = ["stock.picking", "voxel.mixin"]
voxel_enabled = fields.Boolean(
compute="_compute_voxel_enabled",
search="_search_voxel_enabled",
)
voxel_job_ids = fields.Many2many(
comodel_name="queue.job",
relation="stock_picking_voxel_job_rel",
column1="picking_id",
column2="voxel_job_id",
string="Jobs",
copy=False,
)
def get_voxel_login(self, company=None):
"""This method overwrites the one defined in voxel.mixin to provide
the login for this specific model (stock.picking)
"""
return (company or self.company_id).voxel_picking_login_id
def _compute_voxel_enabled(self):
for record in self:
record.voxel_enabled = (
record.company_id.voxel_enabled
and record.partner_id.voxel_enabled
and record.picking_type_code == "outgoing"
)
def _search_voxel_enabled(self, operator, value):
if (operator == "=" and value) or (operator == "!=" and not value):
domain = [
("company_id.voxel_enabled", "=", True),
("partner_id.voxel_enabled", "=", True),
("picking_type_code", "=", "outgoing"),
]
else:
domain = [
"|",
"|",
("company_id.voxel_enabled", "=", False),
("partner_id.voxel_enabled", "=", False),
("picking_type_code", "!=", "outgoing"),
]
return [("id", "in", self.search(domain).ids)]
def action_done(self):
res = super(Picking, self).action_done()
for picking in self.filtered(lambda p: p.picking_type_code == "outgoing"):
picking.action_send_to_voxel()
return res
def action_cancel(self):
self._cancel_voxel_jobs()
return super().action_cancel()
def action_send_to_voxel(self):
# Check if it is a return picking
def able_to_voxel(record):
enabled = record.voxel_enabled
type_code = record.picking_type_code
is_outgoing = type_code == "outgoing"
is_incoming_returned = type_code == "incoming" and bool(
record.move_lines.mapped("origin_returned_move_id")
)
return enabled and (is_outgoing or is_incoming_returned)
pickings = self.filtered(able_to_voxel)
if pickings:
pickings.enqueue_voxel_report(
"edi_voxel_stock_picking_oca.report_voxel_picking"
)
def get_document_type(self):
"""Document type name to be used in the name of the Voxel report"""
return "Albaran"
| 34.869048 | 2,929 |
349 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
voxel_picking_login_id = fields.Many2one(
related="company_id.voxel_picking_login_id", readonly=False
)
| 29.083333 | 349 |
4,767 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class ReportVoxelPicking(models.AbstractModel):
_name = "report.edi_voxel_stock_picking_oca.template_voxel_picking"
_inherit = "report.report_xml.abstract"
_description = "Edi Voxel Stock picking Report"
@api.model
def _get_report_values(self, docids, data=None):
docs = self.env["stock.picking"].browse(docids[:1])
return {
"general": self._get_general_data(docs),
"supplier": self._get_suplier_data(docs),
"client": self._get_client_data(docs),
"customers": self._get_customers_data(docs),
"comments": self._get_comments_data(docs),
"references": self._get_references_data(docs),
"products": self._get_products_data(docs),
}
# report data. Auxiliary methods
# ------------------------------
def _get_general_data(self, picking):
type_mapping = {"outgoing": "AlbaranComercial", "incoming": "AlbaranAbono"}
return {
"Type": type_mapping.get(picking.picking_type_code),
"Ref": picking.name,
"Date": picking.date and picking.date.strftime("%Y-%m-%d") or "",
}
def _get_suplier_data(self, picking):
supplier = picking.company_id.partner_id
return {
"CIF": supplier._get_voxel_vat(),
"Company": supplier.name,
"Address": ", ".join(filter(None, [supplier.street, supplier.street2])),
"City": supplier.city,
"PC": supplier.zip,
"Province": supplier.state_id.name,
"Country": supplier.country_id.code,
"Email": supplier.email,
}
def _get_client_data(self, picking):
client = picking.sale_id.partner_invoice_id or picking.partner_id
return {
"SupplierClientID": client.ref,
"CIF": client._get_voxel_vat(),
"Company": client.commercial_partner_id.name,
"Address": ", ".join(filter(None, [client.street, client.street2])),
"City": client.city,
"PC": client.zip,
"Province": client.state_id.name,
"Country": client.country_id.code_alpha3,
"Email": client.email,
}
def _get_customers_data(self, picking):
customer = picking.partner_id
client = picking.sale_id.partner_invoice_id or picking.partner_id
return [
{
"SupplierClientID": client.ref,
"SupplierCustomerID": customer.ref,
"Customer": customer.name,
"Address": ", ".join(filter(None, [customer.street, customer.street2])),
"City": customer.city,
"PC": customer.zip,
"Province": customer.state_id.name,
"Country": customer.country_id.code_alpha3,
"Email": customer.email,
}
]
def _get_comments_data(self, picking):
return picking.note and [{"Msg": picking.note}] or []
def _get_references_data(self, picking):
so = picking.sale_id
return [{"PORef": (so.client_order_ref or so.name) if so else picking.origin}]
def _get_products_data(self, picking):
lines = picking.move_lines.filtered(lambda x: x.state == "done")
return [{"product": self._get_product_data(line)} for line in lines]
def _get_product_data(self, line):
customer_sku = line.picking_id._get_customer_product_sku(
line.product_id, line.picking_id.partner_id
)
if not customer_sku:
customer_sku = line.picking_id._get_customer_product_sku(
line.product_id, line.picking_id.sale_id.partner_invoice_id
)
vals = {
"SupplierSKU": line.product_id.default_code,
"CustomerSKU": customer_sku,
"Item": line.product_id.name,
"Qty": str(line.product_uom_qty),
"MU": line.product_uom.voxel_code,
}
traceability_vals = self._get_traceability(line)
if traceability_vals:
vals["TraceabilityList"] = traceability_vals
return vals
def _get_traceability(self, line):
if line.product_id.tracking == "none":
return []
return [
{
"BatchNumber": ml.lot_id.name,
"ExpirationDate": (
ml.lot_id.expiration_date
and ml.lot_id.expiration_date.strftime("%Y-%m-%d")
or ""
),
"Quantity": ml.qty_done,
}
for ml in line.move_line_ids
]
| 38.443548 | 4,767 |
647 |
py
|
PYTHON
|
15.0
|
# Copyright 2016-2021 Akretion France (http://www.akretion.com/)
# @author: Alexis de Lattre <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Base Factur-X",
"version": "15.0.1.0.0",
"category": "Invoicing Management",
"license": "AGPL-3",
"summary": "Base module for Factur-X/ZUGFeRD",
"author": "Akretion,Odoo Community Association (OCA)",
"maintainers": ["alexis-via"],
"website": "https://github.com/OCA/edi",
"depends": ["uom_unece", "account_tax_unece", "account_payment_unece"],
"data": ["data/zugferd_codes.xml"],
"installable": True,
}
| 38.058824 | 647 |
481 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-2021 Akretion France
# @author: Alexis de Lattre <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class BaseFacturX(models.AbstractModel):
_name = "base.facturx"
_description = "Common methods to generate and parse Factur-X and Order-X"
# This class will certainly start to be used with the implementation
# of Order-X sooner or later: http://fnfe-mpe.org/factur-x/order-x/
| 37 | 481 |
806 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Voxel account invoice oca",
"summary": "Sends account invoices to Voxel.",
"version": "15.0.1.0.0",
"development_status": "Production/Stable",
"category": "Accounting & Finance",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/edi",
"license": "AGPL-3",
"depends": ["edi_voxel_oca", "stock_picking_invoice_link"],
"data": [
"data/ir_cron_data.xml",
"data/queue_job_function_data.xml",
"views/account_move_views.xml",
"views/report_voxel_invoice.xml",
"views/res_company_view.xml",
"views/res_config_settings_views.xml",
],
"installable": True,
}
| 35.043478 | 806 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.