Ejemplo n.º 1
0
def order(request):
    if request.method == 'GET':
        beers = Card.objects.all()
        context = {'beers': beers}
        return render(request, 'order_page.html', context)
    elif request.method == 'POST' and 'back' in request.POST:
        return redirect('main_page')
    elif request.method == 'POST' and 'confirm' in request.POST:
        name = request.POST.get('name_1')
        address = request.POST.get('address')
        if not name or not address:
            beers = Card.objects.all()
            context = {'beers': beers, 'valid': 'Please, fill in your name and address'}
            return render(request, 'order_page.html', context)
        else:
            customer = Customer(name=name, address=address)
            customer.save()
            all_card = Card.objects.all()
            for orders in all_card:
                Order.objects.create(beer=orders.beer, value=orders.value, customer=customer)
            card = Card.objects.all()
            card.delete()
            return render(request, 'succ_page.html')
    else:
        id_del = request.POST.get('id')
        all_card = Card.objects.get(id=id_del)
        all_card.delete()
        beers = Card.objects.all()
        context = {'beers': beers}
        return render(request, 'order_page.html', context)
Ejemplo n.º 2
0
def link_stripe_to_customer(customer_id_or_service_email, stripe_token,
                            stripe_token_created, contact_id):
    solution_server_settings = get_solution_server_settings()
    stripe.api_key = solution_server_settings.stripe_secret_key
    if isinstance(customer_id_or_service_email, unicode):
        customer = Customer.get_by_service_email(customer_id_or_service_email)
    else:
        customer = Customer.get_by_id(customer_id_or_service_email)

    # Resellers and their customers should not be able to do this
    google_user = gusers.get_current_user()
    if not customer.team.legal_entity.is_mobicage:
        logging.error(
            "user %s tried to access function 'link_stripe_to_customer'",
            google_user.email())
        raise NoPermissionException()
    if google_user:
        azzert(user_has_permissions_to_team(google_user, customer.team_id))

    if customer.stripe_id:
        stripe_customer = stripe.Customer.retrieve(customer.stripe_id)
        card = stripe_customer.cards.create(card=stripe_token)
        stripe_customer.default_card = card.id
        stripe_customer.save()
    else:
        stripe_customer = stripe.Customer.create(
            card=stripe_token,
            description=u"%s %s -- %s, %s, %s, %s, %s, %s" %
            (customer.id, customer.vat, customer.name, customer.address1,
             customer.address2, customer.zip_code, customer.city,
             customer.country))
        card = stripe_customer.cards.data[0]
    try_or_defer(store_stripe_link_to_datastore, customer.key(),
                 stripe_customer.id, card.id, stripe_token_created, contact_id)
Ejemplo n.º 3
0
 def post(self, request):
     if request.POST.get('email'):
         name = request.POST.get('name')
         phone = request.POST.get('phone')
         email = request.POST.get('email')
         customer = Customer(name=name, phone=phone, email=email)
         customer.save()
         qrcode_path = customer.qrcode_create()
         customer.qrcode = qrcode_path
         customer.save()
         order = Order(customer=customer, )
         order.save()
         cart = request.session.get('cart')
         if cart:
             for product_id, quantity in cart.items():
                 cart = Cart(product_id=product_id,
                             quantity=quantity,
                             order=order,
                             complete=True)
                 cart.save()
             del request.session['cart']
             request.session.save()
     cart = order.cart_set.all()
     context = {'cart': cart, 'order': order}
     return render(request, 'shop/order.html', context)
Ejemplo n.º 4
0
def get_customer_subscription_length(customer_id):
    customer = Customer.get_by_id(customer_id)
    if not customer.subscription_order_number:
        raise NoSubscriptionFoundException(customer)
    months_till_charge, _ = get_subscription_order_remaining_length(
        customer_id, customer.subscription_order_number)
    return months_till_charge
def job():
    settings = get_server_settings()
    customers = list(Customer.all().fetch(10))
    customers_per_app = defaultdict(list)
    for customer in customers:
        customers_per_app[customer.default_app_id].append(customer)
    book = xlwt.Workbook(encoding='utf-8')
    for app_id in customers_per_app:
        if not app_id:
            continue
        sheet = book.add_sheet(app_id)
        row = 0
        sheet.write(row, 0, 'Customer name')
        for customer in customers_per_app[app_id]:
            row += 1
            url = '%s/internal/shop/login_as?customer_id=%d' % (settings.baseUrl, customer.id)
            sheet.write(row, 0, xlwt.Formula('HYPERLINK("%s";"%s")' % (url, customer.name.replace('"', ''))))

    excel = StringIO()
    book.save(excel)
    excel_string = excel.getvalue()

    current_date = format_datetime(datetime.datetime.now(), locale=DEFAULT_LANGUAGE)
    to_emails = [u'*****@*****.**', u'*****@*****.**', u'*****@*****.**']
    
    attachments = []
    attachments.append(('Customers %s.xls' % current_date,
                        base64.b64encode(excel_string)))

    subject = 'List of all customers'
    message = 'See attachment.'
    send_mail('*****@*****.**', to_emails, subject, message, attachments=attachments)
