Beispiel #1
0
def index(request):
    query = request.GET.copy()

    # Default organizers: If visiting a local site, default to the owner of the current site (except for DNT central)
    if not request.GET.get("organizers", "") and request.site.forening.id != Forening.DNT_CENTRAL_ID:
        query["organizers"] = "%s:%s" % ("forening", request.site.forening.id)

    # Default minimum duration is always 1
    query["min_duration"] = query.get("min_duration", "1")

    filter, aktivitet_dates = filter_aktivitet_dates(query)
    aktivitet_dates_pagenav = paginate_aktivitet_dates(filter, aktivitet_dates)

    # Usually, the 'sentral' type is sorted first, but in this case we want it last
    all_foreninger = Forening.get_all_sorted()
    sentral = all_foreninger[0]
    if not sentral["code"] == "sentral":
        # We made an incorrect assumption, log it but try to continue rendering instead of raising an error
        logger.error(
            "Assumed first group of forening to be type 'sentral', was really '%s'" % sentral["code"],
            extra={"request": request, "all_foreninger": all_foreninger},
        )
    # Remove and append the sentral group to the end
    all_foreninger.remove(sentral)
    all_foreninger.append(sentral)

    # Look up DNT cabins with serving
    cabins = sorted(
        Sted.list(
            params={
                "tags": "Hytte",
                "betjeningsgrad": "Betjent",
                "privat": {"hytteeier": "DNT"},
                "status": "Offentlig",
                "tilbyder": "DNT",
            }
        ),
        key=lambda s: s["navn"],
    )

    context = {
        "aktivitet_dates": aktivitet_dates_pagenav,
        "difficulties": Aktivitet.DIFFICULTY_CHOICES,
        "categories": Aktivitet.CATEGORY_CHOICES,
        "category_types": Aktivitet.CATEGORY_TYPES_LIST,
        "audiences": Aktivitet.AUDIENCE_CHOICES,
        "omrader": sorted(Område.list(params={"status": "Offentlig", "tilbyder": "DNT"}), key=lambda o: o["navn"]),
        "cabins": cabins,
        "all_foreninger": all_foreninger,
        "filter": filter,
    }
    return render(request, "common/aktiviteter/index.html", context)
    def admin_context(self, site):
        # Look up DNT cabins with serving
        cabins = sorted(Sted.list(params={
            'tags': 'Hytte',
            'betjeningsgrad': 'Betjent',
            'grupper': '',
            'privat': {'hytteeier': 'DNT'},
            'status': 'Offentlig',
            'tilbyder': 'DNT',
        }), key=lambda s: s['navn'])

        return {
            'all_foreninger_sorted': Forening.get_all_sorted(),
            'audiences': Aktivitet.AUDIENCE_CHOICES,
            'categories': Aktivitet.CATEGORY_CHOICES,
            'category_types': [{
                'category': [c[1] for c in Aktivitet.CATEGORY_CHOICES if c[0] == category['category']][0],
                'types': category['types']
            } for category in Aktivitet.CATEGORY_TYPES_LIST],
            'cabins': cabins,
        }
