~lifeeth/sahana-eden/ifrc

« back to all changes in this revision

Viewing changes to modules/s3/s3msg.py

  • Committer: Fran Boon
  • Date: 2012-01-18 14:26:52 UTC
  • mfrom: (1875.1.1269 eden)
  • Revision ID: fran@aidiq.com-20120118142652-1p2fvpmr0xfkfy2z
merge Trunk: S3Compose() RESTful method available from all Search results, Break up PR into more classes

Show diffs side-by-side

added added

removed removed

Lines of Context:
38
38
 
39
39
"""
40
40
 
41
 
__all__ = ["S3Msg"]
 
41
__all__ = ["S3Msg",
 
42
           "S3Compose"]
42
43
 
43
44
import datetime
44
45
import difflib
50
51
from gluon.html import *
51
52
from gluon.http import redirect
52
53
 
 
54
from s3crud import S3CRUD
53
55
from s3utils import s3_debug
54
56
from s3validators import IS_ONE_OF, IS_ONE_OF_EMPTY
55
57
 
62
64
TWITTER_HAS_NEXT_SUFFIX = u' \u2026'
63
65
TWITTER_HAS_PREV_PREFIX = u'\u2026 '
64
66
 
 
67
# =============================================================================
65
68
class S3Msg(object):
66
69
    """ Messaging framework """
67
70
 
333
336
                                request.vars.group_id
334
337
                                request.vars.hrm_id
335
338
            @param message: The default message text
336
 
            @param url: Redirect to the specified url after message sent
 
339
            @param url: Redirect to the specified URL() after message sent
337
340
        """
338
341
 
339
342
        T = current.T
1205
1208
 
1206
1209
        return True
1207
1210
 
1208
 
# END -------------------------------------------------------------------------
1209
 
 
 
1211
# =============================================================================
 
1212
class S3Compose(S3CRUD):
 
1213
    """ RESTful method for messaging """
 
1214
 
 
1215
    # -------------------------------------------------------------------------
 
1216
    def apply_method(self, r, **attr):
 
1217
        """
 
1218
            API entry point
 
1219
 
 
1220
            @param r: the S3Request instance
 
1221
            @param attr: controller attributes for the request
 
1222
        """
 
1223
 
 
1224
        manager = current.manager
 
1225
        if r.http in ("GET", "POST"):
 
1226
            output = self.compose(r, **attr)
 
1227
        else:
 
1228
            r.error(405, manager.ERROR.BAD_METHOD)
 
1229
        return output
 
1230
 
 
1231
    # -------------------------------------------------------------------------
 
1232
    def compose(self, r, **attr):
 
1233
        """
 
1234
            Generate a form to send a message
 
1235
 
 
1236
            @param r: the S3Request instance
 
1237
            @param attr: controller attributes for the request
 
1238
        """
 
1239
 
 
1240
        T = current.T
 
1241
        auth = current.auth
 
1242
        manager = current.manager
 
1243
        session = current.session
 
1244
        response = current.response
 
1245
 
 
1246
        url = r.url()
 
1247
        self.url = url
 
1248
 
 
1249
        # @ToDo: Use API
 
1250
        if auth.is_logged_in() or auth.basic():
 
1251
            pass
 
1252
        else:
 
1253
            redirect(URL(c="default", f="user", args="login",
 
1254
                         vars={"_next" : url}))
 
1255
 
 
1256
        #_vars = r.get_vars
 
1257
 
 
1258
        self.recipients = None
 
1259
        form = self._compose_form()
 
1260
        # @ToDo: A 2nd Filter form
 
1261
        # if form.accepts(r.post_vars, session,
 
1262
                        # formname="compose",
 
1263
                        # keepvalues=True):
 
1264
            # query, errors = self._process_filter_options(form)
 
1265
            # if r.http == "POST" and not errors:
 
1266
                # self.resource.add_filter(query)
 
1267
            # _vars = form.vars
 
1268
       
 
1269
        # Apply method
 
1270
        resource = self.resource
 
1271
        representation = r.representation
 
1272
 
 
1273
        if self.method == "compose":
 
1274
            #output = dict(items=items)
 
1275
            output = dict(form=form)
 
1276
        else:
 
1277
            r.error(501, manager.ERROR.BAD_METHOD)
 
1278
 
 
1279
        # Complete the page
 
1280
        if representation == "html":
 
1281
            title = self.crud_string(self.tablename, "title_compose")
 
1282
            if not title:
 
1283
                title = T("Send Message")
 
1284
 
 
1285
            # subtitle = self.crud_string(self.tablename, "subtitle_compose")
 
1286
            # if not subtitle:
 
1287
                # subtitle = ""
 
1288
 
 
1289
            # Maintain RHeader for consistency
 
1290
            if "rheader" in attr:
 