Ejemplo n.º 6
0
def set_service_disabled(customer_or_id, disabled_reason_int):
    """
    Disables the customer his service, disconnects all users and sets the service invisible.

    Args:
        customer_or_id (int, long, Customer): customer or id
        disabled_reason_int (int, long): reason why the service has been disabled

    Raises:
        NoSubscriptionException
        BusinessException
    """
    if isinstance(customer_or_id, Customer):
        customer = customer_or_id
    else:
        customer = Customer.get_by_id(customer_or_id)

    if not customer.service_email:
        raise NoSubscriptionException(customer)
    if disabled_reason_int not in Customer.DISABLED_REASONS:
        raise BusinessException('Invalid disable service reason')

    service_user = users.User(customer.service_email)
    sln_settings = get_solution_settings(service_user)
    customer.default_app_id = None
    customer.app_ids = []
    customer.service_disabled_at = now()
    customer.disabled_reason_int = disabled_reason_int
    customer.subscription_cancel_pending_date = 0
    sln_settings.search_enabled = False
    sln_settings.service_disabled = True
    db.put([customer, sln_settings])

    rogerthat_set_service_disabled(service_user)
Ejemplo n.º 7
0
def create_task_if_not_order(customer_id):
    customer = Customer.get_by_id(customer_id)
    # Check if the customer has linked his credit card after he clicked the 'pay' button
    # If he didn't (one hour after the last time he tried to pay), create a new ShopTask to call this customer.
    if not customer.stripe_valid and customer.team_id:
        if customer.prospect_id:
            rmt, prospect = db.get([
                RegioManagerTeam.create_key(customer.team_id),
                Prospect.create_key(customer.prospect_id)
            ])
        else:
            prospect = create_prospect_from_customer(customer)
            rmt = RegioManagerTeam.get(
                RegioManagerTeam.create_key(customer.team_id))
        azzert(rmt.support_manager,
               'No support manager found for team %s' % rmt.name)
        task = create_task(
            prospect_or_key=prospect,
            status=ShopTask.STATUS_NEW,
            task_type=ShopTask.TYPE_SUPPORT_NEEDED,
            address=None,
            created_by=STORE_MANAGER.email(),
            assignee=rmt.support_manager,
            execution_time=today() + 86400 + 11 * 3600,  # tomorrow, 11:00,
            app_id=prospect.app_id,
            comment=u"Customer wanted to pay an order in the customer store, "
            "but didn't succeed because he did not link his creditcard.",
            notify_by_email=True)
        task.put()
Ejemplo n.º 8
0
    def get(self):
        customer_id = int(self.request.get("customer_id"))
        try:
            customer = Customer.get_by_id(customer_id)
        except CustomerNotFoundException:
            self.abort(404)

        current_user = users.get_current_user()
        current_customer = get_customer(current_user)
        sln_settings = get_solution_settings(current_user)
        if not sln_settings.can_edit_services(
                current_customer) or not current_customer.can_edit_service(
                    customer):
            logging.warn(
                'Service or user %s is trying to login to the dashboard of %s',
                current_user.email(), customer.name)
            self.abort(401)

        service_identity_user = create_service_identity_user(
            users.User(customer.service_email))
        current_session = users.get_current_session()
        new_secret, new_session = create_session(service_identity_user,
                                                 ignore_expiration=True)
        set_cookie(self.response,
                   get_server_settings().cookieSessionName, new_secret)
        new_session = switch_to_service_identity(new_session,
                                                 service_identity_user,
                                                 read_only=False,
                                                 shop=current_session.shop,
                                                 layout_only=True)
        new_session.parent_session_secret = current_session.secret
        new_session.put()
        self.redirect("/")
def report_on_site_payments():
    one_month_ago = datetime.datetime.today() - relativedelta(months=1)
    min_date = int(time.mktime(one_month_ago.timetuple()))

    invoices = Invoice.all().filter('payment_type',
                                    Invoice.PAYMENT_ON_SITE).filter(
                                        'date >=', min_date)
    charges = Charge.get((i.charge_key for i in invoices))
    customers = Customer.get((i.order_key.parent() for i in invoices))

    l = [
        '[%(date_str)s][%(customer)s][%(manager)s][%(amount).02f][%(charge_number)s]'
        % dict(customer=c.name,
               manager=i.operator,
               amount=i.amount / 100.0,
               date=i.date,
               date_str=time.ctime(i.date),
               charge_number=charge.charge_number)
        for (i, charge, c) in sorted(zip(invoices, charges, customers),
                                     key=lambda t: t[0].date)
    ]
    body = "\n".join(l) or u"There were no on site payments for the last month"
    logging.info(body)

    server_settings = get_server_settings()
    solution_server_settings = get_solution_server_settings()
    subject = u'On site payments for the last month'
    send_mail(server_settings.dashboardEmail,
              solution_server_settings.shop_payment_admin_emails, subject,
              body)
Ejemplo n.º 10
0
def _fix_charge(charge_key):
    charge = Charge.get(charge_key)
    charge.team_id = Customer.get(charge.customer_key).team_id
    if not charge.team_id:
        logging.error(
            'Cannot fix charge {}: No team set on customer {}'.format(
                charge.id, charge.customer_id))
    charge.put()
Ejemplo n.º 11
0
def get_customer(service_user):
    """
    Args:
        service_user (users.User): service user
    Returns:
        customer(Customer)
    """
    return Customer.get_by_service_email(service_user.email())
