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)
def get_customer(service_user): """ Args: service_user (users.User): service user Returns: customer(Customer) """ return Customer.get_by_service_email(service_user.email())
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])
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)
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
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
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))
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}))
def create_voucher_statistics_for_city_service(service_user, language, first_day_of_last_month, first_day_of_current_month): customer = Customer.get_by_service_email(service_user.email()) translate = partial(common_translate, language, SOLUTION_COMMON) if not customer: logging.error("failed to create voucher statistics customer not found") return sln_settings = get_solution_settings(service_user) users.set_user(service_user) try: si = system.get_identity() finally: users.clear_user() app_id = si.app_ids[0] ancestor_key = SolutionCityVoucher.create_parent_key(app_id) qry = SolutionCityVoucherTransaction.all().ancestor(ancestor_key) qry.filter("action =", SolutionCityVoucherTransaction.ACTION_REDEEMED) qry.filter("created >=", first_day_of_last_month) qry.filter("created <", first_day_of_current_month) transactions = [] merchant_transactions = dict() merchants = dict() unique_vouchers = dict() for t in qry: t.dt = format_timestamp(t.created, sln_settings) t.voucher = t.parent() transactions.append(t) if t.service_user not in merchant_transactions: merchant_transactions[t.service_user] = { "value": 0, "transactions": [] } merchant_transactions[t.service_user]["value"] += t.value merchant_transactions[t.service_user]["transactions"].append(t.key()) unique_vouchers[t.voucher.key()] = t.voucher for merchant_service_user in merchant_transactions.keys(): merchants[merchant_service_user] = get_solution_settings( merchant_service_user) qry = SolutionCityVoucher.all().ancestor(ancestor_key) qry.filter("activated =", True) qry.filter("redeemed = ", False) vouchers = [] expired_vouchers = [] for v in qry: v.dt = format_timestamp(v.created, sln_settings) if v.expired: if v.expiration_date >= first_day_of_last_month and \ v.expiration_date < first_day_of_current_month: expired_vouchers.append(v) else: vouchers.append(v) book = xlwt.Workbook(encoding="utf-8") # TAB 1 sheet_transactions = book.add_sheet(translate("Transactions")) row = 0 write_header(sheet_transactions, row, translate, "Date", "Voucher", "Internal account", "Cost center", "merchant", "Withdrawn value") for transaction in transactions: row += 1 sheet_transactions.write(row, 0, transaction.dt) sheet_transactions.write(row, 1, transaction.voucher.uid) sheet_transactions.write(row, 2, transaction.voucher.internal_account) sheet_transactions.write(row, 3, transaction.voucher.cost_center) sheet_transactions.write(row, 4, merchants[transaction.service_user].name) sheet_transactions.write(row, 5, round(transaction.value / 100.0, 2)) row += 2 sheet_transactions.write(row, 0, translate("total")) sheet_transactions.write(row, 5, xlwt.Formula('SUM(F2:F%s)' % (row - 1))) # TAB 2 sheet_merchants = book.add_sheet(translate("merchants")) row = 0 sheet_merchants.write(row, 0, translate("merchant")) sheet_merchants.write(row, 1, translate("address")) sheet_merchants.write(row, 2, "IBAN") sheet_merchants.write(row, 3, "BIC") sheet_merchants.write(row, 4, translate("Total value to be paid")) for merchant_service_user in merchants.keys(): merchant = merchants[merchant_service_user] row += 1 sheet_merchants.write(row, 0, merchant.name) sheet_merchants.write(row, 1, merchant.address) sheet_merchants.write(row, 2, merchant.iban or u"") sheet_merchants.write(row, 3, merchant.bic or u"") sheet_merchants.write( row, 4, round( merchant_transactions[merchant_service_user]["value"] / 100.0, 2)) row += 2 sheet_merchants.write(row, 0, translate("total")) sheet_merchants.write(row, 4, xlwt.Formula('SUM(E2:E%s)' % (row - 1))) # TAB 3 sheet_vouchers = book.add_sheet(translate("Vouchers in circulation")) row = 0 write_header(sheet_vouchers, row, translate, "Voucher", "Internal account", "Cost center", "Date", "Remaining value") for voucher in vouchers: unique_vouchers[voucher.key()] = voucher row += 1 sheet_vouchers.write(row, 0, voucher.uid) sheet_vouchers.write(row, 1, voucher.internal_account) sheet_vouchers.write(row, 2, voucher.cost_center) sheet_vouchers.write(row, 3, voucher.dt) value = voucher.value - voucher.redeemed_value sheet_vouchers.write(row, 4, round(value / 100.0, 2)) row += 2 sheet_vouchers.write(row, 0, translate("total")) sheet_vouchers.write(row, 2, xlwt.Formula('SUM(E2:E%s)' % (row - 1))) # TAB 4 expired_vouchers_sheet = book.add_sheet(translate("expired")) row = 0 write_header(expired_vouchers_sheet, row, translate, "Voucher", "Internal account", "Cost center", "Date", "Expiration date", "Remaining value") for voucher in expired_vouchers: row += 1 expired_vouchers_sheet.write(row, 0, voucher.uid) expired_vouchers_sheet.write(row, 1, voucher.internal_account) expired_vouchers_sheet.write(row, 2, voucher.cost_center) expired_vouchers_sheet.write( row, 3, format_timestamp(voucher.created, sln_settings)) expired_vouchers_sheet.write( row, 4, format_timestamp(voucher.expiration_date, sln_settings, format='yyyy-MM-dd')) value = voucher.value - voucher.redeemed_value expired_vouchers_sheet.write(row, 5, round(value / 100.0, 2)) row += 2 expired_vouchers_sheet.write(row, 0, translate("total")) expired_vouchers_sheet.write(row, 5, xlwt.Formula('SUM(F2:F%s)' % (row - 1))) # TAB 5 sheet_voucher_details = book.add_sheet(translate("Voucher details")) row = 0 for voucher in sorted(unique_vouchers.itervalues(), key=lambda v: v.created): voucher_transactions = [h for h in voucher.load_transactions()] sheet_voucher_details.write(row, 0, translate("Voucher")) sheet_voucher_details.write(row, 1, voucher.uid) sheet_voucher_details.write(row, 2, translate("Remaining value")) sheet_voucher_details.write( row, 3, xlwt.Formula('SUM(D%s:D%s)' % (row + 2, row + 1 + len(voucher_transactions)))) row += 1 sheet_voucher_details.write(row, 0, translate("Internal account")) sheet_voucher_details.write(row, 1, voucher.internal_account) sheet_voucher_details.write(row, 2, translate("Cost center")) sheet_voucher_details.write(row, 3, voucher.cost_center) for history in reversed(voucher_transactions): merchant_service_user = history.service_user or service_user if merchant_service_user not in merchants: merchants[merchant_service_user] = get_solution_settings( merchant_service_user) row += 1 dt = format_timestamp(history.created, sln_settings) sheet_voucher_details.write(row, 0, dt) sheet_voucher_details.write(row, 1, merchants[merchant_service_user].name) sheet_voucher_details.write(row, 2, history.action_str) if history.action == SolutionCityVoucherTransaction.ACTION_ACTIVATED or \ history.action == SolutionCityVoucherTransaction.ACTION_REDEEMED: sheet_voucher_details.write(row, 3, round(history.value / 100.0, 2)) row += 2 excel_file = StringIO() book.save(excel_file) excel_string = excel_file.getvalue() second_day_of_last_month = first_day_of_last_month + 86400 d = datetime.fromtimestamp(second_day_of_last_month) sln_city_voucher_export_key = SolutionCityVoucherExport.create_key( app_id, d.year, d.month) sln_city_voucher_export = SolutionCityVoucherExport( key=sln_city_voucher_export_key) sln_city_voucher_export.xls = excel_string sln_city_voucher_export.year_month = d.year * 100 + d.month sln_city_voucher_export.put() for merchant_service_user in merchant_transactions.keys(): deferred.defer( create_voucher_statistics_for_service, merchants[merchant_service_user], app_id, customer.language, merchant_transactions[merchant_service_user]["transactions"], d.year, d.month) to_emails = sln_settings.inbox_mail_forwarders if to_emails: solution_server_settings = get_solution_server_settings() attachments = [] attachments.append( ('%s %s-%s.xls' % (translate('Vouchers'), d.year, d.month), base64.b64encode(excel_string))) subject = translate('Vouchers export') message = translate('see_attachment_for_vouchers_export') send_mail(solution_server_settings.shop_export_email, to_emails, subject, message, attachments=attachments)