Merge branch 'Storekeeper' into Worker_Raspaev

This commit is contained in:
Николай 2023-05-18 13:37:29 +04:00
commit a166e976de
7 changed files with 76 additions and 42 deletions

View File

@ -11,22 +11,26 @@ namespace HardwareShopBusinessLogic.BusinessLogics.Storekeeper
{ {
private readonly IComponentStorage _componentStorage; private readonly IComponentStorage _componentStorage;
private readonly IGoodStorage _goodStorage;
private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToWord _saveToWord;
public ReportStorekeeperLogic(IComponentStorage componentStorage, AbstractSaveToExcel abstractSaveToExcel, AbstractSaveToWord abstractSaveToWord) public ReportStorekeeperLogic(IComponentStorage componentStorage, AbstractSaveToExcel abstractSaveToExcel, AbstractSaveToWord abstractSaveToWord, IGoodStorage goodStorage)
{ {
_componentStorage = componentStorage; _componentStorage = componentStorage;
_saveToExcel = abstractSaveToExcel; _saveToExcel = abstractSaveToExcel;
_saveToWord = abstractSaveToWord; _saveToWord = abstractSaveToWord;
_goodStorage = goodStorage;
} }
public List<ReportBuildGoodViewModel> GetBuildGood(List<GoodViewModel> goods) public List<ReportBuildGoodViewModel> GetBuildGood(List<GoodViewModel> goods)
{ {
var result = new List<ReportBuildGoodViewModel>(); var result = new List<ReportBuildGoodViewModel>();
foreach (var good in goods) foreach (var g in goods)
{ {
var good = _goodStorage.GetElement(new() { Id = g.Id })!;
var builds = good.GoodComponents var builds = good.GoodComponents
//получили сборки и количество компонентов //получили сборки и количество компонентов
.Select(x => _componentStorage.GetComponentBuilds(new() { Id = x.Key }) .Select(x => _componentStorage.GetComponentBuilds(new() { Id = x.Key })
@ -78,16 +82,6 @@ namespace HardwareShopBusinessLogic.BusinessLogics.Storekeeper
return result; return result;
} }
public void SaveBuildGoodToExcelFile(ReportBindingModel model, List<GoodViewModel> goods)
{
_saveToExcel.CreateBuildGoodReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Cписок сборок по выбранным товарам",
BuildGood = GetBuildGood(goods)
});
}
public byte[] SaveBuildGoodToWordFile(ReportBindingModel model, List<GoodViewModel> goods) public byte[] SaveBuildGoodToWordFile(ReportBindingModel model, List<GoodViewModel> goods)
{ {
_saveToWord.CreateBuildGoodReport(new WordInfo _saveToWord.CreateBuildGoodReport(new WordInfo
@ -102,9 +96,18 @@ namespace HardwareShopBusinessLogic.BusinessLogics.Storekeeper
return file; return file;
} }
byte[] IReportStorekeeperLogic.SaveBuildGoodToExcelFile(ReportBindingModel model, List<GoodViewModel> goods) public byte[] SaveBuildGoodToExcelFile(ReportBindingModel model, List<GoodViewModel> goods)
{ {
throw new NotImplementedException(); _saveToExcel.CreateBuildGoodReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Cписок сборок по выбранным товарам",
BuildGood = GetBuildGood(goods)
});
byte[] file = File.ReadAllBytes(model.FileName);
File.Delete(model.FileName);
return file;
} }
} }
} }

View File

@ -24,7 +24,7 @@ namespace HardwareShopBusinessLogic.OfficePackage
MergeCells(new ExcelMergeParameters MergeCells(new ExcelMergeParameters
{ {
CellFromName = "A1", CellFromName = "A1",
CellToName = "C1" CellToName = "B1"
}); });
uint rowIndex = 2; uint rowIndex = 2;
@ -35,7 +35,7 @@ namespace HardwareShopBusinessLogic.OfficePackage
ColumnName = "A", ColumnName = "A",
RowIndex = rowIndex, RowIndex = rowIndex,
Text = bg.GoodName, Text = bg.GoodName,
StyleInfo = ExcelStyleInfoType.Text StyleInfo = ExcelStyleInfoType.TextWithBroder
}); });
rowIndex++; rowIndex++;
@ -51,8 +51,6 @@ namespace HardwareShopBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
} }
rowIndex++;
} }
SaveExcel(info); SaveExcel(info);

