Angular 系列

(一)新增物流屬性頁面css

前端的Angular.jshtml

1.HTML頁面前端

<div class="pop-content animated fadeIn">
  <div class="modal-header">
    <h3 class="modal-title">物流屬性設置</h3>
    <button type="button" class="close" (click)="closeModal()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <div class="search-wrapper">
    <ul class="search-condition">
      <li>
      <label class="search-title">
        <span class="must">必填</span>商品屬性:</label>
      <label class="checkbox-inline custom-checkbox nowrap">
        <input type="checkbox"   [checked]="SkuAttr.includes('Normal')==true"  (click)="checkForAttr($event.target,'Normal')">
        <span>普貨</span>
      </label>
      <label class="checkbox-inline custom-checkbox nowrap">
        <input type="checkbox" [checked]="SkuAttr.includes('ExternalBattery')==true" (click)="checkForAttr($event.target,'ExternalBattery')">
        <span>帶電</span>
      </label>
      <label class="checkbox-inline custom-checkbox nowrap">
        <input type="checkbox" [checked]="SkuAttr.includes('Copy')==true" (click)="checkForAttr($event.target,'Copy')">
        <span>仿品</span>
      </label>
      <label class="checkbox-inline custom-checkbox nowrap">
        <input type="checkbox" [checked]="SkuAttr.includes('Liquid')==true" (click)="checkForAttr($event.target,'Liquid')">
        <span>液體</span>
      </label>
      <label class="checkbox-inline custom-checkbox nowrap">
        <input type="checkbox" [checked]="SkuAttr.includes('OtherDisableProduct')==true" (click)="checkForAttr($event.target,'OtherDisableProduct')">
        <span>違禁品</span>
      </label>
      </li>
      <li>
        <label class="search-title">
          <span class="must">必填</span>物流分類:</label>
        <div class="screen-wrapper" *ngFor="let subitem of logisticsSorts;let i = index">
          <input type="radio" id="{{subitem.id}}-sort" name="sort" class="regular-radio" [checked]="selectedLogisticsSort==subitem.value"/>
          <label for="{{subitem.id}}-sort" (click)="onSelect(subitem.id,subitem.value)">{{subitem.name}}</label>
        </div>
      </li>
      <li>
      <label class="search-title">
        <span class="explain">選填</span>預估運輸時間: </label>
      <div class="daySearch">
      <input type="number" class="form-control" [(ngModel)]="StartDay">
      <span>~</span>
      <input type="number" class="form-control" [(ngModel)]="EndDay">
      <span style="display: inline-block;width: 20px;text-align: center">(天)</span>
      </div>
      </li>
    </ul>
    </div>
  </div>
  <div class="modal-footer">
    <div class="btn-group">
      <button class="btn btn-default" (click)="closeModal()">取消</button>
      <button class="btn btn-primary" (click)="save()">保存</button>
    </div>
  </div>
</div>
View Code

2.邏輯頁面數據庫

import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal, NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { RootComponent } from "../../../../../shared/component/root.component";
import {ShippingMethodService} from "../../../../../shared/services/shipping-method-service";