Ejemplo n.º 12
0
def job():
    customers = Customer.all()
    to_put = list()
    for c in customers:
        if not c.language:
            if not c.country:
                raise Exception('Customer %s has no country assigned' % c.name)
            c.language = COUNTRY_DEFAULT_LANGUAGES[c.country]
            to_put.append(c)
    db.put(to_put)
Ejemplo n.º 13
0
def get_subscription_order(customer_id):
    customer = Customer.get_by_id(customer_id)
    if not customer.subscription_order_number:
        raise NoSubscriptionException(customer)
    order = Order.get_by_order_number(customer.id,
                                      customer.subscription_order_number)
    if not order.status == Order.STATUS_SIGNED:
        raise BusinessException(
            'The customer his subscription order has not been signed yet.')
    return order
Ejemplo n.º 14
0
def _change_customers_manager(manager_email):
    logging.info(
        'Unsetting regional manager on customers with assigned manager \'%s\'',
        manager_email)
    to_put = []
    manager_user = users.User(manager_email)
    for customer in Customer.all():
        if customer.manager == manager_user:
            customer.manager = None
            to_put.append(customer)
    put_in_chunks(to_put)
Ejemplo n.º 15
0
def set_next_charge_date(customer_id, next_charge_date):
    customer = Customer.get_by_id(customer_id)
    if not customer.subscription_order_number:
        raise NoSubscriptionException(customer)
    order = Order.get_by_order_number(customer_id,
                                      customer.subscription_order_number)
    if not order.status == Order.STATUS_SIGNED:
        raise BusinessException(
            'The customer his subscription order has not been signed yet.')
    order.next_charge_date = next_charge_date
    order.put()
Ejemplo n.º 16
0
def customer_get_editable_organization_types(customer_id):
    request = GenericRESTRequestHandler.getCurrentRequest()
    language = get_languages_from_request(request)[0]
    try:
        customer = Customer.get_by_id(customer_id)

        if not language:
            language = customer.language

        return dict(get_organization_types(customer, language))
    except CustomerNotFoundException:
        return {}
Ejemplo n.º 17
0
def _gather_events_for_customer(customer_key, cap_key, organization_type):
    customer = Customer.get(customer_key)
    if not customer.service_email:
        logging.debug('This customer has no service yet: %s',
                      db.to_dict(customer))
        return
    if cap_key.parent().name() == customer.service_email:
        # do not gather own events
        return
    sln_settings = get_solution_settings(customer.service_user)
    if SolutionModule.AGENDA not in sln_settings.modules:
        return
    if sln_settings.default_calendar is None:
        logging.error(
            'This customer has no default calendar!\n\nSolutionSettings: %s\n\nCustomer: %s',
            db.to_dict(sln_settings),
            db.to_dict(customer),
            _suppress=False)
        return
    sc = SolutionCalendar.get_by_id(
        sln_settings.default_calendar,
        parent_key(customer.service_user, sln_settings.solution))
    if not sc:
        return

    event_items = []
    for event in sc.events:
        event_item = EventItemTO.fromEventItemObject(event)
        event_item.calendar_id = organization_type
        event_items.append(event_item)

    if event_items:
        new_events = serialize_complex_value(event_items, EventItemTO, True)
        gather_events_key = u"%s" % organization_type

        def trans():
            cap = CityAppProfile.get(cap_key)
            stream = cap.gather_events.get(gather_events_key)
            if stream:
                json_list = json.load(stream)
            else:
                json_list = list()
            json_list.extend(new_events)
            with closing(StringIO()) as stream:
                json.dump(json_list, stream)
                cap.gather_events[gather_events_key] = stream
            cap.put()

        db.run_in_transaction(trans)
        sln_settings.put_identity_pending = True
        sln_settings.put()
Ejemplo n.º 18
0
def get_customer_locations_for_app(app_id):
    query_string = (u'app_ids:"%s"' % app_id)
    query = search.Query(query_string=query_string,
                         options=search.QueryOptions(returned_fields=[
                             'service', 'name', 'location', 'description'
                         ],
                                                     limit=1000))
    search_result = search.Index(name=SERVICE_LOCATION_INDEX).search(query)

    customers = {
        customer.service_email: customer
        for customer in Customer.list_by_app_id(app_id)
    }

    def map_result(service_search_result):
        customer_location = CustomerLocationTO()
        for field in service_search_result.fields:
            if field.name == 'service':
                customer = customers.get(field.value.split('/')[0])
                if customer:
                    customer_location.has_terminal = customer.has_loyalty
                    customer_location.address = customer.address1
                    customer_location.type = customer.organization_type
                    if customer.address2:
                        customer_location.address += '\n%s' % customer.address2
                    if customer.zip_code or customer.city:
                        customer_location.address += '\n'
                        if customer.zip_code:
                            customer_location.address += customer.zip_code
                        if customer.zip_code and customer.city:
                            customer_location.address += ' '
                        if customer.city:
                            customer_location.address += customer.city
                else:
                    customer_location.type = ServiceProfile.ORGANIZATION_TYPE_PROFIT
                continue
            if field.name == 'name':
                customer_location.name = field.value
                continue
            if field.name == 'location':
                customer_location.lat = field.value.latitude
                customer_location.lon = field.value.longitude
                continue
            if field.name == 'description':
                customer_location.description = field.value
                continue
        return customer_location

    return json.dumps(
        serialize_complex_value([map_result(r) for r in search_result.results],
                                CustomerLocationTO, True))
