Skip to content

Commit

Permalink
待处理发送通知
Browse files Browse the repository at this point in the history
  • Loading branch information
rainbow-studio-solution committed Feb 4, 2022
1 parent 4c26c5d commit 7fe5b2d
Show file tree
Hide file tree
Showing 9 changed files with 146 additions and 101 deletions.
1 change: 1 addition & 0 deletions wecom_message/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
# "views/mail_message_views.xml",
"views/res_users_views.xml",
"views/res_config_settings_views.xml",
"views/mail_message_views.xml",
"views/mail_template_views.xml",
"views/mail_mail_views.xml",
"views/mail_notification_views.xml",
Expand Down
2 changes: 1 addition & 1 deletion wecom_message/i18n/zh_CN.po
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ msgid ""
"\n"
"> %s"
msgstr ""
"### %s 向您发送消息后,您还可以在系统的收件箱中查看该消息。\n"
"### %s 向您发送了一条消息,您还可以在系统的收件箱中查看该消息。\n"
"\n"
"> **消息内容:**\n"
"\n"
Expand Down
2 changes: 2 additions & 0 deletions wecom_message/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from . import mail_notification
from . import mail_thread

# from . import mail_followers

from . import wecom_apps


Expand Down
25 changes: 4 additions & 21 deletions wecom_message/models/mail_followers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,7 @@
class Followers(models.Model):
_inherit = ["mail.followers"]

def _get_recipient_data(
self, records, message_type, subtype_id, pids=None, cids=None
):
if message_type == "wxwork":
if pids is None:
sms_pids = records._wecom_message_get_partner_fields().ids
else:
sms_pids = pids
res = super(Followers, self)._get_recipient_data(
records, message_type, subtype_id, pids=pids, cids=cids
)
new_res = []
for pid, cid, pactive, pshare, ctype, notif, groups in res:
if pid and pid in sms_pids:
notif = "wxwork"
new_res.append((pid, cid, pactive, pshare, ctype, notif, groups))
return new_res
else:
return super(Followers, self)._get_recipient_data(
records, message_type, subtype_id, pids=pids, cids=cids
)
wecom_userid = fields.Char(string="WeCom User ID", readonly=True,)

is_wecom_user = fields.Boolean("Is WeCom user", readonly=True,)

8 changes: 8 additions & 0 deletions wecom_message/models/mail_notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,11 @@ class MailNotification(models.Model):
_inherit = "mail.notification"

is_wecom_message = fields.Boolean("WeCom Message")

notification_status = fields.Selection(
selection_add=[
("wecom_exception", "Send exception"),
("wecom_recall", "Recall"),
]
)
wecom_msgid = fields.Char("WeCom Message ID")
135 changes: 63 additions & 72 deletions wecom_message/models/mail_thread.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,9 @@
# -*- coding: utf-8 -*-

import ast
import base64
import datetime
import dateutil
import email
import email.policy
import hashlib
import hmac
import lxml
import logging
import pytz
import re
import socket
import time
import threading

from collections import namedtuple
from email.message import EmailMessage
from email import message_from_string, policy
from lxml import etree
from werkzeug import urls
from xmlrpc import client as xmlrpclib

import logging
from odoo import _, api, exceptions, fields, models, tools, registry, SUPERUSER_ID
from odoo.exceptions import MissingError
from odoo.osv import expression

from odoo.tools import ustr
from odoo.tools.misc import clean_context, split_every
from odoo.addons.wecom_api.api.wecom_abstract_api import ApiException

_logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -245,9 +220,7 @@ def message_post(
)
else:
values.update(
{
"is_wecom_message": False,
}
{"is_wecom_message": False,}
)

attachments = attachments or []
Expand Down Expand Up @@ -345,51 +318,69 @@ def _notify_record_by_inbox(
def _notify_record_by_wecom(
self, message, recipients_data, msg_vals=False, **kwargs
):
"""
:param message: mail.message 记录
:param list recipients_data: 收件人
:param dic msg_vals: 消息字典值
"""
Model = self.env[msg_vals["model"]]
model_name = self.env["ir.model"]._get(msg_vals["model"]).display_name

partners = []
if "partners" in recipients_data:
partners = [r["id"] for r in recipients_data["partners"]]
wecom_userids = [
p.wecom_userid
for p in self.env["res.partner"].browse(partners)
if p.wecom_userid
]

message_values = {
"model": msg_vals["model"],
"res_id": msg_vals["res_id"],
"record_name": msg_vals["record_name"],
# "parent_id": msg_vals.parent_id,
"subtype_id": msg_vals["subtype_id"],
"message_type": msg_vals["message_type"],
"author_id": msg_vals["author_id"],
# "partner_ids": msg_vals["partner_ids"],
# 以下为企业微信字段
"msgtype": "markdown",
"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"
)
% (
self.env.user.partner_id.browse(msg_vals["author_id"]).name,
msg_vals["body"],
),
"message_to_user": self.env[msg_vals["model"]]
.browse(msg_vals["res_id"])
.wecom_userid,
"enable_duplicate_check": True,
"duplicate_check_interval": 1800,
}
print("444444", message_values)
# TODO mail.message 待添加发送企业微信消息方法
# mails = self.env["mail.mail"].search(
# [("mail_message_id", "=", message.id)],
# )
# print(mails)
# for mail in mails:
# mail.write(
# {
# "is_wecom_message": True,
# }
sender = self.env.user.partner_id.browse(msg_vals["author_id"]).name