@Component({
  selector: 'app-logisticsAttrSetting',
  templateUrl: './logisticsAttrSetting.component.html',
  styleUrls: ['./logisticsAttrSetting.component.scss'],
  providers: [ShippingMethodService]
})
export class LogisticsAttrSettingComponent extends RootComponent implements OnInit {
  SkuAttr=[];
  ssId : any;
  StartDay : number;
  EndDay : number;
  logisticsSorts=[
    {id:'1',name:"快遞",value:'Expressal'},
    {id:'2',name:"掛號",value:'Register'},
    {id:'3',name:"平郵",value:'SurfaceMail'},
    {id:'4',name:"專線掛號",value:'SpecialRegister'},
    {id:'5',name:"專線平郵",value:'SpecialSurfaceMail'},
    {id:'6',name:"虛擬海外倉",value:'VirtualRsealocation'}];
  selectedLogisticsSort='Expressal';
  constructor(private activeModal: NgbActiveModal,
    private modalService: NgbModal,private  shippingMethodService: ShippingMethodService) {
    super();
  }
  ngOnInit() {

  }
  closeModal() {
    this.activeModal.dismiss();
  }
  save(){

    let saveData={
      SsId:this.ssId,
      logisticsType:this.selectedLogisticsSort,
      StartDay:this.StartDay,
      EndDay : this.EndDay,
      ShippingAttribute : this.SkuAttr
    };
    if(this.SkuAttr.length == 0)
    {
      this.error('商品屬性不能爲空')
      return
    }
    this.shippingMethodService.setLogisticsAttribute(saveData).subscribe(data => {
      this.alertMessage('設置成功')

    }, this.handleError)

    this.activeModal.close();
  }
  onSelect(val){
    this.selectedLogisticsSort=val;
  }
  checkForAttr(target, value) {
    if (target.checked) {
        this.SkuAttr.push(value);
    } else {
      for (var i = 0; i < this.SkuAttr.length; i++) {
        let obj = this.SkuAttr[i];
        if (obj == value) {
          this.SkuAttr.splice(i, 1);
        }
      }
    }
  }
}
View Code

3.Css樣式bootstrap

.pop-content {
    width: 1000px;
    position: relative;
    left: 50%;
    transform:translateX(-50%);
}
.modal-body{
  height: 300px;
}
.screen-wrapper{
  margin-left: 0;
  margin-right: 10px;
}
.search-wrapper {
   .search-condition {
     float: left;
     height: auto;
     padding: 0 5px;
     li {
       width: 100%;
       float: left;
       margin-bottom: 30px;
       font-size: 14px;
       .checkbox-inline {
         margin-top: 8px;
         margin: 8px 10px 0 0;
       }
       .search-input {
         display: inline-block;
         width: 300px;
         height: 30px;
         margin-left: 0;
       }
       .margin-left {
         float: left;
         width: 90%;
       }
       .search-title {
         width: 150px;
         font-weight: bold;
         float: left;
         margin: 7px 0;
         letter-spacing:2px;
       }
       .input-group {
         width: 400px;
         height: 30px;
         float: left;
         .btn-group {
           .btn {
             border-radius: 0 3px 3px 0;
           }
         }
       }
     }
   }
}
.daySearch{
  input{
    display: inline-block;
    width: 100px;
    line-height: 30px;
    height: 30px;
  }
  span{
    display: inline-block;
    line-height: 30px;
  }
}
View Code

 

後端的WebApi(Erp和Shipping兩個項目進行分佈式部署)後端

Shipping項目api

1.Model(將新增的字段經過程序包管理器控制檯映射到數據庫)app

using Lmt.Shared.Domains;
using Shipping.Shared;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;

namespace Shipping.Domains.Models {
    public class SelectedShippingService :IModel{


        public long Id { get; protected set; }
        public long WarehouseId { get; protected set; }
        public long SsId { get; protected set; }
        public bool IsActive { get; set; }

        public Operator Operator { get; private set; }


        /// <summary>
        /// 物流屬性
        /// </summary>
        public string ShippingAttribute { get; set; }


        public LogisticsTypes LogisticsType { get; set; }

        /// <summary>
        /// 物流分類
        /// </summary>
        public enum LogisticsTypes
        {
            [Description("快遞")]
            Expressal = 1,
            [Description("掛號")]
            Register = 2,
            [Description("平郵")]
            SurfaceMail = 3,
            [Description("專線掛號")]
            SpecialRegister = 4,
            [Description("專線平郵")]
            SpecialSurfaceMail = 5,
            [Description("虛擬海外倉")]
            VirtualRsealocation = 6,
        }

        /// <summary>
        /// 預估運輸時間
        /// </summary>
        public int? StartDay { get; set; }
        public int? EndDay { get; set; }

