Skip to content

Commit

Permalink
完成 添加关注者消息、FORM发送消息等功能,待处理mail.message的尸体
Browse files Browse the repository at this point in the history
  • Loading branch information
rainbow-studio-solution committed Feb 4, 2022
1 parent 7fe5b2d commit 8ea3554
Show file tree
Hide file tree
Showing 4 changed files with 200 additions and 71 deletions.
139 changes: 117 additions & 22 deletions wecom_message/models/mail_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
from odoo import api, fields, models, tools, _
from odoo.exceptions import UserError

from datetime import datetime
from datetime import timezone
from datetime import timedelta
from odoo.addons.wecom_api.api.wecom_abstract_api import ApiException

_logger = logging.getLogger(__name__)
_image_dataurl = re.compile(
Expand All @@ -29,14 +27,18 @@ class Message(models.Model):

message_to_user = fields.Char(string="To Users", help="Message recipients (users)")
message_to_party = fields.Char(
string="To Departments", help="Message recipients (departments)",
string="To Departments",
help="Message recipients (departments)",
)
message_to_tag = fields.Char(
string="To Tags",
help="Message recipients (tags)",
)
message_to_tag = fields.Char(string="To Tags", help="Message recipients (tags)",)

body_html = fields.Html("Html Contents", default="", sanitize_style=True)
body_json = fields.Text("Json Contents", default={})
body_markdown = fields.Text("Markdown Contents", default="")
is_wecom_message = fields.Boolean("Is WeCom Message")
is_wecom_message = fields.Boolean("Is WeCom Message",readonly=True)
msgtype = fields.Selection(
[
("text", "Text message"),
Expand All @@ -54,6 +56,7 @@ class Message(models.Model):
],
string="Message type",
default="text",
readonly=True
)

# 企业微信消息选项
Expand Down Expand Up @@ -85,26 +88,118 @@ class Message(models.Model):
default="1800",
)

state = fields.Selection(
[
("sent", "Sent"),
("exception", "Exception"),
("recall", "Recall"),
],
"Status",
readonly=True,
copy=False,
default="sent",
)
failure_reason = fields.Text(
'Failure Reason', readonly=1,)

# ------------------------------------------------------
# CRUD / ORM
# ------------------------------------------------------
# @api.model_create_multi
# def create(self, values_list):
# tracking_values_list = []
# # for values in values_list:
# # if "message_type" not in values:
# # values["message_type"] = "markdown"
# messages = super(Message, self).create(values_list)
# for message, values, tracking_values_cmd in zip(
# messages, values_list, tracking_values_list
# ):
# if message.is_thread_message(values):
# message._invalidate_documents(values.get("model"), values.get("res_id"))

# return super(Message, self).create(values_list)


# ------------------------------------------------------
# MESSAGE READ / FETCH / FAILURE API
# 消息读取 / 获取 / 失败API
# 工具和发送机制
# ------------------------------------------------------

def send_wecom_message(self):
"""
发送企业微信消息
:return:
"""

def recall_message(self):
"""
撤回消息
:return:
"""
if self.is_wecom_message:
# 获取公司
company = self.env[self.model].browse(self.res_id).company_id
if not company:
company = self.env.company

try:
wecomapi = self.env["wecom.service_api"].InitServiceApi(
company.corpid, company.message_app_id.secret
)
res = wecomapi.httpCall(
self.env["wecom.service_api_list"].get_server_api_call(
"MESSAGE_RECALL"
),
{"msgid": self.message_id},
)
# print(res)

except ApiException as e:
return self.env["wecomapi.tools.action"].ApiExceptionDialog(
e, raise_exception=True
)
else:
if res["errcode"] == 0:
return self.write({"state": "recall", "message_id": None})

def resend_message(self):
"""
重新发送消息
"""
if self.is_wecom_message:
# 获取公司
company = self.env[self.model].browse(self.res_id).company_id
if not company:
company = self.env.company

