def save (self, user):
        location = Village.objects.get (id = self.cleaned_data ['locationid'])
        citizen = get_or_create_citizen (self.cleaned_data ['yourmobile'],
                                         self.cleaned_data ['yourname'])

        assignto = None
        if self.cleaned_data ['categoryid'] != None:
            complaint_base = ComplaintType.objects.get (id = self.cleaned_data ['categoryid'])
            department = complaint_base.department
            officials = department.official_set.all ()
            if officials.count () > 0:
                assignto = officials [0]
        else:
            complaint_base = None
            department = None

        cpl = Complaint.objects.create (complainttype = complaint_base,
                                        complaintno = None,
                                        description = self.cleaned_data ['description'],
                                        department  = department,
                                        curstate = STATUS_NEW,
                                        filedby = citizen,
                                        logdate = self.cleaned_data ['logdate'],
                                        location = location,
                                        original = None,
                                        creator = user,
                                        assignto = assignto)
        update_complaint_sequence (cpl)

        ComplaintClosureMetric.objects.create (complaintno = cpl.complaintno)

        return cpl
    def save (self, user):
        location = Village.objects.get (id = self.cleaned_data ['locationid'])
        citizen = get_or_create_citizen (self.cleaned_data ['yourmobile'],
                                         self.cleaned_data ['yourname'])

        complaint_base = ComplaintType.objects.get (id = self.cleaned_data ['categoryid'])
        department = complaint_base.department
        officials = department.official_set.all ()
        if officials.count () > 0:
            assignto = officials [0]
        else:
            assignto = None

        cpl = Complaint.objects.create (complainttype = complaint_base,
                                        complaintno = None,
                                        description = self.cleaned_data ['description'],
                                        department  = department,
                                        curstate = STATUS_NEW,
                                        filedby = citizen,
                                        logdate = self.cleaned_data ['logdate'],
                                        location = location,
                                        original = None,
                                        creator = user,
                                        assignto = assignto,
                                        gender = self.cleaned_data ['gender'],
                                        community = self.cleaned_data ['community'])
        update_complaint_sequence (cpl)

        ComplaintClosureMetric.objects.create (complaintno = cpl.complaintno)

        accept_cpl = cpl.clone (user)
        accept_cpl.curstate = STATUS_ACK
        accept_cpl.save ()

        queue_complaint_ack_official_sms (accept_cpl)

        message = None
        ct = cpl.complainttype
        if ct.defsmsack != None and len (ct.defsmsack.strip ()) != 0:
            message = ct.defsmsack

        if message == None:
            if ct.defsmsnew != None and len (ct.defsmsnew.strip ()) != 0:
                message = ct.defsmsnew

        if message != None:
            queue_complaint_update_sms (cpl.filedby.mobile, message, cpl)

        return accept_cpl
