Ejemplo n.º 1
0
def AddEntry(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = EntryForm(request.POST)
            if form.is_valid():
                parent = request.user.get_profile()
                entry = Entry(patient=parent,
                              entry=form.cleaned_data['entry'],
                              desc=form.cleaned_data['desc'])
                entry.save()
                if form.cleaned_data['entry'].find('CODE') > -1:
                    return HttpResponseRedirect('/code/')
                else:
                    return HttpResponseRedirect('/profile/')
            else:
                print form.errors
                return render_to_response(
                    'entry.html', {'form': form},
                    context_instance=RequestContext(request))
        else:
            ''' user is not submitting the form '''
            form = EntryForm()
            context = {'form': form}
            return render_to_response('entry.html',
                                      context,
                                      context_instance=RequestContext(request))
    else:
        pass
Ejemplo n.º 2
0
    def import_information(self, entry_data, lead, framework, data):
        old_id = data['id']
        print('Entry info - {}'.format(old_id))

        entry = Entry(
            lead=lead,
            analysis_framework=framework,
        )

        if data.get('excerpt'):
            entry.excerpt = data['excerpt']
            entry.entry_type = Entry.EXCERPT
        elif data.get('image'):
            entry.image = data['image']
            entry.entry_type = Entry.IMAGE

        entry.created_by = get_user(entry_data['created_by'])
        entry.modified_by = entry.created_by

        entry.save()
        Entry.objects.filter(id=entry.id).update(
            created_at=entry_data['created_at']
        )

        # Start migrating the attributes
        elements = data['elements']
        # TODO migrate excerpt and image widget
        for element in elements:
            self.migrate_attribute(entry, framework, element)

        return entry
Ejemplo n.º 3
0
 def handle(self, *args, **options):
     # self.stdout.write( options['name'] )
     t = Entry(name=options['name'])
     t.text = "*This is a stub entry. Add vast knowledge here.*"
     t.clean()
     t.save()
     t.tags.add(Tag.objects.get(slug='stub'))
     self.stdout.write("Created stub article '{}'".format(options['name']))
Ejemplo n.º 4
0
def hello(request):
    try:
        t = Tropo()

        session = Session(request.body)
        if ('parameters' in dir(session)):
            print('Message request')

            t.call(to="+" + session.parameters['to'].strip(), network="SMS")
            json = t.say(session.parameters['msg'])
            json = t.RenderJson(json)
            return HttpResponse(json)

        else:

            msg = request.POST.get('msg', '')
            s = Session(request.body)
            cell = s.fromaddress['id']

            # lookup patient with this cell #
            if cell[0] == '1':  # trim leading 1 in cell # if there
                cell = cell[1:]
            print('Cell #%s' % cell)
            p = Patient.objects.filter(
                cell=cell)  # all patients with this cell #
            if p.exists():  # if cell # found then create new entry
                if p.count() > 1:
                    print('WARNING: Multiple patients with cell # %s' % cell)
                parent = p[0]  # assume first
                entry = Entry(patient=parent, entry=msg)
                entry.save()
                if msg.find('CODE') > -1:
                    json = t.say("Congratulations " + parent.name +
                                 " your code qualified you for a prize!")
                else:
                    json = t.say("Entry saved, thank you " + parent.name)
            else:  # if cell # NOT found then notify
                json = t.say("Could not find patient with cell # " + cell)

            json = t.RenderJson(json)
            return HttpResponse(json)

    except Exception, err:
        print('ERROR: %s\n' % str(err))
Ejemplo n.º 5
0
def hello(request):
    try:
        t = Tropo()
                
        session = Session(request.body)
        if('parameters' in dir(session)):
            print('Message request')

            t.call(to="+"+session.parameters['to'].strip(), network = "SMS")
            json = t.say(session.parameters['msg'])
            json = t.RenderJson(json)
            return HttpResponse(json)

        else :

            msg = request.POST.get('msg', '')
            s = Session(request.body)
            cell = s.fromaddress['id']

            # lookup patient with this cell #
            if cell[0]=='1':   # trim leading 1 in cell # if there
                cell = cell[1:]
            print('Cell #%s' % cell)
            p = Patient.objects.filter(cell=cell)   # all patients with this cell #
            if p.exists():                                    # if cell # found then create new entry
                if p.count()>1:
                    print('WARNING: Multiple patients with cell # %s' % cell)
                parent = p[0]  # assume first 
                entry = Entry(patient=parent, entry=msg)
                entry.save()
                if msg.find('CODE')>-1:
                    json = t.say("Congratulations " + parent.name + " your code qualified you for a prize!")            
                else:
                    json = t.say("Entry saved, thank you " + parent.name)
            else:                                               # if cell # NOT found then notify
                json = t.say("Could not find patient with cell # " + cell)

            json = t.RenderJson(json)
            return HttpResponse(json)

    except Exception, err:
        print('ERROR: %s\n' % str(err))
Ejemplo n.º 6
0
def parse():
	"""
		Parses the text file for entries and adds them to the database 
		if it's not already in it
	"""
	regex = re.compile('(\D+);(\d+);(\d+)')
	with open('static/txt/database.txt', 'r') as myfile:
		for line in myfile:
			result = regex.match(line)
			if result:
				try:
					country = result.group(1)
					denomination = int(result.group(2))
					quantity = int(result.group(3))
					entry = Entry.objects.get(country=country, denomination=denomination)
				except Entry.DoesNotExist:
					entry = Entry(country=country, denomination=denomination, quantity=quantity)
					entry.save()
				except:
					pass
Ejemplo n.º 7
0
def newEntry(request):
	"""
		Grabs the information for the new entry, adds 
		it to the database, and updates the text file.
	"""
	if request.POST.has_key('client_response'):
		# Get entry from the client
		entry = json.loads(request.POST['client_response'])
		# Validate first
		if validates(entry):
			currency = entry['currency'].title()
			denom = int(entry['denomination'])
			quantity = int(entry['quantity'])
			# Write to the database and append to text file
			try:
				entry = Entry.objects.get(country=currency, denomination=denom)
				entry.quantity += quantity
				entry.save()
				string = "%s;%s;" % (currency, denom)
				# Find line in text file and update quantity
				mylist = []
				with open('static/txt/database.txt', 'r') as myfile:
					for line in myfile:
						if line.startswith(string):
							line = "%s;%s;%s\n" % (currency, denom, entry.quantity)
							print 'found old line'
						mylist.append(line)
				with open('static/txt/database.txt', 'w') as myfile:
					for line in mylist:
						myfile.write(line)
			except Entry.DoesNotExist:
				entry = Entry(country=currency, denomination=denom, quantity=quantity)
				entry.save()
				with open('static/txt/database.txt', 'r+a') as myfile:
					last = myfile.readlines()[-1]
					# Check if the file ended in a newline
					string = '' if '\n' in last else '\n'
					myfile.write("%s%s;%s;%s\n" % (string, currency, denom, quantity))
			organize(False)
			return HttpResponse('success')
	return HttpResponse('failure')
Ejemplo n.º 8
0
def AddEntry(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = EntryForm(request.POST)
            if form.is_valid():
                parent = request.user.get_profile()
                entry = Entry(patient=parent, entry=form.cleaned_data['entry'], desc=form.cleaned_data['desc'])
                entry.save()
                if form.cleaned_data['entry'].find('CODE')>-1:
                    return HttpResponseRedirect('/code/')
                else:
                    return HttpResponseRedirect('/profile/')
            else:
                print form.errors
                return render_to_response('entry.html', {'form':form}, context_instance=RequestContext(request))
        else:
            ''' user is not submitting the form '''
            form = EntryForm()
            context = {'form': form}
            return render_to_response('entry.html', context, context_instance=RequestContext(request))
    else:
        pass
Ejemplo n.º 9
0
    def test_show_advanced_search_results_csv_escape(self):
        user = self.admin

        dummy_entity = Entity.objects.create(name='Dummy', created_user=user)
        dummy_entry = Entry(name='D,U"MM"Y',
                            schema=dummy_entity,
                            created_user=user)
        dummy_entry.save()

        CASES = [[AttrTypeStr, 'raison,de"tre', '"raison,de""tre"'],
                 [AttrTypeObj, dummy_entry, '"D,U""MM""Y"'],
                 [
                     AttrTypeText, "1st line\r\n2nd line",
                     '"1st line' + "\r\n" + '2nd line"'
                 ],
                 [
                     AttrTypeNamedObj, {
                         "key": dummy_entry
                     }, "\"key: D,U\"\"MM\"\"Y\""
                 ],
                 [
                     AttrTypeArrStr, ["one", "two", "three"],
                     "\"one\nthree\ntwo\""
                 ], [AttrTypeArrObj, [dummy_entry], "\"D,U\"\"MM\"\"Y\""],
                 [
                     AttrTypeArrNamedObj, [{
                         "key1": dummy_entry
                     }], "\"key1: D,U\"\"MM\"\"Y\""
                 ]]

        for case in CASES:
            # setup data
            type_name = case[0].__name__  # AttrTypeStr -> 'AttrTypeStr'
            attr_name = type_name + ',"ATTR"'

            test_entity = Entity.objects.create(name="TestEntity_" + type_name,
                                                created_user=user)

            test_entity_attr = EntityAttr.objects.create(
                name=attr_name,
                type=case[0],
                created_user=user,
                parent_entity=test_entity)

            test_entity.attrs.add(test_entity_attr)
            test_entity.save()

            test_entry = Entry.objects.create(name=type_name + ',"ENTRY"',
                                              schema=test_entity,
                                              created_user=user)
            test_entry.save()

            test_attr = Attribute.objects.create(name=attr_name,
                                                 schema=test_entity_attr,
                                                 created_user=user,
                                                 parent_entry=test_entry)

            test_attr.save()
            test_entry.attrs.add(test_attr)
            test_entry.save()

            test_val = None

            if case[0].TYPE & AttrTypeValue['array'] == 0:
                if case[0] == AttrTypeStr:
                    test_val = AttributeValue.create(user=user,
                                                     attr=test_attr,
                                                     value=case[1])
                elif case[0] == AttrTypeObj:
                    test_val = AttributeValue.create(user=user,
                                                     attr=test_attr,
                                                     referral=case[1])
                elif case[0] == AttrTypeText:
                    test_val = AttributeValue.create(user=user,
                                                     attr=test_attr,
                                                     value=case[1])
                elif case[0] == AttrTypeNamedObj:
                    [(k, v)] = case[1].items()
                    test_val = AttributeValue.create(user=user,
                                                     attr=test_attr,
                                                     value=k,
                                                     referral=v)
            else:
                test_val = AttributeValue.create(user=user, attr=test_attr)
                test_val.set_status(AttributeValue.STATUS_DATA_ARRAY_PARENT)
                for child in case[1]:
                    test_val_child = None
                    if case[0] == AttrTypeArrStr:
                        test_val_child = AttributeValue.create(user=user,
                                                               attr=test_attr,
                                                               value=child)
                    elif case[0] == AttrTypeArrObj:
                        test_val_child = AttributeValue.create(user=user,
                                                               attr=test_attr,
                                                               referral=child)
                    elif case[0] == AttrTypeArrNamedObj:
                        [(k, v)] = child.items()
                        test_val_child = AttributeValue.create(user=user,
                                                               attr=test_attr,
                                                               value=k,
                                                               referral=v)
                    test_val.data_array.add(test_val_child)

            test_val.save()
            test_attr.values.add(test_val)
            test_attr.save()

            test_entry.register_es()

            resp = self.client.post(
                reverse('dashboard:export_search_result'),
                json.dumps({
                    'entities': [test_entity.id],
                    'attrinfo': [{
                        'name': test_attr.name,
                        'keyword': ''
                    }],
                    'export_style':
                    'csv',
                }), 'application/json')
            self.assertEqual(resp.status_code, 200)

            content = Job.objects.last().get_cache()
            header = content.splitlines()[0]
            self.assertEqual(header, 'Name,Entity,"%s,""ATTR"""' % type_name)

            data = content.replace(header, '', 1).strip()
            self.assertEqual(
                data, '"%s,""ENTRY""",%s,%s' %
                (type_name, test_entity.name, case[2]))
Ejemplo n.º 10
0
    def update(self, entry: Entry, validated_data):
        entry.set_status(Entry.STATUS_EDITING)
        user: User = self.context["request"].user

        entity_name = entry.schema.name
        if custom_view.is_custom("before_update_entry", entity_name):
            custom_view.call_custom("before_update_entry", entity_name, user,
                                    validated_data, entry)

        attrs_data = validated_data.pop("attrs", [])

        # update name of Entry object. If name would be updated, the elasticsearch data of entries
        # that refers this entry also be updated by creating REGISTERED_REFERRALS task.
        job_register_referrals: Optional[Job] = None
        if "name" in validated_data and entry.name != validated_data["name"]:
            entry.name = validated_data["name"]
            entry.save(update_fields=["name"])
            job_register_referrals = Job.new_register_referrals(user, entry)

        for entity_attr in entry.schema.attrs.filter(is_active=True):
            attr: Attribute = entry.attrs.filter(schema=entity_attr,
                                                 is_active=True).first()
            if not attr:
                attr = entry.add_attribute_from_base(entity_attr, user)

            # skip for unpermitted attributes
            if not user.has_permission(attr, ACLType.Writable):
                continue

            # make AttributeValue object if the value is specified
            attr_data = [
                x for x in attrs_data if int(x["id"]) == entity_attr.id
            ]
            if not attr_data:
                continue

            # Check a new update value is specified, or not
            if not attr.is_updated(attr_data[0]["value"]):
                continue

            attr.add_value(user, attr_data[0]["value"])

        if custom_view.is_custom("after_update_entry", entity_name):
            custom_view.call_custom("after_update_entry", entity_name, user,
                                    attrs_data, entry)

        # update entry information to Elasticsearch
        entry.register_es()

        # clear flag to specify this entry has been completed to edit
        entry.del_status(Entry.STATUS_EDITING)

        # running job of re-register referrals because of chaning entry's name
        if job_register_referrals:
            job_register_referrals.run()

        # running job to notify changing entry event
        job_notify_event: Job = Job.new_notify_update_entry(user, entry)
        job_notify_event.run()

        return entry