View File

@ -46,5 +46,23 @@ namespace HardwareShopStorekeeperApp
throw new Exception(result); 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

@ -396,7 +396,7 @@ namespace HardwareShopStorekeeperApp.Controllers
} }
[HttpPost] [HttpPost]
public void ListBuilds([FromBody] GoodBindingModel goodModel, [FromQuery] string format, [FromQuery] string filename) public int[]? ListBuilds([FromBody] GoodBindingModel goodModel, [FromQuery] string format)
{ {
if (APIClient.User == null) if (APIClient.User == null)
{ {
@ -404,13 +404,10 @@ namespace HardwareShopStorekeeperApp.Controllers
} }
if (string.IsNullOrEmpty(format)) if (string.IsNullOrEmpty(format))
{ {
throw new FormatException($"Неправильный формат файла: {format}"); throw new FormatException("Неправильный формат файла");
} }
if (string.IsNullOrEmpty(filename)) byte[]? file = APIClient.PostRequestWithResult<GoodBindingModel, byte[]>($"api/report/buildgoodreport?format={format}", goodModel);
{ return file!.Select(b => (int)b).ToArray();
throw new FormatException($"Неправильное название файла: {filename}");
}
APIClient.PostRequest($"api/report/buildgoodreport?format={format}&filename=${filename}", goodModel);
} }
public IActionResult Report() public IActionResult Report()

View File

@ -23,10 +23,6 @@
<tbody id="result"> <tbody id="result">
</tbody> </tbody>
</table> </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"> <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="savedoc">Сохранить в doc-формате</button>
<button type="button" class="btn btn-primary btn-lg m-2" id="saveexcel">Сохранить в xls-формате</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 resultTable = document.getElementById("result");
const saveDocBtn = document.getElementById("savedoc"); const saveDocBtn = document.getElementById("savedoc");
const saveExcelBtn = document.getElementById("saveexcel"); const saveExcelBtn = document.getElementById("saveexcel");
const filename = document.getElementById("filename");
submitGoodBtn.addEventListener("click", () => { submitGoodBtn.addEventListener("click", () => {
console.log('try to add good') console.log('try to add good')
@ -88,32 +83,53 @@
}) })
saveDocBtn.addEventListener("click", async () => { saveDocBtn.addEventListener("click", async () => {
send('doc') send('docx')
}) })
saveExcelBtn.addEventListener("click", async () => { saveExcelBtn.addEventListener("click", async () => {
send('excel') send('xlsx')
}) })
function send(format) { function send(format) {
console.log(`try to save in ${format} format`) console.log(`try to save in ${format} format`)
if (list.length == 0 || !filename.value || filename.value == '') { if (list.length == 0) {
alert('operation failed. goods or filename are empty') alert('operation failed. goods are empty')
return return
} }
$.ajax({ $.ajax({
url: `/Storekeeper/ListBuilds?format=${format}&filename=${filename.value}`, url: `/Storekeeper/ListBuilds?format=${format}`,
type: 'POST', type: 'POST',
contentType: 'application/json', contentType: 'application/json',
data: JSON.stringify({ "Goods" : list }) data: JSON.stringify({ "Goods" : list })
}).done(() => { }).done((file) => {
//let byteArray = new Uint8Array(file); let byteArray = new Uint8Array(file);
saveFile(byteArray, format);
}) })
.fail(function(xhr, textStatus, errorThrown) { .fail(function(xhr, textStatus, errorThrown) {
alert(xhr.responseText); alert(xhr.responseText);
}) })
} }
async function saveFile(bytes, format) {
if (window.showSaveFilePicker) {
const opts = {
suggestedName: `listbuilds.${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() { function reloadTable() {
resultTable.innerHTML = '' resultTable.innerHTML = ''
let count = 0; let count = 0;

View File

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

Binary file not shown.