def gateway(request):
    print "came in gateway"
    if request.method == "GET":
        transferreq = SMSTransferReqFormat(request.GET)
        if transferreq.is_valid() == True:
            messages = []
            for tm in TextMessage.objects.filter(processed=False):
                messages.append({"to": tm.phone, "message": tm.message})
                tm.processed = True
                tm.processed_time = datetime.now()
                tm.save()
            return HttpResponse(json.dumps({"payload": {"task": "send", "secret": "0123456789", "messages": messages}}))
        else:
            # non user generated request, just ignore this
            return HttpResponse(json.dumps({"payload": {"success": "true"}}))
    elif request.method == "POST":
        receivedform = SMSReceivedFormat(request.POST)
        # debug ("Received from: " + str (receivedform))
        if receivedform.is_valid():
            try:
                # debug ("Form is valid")
                sender_phone = receivedform.cleaned_data["from"]
                message = receivedform.cleaned_data["message"]
                rtm = ReceivedTextMessage.objects.create(sender=sender_phone, valid=False, message=message)

                matches = re.match(FORMAT, message, re.S)
                if matches != None:
                    block = str(int(matches.group("block")))
                    gramp = str(int(matches.group("gramp")))
                    villg = str(int(matches.group("villg")))
                    sender_name = matches.group("name")
                    issue_desc = matches.group("complaint")
                    citizen = get_or_create_citizen(sender_phone, sender_name)
                    location = get_location_attr(block, gramp, villg)
                    compl = Complaint.objects.create(
                        complainttype=None,
                        complaintno=None,
                        description=issue_desc,
                        department=None,
                        curstate=STATUS_NEW,
                        filedby=citizen,
                        logdate=datetime.today().date(),
                        location=location,
                        original=None,
                        creator=None,
                    )
                    update_complaint_sequence(compl)
                    ComplaintClosureMetric.objects.create(complaintno=compl.complaintno)

                    # If we reach this point, the message was properly formatted
                    rtm.valid = True
                    rtm.complaint = compl
                    rtm.save()

                    # Remove the user from blacklist in case he is there
                    for sbl in SenderBlacklist.objects.filter(sender=rtm.sender):
                        # debug ("Removing sender from blacklist: " + str (rtm.sender))
                        sbl.delete()

                    text_message = _(
                        "Your Grievance number is %s. We would revert in 36 hours to seek more details"
                        % (compl.complaintno)
                    )
                    queue_sms(sender_phone, text_message)
                    return HttpResponse(json.dumps({"payload": {"success": "true"}}))
                else:
                    itm = IgnoredTextMessage.objects.create(sender=sender_phone, valid=False, message=message)
                    raise InvalidMessageException
            except (InvalidMessageException, ObjectDoesNotExist) as e:
                # Improperly formatted
                # check if the user is black listed, keep the sender black listed and don't respond
                if not is_blacklisted(rtm.sender):
                    if not new_blacklist(rtm.sender):
                        text_message = "Call center would respond in next 36 hrs after looking into your issue"
                        queue_sms(sender_phone, text_message)
                else:
                    # debug ("Sender is blacklisted. Not sending ack: " + str (rtm.sender))
                    pass
                return HttpResponse(json.dumps({"payload": {"success": "true"}}))
        else:
            # In this case, we can safely assume that the message is not coming from
            # SMSSync so silently ignore.
            return HttpResponse(json.dumps({"payload": {"success": "true"}}))
    else:
        return HttpResponseForbidden
    def save_data (self, rowid, cells):
        skiprow = False
        reason = ""

        if cells [-1] != None and cells [-1].lower () == 'reject':
            skiprow = True
            reason = "Row is marked for skipping"

        if skiprow == False:
            if None in cells [:-1]:
                skiprow = True
                reason = "Empty cells in row"

        if skiprow == False:
            try:
                dept = ComplaintDepartment.objects.get (code = cells [COL_DEPT_CODE])
            except ComplaintDepartment.DoesNotExist:
                skiprow = True
                reason = "Department with code [%s] not found" % (cells [COL_DEPT_CODE])
            except ComplaintDepartment.MultipleObjectsReturned:
                skiprow = True
                reason = "Multiple departments found with code: " + cells [COL_DEPT_CODE]

        if skiprow == False:
            try:
                ct = ComplaintType.objects.get (code = "%s.%s" % (dept.code, cells [COL_COMP_CODE]))
            except ComplaintType.DoesNotExist:
                skiprow = True
                reason = "Complaint Type not found with department code [%s] and complaint code [%s]" % (dept.code, cells [COL_COMP_CODE])
            except ComplaintType.MultipleObjectsReturned:
                skiprow = True
                reason = "Multiple Complaint Types found with department code [%s] and complaint code [%s]" % (dept.code, cells [COL_COMP_CODE])

        if skiprow == False:
            try:
                gp = GramPanchayat.objects.get (code = DeployDistrict.DISTRICT.code + ".%s.%s" % (cells [COL_BLOK_CODE], cells [COL_GRAM_CODE]))
            except GramPanchayat.DoesNotExist:
                skiprow = True
                reason = "Gram Panchayat not found with Block code [%s] and Gram Panchayat code [%s]" % (cells [COL_BLOK_CODE], cells [COL_GRAM_CODE])
            except GramPanchayat.MultipleObjectsReturned:
                skiprow = True
                reason = "Multiple Gram Panchayat found with Block code [%s] and Gram Panchayat code [%s]" % (cells [COL_BLOK_CODE], cells [COL_GRAM_CODE])

        if skiprow == False:
            village_codes = sorted ([v.code for v in gp.village_set.all ()])
            if len (village_codes) == 0:
                skiprow = True
                reason  = "No villages are present in Gram Panchayat with Block code [%s] and Gram Panchayat code [%s]" % (cells [COL_BLOK_CODE], cells [COL_GRAM_CODE])
            else:
                try:
                    village = gp.village_set.all ().get (code = village_codes [0])
                except Village.MultipleObjectsReturned:
                    skiprow = True
                    reason = "Multiple village exist with the same code. Gram Panchayat Code [%s] and Village code [%s]" % (gp.code, village_codes [0])

        if skiprow:
            print "Skipping row [%d], REFNO: %s, reason: %s" % ((rowid + 1), cells [COL_REFR_NUMB], reason)
        else:
            c = Complaint.objects.create (complainttype = ct,
                                          description = cells [COL_REFR_NUMB] + ":" +  translate (cells [COL_COMP_DESC]),
                                          department = dept,
                                          curstate = STATUS_NEW,
                                          filedby = get_or_create_citizen ('9977001872', translate (cells [COL_CITI_NAME])),
                                          location = village,
                                          logdate = datetime.today ())
            update_complaint_sequence (c)

            ComplaintClosureMetric.objects.create (complaintno = cpl.complaintno)

            randpos  = int (random () * NUM_DATES)
            backdate = AGOS [randpos]
            c.created    = backdate
            c.createdate = backdate
            c.save ()