Skip to content
This repository has been archived by the owner on Sep 25, 2023. It is now read-only.

Commit

Permalink
Merge pull request #5 from Som-Energia/ADD_callbacks
Browse files Browse the repository at this point in the history
Afegida funcionalitat callbacks
  • Loading branch information
MarJene committed Mar 15, 2021
2 parents 244dcfe + 0ac8af0 commit 5856c98
Show file tree
Hide file tree
Showing 4 changed files with 144 additions and 34 deletions.
8 changes: 4 additions & 4 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import powersms_core
import powersms_templates
import powersms_smsbox
import wizard
from . import powersms_core
from . import powersms_templates
from . import powersms_smsbox
from . import wizard
import logging

logger = logging.getLogger('openerp.powersms')
4 changes: 2 additions & 2 deletions powersms_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ def check_numbers(self, cr, uid, ids, numbers):
def send_sms_lleida(self, cr, uid, ids, number_to, message, from_name, context=None):
if isinstance(ids, list):
ids = ids[0]
if not self.check_numbers(number_to):
if not self.check_numbers(cr, uid, ids, number_to):
raise Exception("Incorrect cell number: " + number_to)

values = self.read(cr, uid, ids, ['api_uname', 'api_pass'])
c = Client(user=str(values['api_uname']), password=str(values['api_pass']))
headers = {'content-type': 'application/x-www-form-urlencoded', 'accept': 'application/json'}
Expand Down
161 changes: 137 additions & 24 deletions powersms_smsbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,146 @@
from tools.config import config
import tools
from oorq.decorators import job
import six

LOGGER = netsvc.Logger()

class PowersmsSMSbox(osv.osv):
_name = "powersms.smsbox"
_description = 'Power SMS SMSbox included all type inbox,outbox,junk..'
_rec_name = "psms_subject"
_rec_name = "reference"
_order = "date_sms desc"

callbacks = {'create': 'powersms_create_callback',
'write': 'powersms_write_callback',
'unlink': 'powersms_unlink_callback',
}

def powersms_callback(self, cursor, uid, ids, func, vals=None, context=None):
"""Crida el callback callbacks[func] del reference de ids
"""
if context is None:
context = {}
data = self.read(cursor, uid, ids, ['reference', 'meta'])
if not isinstance(data, list):
data = [data]
ids_cbk = {}
ctx = context.copy()
ctx['ps_callback_origin_ids'] = {}
ctx['meta'] = {}
if vals:
init_meta = vals.get('meta', {}) or {}
if isinstance(init_meta, basestring):
init_meta = json.loads(init_meta)
else:
init_meta = {}
for i in data:
if not i['reference']:
continue
meta_vals = i['meta']
if meta_vals:
meta = json.loads(meta_vals)
meta.update(init_meta)
else:
meta = {}

ref = i['reference'].split(',')
ids_cbk[ref[0]] = ids_cbk.get(ref[0], []) + [int(ref[1])]
ctx['ps_callback_origin_ids'][int(ref[1])] = i['id']
ctx['meta'][int(ref[1])] = meta
for model in ids_cbk:
src = self.pool.get(model)
try:
if vals:
getattr(src, self.callbacks[func])(cursor, uid,
ids_cbk[model], vals, ctx)
else:
getattr(src, self.callbacks[func])(cursor, uid,
ids_cbk[model], ctx)
except AttributeError:
pass

def create(self, cursor, uid, vals, context=None):
if context is None:
context = {}
src_id = context.get('src_rec_id', False)
if src_id:
upd_vals = {
'reference': '%s,%d' % (context['src_model'], src_id)
}
meta = context.get('meta')
if meta:
upd_vals['meta'] = json.dumps(context['meta'])
vals.update(upd_vals)
ps_id = super(PowersmsSMSbox,
self).create(cursor, uid, vals, context)
self.powersms_callback(cursor, uid, ps_id, 'create', vals, context)
return ps_id

def validate_referenced_object_exists(self, cursor, uid, id, vals, context=None):
ret = True
fields = ['reference']
result = self._read_flat(cursor, uid, id, fields, context, '_classic_read')
for r in result:
if 'reference' in r.keys():
v = r['reference']
if v:
model, ref_id = v.split(',')
ref_obj = self.pool.get(model)

if ref_id != '0':
id_exist = ref_obj.search(cursor, 1, [
('id', '=', ref_id)
], context={'active_test': False})
if not id_exist:
ret = False
return ret

