1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
| from io import BytesIO import pandas as pd import numpy as np from django.db.models import Count, Sum, F from apps.billing.models import *
def groupByOssBill(**kwargs): sum_data = dict() objs = OssBill.objects.filter(**kwargs).values( "instance_id", "billing_cycle", "ownerid" ).annotate( standard_storage_sum=Sum('standard_storage'), infrequent_access_storage_sum=Sum('infrequent_access_storage'), archive_storage_sum=Sum('archive_storage'), cold_archive_storage_sum=Sum('cold_archive_storage'), get_request_count_sum=Sum('get_request_count'), put_request_count_sum=Sum('put_request_count'), internet_send_sum=Sum('internet_send'), cdn_send_sum=Sum('cdn_send'), )
for i in objs: if i["billing_cycle"] not in sum_data.keys(): sum_data[i["billing_cycle"]] = {}
bucket_key = f'{i["ownerid"]}/{i["instance_id"].lower()}' sum_data[i["billing_cycle"]][bucket_key] = { "standard_storage_sum": i["standard_storage_sum"], "infrequent_access_storage_sum": i["infrequent_access_storage_sum"], "archive_storage_sum": i["archive_storage_sum"], "cold_archive_storage_sum": i["cold_archive_storage_sum"], "get_request_count_sum": i["get_request_count_sum"], "put_request_count_sum": i["put_request_count_sum"], "internet_send_sum": i["internet_send_sum"], "cdn_send_sum": i["cdn_send_sum"] } return sum_data
def checkFileContent(file_obj): bio = BytesIO() for chunk in file_obj.chunks(): bio.write(chunk) bio.seek(0)
try: df = pd.read_csv(bio) except ValueError: df = pd.read_excel(bio) except Exception: return {"code": 100400, "message": "Excel 文件读取失败"}
df = df.replace(to_replace=[r"\t|\n|\r", " "], value=["", ""], regex=True)
select_cols = ['账期', '账号ID', '账号', 'Owner账号', '实例ID', '产品Code', '计费项', '应付金额', '计费项Code'] try: all_data = df[select_cols].values except KeyError as ex: return {"code": 100400, "message": "Excel格式识别错误,请确认是从阿里云账单控制台导出的OSS明细!"}
if 'oss' not in df["产品Code"].unique(): return {"code": 100401, "message": "没有找到OSS的相关明细账单,请确认是从阿里云账单控制台导出的OSS明细!"}
cleanAnalyAmount(df["账号ID"].unique(), df["账期"].unique())
return {"code": 0, "data": all_data}
def cleanAnalyAmount(ownerids: list, billing_cycles: list): for ownerid in ownerids: for billing_cycle in billing_cycles: OssBill.objects.filter( ownerid=ownerid, billing_cycle=billing_cycle ).update( standard_storage_amount=0, infrequent_access_storage_amount=0, archive_storage_amount=0, cold_archive_storage_amount=0, get_request_count_amount=0, put_request_count_amount=0, internet_send_amount=0, cdn_send_amount=0, other_item_amount=0, pretax_amount=0, )
def analyOssBillAmount(file_obj): check_response = checkFileContent(file_obj) if check_response["code"] != 0: return check_response
groupby_data = groupByOssBill()
for data in check_response["data"]: billing_cycle, account_id, _, owner, instance_id, product_code, charging, pretax_amount, charging_code = data
if product_code != "oss" or int(pretax_amount) == 0: continue
CHARGE_M = { "Storage": "standard_storage", "LessthanMonthDatasize": "infrequent_access_storage", "PutRequest": "put_request_count", "GetRequest": "get_request_count", "NetworkOut": "internet_send", "CdnOut": "cdn_send", "RetrievalData": "get_request_count"
} objects = OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=account_id, owner=owner, instance_id=instance_id ).values( "bucket_name", "standard_storage", "infrequent_access_storage", "archive_storage", 'cold_archive_storage', "get_request_count", "put_request_count", "internet_send", "cdn_send", ) instance = f"{account_id}/{instance_id.lower()}" for obj in objects: if charging_code == "ChargedDatasize" and "archive" in instance_id.lower(): sum_result = float(groupby_data[billing_cycle][instance]["archive_storage_sum"]) amount = round(float(obj["archive_storage"]) / sum_result * pretax_amount, 2) OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=account_id, bucket_name=obj["bucket_name"] ).update( archive_storage_amount=F('archive_storage_amount') + amount, pretax_amount=F('pretax_amount') + amount )
elif charging_code == "ChargedDatasize" and "ia" in instance_id.lower(): sum_result = float(groupby_data[billing_cycle][instance]["infrequent_access_storage_sum"]) amount = round(float(obj["infrequent_access_storage"]) / sum_result * pretax_amount, 2) OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=account_id, bucket_name=obj["bucket_name"] ).update( infrequent_access_storage_amount=F('infrequent_access_storage_amount') + amount, pretax_amount=F('pretax_amount') + amount )
elif charging_code == "ProcessI": sum_result = float(groupby_data[billing_cycle][instance]["put_request_count_sum"]) amount = round(float(obj["put_request_count"]) / sum_result * pretax_amount, 2) OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=account_id, instance_id=instance_id, bucket_name=obj["bucket_name"] ).update( put_request_count_amount=F('put_request_count_amount') + amount, pretax_amount=F('pretax_amount') + amount )
elif charging_code == "RetrievalData": sum_result = float(groupby_data[billing_cycle][instance]["get_request_count_sum"]) amount = round(float(obj["get_request_count"]) / sum_result * pretax_amount, 2) OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=account_id, instance_id=instance_id, bucket_name=obj["bucket_name"] ).update( other_item_amount=F('other_item_amount') + amount, pretax_amount=F('pretax_amount') + amount )
elif charging_code not in CHARGE_M.keys(): sum_result = float(groupby_data[billing_cycle][instance]["standard_storage_sum"]) amount = round(float(obj["standard_storage"]) / sum_result * pretax_amount, 2) OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=account_id, instance_id=instance_id, bucket_name=obj["bucket_name"] ).update( other_item_amount=F('other_item_amount') + amount, pretax_amount=F('pretax_amount') + amount )
else: sum_result = float(groupby_data[billing_cycle][instance][CHARGE_M[charging_code] + "_sum"]) amount = round(float(obj[CHARGE_M[charging_code]]) / sum_result * pretax_amount, 2) amount_item = CHARGE_M[charging_code] + '_amount' o = OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=account_id, instance_id=instance_id, bucket_name=obj["bucket_name"] ) o.update(**{'pretax_amount': F('pretax_amount') + amount, amount_item: F(amount_item) + amount})
return {"code": 0, "message": "OSS桶分配金额完成"}
def queryset_analysis(df, values: str, columns, index): outfile = BytesIO() alys = pd.pivot_table( data=df, values=values, columns=columns, index=index, aggfunc=np.sum, margins=True, margins_name='合计', dropna=True, fill_value=0 )
writer = pd.ExcelWriter(outfile, engine='xlsxwriter') df.to_excel(writer, sheet_name='原始数据') alys.to_excel(writer, sheet_name='透视分析数据')
workbook = writer.book border_format = { 'border': 1, 'top': 1, 'left': 1, 'right': 1, 'bottom': 1 } common_format = { 'font_name': '微软雅黑', 'align': 'center', 'valign': 'vcenter', **border_format } header_format = workbook.add_format({ **common_format, 'fg_color': '#b9c7f9', 'font_size': 14 })
money_format = workbook.add_format({'num_format': '#,##0.00', **common_format}) worksheet_alys = writer.sheets['透视分析数据'] worksheet_ori = writer.sheets['原始数据']
(max_row_aly, max_col_aly) = alys.shape (max_row_ori, max_col_ori) = df.shape worksheet_alys.set_column(0, max_col_aly + 1, 25) worksheet_ori.set_column(0, max_col_ori + 1, 25)
alys_index_headers = index + list(alys.columns.values) for col_num, value in enumerate(alys_index_headers): worksheet_alys.write(0, col_num, value, header_format)
for col_num, value in enumerate(df.columns.values): worksheet_ori.write(0, col_num + 1, value, header_format)
worksheet_alys.conditional_format(first_row=1, first_col=2, last_row=max_row_aly, last_col=max_col_aly + 1, options={"type": 'no_errors', 'format': money_format} ) worksheet_ori.conditional_format(first_row=1, first_col=1, last_row=max_row_ori, last_col=max_col_ori, options={"type": 'no_errors', 'format': money_format} ) writer.close()
return outfile
def analysisOssBillAmountByAPI(billing_cycle, json_data): groupby_data = groupByOssBill()
for data in json_data: if data["PretaxAmount"] == 0: continue
CHARGE_M = { "Storage": "standard_storage", "LessthanMonthDatasize": "infrequent_access_storage", "PutRequest": "put_request_count", "GetRequest": "get_request_count", "NetworkOut": "internet_send", "CdnOut": "cdn_send", "RetrievalData": "get_request_count"
} objects = OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=data["BillAccountID"], owner=data["BillAccountName"], instance_id=data["InstanceID"] ).values( "bucket_name", "standard_storage", "infrequent_access_storage", "archive_storage", 'cold_archive_storage', "get_request_count", "put_request_count", "internet_send", "cdn_send", ) instance = f"{data['BillAccountID']}/{data['InstanceID'].lower()}" for obj in objects: if data['BillingItemCode'] == "ChargedDatasize" and "archive" in data['InstanceID'].lower(): sum_result = float(groupby_data[billing_cycle][instance]["archive_storage_sum"]) amount = round(float(obj["archive_storage"]) / sum_result * data["PretaxAmount"], 2) OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=data["BillAccountID"], bucket_name=obj["bucket_name"] ).update( archive_storage_amount=F('archive_storage_amount') + amount, pretax_amount=F('pretax_amount') + amount )
elif data['BillingItemCode'] == "ChargedDatasize" and "ia" in data['InstanceID'].lower(): sum_result = float(groupby_data[billing_cycle][instance]["infrequent_access_storage_sum"]) amount = round(float(obj["infrequent_access_storage"]) / sum_result * data["PretaxAmount"], 2) OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=data["BillAccountID"], bucket_name=obj["bucket_name"] ).update( infrequent_access_storage_amount=F('infrequent_access_storage_amount') + amount, pretax_amount=F('pretax_amount') + amount )
elif data['BillingItemCode'] == "ProcessI": sum_result = float(groupby_data[billing_cycle][instance]["put_request_count_sum"]) amount = round(float(obj["put_request_count"]) / sum_result * data["PretaxAmount"], 2) OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=data["BillAccountID"], instance_id=data['InstanceID'], bucket_name=obj["bucket_name"] ).update( put_request_count_amount=F('put_request_count_amount') + amount, pretax_amount=F('pretax_amount') + amount )
elif data['BillingItemCode'] == "RetrievalData": sum_result = float(groupby_data[billing_cycle][instance]["get_request_count_sum"]) amount = round(float(obj["get_request_count"]) / sum_result * data["PretaxAmount"], 2) OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=data["BillAccountID"], instance_id=data['InstanceID'], bucket_name=obj["bucket_name"] ).update( other_item_amount=F('other_item_amount') + amount, pretax_amount=F('pretax_amount') + amount )
elif data['BillingItemCode'] not in CHARGE_M.keys(): sum_result = float(groupby_data[billing_cycle][instance]["standard_storage_sum"]) amount = round(float(obj["standard_storage"]) / sum_result * data["PretaxAmount"], 2) OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=data["BillAccountID"], instance_id=data['InstanceID'], bucket_name=obj["bucket_name"] ).update( other_item_amount=F('other_item_amount') + amount, pretax_amount=F('pretax_amount') + amount )
else: sum_result = float( groupby_data[billing_cycle][instance][CHARGE_M[data["BillingItemCode"]] + "_sum"]) amount = round(float(obj[CHARGE_M[data["BillingItemCode"]]]) / sum_result * data["PretaxAmount"], 2) amount_item = CHARGE_M[data["BillingItemCode"]] + '_amount' o = OssBill.objects.filter( billing_cycle=billing_cycle, ownerid=data["BillAccountID"], instance_id=data['InstanceID'], bucket_name=obj["bucket_name"] ) o.update(**{'pretax_amount': F('pretax_amount') + amount, amount_item: F(amount_item) + amount})
|