Ejemplo n.º 19
0
def get_services(organization_type, cursor=None, limit=50):
    city_service_user = users.get_current_user()
    si = system.get_identity()
    # get all the services in this city
    app_id = si.app_ids[0]
    city_customer = get_customer(city_service_user)
    azzert(organization_type in city_customer.editable_organization_types)
    service_customers_qry = Customer.list_enabled_by_organization_type_in_app(app_id, organization_type)
    service_customers_qry.with_cursor(cursor)
    service_customers = service_customers_qry.fetch(limit)
    new_cursor = unicode(service_customers_qry.cursor())

    services = []
    statistics = get_services_statistics(app_id)
    sln_settings_keys = [SolutionSettings.create_key(city_service_user)]
    for customer in service_customers:
        if not customer.service_email:
            logging.error('Customer %d (%s) has default_app_id, but has no service!', customer.id, customer.name)
        elif customer.app_id == app_id:
            sln_settings_keys.append(SolutionSettings.create_key(users.User(customer.service_email)))
    sln_settings_list = db.get(sln_settings_keys)
    city_sln_settings = sln_settings_list.pop(0)  # type: SolutionSettings
    azzert(city_sln_settings.can_edit_services(city_customer))
    city_service_email = city_sln_settings.service_user.email()
    for customer in service_customers:
        service_email = customer.service_email
        # Exclude the city app's own service
        if customer.app_id == app_id and service_email != city_service_email:
            future_events_count = 0
            broadcasts_last_month = 0
            static_content_count = 0
            last_unanswered_question_timestamp = 0
            modules = []
            for sln_settings in sln_settings_list:
                if sln_settings.key().name() == service_email:
                    modules = sln_settings.modules
            if statistics:
                for mail in statistics.customer_emails:
                    if mail == service_email:
                        index = statistics.customer_emails.index(mail)
                        future_events_count = statistics.future_events_count[index]
                        broadcasts_last_month = statistics.broadcasts_last_month[index]
                        static_content_count = statistics.static_content_count[index]
                        last_unanswered_question_timestamp = statistics.last_unanswered_questions_timestamps[index]

            statistic = ServiceStatisticTO.create(future_events_count, broadcasts_last_month, static_content_count,
                                                  last_unanswered_question_timestamp)
            services.append(ServiceListTO(service_email, customer.name, statistic, modules, customer.id))
    generated_on = statistics.generated_on if statistics else None
    return ServicesTO(sorted(services, key=lambda x: x.name.lower()), generated_on, new_cursor)
Ejemplo n.º 20
0
def remind_user_with_expired_vouchers(sln_settings_key, today_timestamp):
    """Remind voucher owners (users) before the expiration date by n days"""
    sln_settings = SolutionSettings.get(sln_settings_key)
    if not sln_settings:
        return

    customer = Customer.get_by_service_email(sln_settings.service_user.email())
    if not customer:
        return

    for days in EXPIRED_VOUCHERS_REMINDER:
        run_job(expired_vouchers_qry,
                [customer.app_id, today_timestamp + days],
                send_expired_voucher_message, [sln_settings, days / DAY])
Ejemplo n.º 21
0
def get_service_users_for_city(app_id):
    result = []
    for customer in Customer.all().filter('organization_type =',
                                          OrganizationType.CITY):
        if customer.app_ids and app_id == customer.app_id:
            if customer.service_email:
                sln_settings = get_solution_settings(customer.service_user)
                if SolutionModule.CITY_APP in sln_settings.modules:
                    result.append(customer.service_user)
        elif not customer.app_ids:
            logging.debug(
                "get_service_user_for_city failed for customer_id: %s",
                customer.id)

    return result
Ejemplo n.º 22
0
def get_service(service_email):
    city_service_user = users.get_current_user()
    city_customer = get_customer(city_service_user)
    service_user = users.User(email=service_email)
    customer = Customer.get_by_service_email(service_email)
    if not city_customer.can_edit_service(customer):
        logging.warn(u'Service %s tried to save service information for customer %d', city_service_user, customer.id)
        lang = get_solution_settings(city_service_user).main_language
        return ReturnStatusTO.create(False, translate(lang, SOLUTION_COMMON, 'no_permission'))
    contact = Contact.get_one(customer.key())
    solution_settings = get_solution_settings(service_user)
    return ServiceTO(customer.id, customer.name, customer.address1, customer.address2, customer.zip_code, customer.city,
                     customer.user_email, contact.phone_number, solution_settings.main_language,
                     solution_settings.modules, solution_settings.broadcast_types, customer.organization_type,
                     customer.vat, customer.website, customer.facebook_page)