        public static SelectedShippingService Create(long warehouseId,long ssId,long userId) {
            return new SelectedShippingService {
                SsId = ssId,
                WarehouseId = warehouseId,
                Operator = new Operator(UserOperator.Create(userId))
            };
        }
    }
}
View Code

2.Commands(調用Model類)async

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lmt.Shared.Domains;
using Shipping.Shared;
using static Shipping.Domains.Models.SelectedShippingService;

namespace Shipping.Domains.Commands
{
    public class UpdateShippingServiceAttributeCommand
    {
        public long SsId { get; set; }

        public LogisticsTypes LogisticsType { get; set; }

        public int? StartDay { get; set; }
        public int? EndDay { get; set; }

        public List<ShippingAttributeType> ShippingAttribute { get; set; }
    }
}
View Code

3.Services(EF鏈接數據庫進行增刪改查)分佈式

修改物流屬性的方法

 public async Task SetLogisticsAttribute(UpdateShippingServiceAttributeCommand command, long userId)
        {
            using (var db = Db.Shippings)
            {
                var selectedSSsId = db.SelectedShippingServices.FirstOrDefault(m => m.Id == command.SsId);
                if (selectedSSsId == null)
                {
                    throw new DomainException("未找到該數據的信息");
                }
                selectedSSsId.LogisticsType = command.LogisticsType;
                selectedSSsId.StartDay = command.StartDay;
                selectedSSsId.EndDay = command.EndDay;
                selectedSSsId.ShippingAttribute = string.Join(",", command.ShippingAttribute);
                selectedSSsId.Operator.Update(userId);
                await db.SaveChangesAsync().ConfigureAwait(false);
            }
        }
View Code

查詢修改後的方法

 public async Task<UpdateShippingServiceAttributeCommand> QueryLogisticsAttribute(long ssid,long userId)
        {
            using (var db = Db.Shippings)
            {
                var selectedSSsId = db.SelectedShippingServices.FirstOrDefault(m => m.Id == ssid);
                if (selectedSSsId == null)
                {
                    throw new DomainException("未找到該數據的信息");
                }
                List<ShippingAttributeType> type = new List<ShippingAttributeType>();
                if (!selectedSSsId.ShippingAttribute.IsNullOrEmpty())
                {
                    var attr = selectedSSsId.ShippingAttribute.Split(',');
                    foreach (var item in attr)
                    {
                        var enums = (ShippingAttributeType)Enum.Parse(typeof(ShippingAttributeType), item);
                        type.Add(enums);
                    }
                }
                
                var Query = new UpdateShippingServiceAttributeCommand() {
                    SsId=ssid,
                    ShippingAttribute = type, 
                    LogisticsType = selectedSSsId.LogisticsType,
                    StartDay = selectedSSsId.StartDay,
                    EndDay = selectedSSsId.EndDay, };
                return Query;


            }
        }
View Code

4.WebApi(調用Services中的類,定義路由規則給前端Angular.js頁面調用)

修改->Post

 [Route("SetLogistics"), HttpPost]
        [ResponseType(typeof(bool))]
        public async Task<HttpResponseMessage> SetLogisticsAttribute(UpdateShippingServiceAttributeCommand command)
        {
            var shippingMethodService = new ShippingMethodService();
            await shippingMethodService.SetLogisticsAttribute(command, CurrentUser.UserId).ConfigureAwait(false);
            return OkResult(true);
        }
View Code

查詢->Get

 [Route("QueryLogistics/{ssId:long}"),HttpGet]
        [ResponseType(typeof(UpdateShippingServiceAttributeCommand))]
        public async Task<HttpResponseMessage> QueryLogisticsAttribute(long ssid)
        {
            var shippingMethodService = new ShippingMethodService();
            var attributeCommand = await shippingMethodService.QueryLogisticsAttribute(ssid, CurrentUser.UserId).ConfigureAwait(false);
            return OkResult(attributeCommand);
        }
