fffc6e3ac23f0f20a464a42c7dfa5b9f8997f440.svn-base 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Package handling provides the use-case for registering incidents. Used by
  2. // views facing the people handling the cargo along its route.
  3. package handling
  4. import (
  5. "errors"
  6. "time"
  7. "github.com/longjoy/micro-go-course/section19/cargo/inspection"
  8. shipping "github.com/longjoy/micro-go-course/section19/cargo/model"
  9. )
  10. // ErrInvalidArgument is returned when one or more arguments are invalid.
  11. var ErrInvalidArgument = errors.New("invalid argument")
  12. // EventHandler provides a means of subscribing to registered handling events.
  13. type EventHandler interface {
  14. CargoWasHandled(shipping.HandlingEvent)
  15. }
  16. // Service provides handling operations.
  17. type Service interface {
  18. // RegisterHandlingEvent registers a handling event in the system, and
  19. // notifies interested parties that a cargo has been handled.
  20. RegisterHandlingEvent(completed time.Time, id shipping.TrackingID, voyageNumber shipping.VoyageNumber,
  21. unLocode shipping.UNLocode, eventType shipping.HandlingEventType) (bool, error)
  22. }
  23. type service struct {
  24. handlingEventRepository shipping.HandlingEventRepository
  25. handlingEventFactory shipping.HandlingEventFactory
  26. handlingEventHandler EventHandler
  27. }
  28. func (s *service) RegisterHandlingEvent(completed time.Time, id shipping.TrackingID, voyageNumber shipping.VoyageNumber,
  29. loc shipping.UNLocode, eventType shipping.HandlingEventType) (bool, error) {
  30. if completed.IsZero() || id == "" || loc == "" || eventType == shipping.NotHandled {
  31. return false, ErrInvalidArgument
  32. }
  33. e, err := s.handlingEventFactory.CreateHandlingEvent(time.Now(), completed, id, voyageNumber, loc, eventType)
  34. if err != nil {
  35. return false, err
  36. }
  37. s.handlingEventRepository.Store(e)
  38. s.handlingEventHandler.CargoWasHandled(e)
  39. return true, nil
  40. }
  41. // NewService creates a handling event service with necessary dependencies.
  42. func NewService(r shipping.HandlingEventRepository, f shipping.HandlingEventFactory, h EventHandler) Service {
  43. return &service{
  44. handlingEventRepository: r,
  45. handlingEventFactory: f,
  46. handlingEventHandler: h,
  47. }
  48. }
  49. type handlingEventHandler struct {
  50. InspectionService inspection.Service
  51. }
  52. func (h *handlingEventHandler) CargoWasHandled(event shipping.HandlingEvent) {
  53. h.InspectionService.InspectCargo(event.TrackingID)
  54. }
  55. // NewEventHandler returns a new instance of a EventHandler.
  56. func NewEventHandler(s inspection.Service) EventHandler {
  57. return &handlingEventHandler{
  58. InspectionService: s,
  59. }
  60. }