示例#1
0
def new_impress_service(request):
    context = {'categories': Category.create_choices_category()}
    if request.method == 'GET':
        form = ServiceForm()
        context.update({'form': form})
        return render(request, 'dashboard_admin/new_impress_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 = ServiceImpress()
            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.value_creation_art = \
            Service.change_for_decimal(form.cleaned_data['value_creation_art'])
            service.deadline = form.cleaned_data['deadline']
            service.save()
            messages.success(request, 'Novo serviço criado com sucesso!')
            return HttpResponseRedirect(
                reverse('dashboard_admin:all_services'))
        else:
            messages.error(request, form.errors)
            return render(request, 'dashboard_admin/new_impress_service.html',
                          context)
示例#2
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)
示例#3
0
    def get(self, request, *args, **kwargs):

        app_name = request.GET.get('app')
        cmd = request.GET.get('cmd', None)

        app = App.objects.get(short_name=app_name)

        client = BuilderClient('192.168.56.1', 10001)

        service_list = app.service_list()

        res_info = {}

        if cmd is None or cmd == 'status':
            res_info = client.status(service_list)
            Service.update_from_info(res_info)

        if cmd == 'build':

            res_info = client.build(app_name, service_list)
            Service.update_from_info(res_info)

        if cmd == 'start':
            res_info = client.start(app_name, service_list)
            Service.update_from_info(res_info)

        if cmd == 'stop':
            res_info = client.stop(app_name, service_list)
            Service.update_from_info(res_info)

        if cmd == 'remove':
            res_info = client.remove(app_name, service_list)
            Service.update_from_info(res_info)

        return HttpResponse(str(res_info))
示例#4
0
def partnerOrderPrice(request):
    try:
        user = request.user
        Profile.objects.get(user=user)
        originCountry = request.data.get('originCountry')
        destinationCountry = request.data.get('destinationCountry')
        shippingWeight = request.data.get('shippingWeight')
        shippingMode = request.data.get('shippingMode')
        service = Service.objects.get(id=request.data.get('service'))
        if shippingMode == EXPRESS_SHIPPING:
            serviceCosts = Service.computeExpressCosts(
                shippingWeight,
                originCountry,
                destinationCountry,
                service.partnerForwarderMargin
            )
        else:
            serviceCosts = Service.computeStandardCosts(
                shippingWeight,
                originCountry,
                destinationCountry,
                service.partnerForwarderMargin
            )
        finalPrice = functools.reduce(lambda a, b: a + b, map(lambda p: p['amount'], serviceCosts))
        finalPrice = Service.eurToUsdConversion(finalPrice)

        return Response({'success': True, 'price': finalPrice})
    except Exception as e:
        return Response({'success': False, 'error': e.message})
示例#5
0
def edit_service(request, service_id):
    try:
        service = ServiceImpress.objects.get(id=service_id)
    except:
        service = Service.objects.get(id=service_id)

    infos_categories = Category.get_names_and_id()
    current_category = service.category
    context = {
        'service': service,
        'infos_categories': infos_categories,
        'current_category': service.category.id
    }

    if request.method == 'GET':
        data = {
            'description': service.description,
            'image': service.image.url,
            'value': service.value,
        }

        if service.__class__.__name__ == 'ServiceImpress':
            data['value_creation_art'] = service.value_creation_art

        form = ServiceForm(initial=data)
        context.update({'form': form})

    else:

        form = ServiceForm(request.POST, request.FILES)
        if form.is_valid():
            category = Category.objects.get(
                id=int(request.POST.get('category')))

            service.description = form.cleaned_data['description']
            if form.cleaned_data['image']:
                service.image = form.cleaned_data['image']
            service.category = category
            service.value = Service.change_for_decimal(
                form.cleaned_data['value'])
            if service.__class__.__name__ == 'ServiceImpress':
                service.value_creation_art = \
                Service.change_for_decimal(form.cleaned_data['value_creation_art'])
            service.save()
            context.update({'form': form})
            context.update({'current_category': service.category.id})
            messages.success(request, 'Serviço editado com sucesso!')

        else:
            # print(form.errors)
            messages.warning(request,
                             'Não foi possível realizar essa operação')

    return render(request, 'dashboard_admin/edit_service.html', context)
示例#6
0
文件: service.py 项目: rikkyzhu/xos
    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), ))
示例#7
0
def init_database():
    init_db()

    # Creating plans
    plans = [Plan("Free",False),Plan("Basic",False),Plan("Premium",True)]
    
    # Creating services
    services = [Service(name="Evernote"),Service(name="Onenote")]

    db_session.add_all(plans)
    db_session.add_all(services)
    db_session.commit()
    return jsonify(status="ok")
示例#8
0
def searchP2PForwarders(request):
    user = request.user
    profile = Profile.objects.get(user=user)
    locationFrom = request.data.get('locationFrom')
    locationFromList = Location.objects.filter(countryCode=locationFrom['countryCode'])
    locationFrom = locationFromList.values_list('pk', flat=True)
    locationTo = request.data.get('locationTo')
    locationToList = Location.objects.filter(countryCode=locationTo['countryCode'])
    locationTo = locationToList.values_list('pk', flat=True)
    maxWeight = request.data.get('maxWeight')
    maxSize = request.data.get('maxSize')
    maxGoodValue = request.data.get('maxGoodValue')
    if profile.currencySetting == settings.PROFILE_CURRENCY_SETTINGS[1][0]:
        maxGoodValue = Service.eurToUsdConversion(maxGoodValue)
    configMaxGoodValuePercentage = Configuration().getConfiguration("p2p_forwarder_maxgoodvalue_percentage")
    services = []
    if request.data.get('acceptedPacksFromPrivateOrCompany'):
        acceptPackagesFromprivateOrCompanyQuery = Q(acceptedPacksFromPrivate=True)
    else:
        acceptPackagesFromprivateOrCompanyQuery = Q(acceptedPacksFromCompany=True)
    servicesTmp = Service.objects.filter(
        Q(
            type=SERVICE_TYPES[0][0],
            enabled=True,
            locationFrom__in=list(locationFrom),
            locationTos__in=list(locationTo),
            maxSize__gte=maxSize,
            maxWeight__gte=maxWeight,
        )
        & acceptPackagesFromprivateOrCompanyQuery
    ).exclude(profile=profile).distinct()

    # Check Max Good Value in Service -> profile -> wallet
    for s in servicesTmp:
        wallet = Wallet.objects.get(
            profile=s.profile
        )
        if wallet.deposit > 0:
            walletMaxGoodValue = (configMaxGoodValuePercentage * wallet.deposit) / 100
            if walletMaxGoodValue >= maxGoodValue:
                services.append(s)
    shippingWeight = 0.5
    if maxWeight == 1:
        shippingWeight = 7
    elif maxWeight == 2:
        shippingWeight = 8
    for s in services:
        originCountry = CountryManager.countryByCoutryCode(s.locationFrom.countryCode)['name']
        destinationCountry = CountryManager.countryByCoutryCode(locationToList[0].countryCode)['name']
        s.setLowestPrice(
            shippingWeight=shippingWeight,
            originCountry=originCountry,
            destinationCountry=destinationCountry,
            margin=s.partnerForwarderMargin
        )

    serviceSerializer = ServiceProtectedSerializer(services, many=True, context={'request': request})


    return Response({'success': True, 'services': serviceSerializer.data})
示例#9
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)
示例#10
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))
示例#11
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,)
示例#12
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()