if msg_vals.get("subject") or message.subject:
pass
elif msg_vals.get("subject") and message.subject is False:
pass
elif msg_vals.get("subject") is False and message.subject:
msg_vals["subject"] = message.subject
else:
msg_vals["subject"] = _(
"[%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
# )
# mail.send_wecom_mail_message(
# raise_exception=True,
# company=self.env[msg_vals["model"]]
# .browse(msg_vals["res_id"])
# .company_id,
# 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

# ------------------------------------------------------
# 关注者API
Expand Down
4 changes: 2 additions & 2 deletions wecom_message/views/mail_message_views.xml
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@
</group>
<group string="Options">
<field name="msgtype"/>
<field name="use_templates"/>
<field name="templates_id" attrs="{'invisible': [('use_templates','=',False)]}" options="{'quick_create': False,'no_open': True,}"/>
<!-- <field name="use_templates"/> -->
<!-- <field name="templates_id" attrs="{'invisible': [('use_templates','=',False)]}" options="{'quick_create': False,'no_open': True,}"/> -->
</group>

</group>
Expand Down
3 changes: 2 additions & 1 deletion wecom_message/views/menu_views.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@

<!-- 1.讨论 对应菜单:设置→技术→讨论 -->
<menuitem id="menu_wecom_message_discuss" name="Discuss" parent="menu_wecom_message_root" sequence="1"/>
<!-- 1.1.消息 -->

<!-- 1.1.消息 -->
<menuitem name="Message" id="menu_wecom_message_message" parent="menu_wecom_message_discuss" action="action_view_wecom_message" sequence="1" groups="base.group_erp_manager"/>

<!-- 1.6.通知 -->
<menuitem name="Notifications" id="menu_wecom_message_notification" parent="menu_wecom_message_discuss" action="wecom_message_notification_action" sequence="5" groups="base.group_erp_manager"/>
Expand Down
67 changes: 63 additions & 4 deletions wecom_message/wizard/invite.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from lxml import etree
from lxml.html import builder as html

from odoo import _, api, fields, models
from odoo import _, api, fields, models, tools
from odoo.exceptions import UserError


Expand All @@ -21,6 +21,18 @@ class Invite(models.TransientModel):
help="If checked, the partners will receive an message warning they have been added in the document's followers.",
)

def _check_is_wecom_message(self, message_values):
"""
判断是否是企微消息
"""
model = message_values["model"]
res_id = message_values["res_id"]
fields = self.env[model]._fields.keys()
if "is_wecom_user" in fields:
return self.env[model].browse(res_id).is_wecom_user
else:
return False

def add_followers(self):
if not self.env.user.email:
raise UserError(
Expand All @@ -41,7 +53,7 @@ def add_followers(self):
model_name = self.env["ir.model"]._get(wizard.res_model).display_name
# 如果选中选项且存在邮件,则发送电子邮件(不要发送无效邮件)
if (
(wizard.send_mail or wizard.send_wecom_message) and wizard.message and not wizard.message == "<br>"
wizard.send_mail and wizard.message and not wizard.message == "<br>"
): # 删除邮件时,cleditor会保留一个<br>
message = self.env["mail.message"].create(
{
Expand Down Expand Up @@ -78,7 +90,7 @@ def add_followers(self):
partners_data.append(dict(pdata, type="portal"))
else: # 没有用户,因此是客户
partners_data.append(dict(pdata, type="customer"))
print(message, partners_data)

document._notify_record_by_email(
message,
{"partners": partners_data, "channels": []},
Expand All @@ -91,6 +103,53 @@ def add_followers(self):
)
message.unlink()


if (
wizard.send_wecom_message
and wizard.message
and not wizard.message == "<br>"
): # 删除邮件时,cleditor会保留一个<br>
# tools.html2plaintext
msg_vals = {
"subject": _(
"Invitation to follow %(document_model)s: %(document_name)s",
document_model=model_name,
document_name=document.display_name,
),
"message_type": "email",
"body": tools.html2plaintext(wizard.message),
"record_name": document.display_name,
"email_from": email_from,
"model": wizard.res_model,
"res_id": wizard.res_id,
"author_id": self.env.user.partner_id.id,
#
"is_wecom_message": True,
"msgtype": "markdown",
"enable_duplicate_check": True,
"duplicate_check_interval": 1800,
}
message = self.env["mail.message"].create(msg_vals)
partners_data = []
recipient_data = self.env["mail.followers"]._get_recipient_data(
document, "comment", False, pids=new_partners.ids
)
for pid, cid, active, pshare, ctype, notif, groups in recipient_data:
pdata = {
"id": pid,
"share": pshare,
"active": active,
"notif": "email",
"groups": groups or [],
}
if not pshare and notif: # 有一个用户,但不是共享的,因此是用户
partners_data.append(dict(pdata, type="user"))
elif pshare and notif: # 具有用户并且是共享的,因此是门户
partners_data.append(dict(pdata, type="portal"))
else: # 没有用户,因此是客户
partners_data.append(dict(pdata, type="customer"))

document._notify_record_by_wecom(
message, {"partners": partners_data, "channels": []}, msg_vals
)
# message.unlink()
return {"type": "ir.actions.act_window_close"}

0 comments on commit 7fe5b2d

Please sign in to comment.