формирование списков работает

This commit is contained in:
Николай 2023-05-18 14:40:36 +04:00
parent a166e976de
commit 5333817ea8
5 changed files with 61 additions and 24 deletions

View File

@ -115,7 +115,7 @@ namespace HardwareShopContracts.BusinessLogicsContracts
});
byte[] file = File.ReadAllBytes(model.FileName);
//File.Delete(model.FileName);
File.Delete(model.FileName);
return file;
}

View File

@ -47,21 +47,23 @@ namespace HardwareShopRestApi.Controllers
[HttpPost]
public void BuildPurchaseReport(PurchaseBindingModel model, string format, string filename)
public byte[] BuildPurchaseReport(PurchaseBindingModel model, string format)
{
try
{
byte[] file;
switch (format)
{
case "doc":
_reportWorkerLogic.SavePurchasesToWordFile(new ReportBindingModel { FileName = filename }, model.Purchases);
case "docx":
file = _reportWorkerLogic.SavePurchasesToWordFile(new ReportBindingModel { FileName = "temp.docx" }, model.Purchases);
break;
case "excel":
_reportWorkerLogic.SavePurchasesToExcelFile(new ReportBindingModel { FileName = filename }, model.Purchases);
case "xlsx":
file = _reportWorkerLogic.SavePurchasesToExcelFile(new ReportBindingModel { FileName = "temp.xlsx" }, model.Purchases);
break;
default:
throw new FormatException("Неправильный формат файла");
}
return file;
}
catch (Exception ex)
{

View File

@ -46,5 +46,23 @@ namespace HardwareShopWorkerApp
throw new Exception(result);
}
}
public static R? PostRequestWithResult<T, R>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<R>(result);
}
else
{
return default;
}
}
}
}

View File

@ -332,7 +332,7 @@ namespace HardwareShopWorkerApp.Controllers
}
[HttpPost]
public void ListComponents([FromBody] PurchaseBindingModel goodModel, [FromQuery] string format, [FromQuery] string filename)
public int[]? ListComponents([FromBody] PurchaseBindingModel purchaseModel, [FromQuery] string format)
{
if (APIClient.User == null)
{
@ -342,11 +342,11 @@ namespace HardwareShopWorkerApp.Controllers
{
throw new FormatException($"Неправильный формат файла: {format}");
}
if (string.IsNullOrEmpty(filename))
{
throw new FormatException($"Неправильное название файла: {filename}");
}
APIClient.PostRequest($"api/report/buildpurchasereport?format={format}&filename=${filename}", goodModel);
byte[]? file = APIClient.PostRequestWithResult<PurchaseBindingModel, byte[]>($"api/report/buildpurchasereport?format={format}", purchaseModel);
var array = file!.Select(b => (int)b).ToArray();
return array;
}
[HttpGet]

View File

@ -23,10 +23,6 @@
<tbody id="result">
</tbody>
</table>
<div class="col-sm-3">
<label class="form-label">Название файла</label>
<input type="text" class="form-control" name="filename" id="filename">
</div>
<div class="col d-flex justify-content-evenly align-items-baseline">
<button type="button" class="btn btn-primary btn-lg m-2" id="savedoc">Сохранить в doc-формате</button>
<button type="button" class="btn btn-primary btn-lg m-2" id="saveexcel">Сохранить в xls-формате</button>
@ -59,7 +55,6 @@
const resultTable = document.getElementById("result");
const saveDocBtn = document.getElementById("savedoc");
const saveExcelBtn = document.getElementById("saveexcel");
const filename = document.getElementById("filename");
submitPurchaseBtn.addEventListener("click", () => {
console.log('try to add purchase')
@ -88,32 +83,53 @@
})
saveDocBtn.addEventListener("click", async () => {
send('doc')
send('docx')
})
saveExcelBtn.addEventListener("click", async () => {
send('excel')
send('xlsx')
})
function send(format) {
console.log(`try to save in ${format} format`)
if (list.length == 0 || !filename.value || filename.value == '') {
if (list.length == 0) {
alert('operation failed. purchases or filename are empty')
return
}
$.ajax({
url: `/Home/ListComponents?format=${format}&filename=${filename.value}`,
url: `/Home/ListComponents?format=${format}`,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ "Purchases" : list })
}).done(() => {
//let byteArray = new Uint8Array(file);
}).done((file) => {
let byteArray = new Uint8Array(file);
saveFile(byteArray, format);
})
.fail(function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
})
}
async function saveFile(bytes, format) {
if (window.showSaveFilePicker) {
const opts = {
suggestedName: `listcomponents.${format}`,
types: [{
description: `${format} file`,
accept:
{
[`text/${format}`]: [`.${format}`]
},
}],
};
const handle = await showSaveFilePicker(opts);
const writable = await handle.createWritable();
await writable.write(bytes);
writable.close();
alert('done')
}
}
function reloadTable() {
resultTable.innerHTML = ''
let count = 0;
@ -132,5 +148,6 @@
list = list.filter(value => value.id != resultTable.rows[id].cells[0].innerText)
reloadTable()
}
</script>
}