CrazyIter_Bin 1 year ago
parent
commit
7c5b3fc5d6

+ 2 - 2
TEAMModelOS.FunctionV4/HttpTrigger/IESHttpTrigger.cs

@@ -83,8 +83,8 @@ namespace TEAMModelOS.FunctionV4
         public async Task<HttpResponseData> HttpLog([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req) {
             string data = await new StreamReader(req.Body).ReadToEndAsync();
             var response = req.CreateResponse(HttpStatusCode.OK);
-            
-            var appendBlob = _azureStorage.GetBlobContainerClient("0-service-log").GetAppendBlobClient($"http-log/{DateTimeOffset.UtcNow.GetGMTTime(8):yyyy-MM-dd}.log");
+            var gmt8Time =  DateTimeOffset.UtcNow.GetGMTTime(8);
+            var appendBlob = _azureStorage.GetBlobContainerClient("0-service-log").GetAppendBlobClient($"http-log/{gmt8Time:yyyy-MM-dd}/{gmt8Time:HH}.log");
             if (!appendBlob.Exists())
             {
                 appendBlob.Create();

+ 2 - 10
TEAMModelOS.SDK/Helper/Common/DateTimeHelper/DateTimeHelper.cs

@@ -36,11 +36,7 @@ namespace TEAMModelOS.SDK
             //处理UTC时差
             TimeZoneInfo localTimezone = TimeZoneInfo.Local;
             var Hours = localTimezone.BaseUtcOffset.Hours;
-            if (Hours!=0)
-            {
-                //有时差
-                dateTime = dateTime.AddHours(GMT-Hours);
-            }
+            dateTime = dateTime.AddHours(GMT-Hours);
             return dateTime;
         }
         /// <summary>
@@ -54,11 +50,7 @@ namespace TEAMModelOS.SDK
             //处理UTC时差
             TimeZoneInfo localTimezone = TimeZoneInfo.Local;
             var Hours = localTimezone.BaseUtcOffset.Hours;
-            if (Hours!=0)
-            {
-                //有时差
-                dateTime = dateTime.AddHours(GMT-Hours);
-            }
+            dateTime = dateTime.AddHours(GMT-Hours);
             return dateTime;
         }
 

File diff suppressed because it is too large
+ 1148 - 0
TEAMModelOS/Controllers/System/BillController.cs


+ 0 - 716
TEAMModelOS/Controllers/XTest/BillController.cs

@@ -1,716 +0,0 @@
-using Azure.Storage.Blobs.Models;
-using DocumentFormat.OpenXml.Spreadsheet;
-using HTEXLib.COMM.Helpers;
-using Microsoft.AspNetCore.Authorization;
-using Microsoft.AspNetCore.Cors;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.Azure.Amqp.Framing;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Options;
-using NUnit.Framework;
-using OfficeOpenXml;
-using OpenXmlPowerTools;
-using StackExchange.Redis;
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.IdentityModel.Tokens.Jwt;
-using System.IO;
-using System.Linq;
-using System.Net.Http;
-using System.Runtime.Intrinsics.Arm;
-using System.Text;
-using System.Text.Json;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-using System.Web;
-using TEAMModelOS.Filter;
-using TEAMModelOS.Models;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.DI;
-using TEAMModelOS.SDK.Extension;
-using TEAMModelOS.SDK.Helper.Security.ShaHash;
-using TEAMModelOS.SDK.Models;
-using TEAMModelOS.SDK.Models.Cosmos.School;
-using TEAMModelOS.SDK.Models.Service.BI;
-
-namespace TEAMModelOS.Controllers.XTest
-{
-    [ProducesResponseType(StatusCodes.Status200OK)]
-    [ProducesResponseType(StatusCodes.Status400BadRequest)]
-
-    [Route("bill")]
-    [ApiController]
-    public class BillController : ControllerBase
-    {
-        private readonly DingDing _dingDing;
-        private readonly IHttpClientFactory _httpClient;
-        private readonly IConfiguration _configuration;
-        private readonly AzureStorageFactory _azureStorage;
-        private readonly IPSearcher _ipSearcher;
-        private readonly Option _option;
-        public BillController(IHttpClientFactory httpClient, IConfiguration configuration, AzureStorageFactory azureStorage,    IPSearcher searcher, DingDing  dingDing, IOptionsSnapshot<Option> option) 
-        {
-            _httpClient = httpClient;
-            _configuration = configuration;
-            _azureStorage = azureStorage;
-            _ipSearcher = searcher;
-            _dingDing = dingDing;
-            _option = option.Value;
-        }
-        
-        [HttpPost("report")]
-        [EnableCors("AllowSpecificOrigin")]
-        [AllowAnonymous]
-        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
-        public async Task<IActionResult> Report(JsonElement json)
-        {
-            try {
-
-                List<KeyBillDetail> monthData = new List<KeyBillDetail>();
-                List<DayBillDetail> dayData = new List<DayBillDetail>();
-                List<DayBillDetail> resourceGroupDataGroup = new List<DayBillDetail>();
-                List<DayBillDetail> cloudServiceDataGroup = new List<DayBillDetail>();
-                List<DayBillDetail> meterCategoryDataGroup = new List<DayBillDetail>();
-                List<DayBillDetail> consumedServiceDataGroup = new List<DayBillDetail>();
-                string BillToken = _configuration.GetValue<string>("Azure:Bill:Token");
-                List<string> times = json.GetProperty("times").ToObject<List<string>>();
-
-                List<string> ResourceGroup = new List<string>();
-                List<string> CloudService = new List<string>();
-                List<string> Product = new List<string>();
-                List<string> MeterCategory = new List<string>();
-                List<string> MeterSubCategory = new List<string>();
-                List<string> MeterName = new List<string>();
-                List<string> ConsumedService = new List<string>();
-                
-                if (json.TryGetProperty("CloudService", out JsonElement _CloudService)) {
-                    CloudService= _CloudService.ToObject<List<string>>();
-                }
-                if (json.TryGetProperty("ResourceGroup", out JsonElement _ResourceGroup))
-                {
-                    ResourceGroup= _ResourceGroup.ToObject<List<string>>();
-                }
-                if (json.TryGetProperty("Product", out JsonElement _Product))
-                {
-                    Product= _Product.ToObject<List<string>>();
-                }
-                if (json.TryGetProperty("MeterCategory", out JsonElement _MeterCategory))
-                {
-                    MeterCategory= _MeterCategory.ToObject<List<string>>();
-                }
-                if (json.TryGetProperty("MeterSubCategory", out JsonElement _MeterSubCategory))
-                {
-                    MeterSubCategory= _MeterSubCategory.ToObject<List<string>>();
-                }
-                if (json.TryGetProperty("MeterName", out JsonElement _MeterName))
-                {
-                    MeterName= _MeterName.ToObject<List<string>>();
-                }
-                if (json.TryGetProperty("ConsumedService", out JsonElement _ConsumedService))
-                {
-                    ConsumedService= _ConsumedService.ToObject<List<string>>();
-                }
-                var httpClient = _httpClient.CreateClient();
-                httpClient.DefaultRequestHeaders.Remove("Authorization");
-                httpClient.DefaultRequestHeaders.Remove("api-version");
-                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {BillToken}");
-                httpClient.DefaultRequestHeaders.Add("api-version", "2014-09-02");
-                var jwt = new JwtSecurityToken(BillToken);
-                jwt.Payload.TryGetValue("EnrollmentNumber", out object EnrollmentNumber);
-                int? exp = jwt.Payload.Exp;
-                long now = DateTimeOffset.Now.ToUnixTimeSeconds();
-                if (exp.HasValue   && now>=exp.Value)
-                {
-                    return Ok(new { code = 401 });
-                }
-
-                Dictionary<string, HashSet<string>> dict = new Dictionary<string, HashSet<string>>();
-                Dictionary<string, HashSet<string>> dictCond = new Dictionary<string, HashSet<string>>();
-             
-                var BlobClientDict = _azureStorage.GetBlobContainerClient("teammodelos").GetBlobClient($"bill/dict.json");
-                if (BlobClientDict.Exists())
-                {
-                    BlobDownloadResult resultDict = await _azureStorage.GetBlobContainerClient("teammodelos").GetBlobClient($"bill/dict.json").DownloadContentAsync();
-                    var dictBlob = resultDict.Content.ToObjectFromJson<Dictionary<string, HashSet<string>>>();
-                    if (dictBlob!=null  && dictBlob.Count>0)
-                    {
-                        dict=dictBlob;
-                    }
-                }
-                bool change = false;
-                foreach (var time in times) {
-                    IEnumerable<BillDetail> billDetails = new List<BillDetail>();
-                    string force = json.GetProperty("force").GetString();
-                    var BlobClient = _azureStorage.GetBlobContainerClient("teammodelos").GetBlobClient($"bill/{time}.json");
-                    string nowMonth = DateTimeOffset.Now.ToString("yyyy-MM");
-                    if (BlobClient.Exists()&& !force.Equals("1")  &&  !nowMonth.Equals(time))
-                    {
-                        BlobDownloadResult result = await _azureStorage.GetBlobContainerClient("teammodelos").GetBlobClient($"bill/{time}.json").DownloadContentAsync();
-                        var bill = result.Content.ToObjectFromJson<List<BillDetail>>();
-                        billDetails=bill;
-                    }
-                    else
-                    {
-                        string url = $"https://ea.azure.cn/rest/{EnrollmentNumber}/usage-report/paginated?month={time}&fmt=JSON&pageindex=0";
-                        var response = await httpClient.GetAsync(url);
-                        if (response.IsSuccessStatusCode)
-                        {
-                            var content = await response.Content.ReadAsStringAsync(); 
-                            var bill = content.ToObject<List<BillDetail>>();
-                            //移除金额0的项目
-                            bill=  bill.FindAll(x => x.ExtendedCost>0);
-                            bill.ForEach(x => { 
-                                x.ResourceGroup= x.ResourceGroup.ToLower();
-                                x.MeterCategory=x.MeterCategory.ToLower();
-                                x.ConsumedService=x.ConsumedService.ToLower();
-                                if (string.IsNullOrWhiteSpace(x.ConsumedService)) {
-                                    x.ConsumedService="default";
-                                }
-                                if (string.IsNullOrWhiteSpace(x.ResourceGroup))
-                                {
-                                    x.ResourceGroup="default";
-                                }
-                                if (string.IsNullOrWhiteSpace(x.MeterCategory))
-                                {
-                                    x.MeterCategory="default";
-                                }
-                                if (x.ResourceGroup.Equals("teammodelchengdu")) {
-                                    x.CloudService="ies5"; 
-                                }
-                                else if (x.ResourceGroup.Equals("coreservicerg"))
-                                {
-                                    x.CloudService="core";
-                                }
-                                else if (x.ResourceGroup.Equals("mc_iesresourcegroup_sokcluster_chinaeast2")||x.ResourceGroup.Equals("iesresourcegroup"))
-                                {
-                                    x.CloudService="sokrates";
-                                }
-                                else if (x.ResourceGroup.Equals("coreserviceresourcegroupcn"))
-                                {
-                                    x.CloudService="ies3";
-                                }
-                                else 
-                                {
-                                    x.CloudService="other";
-                                }
-                            });
-                            var group = bill.GroupBy(x => $"{x.Date}{x.ResourceGroup}{x.CloudService}{x.Product}{x.MeterCategory}{x.MeterSubCategory}{x.MeterName}{x.ConsumedService}").Select(x=>new { x.Key,list=x.ToList()});
-                            List<BillDetail> details = new List<BillDetail>();
-                            foreach ( var item in group )
-                            {
-                                BillDetail billDetail = item.list.First();
-                                billDetail.ExtendedCost=item.list.Sum(x=>x.ExtendedCost);
-                                details.Add(billDetail);
-                            }
-                            if (!nowMonth.Equals(time))
-                            {
-                                await _azureStorage.GetBlobContainerClient("teammodelos").UploadFileByContainer(details.ToJsonString(), "bill", $"{time}.json", true);
-                            }
-                            billDetails=details;
-                            //MeterCategory 服务
-                            {
-                                var newKey = billDetails.Select(x => x.MeterCategory).ToHashSet();
-                                if (dict.ContainsKey("MeterCategory"))
-                                {
-                                    var moreKey = newKey.Except(dict["MeterCategory"]);
-                                    foreach (var key in moreKey)
-                                    {
-                                        change=true;
-                                        dict["MeterCategory"].Add(key);
-                                    }
-                                }
-                                else
-                                {
-                                    change=true;
-                                    dict.Add("MeterCategory", newKey);
-                                }
-                            }
-                            //MeterSubCategory 服务类型
-                            {
-                                var newKey = billDetails.Select(x => x.MeterSubCategory).ToHashSet();
-                                if (dict.ContainsKey("MeterSubCategory"))
-                                {
-                                    var moreKey = newKey.Except(dict["MeterSubCategory"]);
-                                    foreach (var key in moreKey)
-                                    {
-                                        change=true;
-                                        dict["MeterSubCategory"].Add(key);
-                                    }
-                                }
-                                else
-                                {
-                                    change=true;
-                                    dict.Add("MeterSubCategory", newKey);
-                                }
-                            }
-                            //ConsumedService 服务信息
-                            {
-                                var newKey = billDetails.Select(x => x.ConsumedService).ToHashSet();
-                                if (dict.ContainsKey("ConsumedService"))
-                                {
-                                    var moreKey = newKey.Except(dict["ConsumedService"]);
-                                    foreach (var key in moreKey)
-                                    {
-                                        change=true;
-                                        dict["ConsumedService"].Add(key);
-                                    }
-                                }
-                                else
-                                {
-                                    change=true;
-                                    dict.Add("ConsumedService", newKey);
-                                }
-                            }
-                            //CloudService 资源组
-                            {
-                                var newKey = billDetails.Select(x => x.CloudService.ToLower()).ToHashSet();
-                                if (dict.ContainsKey("CloudService"))
-                                {
-                                    var moreKey = newKey.Except(dict["CloudService"]);
-                                    foreach (var key in moreKey)
-                                    {
-                                        change=true;
-                                        dict["CloudService"].Add(key);
-                                    }
-                                }
-                                else
-                                {
-                                    change=true;
-                                    dict.Add("CloudService", newKey);
-                                }
-                            }
-                            //ResourceGroup 资源组
-                            {
-                                var newKey = billDetails.Select(x => x.ResourceGroup.ToLower()).ToHashSet();
-                                if (dict.ContainsKey("ResourceGroup"))
-                                {
-                                    var moreKey = newKey.Except(dict["ResourceGroup"]);
-                                    foreach (var key in moreKey)
-                                    {
-                                        change=true;
-                                        dict["ResourceGroup"].Add(key);
-                                    }
-                                }
-                                else
-                                {
-                                    change=true;
-                                    dict.Add("ResourceGroup", newKey);
-                                }
-                            }
-                            //MeterName 服务资源
-                            {
-                                var newKey = billDetails.Select(x => x.MeterName).ToHashSet();
-                                if (dict.ContainsKey("MeterName"))
-                                {
-                                    var moreKey = newKey.Except(dict["MeterName"]);
-                                    foreach (var key in moreKey)
-                                    {
-                                        change=true;
-                                        dict["MeterName"].Add(key);
-                                    }
-                                }
-                                else
-                                {
-                                    change=true;
-                                    dict.Add("MeterName", newKey);
-                                }
-                            }
-                            //Product  产品
-                            {
-                                var newKey = billDetails.Select(x => x.Product).ToHashSet();
-                                if (dict.ContainsKey("Product"))
-                                {
-                                    var moreKey = newKey.Except(dict["Product"]);
-                                    foreach (var key in moreKey)
-                                    {
-                                        change=true;
-                                        dict["Product"].Add(key);
-                                    }
-                                }
-                                else
-                                {
-                                    change=true;
-                                    dict.Add("Product", newKey);
-                                }
-                            }
-                        }
-                    }
-                    if (CloudService.IsNotEmpty())
-                    {
-                        billDetails=  billDetails.Where(x => CloudService.Contains(x.CloudService));
-                    }
-                    if (ResourceGroup.IsNotEmpty()) {
-                        billDetails=  billDetails.Where(x => ResourceGroup.Contains(x.ResourceGroup));
-                    }
-                    if (Product.IsNotEmpty())
-                    {
-                        billDetails=  billDetails.Where(x => Product.Contains(x.Product));
-                    }
-                    if (MeterCategory.IsNotEmpty())
-                    {
-                        billDetails=  billDetails.Where(x => MeterCategory.Contains(x.MeterCategory));
-                    }
-                    if (MeterSubCategory.IsNotEmpty())
-                    {
-                        billDetails=  billDetails.Where(x => MeterSubCategory.Contains(x.MeterSubCategory));
-                    }
-                    if (MeterName.IsNotEmpty())
-                    {
-                        billDetails=  billDetails.Where(x => MeterName.Contains(x.MeterName));
-                    }
-                    if (ConsumedService.IsNotEmpty())
-                    {
-                        billDetails=  billDetails.Where(x => ConsumedService.Contains(x.ConsumedService));
-                    }
-                    {
-                        //MeterCategory 服务
-                        {
-                            var newKey = billDetails.Select(x => x.MeterCategory).ToHashSet();
-                            if (dictCond.ContainsKey("MeterCategory"))
-                            {
-                                var moreKey = newKey.Except(dictCond["MeterCategory"]);
-                                foreach (var key in moreKey)
-                                {
-                                    change=true;
-                                    dictCond["MeterCategory"].Add(key);
-                                }
-                            }
-                            else
-                            {
-                                change=true;
-                                dictCond.Add("MeterCategory", newKey);
-                            }
-                        }
-                        //MeterSubCategory 服务类型
-                        {
-                            var newKey = billDetails.Select(x => x.MeterSubCategory).ToHashSet();
-                            if (dictCond.ContainsKey("MeterSubCategory"))
-                            {
-                                var moreKey = newKey.Except(dictCond["MeterSubCategory"]);
-                                foreach (var key in moreKey)
-                                {
-                                    change=true;
-                                    dictCond["MeterSubCategory"].Add(key);
-                                }
-                            }
-                            else
-                            {
-                                change=true;
-                                dictCond.Add("MeterSubCategory", newKey);
-                            }
-                        }
-                        //ConsumedService 服务信息
-                        {
-                            var newKey = billDetails.Select(x => x.ConsumedService).ToHashSet();
-                            if (dictCond.ContainsKey("ConsumedService"))
-                            {
-                                var moreKey = newKey.Except(dictCond["ConsumedService"]);
-                                foreach (var key in moreKey)
-                                {
-                                    change=true;
-                                    dictCond["ConsumedService"].Add(key);
-                                }
-                            }
-                            else
-                            {
-                                change=true;
-                                dictCond.Add("ConsumedService", newKey);
-                            }
-                        }
-                        //CloudService 资源组
-                        {
-                            var newKey = billDetails.Select(x => x.CloudService.ToLower()).ToHashSet();
-                            if (dictCond.ContainsKey("CloudService"))
-                            {
-                                var moreKey = newKey.Except(dictCond["CloudService"]);
-                                foreach (var key in moreKey)
-                                {
-                                    change=true;
-                                    dictCond["CloudService"].Add(key);
-                                }
-                            }
-                            else
-                            {
-                                change=true;
-                                dictCond.Add("CloudService", newKey);
-                            }
-                        }
-
-                        //ResourceGroup 资源组
-                        {
-                            var newKey = billDetails.Select(x => x.ResourceGroup.ToLower()).ToHashSet();
-                            if (dictCond.ContainsKey("ResourceGroup"))
-                            {
-                                var moreKey = newKey.Except(dictCond["ResourceGroup"]);
-                                foreach (var key in moreKey)
-                                {
-                                    change=true;
-                                    dictCond["ResourceGroup"].Add(key);
-                                }
-                            }
-                            else
-                            {
-                                change=true;
-                                dictCond.Add("ResourceGroup", newKey);
-                            }
-                        }
-                        //MeterName 服务资源
-                        {
-                            var newKey = billDetails.Select(x => x.MeterName).ToHashSet();
-                            if (dictCond.ContainsKey("MeterName"))
-                            {
-                                var moreKey = newKey.Except(dictCond["MeterName"]);
-                                foreach (var key in moreKey)
-                                {
-                                    change=true;
-                                    dictCond["MeterName"].Add(key);
-                                }
-                            }
-                            else
-                            {
-                                change=true;
-                                dictCond.Add("MeterName", newKey);
-                            }
-                        }
-                        //Product  产品
-                        {
-                            var newKey = billDetails.Select(x => x.Product).ToHashSet();
-                            if (dictCond.ContainsKey("Product"))
-                            {
-                                var moreKey = newKey.Except(dictCond["Product"]);
-                                foreach (var key in moreKey)
-                                {
-                                    change=true;
-                                    dictCond["Product"].Add(key);
-                                }
-                            }
-                            else
-                            {
-                                change=true;
-                                dictCond.Add("Product", newKey);
-                            }
-                        }
-                    }
-                    monthData.Add(new KeyBillDetail { key=time, 
-                        cost= billDetails.Sum(x=>x.ExtendedCost)
-                    
-                    });
-
-                    var ResourceGroupData = billDetails.GroupBy(x => x.ResourceGroup);
-                    DayBillDetail ResourceGroupDataBillDetail = new DayBillDetail() { month= time };
-                    foreach (var group in ResourceGroupData)
-                    {
-                        ResourceGroupDataBillDetail.bills.Add(new KeyBillDetail() { key= group.Key, cost= group.Select(x => x.ExtendedCost).Sum() });
-                    }
-                    ResourceGroupDataBillDetail.bills= ResourceGroupDataBillDetail.bills.OrderByDescending(x => x.cost).ToList();
-                    resourceGroupDataGroup.Add(ResourceGroupDataBillDetail);
-
-
-
-                    var CloudServiceData = billDetails.GroupBy(x => x.CloudService);
-                    DayBillDetail CloudServiceDataBillDetail = new DayBillDetail() { month= time };
-                    foreach (var group in CloudServiceData)
-                    {
-                        CloudServiceDataBillDetail.bills.Add(new KeyBillDetail() { key= group.Key, cost= group.Select(x => x.ExtendedCost).Sum() });
-                    }
-                    CloudServiceDataBillDetail.bills= CloudServiceDataBillDetail.bills.OrderByDescending(x => x.cost).ToList();
-                    cloudServiceDataGroup.Add(CloudServiceDataBillDetail);
-
-                    var MeterCategoryData = billDetails.GroupBy(x => x.MeterCategory);
-                    DayBillDetail MeterCategoryDataBillDetail = new DayBillDetail() { month= time };
-                    foreach (var group in MeterCategoryData) {
-
-                        MeterCategoryDataBillDetail.bills.Add(new KeyBillDetail() { key= group.Key, cost= group.Select(x => x.ExtendedCost).Sum() });
-                    }
-                    MeterCategoryDataBillDetail.bills= MeterCategoryDataBillDetail.bills.OrderByDescending(x => x.cost).ToList();
-                    meterCategoryDataGroup.Add(MeterCategoryDataBillDetail);
-
-
-                    DayBillDetail ConsumedServiceDataBillDetail = new DayBillDetail() { month= time };
-                    var ConsumedServiceData = billDetails.GroupBy(x => x.ConsumedService);
-                    foreach (var group in ConsumedServiceData) {
-                        ConsumedServiceDataBillDetail.bills.Add(new KeyBillDetail() { key= group.Key, cost= group.Select(x => x.ExtendedCost).Sum() });
-                    }
-                    ConsumedServiceDataBillDetail.bills= ConsumedServiceDataBillDetail.bills.OrderByDescending(x => x.cost).ToList();
-                    consumedServiceDataGroup.Add(ConsumedServiceDataBillDetail);
-
-
-                    DayBillDetail dayBillDetail = new DayBillDetail() { month= time};
-                    for (int i = 1; i<=31; i++)
-                    {
-                        var day = billDetails.Where(x => x.Day==i);
-                        if (day!=null  && day.Count()>0)
-                        {
-                            dayBillDetail.bills.Add(new KeyBillDetail
-                            {
-                                key=$"{i}",
-                                cost= day.Sum(x =>x.ExtendedCost)
-                            });
-                        }
-                        else
-                        {
-                            dayBillDetail.bills.Add(new KeyBillDetail { key=$"{i}",cost=0 });
-                        }
-                    }
-                    dayData.Add(dayBillDetail);
-                }
-                if (change)
-                {
-                    await _azureStorage.GetBlobContainerClient("teammodelos").UploadFileByContainer(dict.ToJsonString(), "bill", $"dict.json", true);
-                }
-                return Ok(new {   monthData, dayData, dict, dictCond, code=200, consumedServiceDataGroup ,meterCategoryDataGroup, cloudServiceDataGroup, resourceGroupDataGroup});
-
-
-            } catch (Exception ex) {
-                return Ok(new { code = 500 ,msg= $"{ex.Message}{ex.StackTrace}"});
-            }
-           
-        }
-
-        public class KeyBillDetail {
-            public string key { get; set; }
-            public double cost { get; set; }
-        }
-        public class DayBillDetail
-        {
-            public string month { get; set; }
-            /// <summary>
-            /// 每天的数据
-            /// </summary>
-            public List<KeyBillDetail> bills { get; set; } = new List<KeyBillDetail>();
-        }
-        public class BillDetail
-        {
-            /// <summary>
-            /// 
-            /// </summary>
-            // public string AccountOwnerId { get; set; }
-            /// <summary>
-            /// 云米
-            /// </summary>
-            //public string AccountName { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            //public string ServiceAdministratorId { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            //public long SubscriptionId { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public string SubscriptionGuid { get; set; }
-            /// <summary>
-            /// 标准预付费服务(Converted to EA)
-            /// </summary>
-            //public string SubscriptionName { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public string Date { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public int Month { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public int Day { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public int Year { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public string Product { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            //public string MeterId { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public string MeterCategory { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public string MeterSubCategory { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-           // public string MeterRegion { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public string MeterName { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-           // public double ConsumedQuantity { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-           // public double ResourceRate { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public double ExtendedCost { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-           // public string ResourceLocation { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public string ConsumedService { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public string InstanceId { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-           // public string ServiceInfo1 { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-           // public string ServiceInfo2 { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-           // public string AdditionalInfo { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-          //  public string Tags { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-         //   public string StoreServiceIdentifier { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-          //  public string DepartmentName { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-           // public string CostCenter { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            //public string UnitOfMeasure { get; set; }
-            /// <summary>
-            /// 
-            /// </summary>
-            public string ResourceGroup { get; set; }
-            public string CloudService { get; set; }
-            public string CloudServiceName { get; set; }
-        }
-
-    }
-}

+ 40 - 23
TEAMModelOS/Filter/RequestAuditFilter.cs

@@ -24,11 +24,12 @@ namespace TEAMModelOS.Filter
         private readonly HttpTrigger _httpTrigger;
         public RequestAuditFilter(/*ILoggerFactory loggerFactory*/HttpTrigger httpTrigger)
         {
-          //  _logger = loggerFactory.CreateLogger<RequestAuditFilter>();
+            //  _logger = loggerFactory.CreateLogger<RequestAuditFilter>();
             _httpTrigger = httpTrigger;
         }
         public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
         {
+            string id = string.Empty, name = string.Empty, picture = string.Empty, school = string.Empty, scope = string.Empty;
             //============== 这里是执行方法之前获取数据 ====================
 
             // 获取控制器、路由信息
@@ -45,11 +46,11 @@ namespace TEAMModelOS.Filter
             var remoteIPv4 = httpContext.GetRemoteIpAddressToIPv4();
 
             // 获取请求的 Url 地址
-           // var requestUrl = httpRequest.GetRequestUrlAddress();
+            // var requestUrl = httpRequest.GetRequestUrlAddress();
+
 
-            
             // 获取来源 Url 地址
-           //var refererUrl = httpRequest.GetRefererUrlAddress();
+            var refererUrl = httpRequest.GetRefererUrlAddress();
 
             // 获取请求参数(写入日志,需序列化成字符串后存储)
             var parameters = context.ActionArguments;
@@ -57,22 +58,32 @@ namespace TEAMModelOS.Filter
             // 获取操作人(必须授权访问才有值)"userId" 为你存储的 claims type,jwt 授权对应的是 payload 中存储的键名
             //var userId = httpContext.User?.FindFirstValue("userId");
             var authtoken = context.HttpContext.GetXAuth("AuthToken");
-            string tokenSha = string.Empty,client = string.Empty;
-            if (context.HttpContext.Request.Headers.TryGetValue("Authorization", out StringValues Authorization)) 
+            string tokenSha = string.Empty, client = string.Empty;
+            if (context.HttpContext.Request.Headers.TryGetValue("Authorization", out StringValues Authorization))
             {
-                try {
-                    string token = Authorization.ToString().Replace("Bearer ", "");
-                    var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
-                      tokenSha = ShaHashHelper.GetSHA1(token);
-                    client = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("roles"))?.Value;
-                } catch (Exception ex ) { }
+
             }
-            string id = string.Empty, name = string.Empty, picture = string.Empty, school = string.Empty;
-            if (!string.IsNullOrWhiteSpace(authtoken)) {
+            if (context.HttpContext.Request.Headers.TryGetValue("X-Auth-School", out StringValues XAuthSchool))
+            {
+                try
+                {
+                    school = XAuthSchool.ToString();
+                }
+                catch (Exception ex) { }
+            }
+
+            if (!string.IsNullOrWhiteSpace(authtoken))
+            {
                 var jwt = new JwtSecurityTokenHandler().ReadJwtToken(authtoken);
                 id = jwt.Payload.Sub;
                 school = jwt.Payload.Azp;
                 name = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("name"))?.Value;
+                scope = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("scope"))?.Value;
+            }
+            string secChUaPlatform = string.Empty;
+            if (httpContext.Request.Headers.TryGetValue("Sec-Ch-Ua-Platform", out var values))
+            {
+                secChUaPlatform = values.FirstOrDefault();
             }
             // 请求时间
             var requestedTime = DateTimeOffset.Now.GetGMTTime(8).ToUnixTimeMilliseconds();