1291
                output["rheader"] = attr["rheader"](r)
 
1292
 
 
1293
            output["title"] = title
 
1294
            #output["subtitle"] = subtitle
 
1295
            #output["form"] = form
 
1296
            #response.view = self._view(r, "list_create.html")
 
1297
            response.view = self._view(r, "create.html")
 
1298
 
 
1299
        return output
 
1300
 
 
1301
    # -------------------------------------------------------------------------
 
1302
    def _compose_onvalidation(self, form):
 
1303
        """
 
1304
            Set the sender
 
1305
            Route the message
 
1306
        """
 
1307
 
 
1308
        T = current.T
 
1309
        db = current.db
 
1310
        s3db = current.s3db
 
1311
        auth = current.auth
 
1312
        msg = current.msg
 
1313
        session = current.session
 
1314
 
 
1315
        vars = current.request.post_vars
 
1316
 
 
1317
        url = self.url
 
1318
 
 
1319
        recipients = self.recipients
 
1320
        if not recipients:
 
1321
            if not vars.pe_id:
 
1322
                session.error = T("Please enter the recipient(s)")
 
1323
                redirect(url)
 
1324
            else:
 
1325
                recipients = vars.pe_id
 
1326
 
 
1327
        table = s3db.pr_person
 
1328
        query = (table.uuid == auth.user.person_uuid)
 
1329
        sender_pe_id = db(query).select(table.pe_id,
 
1330
                                        limitby=(0, 1)).first().pe_id
 
1331
        if msg.send_by_pe_id(recipients,
 
1332
                             vars.subject,
 
1333
                             vars.message,
 
1334
                             sender_pe_id,
 
1335
                             vars.pr_message_method):
 
1336
            # Trigger a Process Outbox
 
1337
            msg.process_outbox(contact_method = vars.pr_message_method)
 
1338
            session.confirmation = T("Check outbox for the message status")
 
1339
            redirect(url)
 
1340
        else:
 
1341
            session.error = T("Error in message")
 
1342
            redirect(url)
 
1343
 
 
1344
    # -------------------------------------------------------------------------
 
1345
    def _compose_form(self):
 
1346
        """ Creates the form for composing the message """
 
1347
 
 
1348
        resource = self.resource
 
1349
        table = resource.table
 
1350
 
 
1351
        T = current.T
 
1352
        db = current.db
 
1353
        s3db = current.s3db
 
1354
        crud = current.crud
 
1355
        session = current.session
 
1356
        response = current.response
 
1357
        s3 = response.s3
 
1358
 
 
1359
        ltable = s3db.msg_log
 
1360
        otable = s3db.msg_outbox
 
1361
 
 
1362
        # @ToDo: read request.get_vars.message?
 
1363
        #ltable.message.default = message
 
1364
 
 
1365
        # See if we have defined a custom recipient type for this table
 
1366
        # pr_person or pr_group
 
1367
        recipient_type = self._config("msg_recipient_type", None)
 
1368
 
 
1369
        # See if we have defined a custom default contact method for this table
 
1370
        type = self._config("msg_contact_method", "SMS")
 
1371
        otable.pr_message_method.default = type
 
1372
 
 
1373
        ltable.pe_id.writable = ltable.pe_id.readable = False
 
1374
        ltable.sender.writable = ltable.sender.readable = False
 
1375
        ltable.fromaddress.writable = ltable.fromaddress.readable = False
 
1376
        ltable.verified.writable = ltable.verified.readable = False
 
1377
        ltable.verified_comments.writable = ltable.verified_comments.readable = False
 
1378
        ltable.actioned.writable = ltable.actioned.readable = False
 
1379
        ltable.actionable.writable = ltable.actionable.readable = False
 
1380
        ltable.actioned_comments.writable = ltable.actioned_comments.readable = False
 
1381
 
 
1382
        ltable.subject.label = T("Subject")
 
1383
        ltable.message.label = T("Message")
 
1384
        #ltable.priority.label = T("Priority")
 
1385
 
 
1386
        if "pe_id" in table:
 
1387
            records = resource.sqltable(as_list=True, start=None, limit=None)
 
1388
            recipients = [record["pe_id"] for record in records]
 
1389
        elif "person_id" in table:
 
1390
            # @ToDo: Optimise through a Join
 
1391
            records = resource.sqltable(as_list=True, start=None, limit=None)
 
1392
            persons = [record["person_id"] for record in records]
 
1393
            table = s3db.pr_person
 
1394
            records = db(table.id.belongs(persons)).select(table.pe_id)
 
1395
            recipients = [record.pe_id for record in records]
 
1396
        elif "group_id" in table:
 
1397
            # @ToDo
 
1398
            recipients = None
 
1399
        else:
 
1400
            recipients = None
 