def read(self, cursor, uid, ids, fields=None, context=None, load='_classic_read'):
if context is None:
context = {}
select = ids
if isinstance(ids, six.integer_types):
select = [ids]
valid_select = []
for id in select:
res = self.validate_referenced_object_exists(cursor, uid, [id], fields, context=None)
if res:
valid_select.append(id)
else:
super(PowersmsSMSbox,
self).unlink(cursor, uid, [id], context)
ret = []
if valid_select:
ret = super(PowersmsSMSbox,
self).read(cursor, uid, valid_select, fields, context, load)
if isinstance(ids, six.integer_types) and ret:
return ret[0]
return ret

def write(self, cursor, uid, ids, vals, context=None):
if context is None:
context = {}
meta = context.get('meta')
if meta:
vals['meta'] = json.dumps(meta)
self.powersms_callback(cursor, uid, ids, 'write', vals, context)
ret = super(PowersmsSMSbox,
self).write(cursor, uid, ids, vals, context)
return ret

def unlink(self, cursor, uid, ids, context=None):
if context is None:
context = {}
self.powersms_callback(cursor, uid, ids, 'unlink', context=context)
ret = super(PowersmsSMSbox,
self).unlink(cursor, uid, ids, context)
return ret

def _get_models(self, cursor, uid, context={}):
cursor.execute('select m.model, m.name from ir_model m order by m.model')
return cursor.fetchall()

def run_sms_scheduler(self, cursor, user, context=None):
"""
This method is called by Open ERP Scheduler
Expand Down Expand Up @@ -109,27 +240,6 @@ def historise(self, cr, uid, ids, message='', context=None, error=False):
if 'lang' not in context:
context.update({'lang': user.context_lang})
for psms_id in ids:
# Notify the sender errors
if context.get('notify_errors', False) \
and not context.get('bounce', False) \
and error:
sms = self.browse(cr, uid, psms_id)
vals = {
'folder': 'outbox',
'history': '',
'pem_to': sms.pem_account_id.email_id,
'pem_subject': _(
u"Error sending email with id {}"
).format(sms.id)
}
bounce_sms_id = self.copy(cr, uid, psms_id, vals)
ctx = context.copy()
ctx.update({'bounce': True})
self.send_this_sms(cr, uid, [bounce_sms_id], ctx)
bounce_sms = self.browse(cr, uid, bounce_sms_id)
# If bounce sms cannot be sent, unlink it
if bounce_sms.folder != 'sent':
bounce_sms.unlink()
history = self.read(
cr, uid, psms_id, ['history'], context).get('history', '') or ''
history_limit = config.get('psms_history_limit', 10)
Expand All @@ -149,8 +259,8 @@ def check_mobile(self, mobile_number):
return True

def is_valid(self, cursor, uid, sms_id, context=None):
mail = self.read(cursor, uid, sms_id, ['psms_to'], context)
return self.check_mobile(mail['psms_to'])
sms = self.read(cursor, uid, sms_id, ['psms_to'], context)
return self.check_mobile(sms['psms_to'])

_columns = {
'psms_account_id' :fields.many2one(
Expand Down Expand Up @@ -186,6 +296,9 @@ def is_valid(self, cursor, uid, sms_id, context=None):
'History',
readonly=True,
store=True),
'reference': fields.reference('Source Object', selection=_get_models,
size=128),
'meta': fields.text('Meta information')
}

_defaults = {
Expand Down
5 changes: 1 addition & 4 deletions wizard/wizard_send_sms.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
class PowersmsSendWizard(osv.osv_memory):
_name = 'powersms.send.wizard'
_description = 'This is the wizard for sending SMS'
_rec_name = "subject"

def _get_accounts(self, cr, uid, context=None):
if context is None:
Expand Down Expand Up @@ -71,7 +70,6 @@ def send_sms(self, cursor, uid, ids, context=None):
smsbox_obj = self.pool.get('powersms.smsbox')
folder = context.get('folder', 'outbox')
values = {'folder': folder}

sms_ids = self.save_to_smsbox(cursor, uid, ids, context)

if sms_ids:
Expand Down Expand Up @@ -111,8 +109,7 @@ def get_end_value(id, value):
'psms_account_id': screen_vals['account'],
'state':'na',
}

numbers = list(set(map(str.strip,vals['psms_to'].split(','))))
numbers = list(set(map(str.strip,str(vals['psms_to']).split(','))))
for number in numbers:
vals.update({'psms_to': number})
#Create partly the mail and later update attachments
Expand Down

0 comments on commit 5856c98

Please sign in to comment.