Преглед на файлове

Move re-export functionaltiy to a separate HTML form so that users can do it directly if necessary.

Andrew Klopper преди 8 години
родител
ревизия
e8b05ebc58
променени са 2 файла, в които са добавени 154 реда и са изтрити 25 реда
  1. 0 25
      BulkPrintingAPI/Controllers/BatchesController.cs
  2. 154 0
      BulkPrintingAPI/Controllers/ReExportBatchController.cs

+ 0 - 25
BulkPrintingAPI/Controllers/BatchesController.cs

@@ -167,30 +167,5 @@ namespace BulkPrintingAPI.Controllers
167 167
 
168 168
             return Ok(orderResponse);
169 169
         }
170
-
171
-        [HttpPost("{id}/a8a7b01e-9da9-4353-ad5c-f47d83d83065")]
172
-        public async Task<IActionResult> ReExportBatchAsync([FromRoute] int id)
173
-        {
174
-            var credentials = await Utils.GetLoginCredentialsFromRequestAsync(HttpContext, _context);
175
-
176
-            var batch = await BatchesForVendor(credentials.Vendor.Id)
177
-                .SingleOrDefaultAsync(m => m.Id == id);
178
-            if (batch == null)
179
-            {
180
-                return NotFound();
181
-            }
182
-            else
183
-            {
184
-                await _context.Database.ExecuteSqlCommandAsync("DELETE FROM [Vouchers] WHERE [BatchId]={0}",
185
-                    System.Threading.CancellationToken.None, id);
186
-
187
-                batch.ReadyForDownload = false;
188
-                await _context.SaveChangesAsync();
189
-
190
-                await MAX.Utils.ReExportBatchAsync(_clientFactory, _logger, credentials, id,
191
-                    Utils.AesDecryptBytes(credentials.Vendor.EncryptedVoucherKey, _dataEncryptionOptions.DefaultKey));
192
-            }
193
-            return Ok();
194
-        }
195 170
     }
196 171
 }

+ 154 - 0
BulkPrintingAPI/Controllers/ReExportBatchController.cs

