Beispiel #1
0
def init_db():

    db.create_all()
    db.session.commit()

    admin_group = models.UserGroup('admin')
    db.session.add(admin_group)
    db.session.commit()

    first_user = models.User('*****@*****.**', 'password')
    first_user.activated = True
    db.session.add(first_user)
    db.session.commit()

    admin_membership = models.UserGroupMembership(first_user, admin_group)
    db.session.add(admin_membership)
    db.session.commit()

    second_user = models.User('*****@*****.**', 'password')
    second_user.activated = True
    db.session.add(second_user)
    db.session.commit()

    third_user = models.User('*****@*****.**', 'password')
    third_user.activated = True
    db.session.add(third_user)
    db.session.commit()

    sprite = models.Item('Sprite', 0.60)
    db.session.add(sprite)
    db.session.commit()

    kitkat = models.Item('KitKat', 0.40)
    db.session.add(kitkat)
    db.session.commit()

    twix = models.Item('Twix', 0.75)
    db.session.add(twix)
    db.session.commit()

    purchase = models.Purchase(second_user, kitkat)
    db.session.add(purchase)
    db.session.commit()

    second_purchase = models.Purchase(second_user, sprite)
    db.session.add(second_purchase)
    db.session.commit()

    third_purchase = models.Purchase(third_user, twix)
    db.session.add(third_purchase)
    db.session.commit()

    db.session.close()
Beispiel #2
0
def addPurchase(portfolio_id, request):
    data = request.get_json()[0]
    purchase = models.Purchase(data['name'], data['stock_id'], data['volume'],
                               data['price'], portfolio_id)
    db.session.add(purchase)
    db.session.commit()
    return str(purchase.id)
Beispiel #3
0
def purchased(request, uid, id):
    resource = get_object_or_404(models.Resource, pk=id)
    user = get_object_or_404(User, pk=uid)
    if request.REQUEST.has_key('tx'):
        tx = request.REQUEST['tx']
        try:
            existing = models.Purchase.objects.get(tx=tx)
            return render_to_response('error.html',
                                      {'error': "Duplicate transaction"},
                                      context_instance=RequestContext(request))
        except models.Purchase.DoesNotExist:
            result = paypal.Verify(tx)
            if result.success() and resource.price == result.amount():  # valid
                purchase = models.Purchase(resource=resource,
                                           purchaser=user,
                                           tx=tx)
                purchase.save()
                return render_to_response(
                    'purchased.html', {'resource': resource},
                    context_instance=RequestContext(request))
            else:  # didn't validate
                return render_to_response(
                    'error.html', {'error': "Failed to validate payment"},
                    context_instance=RequestContext(request))
    else:  # no tx
        return render_to_response('error.html',
                                  {'error': "No transaction specified"},
                                  context_instance=RequestContext(request))
Beispiel #4
0
    def form_valid(self, form):
        tree = ET.fromstring(form.cleaned_data['xml_content_text'])
        try:
            seller = stakeholders.models.Seller.objects.get(
                razon_social=tree.find("infoTributaria/razonSocial").text,
                identificacion=tree.find("infoTributaria/ruc").text,
                company=self.company)
            seller.nombre_comercial = tree.find(
                "infoTributaria/nombreComercial").text
            seller.save()
        except stakeholders.models.Seller.DoesNotExist:
            seller = stakeholders.models.Seller(
                razon_social=tree.find("infoTributaria/razonSocial").text,
                identificacion=tree.find("infoTributaria/ruc").text,
                company=self.company,
                nombre_comercial=tree.find(
                    "infoTributaria/nombreComercial").text)
            seller.save()

        dt = tree.find("infoFactura/fechaEmision").text
        d, m, y = dt.split("/")
        try:
            purchase = models.Purchase.objects.get(
                seller=seller,
                number="{}-{}-{}".format(
                    tree.find("infoTributaria/estab").text,
                    tree.find("infoTributaria/ptoEmi").text,
                    tree.find("infoTributaria/secuencial").text,
                ),
            )
        except models.Purchase.DoesNotExist:
            purchase = models.Purchase(
                date="{}-{}-{}".format(y, m, d),
                xml_content=form.cleaned_data['xml_content_text'],
                seller=seller,
                closed=False,
                comment="",
                number="{}-{}-{}".format(
                    tree.find("infoTributaria/estab").text,
                    tree.find("infoTributaria/ptoEmi").text,
                    tree.find("infoTributaria/secuencial").text,
                ),
                total=Decimal(tree.find("infoFactura/importeTotal").text))
            purchase.save()
        self.success_url = reverse("purchase_detail", args=(purchase.id, ))
        return super(PurchaseCreateFromXMLView, self).form_valid(form)