1401
 
 
1402
        if recipients:
 
1403
            self.recipients = recipients
 
1404
            ltable.pe_id.default = recipients
 
1405
            otable.pe_id.default = recipients
 
1406
            ltable.pe_id.requires = IS_ONE_OF_EMPTY(db, "pr_pentity.pe_id", multiple=True)
 
1407
        else:
 
1408
            if recipient_type:
 
1409
                # Filter by Recipient Type
 
1410
                otable.pe_id.requires = IS_ONE_OF(db, "pr_pentity.pe_id",
 
1411
                                                  orderby="instance_type",
 
1412
                                                  filterby="instance_type",
 
1413
                                                  filter_opts=(recipient_type,))
 
1414
            otable.pe_id.comment = DIV(_class="tooltip",
 
1415
                                       _title="%s|%s" % \
 
1416
                                        (T("Recipients"),
 
1417
                                         T("Please enter the first few letters of the Person/Group for the autocomplete.")))
 
1418
        otable.pe_id.writable = True
 
1419
        otable.pe_id.label = T("Recipient(s)")
 
1420
 
 
1421
        # Source forms
 
1422
        logform = crud.create(ltable,
 
1423
                              onvalidation = self._compose_onvalidation)
 
1424
        outboxform = crud.create(otable)
 
1425
 
 
1426
        # Shortcuts
 
1427
        lcustom = logform.custom
 
1428
        ocustom = outboxform.custom
 
1429
 
 
1430
        pe_row = TR(TD(LABEL("%s:" % ocustom.label.pe_id)),
 
1431
                    _id="msg_outbox_pe_id__row")
 
1432
        if recipients:
 
1433
            if len(recipients) == 1:
 
1434
                represent = s3.pr_pentity_represent(recipients[0],
 
1435
                                                    show_label=False)
 
1436
            else:
 
1437
                # @ToDo: This should be the filter results
 
1438
                represent = T("Multiple")
 
1439
            pe_row.append(TD(represent))
 
1440
        else:
 
1441
            # @ToDo: This should be an S3Search form
 
1442
            pe_row.append(TD(INPUT(_id="dummy", _class="ac_input", _size="50"),
 
1443
                             ocustom.widget.pe_id))
 
1444
            pe_row.append(TD(ocustom.comment.pe_id))
 
1445
 
 
1446
        # Build a custom form from the 2 source forms
 
1447
        form = DIV( lcustom.begin,
 
1448
                    TABLE(
 
1449
                        TBODY(
 
1450
                            TR(TD(LABEL("%s:" % \
 
1451
                                ocustom.label.pr_message_method)),
 
1452
                               TD(ocustom.widget.pr_message_method),
 
1453
                               TD(ocustom.comment.pr_message_method),
 
1454
                               _id="msg_outbox_pr_message_method__row"
 
1455
                            ),
 
1456
                            pe_row,
 
1457
                            TR(TD(LABEL("%s:" % lcustom.label.subject)),
 
1458
                               TD(lcustom.widget.subject),
 
1459
                               TD(lcustom.comment.subject),
 
1460
                               _id="msg_log_subject__row"
 
1461
                            ),
 
1462
                            TR(TD(LABEL("%s:" % lcustom.label.message)),
 
1463
                               TD(lcustom.widget.message),
 
1464
                               TD(lcustom.comment.message),
 
1465
                               _id="msg_log_message__row"
 
1466
                            ),
 
1467
                            # TR(TD(LABEL("%s:" % lcustom.label.priority)),
 
1468
                               # TD(lcustom.widget.priority),
 
1469
                               # TD(lcustom.comment.priority),
 
1470
                               # _id="msg_log_priority__row"
 
1471
                            # ),
 
1472
                            TR(TD(),
 
1473
                               TD(INPUT(_type="submit",
 
1474
                                        _value=T("Send message"),
 
1475
                                        _id="dummy_submit")),
 
1476
                               _id="submit_record__row"
 
1477
                            ),
 
1478
                        )
 
1479
                    ),
 
1480
                    lcustom.end)
 
1481
 
 
1482
        # Control the Javascript in static/scripts/S3/s3.msg.js
 
1483
        if not recipients:
 
1484
            if recipient_type:
 
1485
                s3.js_global.append("S3.msg_search_url = '%s';" % \
 
1486
                                    URL(c="msg", f="search",
 
1487
                                        vars={"type":recipient_type}))
 
1488
            else:
 
1489
                s3.js_global.append("S3.msg_search_url = '%s';" % \
 
1490
                                    URL(c="msg", f="search"))
 
1491
 
 
1492
            s3.jquery_ready.append("s3_msg_ac_pe_input();")
 
1493
 
 
1494
        return form
 
1495
 
 
1496
# END =========================================================================