Merge pull request #1071 from expsa/dev_odex25_mobile

Dev odex25 mobile
This commit is contained in:
eslam 2024-09-11 11:21:03 +03:00 committed by GitHub
commit fc8aaa680d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 170 additions and 24 deletions

View File

@ -2,10 +2,12 @@
import re
import werkzeug
from odoo import http, tools,fields
from datetime import datetime
from datetime import datetime, tzinfo, timedelta
from odoo.http import request, Response
from odoo.addons.auth_signup.models.res_users import SignupError
from odoo.exceptions import UserError ,AccessError, ValidationError
from odoo.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
import base64
from ...validator import validator
from ...http_helper import http_helper
@ -16,6 +18,7 @@ import logging
import calendar
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT
from odoo.tools.translate import _
import pytz
_logger = logging.getLogger(__name__)
@ -228,10 +231,22 @@ class LeaveController(http.Controller):
"You Have issue in your employee profile. please check with one of your team admins"), success=False)
try:
with request.env.cr.savepoint():
from_date=fields.Datetime.from_string(body["start_date"]).replace(hour=0, minute=0, second=0,
microsecond=0)
to_date = fields.Datetime.from_string(body["end_date"]).replace(hour=0, minute=0, second=0,
microsecond=0)
local_tz = pytz.timezone(
user.tz or 'GMT')
from_date = fields.Datetime.from_string(body["start_date"]).replace(hour=0, minute=0, second=0,
microsecond=0,tzinfo=local_tz)
to_date = fields.Datetime.from_string(body["end_date"]).replace(hour=23, minute=59, second=0,
microsecond=0,tzinfo=local_tz)
utc_dt_from = from_date.strftime("%Y-%m-%d %H:%M:%S")
utc_dt_to = to_date.strftime("%Y-%m-%d %H:%M:%S")
#
from_date = datetime.strptime(
utc_dt_from, "%Y-%m-%d %H:%M:%S")
from_date = fields.Datetime.to_string(from_date)
to_date = datetime.strptime(
utc_dt_to, "%Y-%m-%d %H:%M:%S")
to_date = fields.Datetime.to_string(to_date)
vals = {
"employee_id": employee.id,
@ -239,7 +254,8 @@ class LeaveController(http.Controller):
"date_to": to_date,
"name": body["description"] if body.get("description") else "",
"holiday_status_id": int(body["type_id"]),
"delegate_acc": body["delegated_permission"] if body["delegated_permission"] else False ,
"delegate_acc": False if body["delegated_permission"] in ("false","False",'') else True ,
# 'replace_by': int(body['replacement_id']) if body['replacement_id'] else False
}
if 'ticket' in body and body['ticket']:
@ -316,8 +332,23 @@ class LeaveController(http.Controller):
holidays = http.request.env['hr.holidays'].search([('id', '=', int(id))])
if holidays:
days = holidays._get_number_of_days(body['start_date'], body['end_date'], employee)
local_tz = pytz.timezone(
user.tz or 'GMT')
from_date = fields.Datetime.from_string(body["start_date"]).replace(hour=0, minute=0, second=0,
microsecond=0, tzinfo=local_tz)
to_date = fields.Datetime.from_string(body["end_date"]).replace(hour=23, minute=59, second=0,
microsecond=0, tzinfo=local_tz)
utc_dt_from = from_date.strftime("%Y-%m-%d %H:%M:%S")
utc_dt_to = to_date.strftime("%Y-%m-%d %H:%M:%S")
#
from_date = datetime.strptime(
utc_dt_from, "%Y-%m-%d %H:%M:%S")
from_date = fields.Datetime.to_string(from_date)
to_date = datetime.strptime(
utc_dt_to, "%Y-%m-%d %H:%M:%S")
to_date = fields.Datetime.to_string(to_date)
vals = {
'date_from': body['start_date'], 'date_to': body['end_date'],
'date_from': from_date, 'date_to': to_date,
'name': body['description'] if body.get('description') else '',
'holiday_status_id': int(body['type_id']),
'number_of_days_temp': days, 'delegate_acc': json.loads(body['delegated_permission']),

View File

@ -3,3 +3,5 @@ from . import attendence_zone_config
from . import mail_thread
from . import access_token
from . import res_users
from . import mail_message
from . import mail_activity

View File

@ -6,7 +6,9 @@ import datetime
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
web_fcm_server_key = fields.Char(string='Server Key:', related="company_id.web_fcm_server_key", readonly=False)
service_account = fields.Binary(string='Service Account:', related="company_id.service_account", readonly=False)
web_sender_id = fields.Char(string='Sender ID:', related="company_id.web_sender_id", readonly=False)
@ -14,4 +16,5 @@ class ResCompany(models.Model):
_inherit = 'res.company'
web_fcm_server_key = fields.Char(string='Server Key')
service_account = fields.Binary(string='Service Account', attachment=True)
web_sender_id = fields.Char(string='Sender ID')

View File

@ -1,10 +1,15 @@
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from odoo import models,fields,api,_
from odoo.exceptions import ValidationError
import random
import json
import json, requests
from odoo import models, fields
import json, requests, base64
import google.auth.transport.requests
from google.oauth2 import service_account
import io
import tempfile
import os
BASE_URL = 'https://fcm.googleapis.com'
SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']
class HrEmployee(models.Model):
@ -15,18 +20,51 @@ class HrEmployee(models.Model):
def user_push_notification_web(self, notification):
url = "https://fcm.googleapis.com/fcm/send"
header = {
'Content-Type': 'application/json',
'Authorization': 'key=%s' % (self.env.user.company_id.web_fcm_server_key)
}
body = json.dumps({
"to": self.fcm_token_web,
"direct_boot_ok": True,
"notification": notification
})
def _get_access_token(json_file):
"""Retrieve a valid access token that can be used to authorize requests.
:return: Access token.
"""
credentials = service_account.Credentials.from_service_account_file(
json_file, scopes=SCOPES)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
return credentials.token
try:
respons = requests.post(url=url, data=body, headers=header)
json_file_name = 'service-account'
base64_service_account = base64.decodebytes(self.env.user.company_id.service_account)
service_account_json = json.loads(base64_service_account)
with tempfile.TemporaryDirectory() as temp_dir:
temp_file_path = os.path.join(temp_dir, json_file_name)
with open(temp_file_path, 'w') as temp_file:
temp_file.write(base64_service_account.decode('UTF-8'))
header = {
'Content-Type': 'application/json',
'Authorization': 'Bearer %s' % (_get_access_token(temp_file_path))
}
body = json.dumps({
"message": {
"token": self.fcm_token_web,
"notification": notification,
"android": {
"notification": {
"sound": "default"
}
},
"apns": {
"payload": {
"aps": {
"sound": "default"
}
}
}
}
})
FCM_ENDPOINT = 'v1/projects/' + service_account_json['project_id'] + '/messages:send'
FCM_URL = BASE_URL + '/' + FCM_ENDPOINT
respons = requests.post(url=FCM_URL, data=body, headers=header)
return True
except Exception as e:
return False

View File

@ -0,0 +1,23 @@
from odoo import models, api
import re
class MailActivity(models.Model):
_inherit = 'mail.activity'
@api.model
def create(self, values):
activity_ids = super(MailActivity, self).create(values)
for activity_id in activity_ids:
# Build message content
notification_body = re.sub(r'<[^>]+>', '', activity_id.note.replace('<br>', '\n'))
# Send notifications
employee_id = self.env['hr.employee'].sudo().search([('user_id', '=', activity_id.user_id.id)])
if employee_id:
push_notify = employee_id.user_push_notification_web({
"title": activity_id.summary or activity_id.create_uid.name,
"body": notification_body
})
return activity_ids

View File

@ -0,0 +1,43 @@
from odoo import models, api
import re
class Message(models.Model):
_inherit = 'mail.message'
@api.model_create_multi
def create(self, values_list):
mt_comment = self.env.ref('mail.mt_comment')
mt_note = self.env.ref('mail.mt_note')
messages = super(Message, self).create(values_list)
for message in messages.filtered(lambda r: r.subtype_id.id in (mt_comment.id, mt_note.id) and r.model != 'mail.channel' and r.message_type != 'user_notification'):
# Get partners that should receive the message
if message.subtype_id.id == mt_comment.id:
partner_ids = self.env['mail.followers'].sudo().search([
('res_model', '=', message.model),
('res_id', '=', message.res_id),
('partner_id', '!=', message.author_id.id)
]).partner_id
elif message.subtype_id.id == mt_note.id:
partner_ids = message.partner_ids
else:
partner_ids = []
if len(partner_ids):
# Build message content
notification_body = re.sub(r'<[^>]+>', '', message.body.replace('<br>', '\n'))
attachments = len(message.attachment_ids)
if notification_body and attachments:
notification_body += '\n{} File(s)'.format(attachments)
elif attachments:
notification_body = '{} File(s)'.format(attachments)
# Send notifications
for employee_id in self.env['hr.employee'].sudo().search([('user_id', 'in', partner_ids.user_ids.ids)]):
push_notify = employee_id.user_push_notification_web({
"title": message.author_id.name,
"body": notification_body
})
return messages

View File

@ -15,6 +15,12 @@
<h2>WebMobile Configuration</h2>
<div id="web_fcm_settings">
<div class="row mt16 o_settings_container">
<div class="col-xs-12 col-md-6 o_setting_box">
<div class="o_setting_right_pane">
<label for="service_account"/>
<field name="service_account"/>
</div>
</div>
<div class="col-xs-12 col-md-6 o_setting_box">
<div class="o_setting_right_pane">
<label for="web_fcm_server_key"/>