wecom_userids = []
if self.partner_ids:
wecom_userids = [
p.wecom_userid
for p in self.partner_ids
if p.wecom_userid
]
try:
wecomapi = self.env["wecom.service_api"].InitServiceApi(
company.corpid, company.message_app_id.secret
)
msg = self.env["wecom.message.api"].build_message(
msgtype=self.msgtype,
touser="|".join(wecom_userids),
toparty=self.message_to_party,
totag=self.message_to_tag,
subject=self.subject,
media_id=False,
description=self.description,
author_id=self.author_id,
body_html=self.body_html,
body_json=self.body_json,
body_markdown=self.body_markdown,
safe=self.safe,
enable_id_trans=self.enable_id_trans,
enable_duplicate_check=self.enable_duplicate_check,
duplicate_check_interval=self.duplicate_check_interval,
company=company,
)
del msg["company"]
res = wecomapi.httpCall(
self.env["wecom.service_api_list"].get_server_api_call(
"MESSAGE_SEND"
),
msg,
)

except ApiException as e:
return self.env["wecomapi.tools.action"].ApiExceptionDialog(
e, raise_exception=True
)
else:
if res["errcode"] == 0:
return self.write({"state": "sent", "message_id": res["msgid"]})

100 changes: 66 additions & 34 deletions wecom_message/models/mail_thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,9 @@ def message_post(
)
else:
values.update(
{"is_wecom_message": False,}
{
"is_wecom_message": False,
}
)

attachments = attachments or []
Expand Down Expand Up @@ -348,39 +350,69 @@ def _notify_record_by_wecom(
"[%s] Sends a message with the record name [%s] in the application [%s]."
) % (sender, Model.browse(msg_vals["res_id"]).name, model_name)

message.write({"subject": msg_vals["subject"]})

# company = Model.company_id
# if not company:
# company = self.env.company
# try:
# wecomapi = self.env["wecom.service_api"].InitServiceApi(
# company.corpid, company.message_app_id.secret
# )
# msg = self.env["wecom.message.api"].build_message(
# msgtype="markdown",
# touser="|".join(wecom_userids),
# toparty="",
# totag="",
# subject=msg_vals["subject"],
# media_id=None,
# description=None,
# author_id=msg_vals["author_id"],
# body_markdown=_(
# "### %s sent you a message,You can also view it in your inbox in the system."
# + "\n\n"
# + "> **Message content:**\n\n> %s"
# )
# % (sender, msg_vals["body"],),
# enable_duplicate_check=True,
# duplicate_check_interval=1800,
# company=company,
# )
# del msg["company"]
# except ApiException as exc:
# pass
# else:
# pass
body_markdown = _(
"### %s sent you a message,You can also view it in your inbox in the system."
+ "\n\n"
+ "> **Message content:**\n\n> %s"
) % (
sender,
msg_vals["body"],
)

message.write(
{
"subject": msg_vals["subject"],
"message_to_user": "|".join(wecom_userids),
"message_to_party": None,
"message_to_tag": None,
"body_markdown": body_markdown,
}
)

company = Model.company_id
if not company:
company = self.env.company
try:
wecomapi = self.env["wecom.service_api"].InitServiceApi(
company.corpid, company.message_app_id.secret
)
msg = self.env["wecom.message.api"].build_message(
msgtype="markdown",
touser="|".join(wecom_userids),
toparty="",
totag="",
subject=msg_vals["subject"],
media_id=None,
description=None,
author_id=msg_vals["author_id"],
body_markdown=body_markdown,
safe=True,
enable_id_trans=True,
enable_duplicate_check=True,
duplicate_check_interval=1800,
company=company,
)