Ejemplo n.º 23
0
def cancel_charge(customer_id, order_number, charge_id):
    """Cancels a charge so adjustments can be made to the order. Rolls back the next charge date of the subscription order.

    Args:
        customer_id:
        order_number:
        charge_id:

    Returns:
        None
    """
    to_put = list()
    now_ = now()
    charge, order, customer = db.get([Charge.create_key(charge_id, order_number, customer_id),
                                      Order.create_key(customer_id, order_number),
                                      Customer.create_key(customer_id)])
    charge.date_cancelled = now_
    charge.status = Charge.STATUS_CANCELLED
    to_put.append(charge)
    order_items = list(OrderItem.list_by_order(order.key()))
    if order.is_subscription_order:
        months = 0
        for item in order_items:
            product = item.product
            if product.is_subscription and product.price > 0:
                months += item.count
            if not product.is_subscription and product.extra_subscription_months > 0:
                months += product.extra_subscription_months

        if months > 0:
            next_charge_datetime = datetime.datetime.utcfromtimestamp(now()) - relativedelta(months=months)
            order.next_charge_date = get_epoch_from_datetime(next_charge_datetime)
        else:
            order.next_charge_date = Order.default_next_charge_date()
    else:
        extra_months = 0
        for item in order_items:
            product = item.product
            if not product.is_subscription and product.extra_subscription_months > 0:
                extra_months += product.extra_subscription_months

        if extra_months > 0:
            sub_order = Order.get_by_order_number(customer_id, customer.subscription_order_number)
            next_charge_datetime = datetime.datetime.utcfromtimestamp(sub_order.next_charge_date) - relativedelta(
                months=extra_months)
            sub_order.next_charge_date = get_epoch_from_datetime(next_charge_datetime)
            to_put.append(sub_order)
    db.put(to_put)
Ejemplo n.º 24
0
def _put_customers(cursor=None):
    qry = Customer.all()
    if cursor:
        qry.with_cursor(cursor)

    customers = qry.fetch(200)
    if not customers:
        return
    cursor = qry.cursor()
    to_put = list()
    for c in customers:
        if c.service_disabled_at == 0:
            c.service_disabled_at = 0
            to_put.append(c)
    db.put(to_put)
    _put_customers(cursor)
Ejemplo n.º 25
0
def rest_delete_service(service_email):
    city_service_user = users.get_current_user()
    city_customer = get_customer(city_service_user)
    customer = Customer.get_by_service_email(service_email)
    if not city_customer.can_edit_service(customer):
        lang = get_solution_settings(city_service_user).main_language
        logging.warn(u'Service %s tried to save service information for customer %d', city_service_user, customer.id)
        return ReturnStatusTO.create(False, translate(lang, SOLUTION_COMMON, 'no_permission'))
    cancel_subscription(customer.id, Customer.DISABLED_REASONS[Customer.DISABLED_ASSOCIATION_BY_CITY], True)
    session = users.get_current_session()
    service_identity = session.service_identity
    send_message_to_session(city_service_user, session,
                            [{u"type": u"solutions.common.services.deleted",
                              u'service_email': service_email,
                              u'service_organization_type': customer.organization_type}],
                            si=service_identity)
    return RETURNSTATUS_TO_SUCCESS
Ejemplo n.º 26
0
def migrate_and_create_user_profile(executor_user, from_service_user, to_user):
    from shop.models import Customer
    bizz_check(from_service_user.email() != to_user.email(), 'FROM and TO should not be equal')

    from_profile = _get_profile_not_cached(from_service_user)
    bizz_check(from_profile, 'ServiceProfile %s not found' % from_service_user)
    bizz_check(isinstance(from_profile, ServiceProfile),
               'Profile %s is not of expected type ServiceProfile, but of type %s' % (from_service_user, from_profile.kind()))

    service_email = u"*****@*****.**" % uuid.uuid4()

    to_profile = _get_profile_not_cached(to_user)
    if to_profile:
        bizz_check(isinstance(to_profile, UserProfile),
                   'Profile %s is not of expected type UserProfile, but of type %s' % (to_user, to_profile.kind()))
        if service_email not in to_profile.owningServiceEmails:
            to_profile.owningServiceEmails.append(service_email)
    else:
        to_profile = create_user_profile(to_user, to_user.email(), from_profile.defaultLanguage)
        to_profile.isCreatedForService = True
        to_profile.owningServiceEmails = [service_email]
        update_password_hash(to_profile, from_profile.passwordHash, now())

    si = get_default_service_identity_not_cached(from_service_user)
    si.qualifiedIdentifier = to_user.email()
    settings = get_solution_settings(from_service_user)
    settings.qualified_identifier = to_user.email()
    settings.login = to_user
    put_and_invalidate_cache(to_profile, si, settings)

    customer = Customer.all().filter('service_email', from_service_user.email()).get()
    if customer:
        def trans(customer_key):
            customer = db.get(customer_key)
            customer.user_email = to_user.email()
            customer.put()
        db.run_in_transaction(trans, customer.key())

        if SolutionModule.CITY_APP in settings.modules:
            for app_id in customer.app_ids:
                invalidate_service_user_for_city(app_id)
    else:
        logging.debug('There was no customer')

    return migrate(executor_user, from_service_user, users.User(service_email))
