Exemplo n.º 1
0
        public AttachReceipt ToAttachReceipt()
        {
            MemoryStream s = new MemoryStream();

            File.CopyTo(s);
            s.Position = 0;
            AttachReceipt returnValue = new AttachReceipt(Guid.NewGuid(), InvoiceId, UserID, s.ToArray());

            returnValue.FileName = File.FileName;
            returnValue.Amount   = this.Amount;
            return(returnValue);
        }
Exemplo n.º 2
0
        public async Task <CommandResult> Handle(AttachReceipt request, CancellationToken cancellationToken)
        {
            if (!context.Invoices.Any(_ => _.ID == request.InvoiceId && _.UserId == request.UserID))
            {
                return(new CommandResult(false, Guid.Empty, "ERR-1003", $"No invoice found with the given id {request.InvoiceId} for user {request.UserID}"));
            }
            if (context.Receipts.Any(_ => _.FileName == request.FileName && _.UserId == request.UserID))
            {
                return(new CommandResult(false, Guid.Empty, "ERR-1003", "File already exists for this user"));
            }

            context.EventEntries.Add(new EventEntry()
            {
                ID = Guid.NewGuid(), Payload = JsonSerializer.Serialize(request)
            });
            await this.azureBlobRepo.Store("receipts", request.UserID, request.FileName, new MemoryStream(request.Content));

            using (var transaction = this.context.Database.BeginTransaction())
            {
                try
                {
                    Receipt r = new Receipt();
                    r.ReferenceBlobAdress = string.Concat(request.UserID, "/", request.FileName);
                    r.InvoiceID           = request.InvoiceId;
                    r.UserId   = request.UserID;
                    r.Amount   = request.Amount;
                    r.FileName = request.FileName;
                    await context.Receipts.AddAsync(r, cancellationToken);

                    await context.SaveChangesAsync(cancellationToken);

                    await transaction.CommitAsync(cancellationToken);

                    // Publish Create Event to subscriber.
                    await this.mediator.Publish(new ReceiptCreatedEvent(r.ID, r.ReferenceBlobAdress), cancellationToken);

                    return(new CommandResult(true, r.ID));
                }
                catch (Exception e)
                {
                    await transaction.RollbackAsync(cancellationToken);

                    return(new CommandResult(true, Guid.Empty, "ERR-2000", e.Message));
                }
            }
        }