View Code

 

Erp的項目

1.ShippingModel(和Model保持一致)

using Shipping.Shared;
using System;
using System.Collections.Generic;
using static Shipping.Domains.Models.SelectedShippingService;

namespace Erp.ApiClients.Shipping.RequestModel
{
    public class UpdateShippingServiceAttributeRequest
    {
        public long SsId { get; set; }

        public LogisticsTypes LogisticsType { get; set; }

        public int? StartDay { get; set; }
        public int? EndDay { get; set; }

        public List<ShippingAttributeType> ShippingAttribute { get; set; }
    }
}
View Code

2.調用Shipping項目的WebApi的路徑(兩邊的接口經過反序列化進行數據的傳遞)

調用修改的Post路徑

 public Task<WebApiResult<bool?>> SetLogisticsAttribute(UpdateShippingServiceAttributeCommand command, long userId)
        {
            var request = new UpdateShippingServiceAttributeRequest
            {
                LogisticsType = command.LogisticsType,
                ShippingAttribute = command.ShippingAttribute,
                StartDay = command.StartDay,
                EndDay = command.EndDay,
                SsId = command.SsId
            };
            return ApiClient
                .Auth(DmtApiAuth.User(userId))
                .Path("api/v1/shipping-service/SetLogistics")
                .PostJsonAsync<WebApiResult<bool?>>(request);
        }
View Code

調用查詢的Get路徑

 public Task<WebApiResult<UpdateShippingServiceAttributeRequest>> QueryLogisticsAttribute(long ssid, long userId)
        {
            return ApiClient
                .Auth(DmtApiAuth.User(userId))
                .Path($"api/v1/shipping-service/QueryLogistics/{ssid}")
                .GetAsync<WebApiResult<UpdateShippingServiceAttributeRequest>>();
        }
View Code

3.Services(EF鏈接數據庫進行增刪改查)

修改

 public async Task SetLogisticsAttribute(UpdateShippingServiceAttributeCommand command, long userId)
        {
            await CallShippingApi(c => c.SetLogisticsAttribute(command, userId)).ConfigureAwait(false);
        }
View Code

查詢

 public async Task<UpdateShippingServiceAttributeRequest> QueryLogisticsAttribute(long ssid,long userId)
        {
            return await CallShippingApi(c => c.QueryLogisticsAttribute(ssid,userId)).ConfigureAwait(false);
        }
View Code

4.WebApi(調用Services中的類,定義路由規則給前端Angular.js頁面調用)

定義路由規則的入口

 [RoutePrefix("api/v1/shipping/shipping-method")]
    public class ShippingServiceController : ErpApiController {
        private readonly ShippingMethodService _shippingMethodService;

        public ShippingServiceController() {
            _shippingMethodService = new ShippingMethodService();
        }

...

}
View Code

修改的WebApi

  [Route("setLogisticsAttribute"), HttpPost]
        [ResponseType(typeof(bool))]
        public async Task<HttpResponseMessage> SetLogisticsAttribute(UpdateShippingServiceAttributeCommand command)
        {
            var ssService = new ShippingMethodService();
            await ssService.SetLogisticsAttribute(command, User.UserId).ConfigureAwait(false);
            return OkResult(true);
        }
View Code

查詢的WebApi

[Route("queryLogisticsAttribute"), HttpPost]
        [ResponseType(typeof(UpdateShippingServiceAttributeCommand))]
        public async Task<HttpResponseMessage> QueryLogisticsAttribute(long ssid)
        {
            var ssService = new ShippingMethodService();
            var attributeCommand = await ssService.QueryLogisticsAttribute(ssid,User.UserId).ConfigureAwait(false);
            return OkResult(attributeCommand);
        }
View Code

 5.附加(在查詢中去重複數據,在ERP的主表新增SelectedShippingServicesId來關聯Shipping表中的主鍵ID)

