def page_category_create(request): request_data = json.loads(request.body) validator = Validator() form = PageCategoryForm(request_data) if not form.is_valid(): validator.errors.errors = get_form_errors(form, {}) market_id = request_data.get('market_id', None) if market_id: market = Market.objects.filter(pk=market_id).first() if not market: return JsonResponse({'general': 'Market not found.'}, status=500) if validator.has_errors(): return JsonResponse(validator.get_errors(), status=400) is_active = to_boolean(request_data['is_active']) role_id = request_data.get('role_id') category = PageCategory() category.is_active = is_active category.market = market category.name = request_data['name'] category.role_id = role_id category.save() return JsonResponse({}, status=200)
def city_edit(request): request_data = json.loads(request.body) validator = Validator() form = CityForm(request_data) if not form.is_valid(): validator.errors.errors = get_form_errors(form, {}) country_id = request_data.get('country_id', None) if country_id: country = Country.objects.filter(pk=country_id).first() if not country: return JsonResponse({'general': 'Country not found.'}, status=500) state_id = request_data.get('state_id', None) if state_id: state = State.objects.filter(pk=state_id).first() if not state: return JsonResponse({'general': 'State not found.'}, status=500) else: if state.country_id != country_id: validator.errors.add( 'state_id', 'This state do not belong to the country.') city_id = request_data.get('id', None) if not city_id: return JsonResponse({'general': 'City not found.'}, status=500) city = City.objects.filter(pk=city_id).first() if not city: return JsonResponse({'general': 'City not found.'}, status=500) if validator.has_errors(): return JsonResponse(validator.get_errors(), status=400) is_active = to_boolean(request_data['is_active']) city.name = request_data['name'] city.state = state city.is_active = is_active city.save() return JsonResponse({}, status=200)
def edit_market(request): request_data = request.POST pk = request_data.get('id') name = request_data.get('name') is_active = to_boolean(request_data.get('is_active')) image = request.FILES.get('image', None) market = Market.objects.filter(pk=pk).first() if not market: return JsonResponse({}, status=400) market.name = name market.is_active = is_active if image: market.image = image market.save() return JsonResponse({})
def api_program_base(request): keep_currency_change = False if request.is_ajax(): results = re.findall(r'/(.*?);', request.META['CONTENT_TYPE']) if len(results) > 0 and results[0] == 'json': request_data = json.loads(request.body) else: request_data = request.POST program_base_id = request_data.get('id', None) admin_fee_currency_id = request_data.get('admin_fee_currency_id', None) prices_currency_id = request_data.get('prices_currency_id', None) admin_fee_currency = None if admin_fee_currency_id: admin_fee_currency = Currency.objects.filter( pk=admin_fee_currency_id).first() if not admin_fee_currency: return JsonResponse({}, status=400) prices_currency = None if prices_currency_id: prices_currency = Currency.objects.filter( pk=prices_currency_id).first() if not prices_currency: return JsonResponse({}, status=400) with transaction.atomic(): program_base = ProgramBase.objects.select_for_update().filter( pk=program_base_id).first() if not program_base: return JsonResponse({}, status=400) if admin_fee_currency: program_base.admin_forms_currency = admin_fee_currency if prices_currency: program_base.prices_forms_currency = prices_currency if 'keep_currency' in request_data: keep_currency_input = to_boolean(request_data['keep_currency']) keep_currency_change = not keep_currency_input == program_base.keep_currency if keep_currency_change: program_base.keep_currency = keep_currency_input if admin_fee_currency or prices_currency or 'keep_currency' in request_data: program_base.save() if 'keep_currency' in request_data and keep_currency_change: registrations = Registration.objects.select_for_update( ).filter(program__program_base=program_base).select_related( 'program__program_base__category', 'costumer__profile', 'registrationfinance') main_currency = Currency.objects.get(main=True) for registration in registrations: finance = registration.registrationfinance if finance.special: if program_base.keep_currency: if ( finance.special and finance.commission and finance.commission.currency \ and finance.exchange_date ): exchange = ExchangeRate.objects.filter( target=finance.commission.currency, rate__gt=Decimal('0.00'), start_date__lte=finance.exchange_date, end_date__gte=finance.exchange_date).first( ) if exchange: finance.commission_currency = finance.commission.currency finance.commission_adastra = ( finance.commission_adastra / exchange.rate).quantize( Decimal("0.01"), decimal.ROUND_HALF_DOWN) else: finance.commission_currency = main_currency finance.commission_adastra = finance.commission_market_exchange registration.update_commission(main_currency, True) return JsonResponse({}, status=200)
def create_market(request): name = request.POST['name'] is_active = to_boolean(request.POST['is_active']) image = request.FILES.get('image', None) with transaction.atomic(): program_bases = ProgramBase.objects.all() main_market = Market.objects.filter(main_market=True).first() program_parents = Program.objects.filter(markets=main_market) academic_periods = AcademicPeriod.objects.order_by('-start_date')[:3] market = Market() market.name = name market.is_active = is_active market.image = image market.save() program_periods = [] commissions_to_create = [] for program_base in program_bases: program_parent = None for parent in program_parents: if parent.program_base == program_base: program_parent = parent break params = {'is_active': False, 'program_id': program_parent.pk} category = program_base.category program = create_program(program_base, market, params) # UNIVERSITIES & COLLEGES prices are handled per registration if category.name.upper() == 'UNIVERSITIES & COLLEGES': continue durations_to_create = [] for academic_period in academic_periods: default_periods = [] program_period = ProgramPeriod() program_period.program = program program_period.period_academic = academic_period program_periods.append(program_period) if category.name.upper() in ['PUBLIC', 'PRIVATE', 'BOARDING']: default_periods = AcademicPeriod.get_default_periods( academic_period.start_date, academic_period.end_date) elif category.name.upper() in ['CAMP', 'LANGUAGE']: default_periods.append({ 'period': 'w', 'start_date': None, 'end_date': None }) else: for x, y in Duration.EXT_DURATION_CHOICES: default_periods.append({ 'period': x, 'start_date': None, 'end_date': None }) for period in default_periods: duration = Duration() duration.period = period['period'] duration.academic_period = academic_period duration.program = program duration.start_date = period['start_date'] duration.end_date = period['end_date'] durations_to_create.append(duration) Duration.objects.bulk_create(durations_to_create) durations = Duration.objects.prefetch_related( 'program__program_base__category').filter(program=program) for duration in durations: commission = Commission() commission.duration = duration commissions_to_create.append(commission) ProgramPeriod.objects.bulk_create(program_periods) Commission.objects.bulk_create(commissions_to_create) return JsonResponse({})
def reimbursements_status_update(request): role = get_role(request.user) if role not in ['corporate', 'finance']: return JsonResponse({}, status=400) request_data = json.loads(request.body) pk = request_data.get('id', 0) need_exchange = to_boolean(request_data.get('need_exchange', '0')) reimbursement = Reimbursement.objects.prefetch_related('items').filter( pk=pk).first() if not reimbursement: return JsonResponse({}, status=400) if ('status' not in request_data or (request_data['status'] == 2 and 'reason' not in request_data) or request_data['status'] not in [1, 2]): return JsonResponse({}, status=400) if request_data['status'] == 1 and need_exchange: validator = Validator() item_errors = [] for item in reimbursement.items.all(): errors = {'id': item.pk} if item.exchange_rate <= Decimal(0): errors['exchange_rate'] = ['Must be greater than zero.'] if len(errors) > 1: item_errors.append(errors) if len(item_errors) > 0: validator.errors.errors['items'] = item_errors if validator.has_errors(): return JsonResponse(validator.get_errors(), status=400) notification = create_notification_from(reimbursement) notification.creator = request.user if request_data['status'] == 2: notification.type = 13 notification.description = u'Reimbursement rejected' notification.details = u'Rejected reason: {}'.format( request_data['reason']) reimbursement.status = 2 reimbursement.reject_reason = request_data['reason'] else: notification.type = 14 notification.description = u'Reimbursement approved' notification.details = u'Reimbursement has been approved' reimbursement.status = 1 reimbursement.date_approved = dt.now() reimbursement.save() notification.save() notification_receiver = NotificationReceiver() notification_receiver.receiver_id = reimbursement.creator_id notification_receiver.notification = notification notification_receiver.save() return JsonResponse({})
def page_category_edit(request): request_data = json.loads(request.body) validator = Validator() form = PageCategoryEditForm(request_data) role_id = request_data.get('role_id', None) if not form.is_valid(): validator.errors.errors = get_form_errors(form, {}) page_category_id = request_data.get('id', None) if page_category_id: page_category = PageCategory.objects.filter( pk=page_category_id).first() if not page_category: return JsonResponse({'general': 'Page Category not found.'}, status=500) market_id = request_data.get('market_id', None) if market_id: market = Market.objects.filter(pk=market_id).first() if not market: return JsonResponse({'general': 'Market not found.'}, status=500) if validator.has_errors(): return JsonResponse(validator.get_errors(), status=400) to_create = request_data.get('to_create', []) to_remove = request_data.get('to_remove', []) to_edit = request_data.get('to_edit', []) for e_page in to_edit: id_page = e_page['id'] name_page = e_page['name'] if name_page: page = Page.objects.filter(pk=id_page).update(title=name_page) for r_page in to_create: page = Page() page.title = r_page['name'] page.type = r_page['type'] if page.type == 2: for icons in r_page['icons']: icons_id = icons['id'] if page.type == 3 or page.type == 4: page.view = r_page['view'] if page.type == 5: page.view_video = r_page['view_video'] page.category = page_category page.save() if r_page['type'] == 2: for icons in r_page['icons']: icons_id = icons['id'] attachment_page = AttachmentCategory.objects.get(pk=icons_id) page.attachment_category.add(attachment_page) Page.objects.filter(category_id=page_category_id, id__in=to_remove).delete() page_category.role_id = role_id page_category.is_active = to_boolean(request_data['is_active']) page_category.market = market page_category.name = request_data['name'] page_category.save() return JsonResponse({}, status=200)
def dt_commissions(request): results = [] user_id = request.POST.get('user_id') role_user = request.POST.get('role_user') columns = { 'id': 'id', 'registration.academic_period.year': 'registration__academic_period__start_date', 'registration.costumer.id': 'registration__costumer_id', 'registration.costumer.full_name': 'costumer_full_name', 'registration.program.program_base.code': 'registration__program__program_base', 'created_at': 'created_at', 'registration.consultant': 'registration__consultant__common_name', 'registration.id': 'registration_id', 'commission_available': 'commission_available', 'total_commission': 'amount', 'total_paid_to_consultant': 'total_paid_to_consultant' } data_table = DataTable(request.POST, columns) query_set = RegistrationCommission.objects.select_related( 'registration__costumer', 'registration__academic_period', 'registration__program__program_base', 'registration__program__program_base', 'registration__registrationfinance').annotate( costumer_id=Cast('registration__costumer_id', CharField()), costumer_full_name=Concat('registration__costumer__first_name', Value(' '), 'registration__costumer__last_name'), balance=Coalesce(F('amount'), 0) - Coalesce(Sum('commission_payment__deposit_amount'), 0), total_paid_to_consultant=Coalesce( Sum('commission_payment__deposit_amount'), 0)).commission_available_annotation().filter( registration__academic_period__start_date__year__gte='2020' ).exclude(registration__status=5) if user_id: query_set = query_set.filter(user_id=user_id) if role_user in ['supervisor']: table = request.POST.get('table') if table == '#supervisor-commissions': query_set = query_set.exclude(registration__consultant_id=user_id) if table == '#agent-commissions': query_set = query_set.filter(registration__consultant_id=user_id) if 'is_special' in request.POST: is_special = to_boolean(request.POST['is_special']) query_set = query_set.filter(is_special=is_special) total = query_set.count() if 'academic_period_id' in request.POST: query_set = query_set.filter(registration__academic_period_id=request. POST['academic_period_id']) if 'program_base_id' in request.POST: query_set = query_set.filter( registration__program__program_base_id=request. POST['program_base_id']) if data_table.search_value != "": try: query_set = query_set.filter( Q(registration__id__icontains=int(data_table.search_value)) | Q(costumer_full_name__icontains=data_table.search_value)) except ValueError: query_set = query_set.filter( Q(costumer_full_name__icontains=data_table.search_value)) records_filtered = query_set.count() query_set = query_set.order_by(*data_table.get_orderings()) commissions = query_set[data_table.start:data_table.limit] for commission in commissions: result = { 'id': commission.pk, 'created_at': commission.created_at.isoformat(), 'registration': { 'id': commission.registration_id, 'academic_period': { 'year': commission.registration.academic_period.get_year() }, 'costumer': { 'id': commission.registration.costumer.pk, 'full_name': commission.costumer_full_name }, 'program': { 'program_base': { 'code': commission.registration.program.program_base.code } }, 'consultant': commission.registration.consultant.common_name }, 'commission_available': round(commission.commission_available, 2), 'total_paid_to_consultant': commission.total_paid_to_consultant, 'total_commission': commission.amount, } if commission.registration.registrationfinance.commission_currency: commission_currency = commission.registration.registrationfinance.commission_currency.as_dict( ) result['registration']['commission_currency'] = commission_currency results.append(result) response = { 'draw': data_table.draw, 'recordsTotal': total, 'recordsFiltered': records_filtered, 'data': results } return JsonResponse(response, status=200)
def api_edit_user(request): request_data = json.loads(request.POST['data']) market = None supervisor = None markets = [] programs_base = [] validator = Validator() user_id = request_data.get('id', '') common_name = request_data.get('common_name', '') first_name = request_data.get('first_name', '') last_name = request_data.get('last_name', '') email = request_data.get('email', '') username = request_data.get('username', '') password = request_data.get('password', '') code = request_data.get('code', '') title = request_data.get('title', '') supervisor_id = request_data.get('supervisor_id', 0) market_id = request_data.get('market_id', 0) commission_category_id = request_data.get('commission_category', None) commission_start = request_data.get('commission_start', 0) want_account = request_data.get('want_account', False) remove_account = request_data.get('remove_account', False) is_active = to_boolean(request_data.get('is_active', '0')) markets_mtm = request_data.get('markets_mtm', []) programs_mtm = request_data.get('programs_mtm', []) profile_picture = request.FILES.get('profile_picture', None) old_mnemonic = '' # region Validations user = get_user_model().objects.select_related( 'role', 'person').filter(pk=user_id).first() if not user: return JsonResponse({'general': ['Something went wrong. code: 1']}, status=500) user_name = get_user_model().objects.filter(username=username).first() if user_name and user_name.pk != user.pk: validator.errors.add('username', 'Is already in use.') role = Role.objects.filter(code=request_data['role']).first() if not role: return JsonResponse({'general': ['Something went wrong. code: 2']}, status=500) groups_required = groups_by_role(role.code) groups = Group.objects.filter(name__in=groups_required) if len(groups) != len(groups_required): return JsonResponse({'general': ['Something went wrong. code: 2']}, status=500) if role.code in [ 'consultant', 'free_agent', 'supervisor', 'coordinator', 'info', 'trainee' ]: consultant_profile = ConsultantProfile.objects.filter( mnemonic=code).first() if consultant_profile and consultant_profile.consultant_id != user.pk: validator.errors.add('code', 'Is already in use.') if consultant_profile: old_mnemonic = consultant_profile.mnemonic if role.code in ['consultant', 'free_agent', 'supervisor', 'trainee']: supervisor = get_user_model().objects.filter( groups__name='supervisors', is_active=True, pk=supervisor_id).first() if not supervisor: return JsonResponse({'general': ['Something went wrong. code: 3']}, status=500) if role.code in ['consultant', 'free_agent', 'supervisor' ] and commission_category_id: commission_category = CommissionCategory.objects.filter( pk=commission_category_id).first() if not commission_category: validator.errors.add('commission_category', 'Invalid commission category.') if role.code != 'program': market = Market.objects.filter(pk=market_id).first() if not market: return JsonResponse({'general': ['Something went wrong. code: 4']}, status=500) if len(markets_mtm) > 0: markets = Market.objects.filter(pk__in=markets_mtm) if len(programs_mtm) > 0: programs_base = ProgramBase.objects.filter(pk__in=programs_mtm) if role.code != 'program': parts = email.split('@') if len(parts) != 2: validator.errors.add('email', 'Invalid email.') else: if parts[1] != 'adastra.ca': validator.errors.add('email', 'Must finish in @adastra.ca') if validator.has_errors(): return JsonResponse(validator.get_errors(), status=400) # endregion user_role = Role.objects.get(user=user) role_change = role.code != user_role.code mailbox_name, domain = email.split('@') mailbox = Mailbox.objects.filter(user=user).first() try: rs_request_data = {} if mailbox and role.code != 'program' and not remove_account: if user.is_active != is_active: rs_request_data[ 'enabled'] = 'true' if not user.is_active else 'false' if user.person.first_name != first_name: rs_request_data['firstName'] = user.person.first_name if user.person.last_name != last_name: rs_request_data['lastName'] = user.person.last_name if user.person.first_name != first_name or user.person.last_name != last_name: rs_request_data['displayName'] = user.person.get_full_name() if password != '': rs_request_data['password'] = password if mailbox.name != mailbox_name: rs_request_data['name'] = mailbox_name with transaction.atomic(): user.person.first_name = first_name user.person.last_name = last_name user.person.email = email user.person.save() if password != '': user.password = make_password(password) user.common_name = common_name user.username = username user.is_active = is_active user.title = title user.role = role user.save() if role_change: RoleChange.objects.create(user=user, before=user_role, after=role) user.groups.clear() for group in groups: user.groups.add(group) if not role == 'program': consultant_profile, created = ConsultantProfile.objects.get_or_create( consultant=user) if role.code in [ 'consultant', 'free_agent', 'supervisor', 'coordinator', 'info', 'trainee' ]: if role.code in ['consultant', 'free_agent', 'supervisor']: consultant_profile.commission_start = commission_start if commission_category_id: consultant_profile.commission_category = commission_category if 'probation_start_date' in request_data and 'probation_end_date' in request_data: consultant_profile.probation_start_date = request_data[ 'probation_start_date'] consultant_profile.probation_end_date = request_data[ 'probation_end_date'] consultant_profile.probation = True else: consultant_profile.probation = False consultant_profile.mnemonic = code consultant_profile.supervisor = supervisor consultant_profile.save() consultant_profile.market.clear() consultant_profile.market.add(market) if role_change: if not role.code == 'visa' and user_role.code == 'visa': VisasProfile.objects.filter(user=user).delete() if not role.code == 'program' and user_role.code == 'program': ProgramProfile.objects.filter(user=user).delete() profile, created = Profile.objects.get_or_create(user=user.person) if role.code == 'program' and profile_picture: profile.profile_picture = profile_picture profile.save() if role.code == 'visa': visas_profile, created = VisasProfile.objects.get_or_create( user=user) visas_profile.user = user visas_profile.save() visas_profile.markets.clear() visas_profile.markets.add(market) if role.code == 'program': program_profile = ProgramProfile.objects.filter( user=user).first() if not program_profile: program_profile = ProgramProfile() program_profile.user = user program_profile.program_base = programs_base[0] program_profile.save() else: if not program_profile.program_base: program_profile.program_base = programs_base[0] program_profile.save() program_profile.programs_base.clear() program_profile.markets.clear() for program in programs_base: program_profile.programs_base.add(program) for market in markets: program_profile.markets.add(market) rackspace = None is_production = settings.APP_ENV == 'production' if is_production: rackspace = RackSpace() if mailbox: # Remove rackspace account if remove_account: mailbox.delete() if is_production: rackspace.delete_mailbox(mailbox.name) # Edit rackspace account elif len(rs_request_data.keys()) > 0 and role != 'program': if is_production: rackspace.edit_mailbox(mailbox.name, data=rs_request_data) if 'name' in rs_request_data: if is_production: rackspace.delete_alias(mailbox.name) Mailbox.objects.filter(pk=mailbox.pk).update( name=rs_request_data['name']) # Create rackspace account elif want_account and role.code != 'program': if is_production: rackspace.add_mailbox(mailbox_name, data={ 'displayName': user.person.get_full_name(), 'firstName': user.person.first_name, 'lastName': user.person.last_name, 'password': password, 'customID': user.pk, 'enabled': user.is_active }) Mailbox.objects.create(name=mailbox_name, user=user) if role.code in [ 'consultant', 'free_agent', 'supervisor', 'trainee' ] and not old_mnemonic == consultant_profile.mnemonic: update_mnemonic_by_consultant_profile(consultant_profile) except IntegrityError as e: log.info(repr(e)) return JsonResponse( { 'general': ['The system could not create the user, please try again.'] }, status=400) except WebServiceException as e: log.info(repr(e.errors)) return JsonResponse( { 'general': [ 'It seems that the Rackspace service is busy, please try again.' ] }, status=400) except ValidationException as e: return JsonResponse({'general': [e.errors]}, status=400) except Exception as e: log.info(repr(e)) return JsonResponse({}, status=500) return JsonResponse({}, status=200)
def api_user_create(request): request_data = json.loads(request.POST['data']) market = None supervisor = None markets = [] programs_base = [] response = {} validator = Validator() common_name = request_data.get('common_name', '') first_name = request_data.get('first_name', '') last_name = request_data.get('last_name', '') email = request_data.get('email', '') username = request_data.get('username', '') password = request_data.get('password', '') code = request_data.get('code', '').strip() title = request_data.get('title', '') supervisor_id = request_data.get('supervisor_id', 0) market_id = request_data.get('market_id', 0) commission_category_id = request_data.get('commission_category', None) commission_start = request_data.get('commission_start', 0) want_account = request_data.get('want_account', False) is_active = to_boolean(request_data.get('is_active', '0')) markets_mtm = request_data.get('markets_mtm', []) programs_mtm = request_data.get('programs_mtm', []) profile_picture = request.FILES.get('profile_picture', None) # region Validations user = get_user_model().objects.filter(username=username).first() if user: validator.errors.add('username', 'Is already in use.') role = Role.objects.filter(code=request_data['role']).first() if not role: return JsonResponse({'general': ['Something went wrong. code: 2']}, status=500) groups_required = groups_by_role(role.code) groups = Group.objects.filter(name__in=groups_required) if len(groups) != len(groups_required): return JsonResponse({'general': ['Something went wrong. code: 1']}, status=500) if role.code in [ 'consultant', 'free_agent', 'supervisor', 'coordinator', 'info', 'trainee' ]: consultant_profile = ConsultantProfile.objects.filter( mnemonic=code).first() if consultant_profile: validator.errors.add('code', 'Is already in use.') if role.code in ['consultant', 'free_agent', 'supervisor', 'trainee']: supervisor = get_user_model().objects.filter( is_active=True, pk=supervisor_id, role__code="supervisor").first() if not supervisor: validator.errors.add('supervisor', 'Invalid user.') if role.code in ['consultant', 'free_agent', 'supervisor' ] and commission_category_id: commission_category = CommissionCategory.objects.filter( pk=commission_category_id).first() if not commission_category: validator.errors.add('commission_category', 'Invalid commission category.') if role.code != 'program': market = Market.objects.filter(pk=market_id).first() if not market: validator.errors.add('market', 'This field is required.') if role.code == 'coordinator': query_set = get_user_model().objects.filter( consultantprofile__market=market, role__name='coordinator') if query_set.exists(): validator.errors.add( 'general', 'The coordinator for this market already exist.') if len(markets_mtm) > 0: markets = Market.objects.filter(pk__in=markets_mtm) if len(programs_mtm) > 0: programs_base = ProgramBase.objects.filter(pk__in=programs_mtm) if role.code != 'program': parts = email.split('@') if len(parts) != 2: validator.errors.add('email', 'Invalid email.') else: if parts[1] != 'adastra.ca': validator.errors.add('email', 'Must finish in @adastra.ca') if validator.has_errors(): return JsonResponse(validator.get_errors(), status=400) # endregion try: with transaction.atomic(): person = Person.objects.create(first_name=first_name, last_name=last_name, email=email) user = get_user_model().objects.create( common_name=common_name, password=make_password(password), username=username, is_active=is_active, title=title, role=role, person=person) response['id'] = user.pk for group in groups: user.groups.add(group) if not role == 'program': consultant_profile = ConsultantProfile() consultant_profile.consultant = user if role.code in [ 'consultant', 'free_agent', 'supervisor', 'coordinator', 'info', 'trainee' ]: consultant_profile.mnemonic = code consultant_profile.supervisor = supervisor if role.code in ['consultant', 'free_agent', 'supervisor']: consultant_profile.commission_start = commission_start if 'probation_start_date' in request_data and 'probation_end_date' in request_data: consultant_profile.probation_start_date = request_data[ 'probation_start_date'] consultant_profile.probation_end_date = request_data[ 'probation_end_date'] consultant_profile.probation = True if commission_category_id: consultant_profile.commission_category_id = commission_category_id consultant_profile.save() consultant_profile.market.add(market) profile = Profile() profile.user = person if role.code == 'program': profile.profile_picture = profile_picture profile.save() if role.code == 'visa': visas_profile = VisasProfile.objects.create(user=user) visas_profile.markets.add(market) if role.code == 'program': program_profile = ProgramProfile.objects.create( user=user, program_base=programs_base[0]) for program in programs_base: program_profile.programs_base.add(program) for market in markets: program_profile.markets.add(market) # TODO: posiblemente agregar el switch para habilitar link if role.code != 'program' and want_account: mailbox, domain = email.split('@') if settings.APP_ENV == 'production': rackspace = RackSpace() rackspace.add_mailbox(mailbox, data={ 'displayName': person.get_full_name(), 'firstName': person.first_name, 'lastName': person.last_name, 'password': password, 'customID': user.pk, 'enabled': user.is_active }) Mailbox.objects.create(name=mailbox, user=user) except IntegrityError as e: log.error('{}'.format(e)) return JsonResponse( { 'general': ['The system could not create the user, please try again.'] }, status=400) except WebServiceException as e: log.error('{}'.format(e)) return JsonResponse( { 'general': [ 'It seems that the Rackspace service is busy, please try again.' ] }, status=400) except ValidationException as e: return JsonResponse({'general': [e.errors]}, status=400) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() log.info('{} at line: {}.'.format(e, exc_tb.tb_lineno)) return JsonResponse({}, status=500) return JsonResponse(response, status=200)
def generate_excel(request): menu_type = request.GET.get('menu_type') if request.method == 'POST': date1 = request.POST['date1'] date2 = request.POST['date2'] status = request.POST.getlist('id_status[]') academic_period_id = request.POST['id_academic_period'] reports = request.POST.getlist('id_reports[]') market_id = request.POST.get('market', None) full_year = to_boolean(request.POST.get('full_year', False)) report_type = int(reports[0]) role = get_role(request.user) today_end = utc_to_local(timezone.now()).replace( hour=0, minute=0, second=0, microsecond=0) + datetime.timedelta( days=1) - datetime.timedelta(seconds=1) if date1: date1 = unaware_to_local( datetime.datetime.strptime(date1, '%Y-%m-%d')) if date2: date2 = unaware_to_local( datetime.datetime.strptime( date2, '%Y-%m-%d')) + datetime.timedelta( days=1) - datetime.timedelta(seconds=1) # if report_type == 9 and not market_id and role in ['admin', 'corporate', 'finance']: # return redirect('static_pages:reports_view') if role in ['admin', 'corporate', 'finance']: market_user = get_user_market_or_main_market(request.user) if role == 'corporate' and menu_type == 'general': market_filter = get_market_or_main_market(request, menu_type) market_user = market_filter else: if market_id: market_filter = Market.objects.filter(pk=market_id).first() else: market_filter = None elif role in ['info', 'visa']: market_user = None market_filter = None else: market_user = get_user_market_or_main_market(request.user) market_filter = market_user selected_report = ReportList().get_report(report_type) query = Registration.objects.select_related( 'short_term', 'program__program_base', 'program__parent', 'academic_period', 'costumer', 'costumer__profile', 'payment_responsible', 'emergency_contact', 'consultant__person', 'costumer__profile__address__city', 'costumer__profile__address__state', 'registrationflight', 'registrationfinance', 'grade').prefetch_related( 'registrationvisa', 'program__program_base__category', 'program__program_base__city__state__country', 'tutors', 'tutors__profile__phone_set', 'note_set', 'costumer__profile__address', 'costumer__profile__phone_set', 'consultant__consultantprofile__supervisor__person') if date1 and date2: query = query.filter(created__range=[date1, date2]) # review only admins should download all info , if not only their registrations if role in [ 'admin', 'corporate', 'finance', 'program_review', 'info', 'visa' ] or report_type == 11: if role == 'coordinator': query = query.by_consultantprofile_market(market_user) elif role == 'corporate' and menu_type == 'general': market_filter = get_market_or_main_market(request, menu_type) query = query.by_consultantprofile_market(market_filter) else: pass elif role == 'coordinator': if report_type != 9: query = query.by_consultantprofile_market(market_user) # if user is supervisor, then only their consultant and his own elif role == 'supervisor': if not report_type == 12: query = query.filter( Q(consultant__consultantprofile__supervisor=request.user) | Q(consultant=request.user)) else: query = query.filter(Q(consultant=request.user)) # regular consultant else: query = query.filter(consultant=request.user) # filter by academic period ( if present ) if academic_period_id != '' and selected_report.id != 9: query = query.filter(academic_period_id=academic_period_id) query_all_status = query # filter by status ( if present ) if len(status) > 0: query = query.filter(status__in=status) today = datetime.datetime.today() month_abbrev, day, year_abbrev = ( today.strftime('%b-%d-%y')).split('-') if role in ['admin', 'corporate', 'finance']: report_name = u'{}-{}'.format( selected_report.safe_name, u'{}.{}.{}'.format(month_abbrev, day, year_abbrev)) password = u'AdastraALL{}!'.format(year_abbrev) elif role in ['info', 'visa']: report_name = u'{}-{}'.format( selected_report.safe_name, u'{}.{}.{}'.format(month_abbrev, day, year_abbrev)) if role == 'info': password = u'Leads!' elif role == 'visa': # not defined password = u'' else: report_name = u'{}-{}-{}'.format( selected_report.safe_name, market_user.code.upper(), u'{}.{}.{}'.format(month_abbrev, day, year_abbrev)) password = u'Adastra{}{}!'.format(market_user.code.upper(), year_abbrev) class DTO(object): pass dto = DTO() dto.user = request.user dto.role = get_role(request.user) dto.academic_period_id = academic_period_id dto.market_id = market_id dto.status = status dto.timezone = request.POST['timezone'] dto.market_user = market_user dto.market_filter = market_filter dto.start_date = date1 if date1 else None dto.end_date = date2 if date2 else None dto.now = timezone.now().replace(hour=23, minute=59, second=59) dto.today_end = today_end dto.full_year = full_year if selected_report.protected: compression_level = 5 # 1-9 temp_dir = tempfile.gettempdir() dst_file = '{}.xlsx'.format(report_name) dst_dir = '{}/{}.zip'.format(temp_dir, report_name) src_dir = '{}/{}'.format(temp_dir, dst_file) xlsx_data = write_to_excel(query, selected_report.id, query_all_status, request, date1, date2, academic_period_id, dto, dest_dir=src_dir) pyminizip.compress(src_dir, None, dst_dir, password, compression_level) f = open(dst_dir, 'rb') response = HttpResponse(f, content_type='application/zip') response[ 'Content-Disposition'] = 'attachment; filename={}.zip'.format( report_name) return response else: response = HttpResponse(content_type='application/vnd.ms-excel') response[ 'Content-Disposition'] = 'attachment; filename={}.xlsx'.format( report_name) xlsx_data = write_to_excel(query, selected_report.id, query_all_status, request, date1, date2, academic_period_id, dto, dest_dir=None) response.write(xlsx_data) return response else: return HttpResponse('{Only POST request allowed.}', status=200)