Ejemplo n.º 27
0
def cancel_subscription(customer_id, cancel_reason, immediately=False):
    """
    Marks the customer his subscription as disabled.
    Recurrent billing will disable the service and disconnect all users after the subscription has ended.
    When the 'immediately' parameter is set, the service will be disabled immediately.

    Args:
        customer_id (int, long): Customer id
        cancel_reason (unicode): Reason why the subscription has been canceled.
        immediately (bool): Set to True to disable the service immediately

    Returns: None

    Raises:
        EmptyValueException
        CustomerNotFoundException
        NoSubscriptionException
    """
    if not cancel_reason:
        raise EmptyValueException('cancel_reason')

    customer = Customer.get_by_id(customer_id)

    if not customer.subscription_order_number:
        raise NoSubscriptionException(customer)

    order = Order.get_by_order_number(customer_id,
                                      customer.subscription_order_number)
    if immediately or order.status != Order.STATUS_SIGNED:

        def trans():
            try:
                cancel_order(customer, customer.subscription_order_number)
            except OrderAlreadyCanceledException as exception:
                logging.info('Order %s already canceled, continueing...' %
                             exception.order.order_number)

            customer.disabled_reason = cancel_reason
            set_service_disabled(customer, Customer.DISABLED_OTHER)

        run_in_xg_transaction(trans)
    else:
        customer.disabled_reason = cancel_reason
        customer.subscription_cancel_pending_date = now()
        customer.put()
 def trans():
     to_put = list()
     customer = Customer.get(customer_key)
     if App.APP_ID_ROGERTHAT not in customer.app_ids and customer.service_email:
         customer.app_ids.append(App.APP_ID_ROGERTHAT)
         to_put.append(customer)
         service_identity = get_default_service_identity(
             customer.service_user)
         if App.APP_ID_ROGERTHAT not in service_identity.appIds:
             service_identity.appIds.append(App.APP_ID_ROGERTHAT)
             deferred.defer(re_index,
                            service_identity.service_identity_user,
                            _queue=MIGRATION_QUEUE,
                            _transactional=True)
             to_put.append(service_identity)
         deferred.defer(re_index_customer,
                        customer.key(),
                        _queue=MIGRATION_QUEUE,
                        _transactional=True)
         put_and_invalidate_cache(*to_put)
Ejemplo n.º 29
0
def set_service_enabled(customer_id):
    customer = Customer.get_by_id(customer_id)
    if not customer.service_email:
        raise NoSubscriptionException(customer)

    service_user = users.User(customer.service_email)
    service_identity_user = create_service_identity_user(service_user)
    si = get_service_identity(service_identity_user)
    sln_settings = get_solution_settings(service_user)
    sln_settings.service_disabled = False
    customer.service_disabled_at = 0
    customer.disabled_reason = u''
    customer.disabled_reason_int = 0
    customer.subscription_cancel_pending_date = 0
    # restore app ids
    customer.app_ids = si.sorted_app_ids
    customer.default_app_id = si.app_id
    db.put([customer, sln_settings])

    rogerthat_re_enable_service(service_user)
Ejemplo n.º 30
0
def get_all_signup_enabled_apps():
    signup_enabled_app_keys = ShopApp.all(keys_only=True).filter(
        'signup_enabled', True)
    signup_enabled_apps = filter(
        lambda app: app.main_service,
        db.get([
            App.create_key(app_key.name())
            for app_key in signup_enabled_app_keys
        ]))

    for app in reversed(signup_enabled_apps):
        # TODO: cache Customer.get_by_service_email(app.main_service)
        customer = Customer.get_by_service_email(app.main_service)
        if not customer:
            signup_enabled_apps.remove(app)
            continue
        app.customer_id = customer.id
        app.country = customer.country

    return signup_enabled_apps