def new_order_notification(notification_dict):
    "Create Purchase and PurchaseItems, but don't give access until the purchase is charged/amount notification received."
    #make sure this notification hasn't already been processed
    purchase = models.Purchase.all().filter(
        "google_order_number =",
        int(notification_dict['google-order-number'])).get()
    session = models.Session.get_by_key_name(
        notification_dict['session-key-name'])
    email = notification_dict['email']
    if session is not None:  #session dict will be empty, so we need this test
        session.load_values()
        if 'cart' in session:
            del session['cart']  #remove the purchased cart
            session['number_cart_items'] = 0
        if session.has_user(): user = session.user
        else: user = None
        session.google_order_number = int(
            notification_dict['google-order-number'])
        session.put()
    else:
        user = None
    errors = ''
    if not user: user = models.User().all().filter('email =', email).get()
    if not purchase:
        purchase_key = models.generate_purchase_key()
        purchase_id = int(purchase_key.split('-')
                          [0])  #get the id from the beginning of the key
        purchase = models.Purchase(
            key_name=purchase_key,
            purchase_email=email,  #give the purchase the shipping email address
            purchase_id=purchase_id,
            user=user,
            google_order_number=int(notification_dict['google-order-number']),
        )
    if session is None:  #session wasn't found - unlikely
        errors = 'session not found'
    if errors:
        purchase.errors = errors
    purchase.put(
    )  #need to add purchase to the datastore before we can add purchase items
    #get all the items from the notification_dict and add to the purchase
    item_ids = get_list_from_value(notification_dict['merchant-item-id'])
    quantities = get_list_from_value(notification_dict['quantity'])
    item_dict = dict(zip(item_ids, quantities))
    purchase.add_purchase_items(item_dict, user)
    return True
Beispiel #6
0
def create_purchase(db: Session, purchase: PurchaseCreate, user_id: int,
                    days: int, movies: List[int]):
    db_movies = db.query(models.Movie).filter(
        models.Movie.id.in_(movies)).all()
    cost = 0

    for db_movie in db_movies:
        cost += days * db_movie.cost_per_day

    db_purchase = models.Purchase(**purchase.dict(),
                                  user_id=user_id,
                                  cost=cost)
    db_purchase.movie_list = [db_movie for db_movie in db_movies]

    db.add(db_purchase)
    db.commit()
    db.refresh(db_purchase)

    return db_purchase