在Model中新增字段

using System.Collections.Generic;
using Erp.Shared;

namespace Erp.ApiClients.Shipping.ResponseModel {
    public class ShippingServiceListModel {
        public long SsId { get; set; }
        public string SsCode { get; set; }
        public string SsName { get; set; }

        /// <summary>
        /// 物流別名
        /// </summary>
        public string ShippingServiceAlias { get; set; }

        public string SpCode { get; set; }
        public string SpName { get; set; }
        public long SpId { get; set; }

        public long? SelectedShippingServicesId { get; set; }

        public bool NeedAuthorize { get; set; }
        public bool? IsAuthorized { get; set; }

        public bool IsActive { get; set; }
        public bool IsCustom { get; set; }
        public string LogisticsProviderShippingMethod { get; set; }
        public bool IsSelected { get; set; }
        public bool HasTrackingNumber { get; set; }
        public string TrackingNumberApiName { get; set; }
        public TrackingNumberApiFetchType TrackingNumberApiFetchType { get; set; }

        public List<ShippingMethodCarrireCodeModel> CarrireCodes { get; set; }
    }
 
    public class ShippingMethodCarrireCodeModel {
        public ChannelType ChannelType { get; set; }
        public string CarrierCode { get; set; }
        public string CustomCarrierName { get; set; }
    }
}
View Code

 6.屬性的枚舉類

using System.Collections.Generic;
using System.ComponentModel;

namespace Shipping.Shared {

    public enum ShippingAttributeType {
        [Description("普貨")]
        Normal = 0,
        [Description("純電池")]
        Battery = 1,

        [Description("帶內置電池")]
        InternalBattery = 2,

        [Description("帶外置電池")]
        ExternalBattery = 3,

        [Description("含鈕釦電池")]
        IncludeButtonBattery = 4,

        [Description("液體")]
        Liquid = 5,
        [Description("粉末")]
        Powder = 6,
        [Description("打火機")]
        Zippo = 7,
        [Description("")]
        Knife = 8,
        [Description("")]
        Gun = 9,
        [Description("帶磁物品")]
        MagneticProduct = 10,
        [Description("其餘禁運物品")]
        OtherDisableProduct = 11,
        [Description("膏狀")]
        Balm = 13,
        [Description("易碎")]
        Fragile = 14,
        [Description("動物羽毛類")]
        AnimalFeatherProduct = 15,
        [Description("大功率電池")]
        HighPowerBattery = 16,
        [Description("電子煙")]
        ElectronicCigarette = 17,
        [Description("移動電源")]
        MobilePower = 18,
        [Description("可拆卸電池")]
        RemovableBattery = 19,
        [Description("電機_馬達")]
        Motor = 21,
        [Description("手機")]
        CellPhone = 24,
        [Description("平衡車")]
        BalanceBike = 25,
        [Description("液體筆類")]
        LiquidPen = 26,
        [Description("仿品")]
        Copy = 27,
    }

    public static class ShippingAttributeTypeHelper {

        public static readonly IReadOnlyCollection<ShippingAttributeType> HasBatteryAttributes = new ShippingAttributeType[]
        {
           ShippingAttributeType.Battery,
           ShippingAttributeType.InternalBattery,
           ShippingAttributeType.ExternalBattery,
           ShippingAttributeType.IncludeButtonBattery, 
           ShippingAttributeType.ElectronicCigarette,
           ShippingAttributeType.MobilePower,
           ShippingAttributeType.RemovableBattery,
           ShippingAttributeType.Motor,
           ShippingAttributeType.CellPhone
        };

    }
}
View Code

 

(二)站內信消息的推送

WebApi

1.主表和子表