@@ -88,22 +99,28 @@ namespace TEAMModelOS.Filter
             // var stackTrace = EnhancedStackTrace.Current();
             // string region = await _searcher.SearchIpAsync(remoteIPv4);
             //同一个账号,同一IP,同一接口,UA标识(UA标识随意切换则表示可能会存在DDOS),时间段
-             //_logger.LogInformation(new{ ua=httpContext.GetUserAgent(), ip=remoteIPv4,time=requestedTime,path =$"{httpRequest.PathBase}{httpRequest.Path}",host= $"{httpRequest.Host}", param=parameters,id ,name ,school,succeed =isRequestSucceed }.ToJsonString());
-            var data = new {
-                //ua = httpContext.GetUserAgent(),
+            //_logger.LogInformation(new{ ua=httpContext.GetUserAgent(), ip=remoteIPv4,time=requestedTime,path =$"{httpRequest.PathBase}{httpRequest.Path}",host= $"{httpRequest.Host}", param=parameters,id ,name ,school,succeed =isRequestSucceed }.ToJsonString());
+          
+            var data = new
+            {
+                ua = httpContext.GetUserAgent(),
                 ip = remoteIPv4,
                 time = requestedTime,
                 path = $"{httpRequest.PathBase}{httpRequest.Path}",
                 host = $"{httpRequest.Host}",
                 param = parameters,
-                id,
-                name,
-                school,
-                client,tid= tokenSha,
-                p="os",
+                id = id,
+                name = name,
+                school = school,
+                client = client,
+                tid = tokenSha,
+                scope = scope,
+                referer = refererUrl,
+                platform = secChUaPlatform,
+                p = "os",
             };
             _= _httpTrigger.RequestHttpTrigger(data, "China", "http-log");
-            
+
         }
     }
 }

+ 1 - 1
TEAMModelOS/Startup.cs

@@ -113,7 +113,7 @@ namespace TEAMModelOS
 #if DEBUG
                     builder.AllowAnyOrigin() // 添加允许的源
                            .AllowAnyHeader() // 允许任何请求标头
-                           //.AllowCredentials()
+                           .AllowCredentials()
                            ; // 允许包含凭据
 #else
                     //builder.WithOrigins("https://teammodeltest.blob.core.chinacloudapi.cn",  "https://teammodelos.blob.core.chinacloudapi.cn") // 添加允许的源       .AllowAnyMethod() // 允许任何请求方法