Ejemplo n.º 31
0
def results(request):
    if request.method == 'POST': # Submitted the purchase form:
        form = PurchaseForm(request.POST)
        print 'GOT POST'

        if not request.user.is_authenticated():
            errors = form._errors.setdefault("loggedin", ErrorList())
            errors.append("Please log in before ordering")

        elif form.is_valid(): # TODO if form is not valid because no items in cart, say so! item_list is hidden field so user cannot see error.
            hasError = False
            user_email = request.user.username # form.cleaned_data['email']
            email_html = '<p>Name: ' + form.cleaned_data['name'] + '<br />Email: ' + user_email + '<br />Address: ' + form.cleaned_data['living_group'] + '<br />Room number: ' + form.cleaned_data['room_number'] + '<br />Phone number: ' + form.cleaned_data['phone_number'] + '</p><p><b>Delivery date: Saturday, April 6, 2013</b></p><p><b>Order:</b></p>'

            cart_items = json.loads(form.cleaned_data['items_list'])
            cart_total = 0

            print 'cart items: ', cart_items

            for cart_item_id in cart_items:
                # make sure JSON output in cart_item_id form field is int as saved by browser, on chrome is. Otherwise would need to cast.
                qty = cart_items[cart_item_id]
                item = ShopItem.objects.get(pk=cart_item_id)
                cart_total += (item.item_price * qty)
                email_html += '<p>' + str(qty) + 'x ' + item.item_name + ' @ ' + pretty_price(item.item_price) + ' = ' + pretty_price(item.item_price * qty) + ' </p>'


            email_html += '<p>Order total: ' + pretty_price(cart_total) + '</p>'
            # Should also check cart matches the one saved in databse.

            card_dictionary = {
                'number': form.cleaned_data['card_number'],
                'exp_month': form.cleaned_data['card_expiration_month'],
                'exp_year': form.cleaned_data['card_expiration_year'],
                'cvc': form.cleaned_data['card_cvc'],
                'address_zip': form.cleaned_data['card_zip'],
            }

            # process order immediately
            """
            charge = stripe.Charge.create(
                amount=cart_total,
                currency='usd',
                card=card_dictionary,
                description='SnapShop order for ' + form.cleaned_data['name'],
                )
            """

            useCard = False
            if form.cleaned_data['payment_choices'] == 'use_old':
                try:
                    customer = Customer.objects.get(user=request.user)
                    try:
                        card = CreditCard.objects.get(cc_owner=customer)
                        # TODO increase balance from Stripe

                    except CreditCard.DoesNotExist:
                        hasError = True
                        errors = form._errors.setdefault("username", ErrorList())
                        errors.append("An error ocurred in retreiving your saved card. Please re-enter the information below.")

                except Customer.DoesNotExist:
                    hasError = True
                    errors = form._errors.setdefault("username", ErrorList())
                    errors.append("An error ocurred in retreiving your saved card. Please re-enter the information below.")
            else: # payment_choices == 'save_new' or 'no_save'
                # Try only creating customer: should account for customer already created, and save in DB.
                # Catching errors in: https://stripe.com/docs/api?lang=python
                try:
                    stripe_customer = stripe.Customer.create(
                                # use SnapShop username?
                                description="Customer " + form.cleaned_data['name'],
                                card=card_dictionary,
                                account_balance=cart_total,
                                email=user_email, #request.user.username
                            )
                    print stripe_customer
                except stripe.CardError, e:
                    print e
                    errors = form._errors.setdefault("card_number", ErrorList())
                    errors.append("Card error: " + e.message)
                    hasError = True
                except stripe.StripeError, e:
                    print e
                    errors = form._errors.setdefault("card_number", ErrorList())
                    errors.append("A stripe error has ocurred. Please contact the site administrator")
                    hasError = True
                if not hasError:
                    try:
                        our_customer = Customer.objects.get(user=request.user)
                    except Customer.DoesNotExist:
                        our_customer = Customer(stripe_token=stripe_customer.id, phone_number='', delivery_time=datetime.datetime(2013, 03, 16), user=request.user)
                        our_customer.save()

                    # TODO will this create duplicate credit card entries
                    if form.cleaned_data['payment_choices'] == 'save_new':
                        card_number = form.cleaned_data['card_number']
                        our_card = CreditCard(cc_stub=card_number[-4:], cc_type=0, cc_owner=our_customer)
                        our_card.save()

            if not hasError:
                # Send email to us - admins
                admin_msg = EmailMessage('New Snapshop order!', email_html, '*****@*****.**', ['*****@*****.**', '*****@*****.**'])
                admin_msg.content_subtype = 'html'
                admin_msg.send(fail_silently=False)

                # Senc copy of email to customer
                user_msg = EmailMessage('Thank you for your SnapShop order!', email_html, '*****@*****.**', [user_email])
                user_msg.content_subtype = 'html'
                user_msg.send(fail_silently=True)
                return HttpResponseRedirect('/thanks/')