using Lmt.Shared.Domains;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Erp.Domains.Models.Message
{
    public class SystemMessage : IModel
    {
        /// <summary>
        /// 主鍵ID
        /// </summary>
        public long Id { get; set; }
        /// <summary>
        /// 關聯SystemMessageItem表的外鍵ID
        /// </summary>
        public ICollection<SystemMessageItem>SystemMessageItemKey { get; set; }

        /// <summary>
        /// 站內信標題
        /// </summary>
        public string MessageTitle { get; set; }

        /// <summary>
        /// 站內信內容
        /// </summary>
        public string MessageDetail { get; set; }

        /// <summary>
        /// 建立時間
        /// </summary>
        public DateTimeOffset CreateTime { get; set; }

        /// <summary>
        /// 消息類型
        /// </summary>
        public SystemMessageType MessageType { get; set; }


        public static SystemMessage CreateMessage(string messageTitle, string messageDetail, SystemMessageType messageType)
        {
            return new SystemMessage
            {
                MessageTitle = messageTitle,
                MessageDetail = messageDetail,
                CreateTime = DateTimeOffset.Now,
                MessageType = messageType

            };
        }

    }
    public enum SystemMessageType
        {
            [Description("帳號異常通知")]
            AccountExceptionType = 1,
        }


    
}
View Code
using Lmt.Shared.Domains;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Erp.Domains.Models.Message
{
    public class SystemMessageItem : IModel
    {
        /// <summary>
        /// 主鍵ID
        /// </summary>
        public long Id { get; set; }

        /// <summary>
        /// 外鍵
        /// </summary>
        public long SystemMessageKey { get; set; }

        /// <summary>
        /// 指定的帳號
        /// </summary>
        public long UserId { get; set; }

        /// <summary>
        /// 讀取狀態
        /// </summary>
        public bool IsRead { get; set; }

        /// <summary>
        /// 最後閱讀時間
        /// </summary>
        public DateTimeOffset? LastReadingTime { get; set; }

        public static SystemMessageItem CreateMessageItem(long systemMessageKey, long userId, bool isRead)
        {
            return new SystemMessageItem
            {
                SystemMessageKey = systemMessageKey,
                UserId = userId,
                IsRead = isRead,
                LastReadingTime = DateTimeOffset.Now
            };
        }
    }
}
View Code

 

2.Model

using Erp.Domains.Models.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Erp.Services.ReadModels.Message
{
    public class SystemMessageModel
    {
        /// <summary>
        /// 主鍵
        /// </summary>
        public long SystemMessageId { get; set; }

        /// <summary>
        /// 站內信標題
        /// </summary>
        public string MessageTitle { get; set; }

        /// <summary>
        /// 站內信內容
        /// </summary>
        public string MessageDetail { get; set; }

        /// <summary>
        /// 建立時間
        /// </summary>
        public DateTimeOffset CreateTime { get; set; }

        /// <summary>
        /// 消息類型
        /// </summary>
        public SystemMessageType MessageType { get; set; }

        public List<SystemMessageItemModel> SystemMessageItemModels { get; set; }

    }
}
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Erp.Services.ReadModels.Message
{
    public class SystemMessageItemModel
    {
        /// <summary>
        /// 主鍵
        /// </summary>
        public long SystemMessageItemId { get; set; }

        /// <summary>
        /// 外鍵
        /// </summary>
        public long SystemMessageKey { get; set; }

        /// <summary>
        /// 指定的對象
        /// </summary>
        public long UserId { get; set; }

        /// <summary>
        /// 讀取狀態
        /// </summary>
        public bool IsRead { get; set; }

        /// <summary>
        /// 最後閱讀時間
        /// </summary>
        public DateTimeOffset? LastReadingTime { get; set; }

    }
}
View Code
using Erp.Domains.Models.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Erp.Services.ReadModels.Message
{
   public class SystemMessageAllModel
    {
        /// <summary>
        /// 站內信標題
        /// </summary>
        public string MessageTitle { get; set; }

        /// <summary>
        /// 站內信內容
        /// </summary>
        public string MessageDetail { get; set; }

        /// <summary>
        /// 消息類型
        /// </summary>
        public SystemMessageType MessageType { get; set; }
        
        /// <summary>
        /// 判斷是不是用戶或角色
        /// </summary>
        public bool IsRoleOrUser { get; set; }

        /// <summary>
        /// 用戶id或者角色id集合
        /// </summary>
        public List<long> IsRoleOrUserId { get; set; }

        /// <summary>
        /// 讀取狀態
        /// </summary>
        public bool IsRead { get; set; }

        /// <summary>
        /// 最後閱讀時間
        /// </summary>
        public DateTimeOffset? LastReadingTime { get; set; }
    }
}
View Code

 

3.Services

查詢站內信消息

/// <summary>
        /// 查詢站內信消息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<PagedList<SystemMessageModel>> QuerySystemMessage(int pageIndex, int pageSize)
        {
            using (var db = Db.Commons)
            {
                List<SystemMessageModel> messageList = new List<SystemMessageModel>();
                var systemMessages = db.SystemMessages;
                var result = db.SystemMessageItems;

                foreach (var item in systemMessages)
                {
                    var messageModel = new SystemMessageModel();
                    messageModel.SystemMessageId = item.Id;
                    messageModel.MessageTitle = item.MessageTitle;
                    messageModel.CreateTime = item.CreateTime;
                    messageModel.MessageType = item.MessageType;
                    messageModel.MessageDetail = item.MessageDetail;
                    messageModel.SystemMessageItemModels = result.Where(m => m.SystemMessageKey == item.Id).Select(m => new SystemMessageItemModel()
                    {
                        SystemMessageItemId = m.Id,
                        SystemMessageKey = m.SystemMessageKey,
                        UserId = m.UserId,
                        IsRead = m.IsRead,
                        LastReadingTime = m.LastReadingTime
                    }).ToList();

                    messageList.Add(messageModel);
                }
                var data = new PagedList<SystemMessageModel>(messageList);
                data.PageInfo.Initialize(messageList.Count, pageIndex, pageSize);
                return data;

            }
        }
View Code

閱讀站內信

/// <summary>
        /// 閱讀站內信
        /// </summary>
        /// <param name="messageModel"></param>
        /// <returns></returns>
        public async Task IsReadMessageState(long Id)
        {
            using (var db = Db.Commons)
            {
                var message = db.SystemMessageItems.FirstOrDefault(m => m.Id == Id);
                if (message == null)
                {
                    throw new DomainException("未找到該數據的信息");
                }
                message.IsRead = true;
                await db.SaveChangesAsync().ConfigureAwait(false);
            }
        }
View Code

建立站內信消息

 /// <summary>
        /// 建立站內信消息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task CreateSystemMessage(SystemMessageAllModel messageModel)
        {
            using (var db = Db.Commons)
            {
                using (var trans = TransactionFactory.Default())
                {
                    var message = SystemMessage.CreateMessage(messageModel.MessageTitle, messageModel.MessageDetail, messageModel.MessageType);
                    db.SystemMessages.Add(message);
                    await db.SaveChangesAsync().ConfigureAwait(false);
                    if (messageModel.IsRoleOrUser)
                    {
                        var show = SystemMessageItem.CreateMessageItem(message.Id, messageModel.IsRoleOrUserId.FirstOrDefault(), messageModel.IsRead);
                        db.SystemMessageItems.Add(show);
                    }
                    else
                    {
                        var users = db.Users.Where(m => m.Roles.Any(w => messageModel.IsRoleOrUserId.Contains(w.Id)));
                        foreach (var item in users)
                        {
                            var show = SystemMessageItem.CreateMessageItem(message.Id, item.Id, messageModel.IsRead);
                            db.SystemMessageItems.Add(show);
                        }
                    }
                    await db.SaveChangesAsync().ConfigureAwait(false);
                    trans.Complete();
                }
            }
        }
View Code

 

4.WebApi

查詢站內信消息

/// <summary>
        /// 查詢站內信
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [Route("QuerySystemMessage"), HttpGet]
        [ResponseType(typeof(PagedList<SystemMessageModel>))]
        public async Task<HttpResponseMessage> QuerySystemMessages(int pageIndex = 0, int pageSize = 20)
        {
            var announcementService = new AnnouncementService();
            var querySystemMessages = await announcementService.QuerySystemMessage(pageIndex, pageSize).ConfigureAwait(false);
            var data = querySystemMessages.ConvertToApiPageList();
            return OkResult(data);
        }
View Code

閱讀站內信

/// <summary>
        /// 閱讀站內信
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [Route("IsReadMessageState"), HttpPost]
        [ResponseType(typeof(bool))]
        public async Task<HttpResponseMessage> IsReadMessageState(long Id)
        {
            var announcementService = new AnnouncementService();
            await announcementService.IsReadMessageState(Id).ConfigureAwait(false);
            return OkResult(true);
        }
View Code

建立站內信消息

/// <summary>
        /// 建立站內信測試
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("CreateSystemMessage"), HttpPost]
        [ResponseType(typeof(bool))]
        public async Task<HttpResponseMessage> CreateSystemMessages(SystemMessageAllModel messageModel)
        {
            var announcementService = new AnnouncementService();
            await announcementService.CreateSystemMessage(messageModel).ConfigureAwait(false);
            return OkResult(true);
        }
View Code

 

5.附加(配置db)

using Erp.Domains.Models.Users;
using Lmt.Shared.Data;

namespace Erp.Domains {
    public class Db {
        public static IUserDbContext Users => DbContextFactory.Create<IUserDbContext>();
        public static IOrderDbContext Orders => DbContextFactory.Create<IOrderDbContext>();
        public static ICommonContext Commons => DbContextFactory.Create<ICommonContext>();
        public static IProductDbContext Products => DbContextFactory.Create<IProductDbContext>();
        public static IWarehouseDbContext Warehouses => DbContextFactory.Create<IWarehouseDbContext>();
        public static IPackageDbContext Packages => DbContextFactory.Create<IPackageDbContext>();
        public static IShippingContext Shippings => DbContextFactory.Create<IShippingContext>();
        public static IPurchaseContext Purchases => DbContextFactory.Create<IPurchaseContext>();
        public static IAccountsDbContext Accounts => DbContextFactory.Create<IAccountsDbContext>();
        public static IPdaDbContext Pda => DbContextFactory.Create<IPdaDbContext>();
        public static IEmailDbContext Emails => DbContextFactory.Create<IEmailDbContext>(); 
        public static ISkuSalesRandContext Statistics => DbContextFactory.Create<ISkuSalesRandContext>();
        public static IOADbContext OA=> DbContextFactory.Create<IOADbContext>();
        public static IFollowNoticeDbContext FollowNotices => DbContextFactory.Create<IFollowNoticeDbContext>();
        public static IHelperDocsClassDbContext HelperDocsClasss => DbContextFactory.Create<IHelperDocsClassDbContext>();
    }
}
View Code
using Erp.Domains.Models.Common;
using Erp.Domains.Models.Message;
using Erp.Domains.Models.Orders;
using Erp.Domains.Models.Users;
using Lmt.Shared.Data;

namespace Erp.Domains {
    public interface ICommonContext : IModelContext { 
        IModelDbSet<Country> Countries { get; }
        IModelDbSet<CurrencyRate> CurrencyRates { get; }
        IModelDbSet<Announcement> Announcements { get; }
        IModelDbSet<SystemConfig> SystemConfigs { get; }
        IModelDbSet<User> Users { get; }

        IModelDbSet<Order> Orders { get; }
        IModelDbSet<SystemMessage> SystemMessages { get; }
        IModelDbSet<SystemMessageItem> SystemMessageItems { get; }

    } 
}
View Code
相關文章
相關標籤/搜索