Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.82 KB | None | 0 0
  1.     /// <summary>
  2.     /// Интерфейс состояния документа отправляемого в ОИ.рф.
  3.     /// </summary>
  4.     public interface IShippingDocumentState
  5.     {
  6.         // todo: специфицировать тип object до конкретного класса контракта.
  7.        
  8.         /// <summary>
  9.         /// Создать документ для отправки в ОИ.рф.
  10.         /// </summary>
  11.         void CreateDocument(object creatingDocument);
  12.  
  13.         /// <summary>
  14.         /// Отправить документ в ОИ.рф.
  15.         /// </summary>
  16.         void ShipDocument(object shippingDocument);
  17.  
  18.         /// <summary>
  19.         /// Зарегистрировать факт доставки в ОИ.рф.
  20.         /// </summary>
  21.         void RegisterDelivery(object deliveringData);
  22.  
  23.         /// <summary>
  24.         /// Зарегистрировать факт подтверждения доставки в ОИ.рф.
  25.         /// </summary>
  26.         void RegisterConfirmation(object confirmationData);
  27.     }
  28.    
  29.     /// <summary>
  30.     /// Класс состояния документа отправляемого в ОИ.рф.
  31.     /// </summary>
  32.     public class ShippingDocumentState : IShippingDocumentState
  33.     {
  34.         private static ILogger _logger = LogManager.GetCurrentClassLogger();
  35.         protected DocumentHandler Handler;
  36.  
  37.         public ShippingDocumentState(DocumentHandler handler)
  38.         {
  39.             Handler = handler;
  40.         }
  41.  
  42.         void SetHandler(DocumentHandler handler)
  43.         {
  44.             Handler = handler;
  45.         }
  46.  
  47.         public virtual void CreateDocument(object creatingDocument)
  48.         {
  49.             _logger.Error("Операция не поддерживается текущим состоянием.");
  50.             throw new InvalidOperationException("Операция не поддерживается текущим состоянием.");
  51.         }
  52.  
  53.         public virtual void ShipDocument(object shippingDocument)
  54.         {
  55.             _logger.Error("Операция не поддерживается текущим состоянием.");
  56.             throw new InvalidOperationException("Операция не поддерживается текущим состоянием.");
  57.         }
  58.  
  59.         public virtual void RegisterDelivery(object deliveringData)
  60.         {
  61.             _logger.Error("Операция не поддерживается текущим состоянием.");
  62.             throw new InvalidOperationException("Операция не поддерживается текущим состоянием.");
  63.         }
  64.  
  65.         public virtual void RegisterConfirmation(object cofirmationData)
  66.         {
  67.             _logger.Error("Операция не поддерживается текущим состоянием.");
  68.             throw new InvalidOperationException("Операция не поддерживается текущим состоянием.");
  69.         }
  70.     }
  71.  
  72.     /// <summary>
  73.     /// Тип состояния документа.
  74.     /// </summary>
  75.     public enum StateType
  76.     {
  77.         Initial = 0,
  78.         Created = 1,
  79.         Shipped = 2,
  80.         DeliveryFailed = 3,
  81.         Delivered = 4,
  82.         Confirmed = 5,
  83.         ConfirmationFailed = 6
  84.     }
  85.  
  86.     // todo: базовый интерфейс сообщения из ОИ.рф.
  87.     public interface IElectroInspectionMessageStub
  88.     {
  89.         string DocumentId { get; }
  90.         ElectroInspectionMessageType MessageType { get; set; }
  91.     }
  92.  
  93.     public enum ElectroInspectionMessageType
  94.     {
  95.         DeliveryMessage,
  96.         ConfirmationMessage
  97.     }
  98.    
  99.     public interface IElectroDocumentStub
  100.     {
  101.         StateType State { get; }
  102.         string OperationType { get; }
  103.     }
  104.    
  105.     /// <summary>
  106.     /// Подписчик сообщений сервиса 'Электронная проверка сервиса ОИ.рф'.
  107.     /// </summary>
  108.     public class ElectronicCheckSubscriber
  109.     {
  110.         void Start()
  111.         {
  112.             // Создаем NATS и подписку.
  113.         }
  114.  
  115.         // todo: поиск по идентификатору в БД.
  116.         protected virtual IElectroDocumentStub FindDocument(string id)
  117.         {
  118.             return null;
  119.         }
  120.        
  121.         void HandleMessage(IElectroInspectionMessageStub msg)
  122.         {
  123.             var searchedDoc = FindDocument(msg.DocumentId);
  124.             var handler = new DocumentHandler();
  125.             if (searchedDoc != null)
  126.             {
  127.                 // Восстанавливаем состояние из БД.
  128.                 handler.RestoreState(searchedDoc.State);
  129.                
  130.                 switch (msg.MessageType)
  131.                 {
  132.                     case ElectroInspectionMessageType.ConfirmationMessage:
  133.                         handler.RegisterConfirmation(msg);
  134.                         break;
  135.                     case ElectroInspectionMessageType.DeliveryMessage:
  136.                         handler.RegisterDelivery(msg);
  137.                         break;
  138.                 }
  139.             }
  140.             else
  141.             {
  142.                 // todo: Ошибка.
  143.             }
  144.         }
  145.     }
  146.    
  147.     /// <summary>
  148.     /// Обработчик полученных сообщений от ОИ.рф сервиса 'Электронная проверка'.
  149.     /// </summary>
  150.     public class DocumentHandler
  151.     {
  152.         // Текущее состояние обработчика.
  153.         private IShippingDocumentState _currentState;
  154.  
  155.         public DocumentHandler()
  156.         {
  157.             _currentState = GetInitialState();
  158.         }
  159.        
  160.         public DocumentHandler(IShippingDocumentState state)
  161.         {
  162.             _currentState = state ?? throw new ArgumentNullException(nameof(state));
  163.         }
  164.  
  165.         public void RestoreState(StateType type)
  166.         {
  167.             IShippingDocumentState state;
  168.                
  169.             // Инициализируем handler в зависимости от сохраненного состояния.
  170.             switch (type)
  171.             {
  172.                 case StateType.Initial:
  173.                     state = GetInitialState();
  174.                     break;
  175.                 case StateType.Created:
  176.                     state = GetCreatedState();
  177.                     break;
  178.                 case StateType.Shipped:
  179.                     state = GetShippedState();
  180.                     break;
  181.                 case StateType.Delivered:
  182.                     state = GetDeliveredState();
  183.                     break;
  184.                 case StateType.DeliveryFailed:
  185.                     state = GetConfirmationFailedState();
  186.                     break;
  187.                 case StateType.Confirmed:
  188.                     state = GetConfirmedState();
  189.                     break;
  190.                 case StateType.ConfirmationFailed:
  191.                     state = GetConfirmationFailedState();
  192.                     break;
  193.                 default:
  194.                     throw new InvalidOperationException("Состояние не поддерживается.");
  195.             }
  196.            
  197.             // Устанавливаем текущее состояние обработчика.
  198.             ChangeState(state);
  199.         }
  200.        
  201.         public void ChangeState(IShippingDocumentState state)
  202.         {
  203.             _currentState = state;
  204.         }
  205.  
  206.         /// <summary>
  207.         /// Создать документ для отправки в ОИ.рф.
  208.         /// </summary>
  209.         public void CreateDocument(object creatingDocument)
  210.         {
  211.             _currentState.CreateDocument(creatingDocument);
  212.         }
  213.  
  214.         /// <summary>
  215.         /// Отправить документ в ОИ.рф.
  216.         /// </summary>
  217.         public void ShipDocument(object shippingDocument)
  218.         {
  219.             _currentState.ShipDocument(shippingDocument);
  220.         }
  221.  
  222.         /// <summary>
  223.         /// Зарегистрировать факт доставки в ОИ.рф.
  224.         /// </summary>
  225.         public void RegisterDelivery(object deliveringData)
  226.         {
  227.             _currentState.RegisterDelivery(deliveringData);
  228.         }
  229.  
  230.         /// <summary>
  231.         /// Зарегистрировать факт подтверждения доставки в ОИ.рф.
  232.         /// </summary>
  233.         public void RegisterConfirmation(object confirmationData)
  234.         {
  235.             _currentState.RegisterConfirmation(confirmationData);
  236.         }
  237.        
  238.         public InitialState GetInitialState()
  239.         {
  240.             return new InitialState(this);
  241.         }
  242.  
  243.         public CreatedState GetCreatedState()
  244.         {
  245.             return new CreatedState(this);
  246.         }
  247.  
  248.         public ShippedState GetShippedState()
  249.         {
  250.             return new ShippedState(this);
  251.         }
  252.  
  253.         public DeliveryFailedState GetDeliveryFailedState()
  254.         {
  255.             return new DeliveryFailedState(this);
  256.         }
  257.  
  258.         public DeliveredState GetDeliveredState()
  259.         {
  260.             return new DeliveredState(this);
  261.         }
  262.        
  263.         public ConfirmedState GetConfirmedState()
  264.         {
  265.             return new ConfirmedState(this);
  266.         }
  267.        
  268.         public ConfirmationFailedState GetConfirmationFailedState()
  269.         {
  270.             return new ConfirmationFailedState(this);
  271.         }
  272.     }
  273.  
  274.     /// <summary>
  275.     /// Документ для отправки в ОИ.рф отсутствует.
  276.     /// </summary>
  277.     public class InitialState : ShippingDocumentState
  278.     {
  279.         public override void CreateDocument(object creatingDocument)
  280.         {
  281.             // 1. Создать документ для отправки в ОИ.рф.
  282.             // 2. Сохранить созданный документ в БД.
  283.             Handler.ChangeState(Handler.GetCreatedState());
  284.         }
  285.  
  286.         public InitialState(DocumentHandler handler) : base(handler)
  287.         {
  288.         }
  289.     }
  290.    
  291.     /// <summary>
  292.     /// Документ для отправки в ОИ.рф создан.
  293.     /// </summary>
  294.     public class CreatedState : ShippingDocumentState
  295.     {
  296.         public override void ShipDocument(object shippingDocument)
  297.         {
  298.             // 1. Найти документ в БД (если нужно)
  299.             // 2. Отправить сообщение в NATS.
  300.         }
  301.  
  302.         public CreatedState(DocumentHandler handler) : base(handler)
  303.         {
  304.         }
  305.     }
  306.  
  307.     /// <summary>
  308.     /// Документ отправлен в ОИ.рф.
  309.     /// </summary>
  310.     public class ShippedState : ShippingDocumentState
  311.     {
  312.         public override void RegisterDelivery(object deliveringData)
  313.         {
  314.             // 1. Зарегистрировать сообщение от ОИ.рф.
  315.         }
  316.  
  317.         public ShippedState(DocumentHandler handler) : base(handler)
  318.         {
  319.         }
  320.     }
  321.  
  322.     /// <summary>
  323.     /// Документ не доставлен в ОИ.рф (ошибка ФЛК на стороне ОИ.рф).
  324.     /// </summary>
  325.     public class DeliveryFailedState : ShippingDocumentState
  326.     {
  327.         public override void RegisterDelivery(object deliveringData)
  328.         {
  329.             // Повторное подтверждение доставки из ОИ.рф.
  330.         }
  331.  
  332.         public DeliveryFailedState(DocumentHandler handler) : base(handler)
  333.         {
  334.         }
  335.     }
  336.  
  337.     /// <summary>
  338.     /// Документ доставлен в ОИ.рф.
  339.     /// </summary>
  340.     public class DeliveredState : ShippingDocumentState
  341.     {
  342.         public override void RegisterConfirmation(object confirmationData)
  343.         {
  344.             // Подтверждение получения документа.
  345.         }
  346.  
  347.         public DeliveredState(DocumentHandler handler) : base(handler)
  348.         {
  349.         }
  350.     }
  351.  
  352.     /// <summary>
  353.     /// Подтверждено получение документа в ОИ.рф пользователем.
  354.     /// </summary>
  355.     public class ConfirmedState : ShippingDocumentState
  356.     {
  357.         // Конечное состояние.
  358.         public ConfirmedState(DocumentHandler handler) : base(handler)
  359.         {
  360.         }
  361.     }
  362.  
  363.     /// <summary>
  364.     /// Ошибка подтверждения получения документа в ОИ.рф пользователем (ошибка ФЛК на стороне АСУ КНД).
  365.     /// </summary>
  366.     public class ConfirmationFailedState : ShippingDocumentState
  367.     {
  368.         public override void RegisterConfirmation(object confirmationData)
  369.         {
  370.             // Повторное получения документа.
  371.         }
  372.  
  373.         public ConfirmationFailedState(DocumentHandler handler) : base(handler)
  374.         {
  375.         }
  376.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement