Beispiel #1
0
def create_programs(output=True):
    """Create programs and services from the DEFAULT_PROGRAMS dictionary, reflecting actual P-P organization"""
    for program, services in DEFAULT_PROGRAMS.items():
        p = Program()
        p.name = program

        if p.name in HAS_QUEUE:
            p.has_queue = True
        else:
            p.has_queue = False
        p.full_clean()
        p.save()

        if output:
            print("Created program {}".format(p.name))

        for service in services:
            s = Service()
            s.name = service
            s.slug = f"{p.name}-{s.name}"

            s.available = random_bool()
            s.program = p
            s.full_clean()
            s.save()

            if output:
                print("Created {}: '{}'".format(p.name, s.slug))

        """ Create forms for the program """
        for _ in range(DEFAULT_NUMBER_FORMS):
            create_form(p)
def new_art_service(request):
    context = {'categories': Category.create_choices_category()}
    if request.method == 'GET':
        form = ServiceForm()
        context.update({'form': form})
        return render(request, 'dashboard_admin/new_art_service.html', context)

    else:
        form = ServiceForm(request.POST, request.FILES)
        context.update({'form': form})
        if form.is_valid():
            category_id = int(request.POST.get('category'))
            category = Category.objects.get(id=category_id)

            service = Service()
            service.description = form.cleaned_data['description']
            service.image = form.cleaned_data['image']
            service.category = category
            service.value = Service.change_for_decimal(
                form.cleaned_data['value'])
            service.save()

            messages.success(request, 'Novo serviço criado com sucesso!')
            return HttpResponseRedirect(
                reverse('dashboard_admin:all_services'))
        else:
            messages.error(request, 'Erro ao tentar salvar!')
            return render(request, 'dashboard_admin/new_art_service.html',
                          context)
Beispiel #3
0
    def create(self):
        nodetemplate = self.nodetemplate

        xos_args = self.get_xos_args()
        service = Service(**xos_args)
        service.caller = self.user
        service.save()

        self.postprocess(service)

        self.info("Created Service '%s'" % (str(service), ))
Beispiel #4
0
def service_add_page(request):
    if request.method == "POST":

        plan = request.POST.get('plan')
        users = request.POST.get('users')
        hostname = request.POST.get('hostname')

        if not plan:
            context = {
                    "plans": Plan.objects.all(),
                    "form_message": {"error": "Add service error", "message": "No plan selected.", "type": "danger"}
                    }
            return render(request, 'service_add.html', context)

        if not hostname:
            context = {
                    "plans": Plan.objects.all(),
                    "form_message": {"error": "Add service error", "message": "No hostname given.", "type": "danger"}
                    }
            return render(request, 'service_add.html', context)

        if Service.objects.filter(hostname=hostname).count():
            context = {
                    "plans": Plan.objects.all(),
                    "form_message": {"error": "Add service error", "message": "Hostname \"%s\" already taken. Choose another one." % hostname, "type": "danger"}
                    }
            return render(request, 'service_add.html', context)

        try:
            this_user = Account.objects.get(id=request.user.id)
            chosen_base_plan = Plan.objects.get(id=plan)
            new_service = Service()
            new_service.account = this_user
            new_service.plan = chosen_base_plan
            new_service.users = users
            new_service.hostname = hostname
            new_service.status = 'active'
            new_service.save()

            Notification.objects.create(account=this_user, description="New service \"%s\" added." % new_service.hostname, status="info")

        except Exception as e:
            context = {"form_message": {"error": "Add service error", "message": str(e), "type": "danger"}}
            return render(request, 'service_add.html', context)

        return HttpResponseRedirect(reverse('index_page'))

    else:
        if not request.user.has_balance():
            context = {"form_message": {"error": "Add service error", "message": "You cannot add service if your balance is below $1.", "type": "danger"} }
            return render(request, 'services.html', context)

        context = { "plans": Plan.objects.all()}
        return render(request, 'service_add.html', context)
Beispiel #5
0
def create_programs(output=True):
    '''Create programs and services from the DEFAULT_PROGRAMS dictionary, reflecting actual P-P organization'''
    for program, services in DEFAULT_PROGRAMS.items():
      p = Program()
      p.name = program
      p.full_clean()
      p.save()

      if output:
          print("Created program {}". format(p.name))

      for service in services:
          s = Service()
          s.name = service
          s.program = p
          s.available = random_bool()
          s.full_clean()
          s.save()

          if output:
              print("Created {}: '{}'". format(p.name, s.name))
Beispiel #6
0
    def import_mu_data(self, legal_entities, reader, encoding):
        reader.next()
        header = self.parse_header(reader.next(), encoding)

        counter = 2
        created_types = 0
        empty_types = 0
        empty_streets = 0
        unknown_streets = 0
        unknown_addresses = 0
        for row in reader:
            print "Processing row", counter
            counter += 1
            lpu = row[header["GLAVNOE_LPU"]].decode(encoding).strip()
            if len(lpu) == 0:
                lpu = row[header["NAME"]].decode(encoding).strip()
            if len(lpu) == 0:
                stderr.write("Legal entity name is empty at %d" % (counter))
                continue
            lpu = legal_entities[lpu]
            hotype = row[header["TYPE"]].decode(encoding).strip()
            if len(hotype) == 0:
                stderr.write(u"Empty type at %d\n" % (str(counter + 3),))
                empty_types += 1
                continue
            hotype, created = HealthObjectType.objects.get_or_create(name=hotype)
            if created:
                created_types += 1

            street = row[header["ADRES_UL_NAME"]].decode(encoding).strip()
            address = None
            if len(street) == 0:
                stderr.write(u"Empty street at %d\n" % (counter + 3,))
                empty_streets += 1
                unknown_addresses += 1
            else:
                streets = self.get_streets(header, row, street, encoding)
                if len(streets) == 0:
                    stderr.write(u"Unknown street at %d\n" % (counter + 3,))
                    error = u"Улица не найдена: " + street
                    unknown_streets += 1
                    unknown_addresses += 1
                else:
                    address, error = self.get_address(header, row, streets, encoding, counter + 3)
                    if address is None:
                        unknown_addresses += 1

            mu = HealingObject()
            mu.object_type = hotype
            mu.legal_entity = lpu
            #self.fill_chief_data(header, row, mu, counter + 3, encoding)
            mu.address = address
            mu.original_address = row[header["ADRES_STR"]].decode(encoding).strip()
            name = row[header["NAME"]].decode(encoding).strip()
            mu.name = name
            mu.short_name = row[header["SHORT_NAME"]].decode(encoding).strip()
            mu.full_name = row[header["FULL_NAME"]].decode(encoding).strip() or name
            mu.global_id = row[header["GLOBALID"]].strip()
            mu.info = row[header["INFO"]].decode(encoding).strip()
            mu.errors = error
            try:
                mu.clean_fields()
                mu.save()
            except ValidationError as e:
                self.show_validation_error("Error validating healing object", mu, e)
                raise

            service = Service()
            service.healing_object = mu
            service_type_name = object_type_to_service_type[hotype.name]
            service.service = ServiceType.objects.get(name=service_type_name)
            self.fill_chief_data(header, row, service, counter + 3, encoding)
            service.phone = row[header["TEL_NOMER"]].decode(encoding).strip()
            service.fax = row[header["FAX_NOMER"]].decode(encoding).strip()
            service.info = row[header["INFO"]].decode(encoding).strip()
            service.workdays = row[header["DNY_RABOTY1"]].decode(encoding).strip()
            service.workhours = row[header["CHAS_RABOTY"]].decode(encoding).strip()
            service.daysoff = row[header["DNY_NE_RABOT"]].decode(encoding).strip()
            service.daysoff_restrictions = row[header["VYHODNOJ_TYPE"]].decode(encoding).strip()
            service.specialization = row[header["SPECIAL"]].decode(encoding).strip()
            service.paid_services = row[header["PLAT_USLUGI"]].decode(encoding).strip()
            service.free_services = row[header["BESPL_USLUGI"]].decode(encoding).strip()
            service.drug_provisioning = row[header["LEK_OBESP"]].decode(encoding).strip()
            service.departments = row[header["OTDELENIE"]].decode(encoding).strip()
            service.hospital_levels = row[header["LVL"]].decode(encoding).strip()
            service.tour = row[header["SMENA"]].decode(encoding).strip()
            service.receipes_provisioning = row[header["RECEPT"]].decode(encoding).strip()
            service.drugstore_type = row[header["DRUGSTORE_TYPE"]].decode(encoding).strip()
            service.hospital_type = row[header["HOSPITAL_TYPE"]].decode(encoding).strip()
            beds = row[header["KOIKI"]].decode(encoding).strip()
            if len(beds) == 0:
                beds = row[header["KOJKA"]].decode(encoding).strip()
                if len(beds) == 0:
                    beds = row[header["KOIKA"]].decode(encoding).strip()
            service.hospital_beds = beds
            try:
                service.clean_fields()
                service.save()
            except ValidationError as e:
                self.show_validation_error("Error validating service", service, e)
                raise

        print "Total: %d" % (counter,)
        print "Unknown addresses: %d" % (unknown_addresses,)
        print "Empty streets: %d" % (empty_streets,)
        print "Unknown streets: %d" % (unknown_streets,)
        print "Empty types: %d" % (empty_types,)
Beispiel #7
0
    def handle(self, *args, **options):
        print "Pulling"
        for s in self.STATES:
            resp = urllib2.urlopen(self.URL % s).read()
            soup = BeautifulSoup(resp)
            entries = soup.findAll('p', {'align' : 'center'})
            for e in entries:
                raw = str(e)
                content = e.text.lower()


                person = Person()

                beer = re.search('(?<=beer type:).*?(?=<)', raw, re.IGNORECASE+re.DOTALL)
                if beer:
                    person.beer = beer.group(0)

                name = re.search('[a-z ]+?(?=<)', raw, re.IGNORECASE)
                if name:
                    person.name = name.group(0)
                email = e.findAll('a')
                if email:
                    person.email = email[0]['href'].replace('mailto:', '')

                if 'emergency' in content:
                    person.ok_contact = 0

                phone = re.search('(?<=phone:)[ 0-9-]{7,14}', content)
                if phone:
                    person.phone = phone.group(0).strip()


                #Location stuff
                loc = ''
                location = re.search('(?<=crossroads:).*?(?=<)', raw, re.DOTALL+re.IGNORECASE)
                if location:
                    location = location.group(0)
                    location = location.replace('&nbsp;', '')
                    location = location.replace('&amp;', ' and ')
                    loc += location
                zipcode = re.search('[0-9]{5}', raw)
                if zipcode:
                    loc += ' ' + zipcode.group(0)
                loc = loc.strip()
                if len(loc) > 4:
                    loc += ' ' + s + ', USA'
                    url = 'https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false' % loc
                    geocode = urllib2.urlopen(urllib.quote(url, safe="%/:=&?~#+!$,;'@()*[]")).read()
                    data = json.loads(geocode)
                    if data.get('results', False) and data['results'][0].get('geometry', False):
                        lat = data['results'][0]['geometry']['location']['lat']
                        lng = data['results'][0]['geometry']['location']['lng']
                        address = data['results'][0]['formatted_address']
                        person.lat = lat
                        person.lng = lng
                        person.address = address
                    if person.lat != 0 and person.lng != 0 and len(person.phone) > 6:
                        try:
                            Person.objects.get(lat = lat, lng = lng)
                            print "Skipping %s" % person.name
                        except Person.DoesNotExist:
                            print "Saving %s" % person.name
                            print "PHONE %s" % person.phone
                            print "EMAIL %s" % person.email
                            person.save()
                            services = re.search('(?<=services:).*?(?=camping:)', raw, re.DOTALL+re.IGNORECASE)
                            if services:
                                services = services.group(0)
                                services = services.split('<br />')
                                for s in services:
                                    service = re.search('[A-Za-z -&]+', s)
                                    if service and len(service.group(0)):
                                        name = service.group(0)
                                        try:
                                            srv = Service.objects.get(name__iexact = self.first_letter_caps(name))
                                            person.services.add(srv)
                                        except Service.DoesNotExist:
                                            ns = Service(name = self.first_letter_caps(name))
                                            ns.save()
                                            person.services.add(ns)

                            person.save()