def prices(request, version, format):
    def format_prices(forening, lang):
        return {
            'overnatting': [{
                'id': lodging.id,
                'navn': lodging.name_eng if lang == 'en' else lodging.name,
                'pris_medlem': lodging.price_member,
                'pris_ikkemedlem': lodging.price_nonmember,
            } for lodging in forening.lodging_prices.all()],

            'proviant': [{
                supply_category.name_eng if lang == 'en' else supply_category.name: [{
                    'id': supply.id,
                    'navn': supply.name_eng if lang == 'en' else supply.name,
                    'pris_medlem': supply.price_member,
                    'pris_ikkemedlem': supply.price_nonmember,
                } for supply in supply_category.supplies.all()]
            } for supply_category in forening.supply_categories.all()]
        }

    librato.increment('sherpa.api.tailored.priser.request')

    if request.method != 'GET':
        librato.increment('sherpa.api.tailored.priser.response.400')
        raise BadRequest(
            "Unsupported HTTP verb '%s'" % request.method,
            code=error_codes.UNSUPPORTED_HTTP_VERB,
            http_code=400,
        )

    if request.GET.get('språk', 'nb').lower().startswith('en'):
        lang = 'en'
    else:
        lang = 'nb'

    if 'forening' in request.GET:
        try:
            forening = Forening.objects.get(turbasen_object_id=request.GET['forening'])
            return HttpResponse(json.dumps(format_prices(forening, lang)))
        except Forening.DoesNotExist:
            librato.increment('sherpa.api.tailored.priser.response.404')
            raise BadRequest(
                "A forening with object id '%s', does not exist." % request.GET['forening'],
                code=error_codes.RESOURCE_NOT_FOUND,
                http_code=404,
            )
    elif 'hytte' in request.GET:
        try:
            sted = Sted.get(request.GET['hytte'])
            # @TODO: Use private fields to get the appropriate owner: first forening of privat.juridisk_eier,
            # privat.vedlikeholdes_av
            forening = Forening.objects.get(turbasen_object_id=sted['grupper'][0])
            librato.increment('sherpa.api.tailored.priser.response.200')
            return HttpResponse(json.dumps(format_prices(forening, lang)))
        except DocumentNotFound:
            librato.increment('sherpa.api.tailored.priser.response.404')
            raise BadRequest(
                "A cabin with object id '%s', does not exist." % request.GET['hytte'],
                code=error_codes.RESOURCE_NOT_FOUND,
                http_code=404,
            )
    else:
        librato.increment('sherpa.api.tailored.priser.response.200')
        return HttpResponse(json.dumps([{
            'object_id': forening.turbasen_object_id,
            'navn': forening.name,
            'priser': format_prices(forening, lang),
        } for forening in Forening.objects.filter(type='forening')]))
Beispiel #4
0
def cabin_visit(product_data, user):
    # Create an order with a cabin settlement product
    order = Order(
        amount=0, # Default to 0 and update to correct amount later
        language_code=product_data['språk'],
    )
    if not user.is_anonymous():
        order.user = user
    order.save() # Save to DB in order to create relations, even though we'll have to do an UPDATE later

    cabin_settlement = CabinSettlement(order=order)
    if 'brukerdata' in product_data:
        cabin_settlement.name = product_data['brukerdata']['navn']
        cabin_settlement.email = product_data['brukerdata']['epost']
    cabin_settlement.save()

    amount = 0
    for cabin in product_data['hytter']:
        sted = Sted.get(cabin['id'])
        # @TODO: Use private fields to get the appropriate owner: first forening of privat.juridisk_eier,
        # privat.vedlikeholdes_av
        forening = Forening.objects.get(turbasen_object_id=sted['grupper'][0])

        cabin_visit = CabinVisit(
            cabin_settlement=cabin_settlement,
            cabin_object_id=sted['_id'],
        )
        cabin_visit.save()

        for losji in cabin['losji']:
            # Business rule: Anyone claiming to be a member will get the membership price
            pays_membership_price = losji['ermedlem']

            lodging = Lodging.objects.get(
                id=losji['id'],
                forening=forening.id,
            )

            if losji['antall'] < 0:
                raise PermissionDenied

            # Try to relate this visitor to a user
            user = None
            memberid_unrecognized = None
            if losji['medlemsnummer'] is not None:
                try:
                    user = User.get_or_create_inactive(memberid=losji['medlemsnummer'])
                    # Note that this is where we could verify that the member has paid their annual fee, but it is
                    # currently ignored
                except User.DoesNotExist:
                    # We received an unrecognized memberid, but we'll still allow the purchase, so save the given
                    # memberid for future reference, whatever it is
                    memberid_unrecognized = losji['medlemsnummer']

            # Save the visitor details
            cabin_visitor = CabinVisitor(
                cabin_visit=cabin_visit,
                protocol_number=losji['protokollnummer'],
                user=user,
                memberid_unrecognized=memberid_unrecognized,
                lodging_type=lodging.name,
                price=lodging.get_price(pays_membership_price),
                nights=losji['antall'],
                paid_membership_price=pays_membership_price,
            )
            cabin_visitor.save()

            # Now calculate the lodging price and add it to the total amount
            amount += lodging.get_price(pays_membership_price) * losji['antall']

        for proviant in cabin['proviant']:
            # Business rule: The client decides whether or not supplies should have membership price
            pays_membership_price = product_data['medlemspris']

            supply = Supply.objects.get(
                id=proviant['id'],
                supply_category__forening=forening.id,
            )

            if proviant['antall'] < 0:
                raise PermissionDenied

            # Save a copy of the current products and prices
            supply_purchase = SupplyPurchase(
                cabin_visit=cabin_visit,
                category=supply.supply_category.name,
                name=supply.name,
                price=supply.get_price(pays_membership_price),
                count=proviant['antall'],
                paid_membership_price=pays_membership_price,
            )
            supply_purchase.save()

            # Now calculate the supplies price and add it to the total amount
            amount += supply.get_price(pays_membership_price) * proviant['antall']

    # Save the total amount in øre
    amount *= 100
    order.amount = amount
    order.save()
    return order