@@ -0,0 +1,154 @@
1
+using BulkPrintingAPI.Configuration;
2
+using MAX.Models;
3
+using Microsoft.AspNetCore.Authorization;
4
+using Microsoft.AspNetCore.Mvc;
5
+using Microsoft.EntityFrameworkCore;
6
+using Microsoft.Extensions.Logging;
7
+using System;
8
+using System.ComponentModel.DataAnnotations;
9
+using System.Linq;
10
+using System.Net;
11
+using System.Text;
12
+using System.Threading.Tasks;
13
+
14
+namespace BulkPrintingAPI.Controllers
15
+{
16
+    [Produces("text/html")]
17
+    [Route("c6e2a863-ed16-4f96-b4f5-eff97fba35e2")]
18
+    public class ReExportBatchController : Controller
19
+    {
20
+        public class ReExportRequest : LoginController.LoginRequest
21
+        {
22
+            [Required]
23
+            public int? BatchId { get; set; }
24
+        };
25
+
26
+        private readonly ILogger _logger;
27
+        private readonly DataEncryptionOptions _dataEncryptionOptions;
28
+        private readonly MAX.ClientFactory _clientFactory;
29
+        private readonly MAXContext _context;
30
+
31
+        public ReExportBatchController(ILoggerFactory loggerFactory, DataEncryptionOptions dataEncryptionOptions,
32
+            MAX.ClientFactory clietnFactory, MAXContext context)
33
+        {
34
+            _logger = loggerFactory.CreateLogger(GetType().FullName);
35
+            _dataEncryptionOptions = dataEncryptionOptions;
36
+            _clientFactory = clietnFactory;
37
+            _context = context;
38
+        }
39
+
40
+        [AllowAnonymous]
41
+        public ActionResult Index()
42
+        {
43
+            return Ok(
44
+                "<html>" +
45
+                    "<head><title>Re-export Batch</title></head>" +
46
+                    "<body>" +
47
+                        "<h1>Re-export Batch</h1>" +
48
+                        "<form method=\"POST\">" +
49
+                            "<dl>" +
50
+                                "<dt>Vendor ID</dt><dd><input type=\"text\" name=\"VendorId\"></dd>" +
51
+                                "<dt>Serial Number</dt><dd><input type=\"text\" name=\"SerialNumber\"></dd>" +
52
+                                "<dt>User ID</dt><dd><input type=\"text\" name=\"UserId\"></dd>" +
53
+                                "<dt>Username</dt><dd><input type=\"text\" name=\"Username\"></dd>" +
54
+                                "<dt>Password</dt><dd><input type=\"password\" name=\"Password\"></dd>" +
55
+                                "<dt>Batch ID</dt><dd><input type=\"text\" name=\"BatchId\"></dd>" +
56
+                            "</dl>" +
57
+                            "<input type=\"submit\" value=\"Re-export\">" +
58
+                        "</form>" +
59
+                    "</body>" +
60
+                "</html>"
61
+            );
62
+        }
63
+
64
+        [AllowAnonymous]
65
+        [HttpPost]
66
+        public async Task<ActionResult> ReExportBatch([FromForm] ReExportRequest reExportRequest)
67
+        {
68
+            if (! ModelState.IsValid)
69
+            {
70
+                var errorList = new StringBuilder("<ul>");
71
+                foreach (var modelState in ModelState.Values)
72
+                {
73
+                    foreach (var error in modelState.Errors)
74
+                    {
75
+                        errorList.Append(string.Format("<li>{0}</li>", WebUtility.HtmlEncode(error.ErrorMessage)));
76
+                    }
77
+                }
78
+                errorList.Append("</ul>");
79
+
80
+                return RenderHtmlMessage("Error", errorList.ToString());
81
+            }
82
+
83
+            try
84
+            {
85
+                var credentials = new MAX.LoginCredentials()
86
+                {
87
+                    User = await _context.Users
88
+                        .Include(u => u.Account)
89
+                        .ThenInclude(a => a.Warehouse)
90
+                        .SingleOrDefaultAsync(u => u.Id == reExportRequest.UserId)
91
+                        .ConfigureAwait(false),
92
+                    Vendor = await _context.Vendors
93
+                        .Include(v => v.Account) // Technically not necessary as the account is loaded above
94
+                        .SingleOrDefaultAsync(v => v.Id == reExportRequest.VendorId)
95
+                        .ConfigureAwait(false),
96
+                    Password = reExportRequest.Password
97
+                };
98
+
99
+                if ((credentials.User == null) || (credentials.Vendor == null))
100
+                {
101
+                    throw new Exception(String.Format(
102
+                        "Missing user or vendor information for userId={0} vendorId={1}",
103
+                        reExportRequest.UserId, reExportRequest.VendorId));
104
+                }
105
+
106
+                var batch = await _context.Batches
107
+                    .Where(b => b.VendorId == reExportRequest.VendorId)
108
+                    .SingleOrDefaultAsync(m => m.Id == reExportRequest.BatchId);
109
+
110
+                if (batch == null)
111
+                {
112
+                    return NotFound("Batch not found");
113
+                }
114
+                else
115
+                {
116
+                    await _context.Database.ExecuteSqlCommandAsync("DELETE FROM [Vouchers] WHERE [BatchId]={0}",
117
+                        parameters: batch.Id);
118
+
119
+                    batch.ReadyForDownload = false;
120
+                    await _context.SaveChangesAsync();
121
+
122
+                    await MAX.Utils.ReExportBatchAsync(_clientFactory, _logger, credentials, batch.Id,
123
+                        Utils.AesDecryptBytes(credentials.Vendor.EncryptedVoucherKey, _dataEncryptionOptions.DefaultKey));
124
+                }
125
+
126
+                return RenderTextMessage("Success", "The re-export succeeded.");
127
+            }
128
+            catch (Exception e)
129
+            {
130
+                return RenderTextMessage("Error", e.Message);
131
+            }
132
+        }
133
+
134
+        private ActionResult RenderHtmlMessage(string caption, string html)
135
+        {
136
+            return Ok(string.Format(
137
+                "<html>" +
138
+                    "<head><title>Re-export Batch</title></head>" +
139
+                    "<body>" +
140
+                        "<h1>{0}</h1>" +
141
+                        "{1}" +
142
+                    "</body>" +
143
+                "</html>",
144
+                WebUtility.HtmlEncode(caption),
145
+                html
146
+            ));
147
+        }
148
+
149
+        private ActionResult RenderTextMessage(string caption, string text)
150
+        {
151
+            return RenderHtmlMessage(caption, WebUtility.HtmlEncode(text));
152
+        }
153
+    }
154
+}