def amount_notification(notification_dict):
    "Charge the purchase and give the user access to the files."
    purchase = models.Purchase.all().filter(
        "google_order_number =",
        int(notification_dict['google-order-number'])).get()
    errors = [purchase.errors]
    if purchase:  #add charge amount and expiration date, charge date
        purchase.purchase_charged(notification_dict['total-charge-amount'])
    else:  #orphan amount notification - just in case
        errors.append('no previous notification for this order')
        purchase_key = models.generate_purchase_key()
        purchase_id = int(purchase_key.split('-')[0])
        purchase = models.Purchase(
            key_name=purchase_key,
            errors=errors,
            purchase_id=purchase_id,
            google_order_number=int(notification_dict['google-order-number']))
        purchase.purchase_charged(notification_dict['total-charge-amount'])
    user = purchase.user  #change user purchase access attribute
    session = None
    if user:  #Google user associated with purchase
        user.purchase_access = True
        user.put()
        session = models.Session.all().filter(
            'user ='******'google-order-number'])
        session = models.Session.all().filter('google_order_number =',
                                              google_order_number).get()
        if session is not None:
            session.load_values()  #need to load values in order to update them
            session.add_purchase(purchase)
            session.put()
    emails.mail_user_purchase(purchase.purchase_email,
                              str(purchase.key().name()))
    if errors:
        purchase.errors = models.build_string_from_list(errors, '\n')
        purchase.put()
    return True
    def post(self):
        if self.template_values['admin']:
            action = self.request.get('action')
            model = self.request.get('item')
            id = self.request.get(
                'id')  #entity id for purchases and title for pages
            post_url = self.build_post_url(action, model, id)
            if action == 'new':
                entity = False
                page_title = 'New ' + model.capitalize()
                data = self.model_form_dict[model](data=self.request.POST)
            else:
                entity = self.get_entity(model, id)
                if not entity:
                    self.generate_error(404)
                    return
                if model == 'product':
                    old_tag_list = entity.tags  #keep copy of old tags
                    original_product_status = entity.active  #keep copy of original active status
                    original_title = entity.title
                if not action:
                    page_title = 'Edit'
                    data = self.model_form_dict[model](data=self.request.POST,
                                                       instance=entity)
                elif action == 'delete':
                    redirect_url = '/admin/home?item=%ss' % (model)
                    if model == 'product':  #make sure entity is not purchased before deleting
                        is_entity_purchased = entity.is_entity_purchased()
                        if is_entity_purchased:
                            redirect_url = '/edit?action=delete&item=product&id=%s' % str(
                                entity.key().id())
                            self.redirect(redirect_url +
                                          '&errors=product_purchased')
                            return
                        else:
                            models.update_popular_products()
                    entity.delete()
                    self.redirect(redirect_url)
                    return
                else:
                    self.generate_error(400)
                    return

            data_valid = data.is_valid()
            if data_valid:  #check the to make sure the data is valid
                entity = data.save(commit=False)
                if model == 'product':
                    product_tags = self.request.POST.get('tags')
                    new_tag_list = models.Tag.clean_tags(product_tags, ',')
                    entity.tags = new_tag_list
                elif model == 'page':  # for pages slugify the title for the url
                    entity.url = '%s' % (models.slugify(entity.title))
                elif model == 'purchase':  #for purchases
                    product_id_add_list = self.request.get_all('product_ids')
                    email = entity.purchase_email
                    user = models.User().all().filter('email =', email).get()
                    if user:
                        user.delete_sessions(
                        )  #delete current user session, so purchases get updated
                        entity.user = user
                    if action == "new":
                        key_name = models.generate_purchase_key()
                        entity.purchase_id = int(key_name.split('-')[0])
                        entity = models.Purchase(
                            key_name=key_name,
                            **dict([(prop, getattr(entity, prop))
                                    for prop in models.Purchase.properties()]))
                entity.put()
                if model == 'product':
                    need_update_popular_products = False
                    try:
                        entity.index()
                    except:
                        print 'indexing failed - at least one tag is required'
                    if action == 'new':
                        old_tag_list = []  #no tags for new product
                        need_update_popular_products = True
                    else:
                        if not entity.active == original_product_status or not entity.title == original_title:
                            need_update_popular_products = True
                    if not new_tag_list == old_tag_list:
                        models.Tag.update_tags(new_tag_list, old_tag_list,
                                               entity)
                        need_update_popular_products = True
                    if need_update_popular_products:
                        models.update_popular_products()
                elif model == 'purchase':
                    if product_id_add_list:
                        entity.admin_add_purchase_items(
                            entity.charge_date, product_id_add_list, user,
                            entity.total_charge_amount)
                self.redirect(self.build_redirect_url(entity, model))

            else:
                template = 'templates/edit.html'
                self.generate_edit_form(data,
                                        model,
                                        page_title,
                                        post_url,
                                        template,
                                        entity=entity)