Beispiel #5
0
 def get_cabin(self):
     return Sted.get(self.cabin_object_id)
Beispiel #6
0
def index(request):
    filter_ = DEFAULT_FILTER.copy()
    filter_.update(request.GET.dict())

    # Default organizers: If visiting a local site, default to the owner of the current site (except for DNT central)
    if not filter_['organizers'] and request.site.forening.id != Forening.DNT_CENTRAL_ID:
        filter_['organizers'] = '%s:%s' % ('forening', request.site.forening.id)

    # Interestingly, the paginator will perform a COUNT query to count the
    # total number of objects, regardless of whether it is used in the
    # template. Therefore, even if we get a cache hit for the listing template
    # fragment, it will perform the query unnecessarily. So explicitly check
    # if the current filter is cached or not, and if so, skip the pagination.
    cache_key = make_template_fragment_key(
        'aktivitet_listing',
        [filter_hash(filter_)],
    )
    if cache.get(cache_key) is not None:
        aktivitet_dates_pagenav = None
    else:
        filter_, aktivitet_dates = filter_aktivitet_dates(filter_)
        aktivitet_dates_pagenav = paginate_aktivitet_dates(filter_, aktivitet_dates)

    # Usually, the 'sentral' type is sorted first, but in this case we want it last
    all_foreninger = Forening.get_all_sorted()
    sentral = all_foreninger[0]
    if not sentral['code'] == 'sentral':
        # We made an incorrect assumption, log it but try to continue rendering instead of raising an error
        logger.error(
            "Assumed first group of forening to be type 'sentral', was really '%s'" % sentral['code'],
            extra={
                'request': request,
                'all_foreninger': all_foreninger,
            }
        )
    # Remove and append the sentral group to the end
    all_foreninger.remove(sentral)
    all_foreninger.append(sentral)

    # Look up DNT cabins with serving
    cabins = sorted(Sted.list(params={
        'tags': 'Hytte',
        'betjeningsgrad': 'Betjent',
        'privat': {'hytteeier': 'DNT'},
        'status': 'Offentlig',
        'tilbyder': 'DNT',
    }), key=lambda s: s['navn'])

    # Set url query parameters for pagination links
    query_string = get_filter_query_string(request.GET.dict())

    context = {
        'aktivitet_dates': aktivitet_dates_pagenav,
        'difficulties': Aktivitet.DIFFICULTY_CHOICES,
        'categories': Aktivitet.CATEGORY_CHOICES,
        'category_types': Aktivitet.CATEGORY_TYPES_LIST,
        'audiences': Aktivitet.AUDIENCE_CHOICES,
        'omrader': sorted(Område.list(params={'status': 'Offentlig', 'tilbyder': 'DNT'}), key=lambda o: o['navn']),
        'cabins': cabins,
        'all_foreninger': all_foreninger,
        'query_string': query_string,
        'filter': filter_,
        'filter_hash': filter_hash(filter_),
    }
    return render(request, 'common/aktiviteter/index.html', context)