del msg["company"]
res = wecomapi.httpCall(
self.env["wecom.service_api_list"].get_server_api_call("MESSAGE_SEND"),
msg,
)
except ApiException as exc:
error = self.env["wecom.service_api_error"].get_error_by_code(exc.errCode)
message.write(
{
"state": "exception",
"failure_reason": "%s %s" % (str(error["code"]), error["name"]),
}
)
else:
message.write(
{
"state": "sent",
"message_id": res["msgid"],
}
)

# ------------------------------------------------------
# 关注者API
Expand Down
30 changes: 15 additions & 15 deletions wecom_message/views/mail_message_views.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@
<field name="priority">20</field>
<field name="arch" type="xml">
<form string="WeCom Message">
<header>
<button name="recall_message" string="Recall Message" type="object" states='sent' class="oe_highlight" icon="fa-times-circle"/>
<button name="resend_message" string="Resend Message" type="object" states='exception' icon="fa-repeat" />
<field name="state" widget="statusbar" statusbar_visible="sent,exception,recall"/>
</header>
<sheet>
<group>
<group>
Expand All @@ -42,14 +47,16 @@
</group>
</group>
<group string="Message">
<field name="is_wecom_message"/>
<group string="Recipients">
<field name="message_to_user" widget="many2many_tags" options="{'no_create': True,'no_open': True}"/>
<field name="message_to_party" widget="many2many_tags" options="{'no_create': True,'no_open': True}"/>
<field name="message_to_tag" widget="many2many_tags" options="{'no_create': True,'no_open': True}"/>
</group>
<group string="Options">
<field name="is_wecom_message"/>
<field name="msgtype"/>
<field name="message_id"/>
<field name="failure_reason"/>
<!-- <field name="use_templates"/> -->
<!-- <field name="templates_id" attrs="{'invisible': [('use_templates','=',False)]}" options="{'quick_create': False,'no_open': True,}"/> -->
</group>
Expand All @@ -66,18 +73,7 @@
<page string="Markdown Content" name="markdown_content" attrs="{'invisible': [('msgtype','!=','markdown')]}">
<field name="body_markdown" widget="wecom_markdown" />
</page>
<page string="Gateway" name="gateway">
<group>
<group>
<field name="reply_to"/>
<field name="no_auto_thread"/>
</group>
<group>
<field name="message_id"/>
<!-- <field name="mail_server_id"/> -->
</group>
</group>
</page>

<page string="Recipients" name="recipients">
<group>
<group>
Expand Down Expand Up @@ -113,16 +109,20 @@
<record model="ir.ui.view" id="view_wecom_message_tree">
<field name="name">wecom.message.tree</field>
<field name="model">mail.message</field>
<field name="priority">20</field>
<!-- <field name="priority">20</field> -->
<field name="arch" type="xml">
<tree string="Messages">
<tree string="Messages" decoration-muted="state=='sent'" decoration-danger="state=='exception'">
<field name="date"/>
<field name="message_type"/>
<field name="is_wecom_message"/>
<field name="subject"/>
<field name="author_id"/>
<field name="model"/>
<field name="res_id" widget="integer"/>
<field name="state" />
<button name="recall_message" string="Recall Message" type="object" icon="fa-times-circle" states='sent'/>

<button name="resend_message" string="Resend Message" type="object" icon="fa-repeat" states='exception'/>
</tree>
</field>
</record>
Expand Down
2 changes: 2 additions & 0 deletions wecom_message/wizard/invite.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def add_followers(self):
document_model=model_name,
document_name=document.display_name,
),

"body": wizard.message,
"record_name": document.display_name,
"email_from": email_from,
Expand Down Expand Up @@ -129,6 +130,7 @@ def add_followers(self):
"duplicate_check_interval": 1800,
}
message = self.env["mail.message"].create(msg_vals)
message.write({"partner_ids": new_partners})
partners_data = []
recipient_data = self.env["mail.followers"]._get_recipient_data(
document, "comment", False, pids=new_partners.ids
Expand Down

0 comments on commit 8ea3554

Please sign in to comment.