Ejemplo n.º 32
0
    def post(self):
        logging.debug(self.request.POST)
        data = self.request.get("data", None)
        if not data:
            self.redirect('/mobiadmin/google/news')
            return

        self.response.headers['Content-Type'] = 'text/json'

        data = json.loads(data)

        service_user_email = data.get("service_user_email", None)
        action = data.get("action", None)
        nss = NewsSettingsService.create_key(users.User(service_user_email)).get()
        if action == 'delete':
            should_delete = False
            try:
                from shop.models import Customer
                c = Customer.get_by_service_email(service_user_email)
                if c and c.service_disabled_at:
                    should_delete = True
            except:
                pass

            total_user_count = 0
            for si in get_service_identities(nss.service_user):
                user_count = count_users_connected_to_service_identity(si.user)
                total_user_count += user_count

            if total_user_count == 0:
                should_delete = True

            last_activity = get_last_activity(nss.service_user)
            if not should_delete and not last_activity:
                self.response.out.write(json.dumps({'success': False,
                                                    'errormsg': 'Delete failed could not find last activity'}))
                return

            latest_activity_days = get_days_between_last_activity(last_activity) if last_activity else -1
            if not should_delete and latest_activity_days <= 300:
                self.response.out.write(json.dumps({'success': False,
                                                    'errormsg': 'Service was active in the last 300 days'}))
                return

            nss.setup_needed_id = 998
            nss.put()

            service_profile = get_service_profile(nss.service_user, False)
            if service_profile.solution:
                from solutions.common.bizz.jobs import delete_solution
                delete_solution(nss.service_user, True)
            else:
                from rogerthat.bizz.job import delete_service
                delete_service.job(nss.service_user, nss.service_user)

        elif action == 'skip':
            nss.setup_needed_id = 999
            nss.put()
        elif action == 'save_group':
            groups = data.get("groups", None)
            if not groups:
                self.response.out.write(json.dumps({'success': False,
                                                    'errormsg': 'This is awkward... (groups not found)'}))
                return

            nss.groups = []
            if nss.setup_needed_id == 1:
                nss.setup_needed_id = 11
            else:
                nss.setup_needed_id = random.randint(12, 20)

            if groups == 'city':
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_CITY,
                                                           filter=None,
                                                           broadcast_types=[]))
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_TRAFFIC,
                                                           filter=None,
                                                           broadcast_types=[]))
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_EVENTS,
                                                           filter=None,
                                                           broadcast_types=[]))
            elif groups == 'food':
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_PROMOTIONS,
                                                           filter=NewsGroup.FILTER_PROMOTIONS_FOOD,
                                                           broadcast_types=[]))
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_EVENTS,
                                                           filter=None,
                                                           broadcast_types=[]))
            elif groups == 'restaurant':
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_PROMOTIONS,
                                                           filter=NewsGroup.FILTER_PROMOTIONS_RESTAURANT,
                                                           broadcast_types=[]))
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_EVENTS,
                                                           filter=None,
                                                           broadcast_types=[]))
            elif groups == 'clothing':
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_PROMOTIONS,
                                                           filter=NewsGroup.FILTER_PROMOTIONS_CLOTHING,
                                                           broadcast_types=[]))
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_EVENTS,
                                                           filter=None,
                                                           broadcast_types=[]))
            elif groups == 'associations':
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_PROMOTIONS,
                                                           filter=NewsGroup.FILTER_PROMOTIONS_ASSOCIATIONS,
                                                           broadcast_types=[]))
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_EVENTS,
                                                           filter=None,
                                                           broadcast_types=[]))
            elif groups == 'other':
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_PROMOTIONS,
                                                           filter=NewsGroup.FILTER_PROMOTIONS_OTHER,
                                                           broadcast_types=[]))
                nss.groups.append(NewsSettingsServiceGroup(group_type=NewsGroup.TYPE_EVENTS,
                                                           filter=None,
                                                           broadcast_types=[]))
            else:
                self.response.out.write(json.dumps({'success': False,
                                                    'errormsg': 'This is awkward... (group not found)'}))
                return

            nss.put()

        elif action == 'save_mapping':
            broadcast_types = get_service_profile(nss.service_user).broadcastTypes
            nss.setup_needed_id = 0
            mapping = data.get("mapping", None)
            if mapping:
                for group_type, broadcast_mapping in mapping.iteritems():
                    g = nss.get_group(group_type)
                    if not g:
                        self.response.out.write(json.dumps({'success': False,
                                                            'errormsg': 'You need to map every broadcast_type to 1 group (group "%s" missing)' % group_type}))
                        return
                    for broadcast_type in broadcast_mapping:
                        if broadcast_type not in broadcast_types:
                            self.response.out.write(json.dumps({'success': False,
                                                                'errormsg': 'You need to map every broadcast_type to 1 group (broadcast_type "%s" missing)' % broadcast_type}))
                            return
                        broadcast_types.remove(broadcast_type)

                    g.broadcast_types = broadcast_mapping

            if broadcast_types:
                self.response.out.write(json.dumps({'success': False,
                                                    'errormsg': 'You need to map every broadcast_type to 1 group (broadcast_type incomplete)'}))
                return
            nss.put()

            deferred.defer(migrate_service, nss.service_user, dry_run=False,
                           force=True, _countdown=5, _queue=NEWS_MATCHING_QUEUE)

        self.response.out.write(json.dumps({'success': True}))
Ejemplo n.º 33
0
    def get(self):
        app_id = self.request.get("app_id", None)
        sni = self.request.get("sni", None)
        if not app_id or not sni:
            self.redirect('/mobiadmin/google/news')
            return

        sni = int(sni)
        qry = NewsSettingsService.list_setup_needed(app_id, sni)
        item = qry.get()
        if not item:
            self.redirect('/mobiadmin/google/news?app_id=%s' % app_id)
            return
        
        sp = get_service_profile(item.service_user)
        last_activity = get_last_activity(item.service_user)
        latest_activity_days = get_days_between_last_activity(last_activity) if last_activity else -1
        disabled_reason = None
        if sp.solution and sp.solution == u'flex':
            try:
                from shop.models import Customer
                c = Customer.get_by_service_email(item.service_user.email())
                if c and c.service_disabled_at:
                    disabled_reason = c.disabled_reason
            except:
                pass
        
        identities = []

        total_user_count = 0
        all_hidden = True
        for si in get_service_identities(item.service_user):
            news_count = NewsItem.query().filter(NewsItem.sender == si.user).count(None)
            user_count = count_users_connected_to_service_identity(si.user)
            total_user_count += user_count
            sc, _ = get_search_config(si.user)
            if sc.enabled and all_hidden:
                all_hidden = False
            identities.append(dict(id=si.identifier,
                                   name=si.name,
                                   news_count=news_count,
                                   user_count=user_count,
                                   app_ids=si.appIds,
                                   search_enabled=sc.enabled))

        delete_enabled = False
        if disabled_reason:
            delete_enabled = True
        elif total_user_count == 0 and all_hidden:
            delete_enabled = True
        elif latest_activity_days > 300 and total_user_count < 20 and all_hidden:
            delete_enabled = True

        context = dict(sni=sni,
                       count=qry.count(None),
                       item=item,
                       sp=sp,
                       auto_login_url=generate_auto_login_url(item.service_user),
                       latest_activity=dict(date=str(last_activity) if last_activity else 'never', days=latest_activity_days),
                       delete_enabled=delete_enabled,
                       disabled_reason=disabled_reason,
                       identities=identities)
        path = os.path.join(os.path.dirname(__file__), 'services_detail.html')
        channel.append_firebase_params(context)
        self.response.out.write(template.render(path, context))