def aws_accounts_m_stats_monthlycostbyproductbyaccount(accounts, nb_months): """--- get: tags: - aws produces: - application/json description: &desc Get monthly costs summed by product for each account summary: *desc responses: 200: description: List of AWS accounts schema: properties: months: type: array items: properties: month: type: string products: type: array items: properties: cost: type: number product: type: string 403: description: Not logged in 404: description: AWS account not registered """ assert len(accounts) > 0 now = datetime.utcnow() month = nb_months - 1 date_from = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) - relativedelta(months=month) date_to = now.replace(day=calendar.monthrange(now.year, now.month)[1], hour=23, minute=59, second=59, microsecond=999999) res = [{ 'account_id': account.get_aws_user_id(), 'account_name': account.pretty, 'months': AWSDetailedLineitem.get_monthly_cost_by_product( keys=account.get_aws_user_id(), date_from=date_from, date_to=date_to)['months'], } for account in accounts] if 'csv' in request.args: return Response(generate_csv(res, 'products', 'product', account=True), mimetype='text/csv') return jsonify(accounts=res)
def aws_accounts_m_stats_monthlycostbyproduct(accounts, nb_months): """--- get: tags: - aws produces: - application/json description: &desc Get monthly costs summed by product summary: *desc responses: 200: description: List of AWS accounts schema: properties: months: type: array items: properties: month: type: string products: type: array items: properties: cost: type: number product: type: string 403: description: Not logged in 404: description: AWS account not registered """ assert len(accounts) > 0 now = datetime.utcnow().replace(hour=23, minute=59, second=59, microsecond=999999) now = AWSDetailedLineitem.get_last_date([account.get_aws_user_id() for account in accounts], limit=now) date_from = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) - relativedelta(months=nb_months - 1) date_to = now.replace(day=calendar.monthrange(now.year, now.month)[1], hour=23, minute=59, second=59, microsecond=999999) data = AWSDetailedLineitem.get_monthly_cost_by_product(keys=[account.get_aws_user_id() for account in accounts], date_from=date_from, date_to=date_to)['months'] for d in data: if 'csv' not in request.args: d['products'] = cut_cost_by_product(sorted(d['products'], key=lambda x: x['cost'], reverse=True), int(request.args['show']) - 1 if 'show' in request.args else 9) if not len(data): return jsonify(message=get_next_update_estimation_message_aws(accounts, AWS_KEY_PROCESSING_INTERVAL_HOURS)) if 'csv' in request.args: return Response(generate_csv(data, 'products', 'product'), mimetype='text/csv') return jsonify(months=data)