474 lines
18 KiB
C#
474 lines
18 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||
using Microsoft.AspNetCore.Mvc.Rendering;
|
||
using Microsoft.DotNet.Scaffolding.Shared.CodeModifier.CodeChange;
|
||
using Microsoft.Extensions.Hosting.Internal;
|
||
using Newtonsoft.Json;
|
||
using System;
|
||
using System.Diagnostics;
|
||
using System.Reflection;
|
||
using System.Text;
|
||
using System.Web;
|
||
using VirtualTask.Models;
|
||
|
||
namespace VirtualTask.Controllers
|
||
{
|
||
public class DatiAziendaController : Controller
|
||
{
|
||
|
||
string apiUrl = string.Empty;
|
||
string urlBase = string.Empty;
|
||
string token = string.Empty;
|
||
string tenant = string.Empty;
|
||
string tenant2 = string.Empty;
|
||
string errMes = string.Empty;
|
||
string _pathLoghi = string.Empty;
|
||
string _urlLoghi = string.Empty;
|
||
HttpClient client;
|
||
string admin = string.Empty;
|
||
private readonly IConfiguration _configuration;
|
||
//private readonly Microsoft.Extensions.Hosting.IHostingEnvironment _hostingEnvironment;
|
||
string time_sheet=string.Empty;
|
||
public DatiAziendaController(IConfiguration configuration /*,Microsoft.Extensions.Hosting.IHostingEnvironment hostingEnvironment*/)
|
||
{
|
||
client = new HttpClient();
|
||
_configuration = configuration;
|
||
var key = _configuration["ApplicationInsights:rootUrlApi"];
|
||
apiUrl = key;
|
||
//_hostingEnvironment = hostingEnvironment;
|
||
_pathLoghi = _configuration["ApplicationInsights:rootWebLoghi"];
|
||
_urlLoghi = _configuration["ApplicationInsights:rootUrlApi2"];
|
||
|
||
}
|
||
|
||
#region INDEX
|
||
|
||
public IActionResult Index()
|
||
{
|
||
SessionHelper helper = new SessionHelper(this);
|
||
token = helper.GetStringValue("tok");
|
||
tenant = helper.GetStringValue("tenant");
|
||
tenant2= helper.GetStringValue("tenant2");
|
||
time_sheet = helper.GetStringValue("time_sheet");
|
||
ViewBag.TimeSheet = time_sheet;
|
||
if (string.IsNullOrEmpty(token))
|
||
{
|
||
return RedirectToAction("Login2", "Login");
|
||
}
|
||
|
||
apiUrl = helper.GetStringValue("apiUrl");
|
||
admin = helper.GetStringValue("admin");
|
||
ViewBag.Admin = admin;
|
||
urlBase = apiUrl + "datiaziendaList";
|
||
urlBase = urlBase + "?token=" + token;
|
||
Uri baseAddress = new Uri(urlBase);
|
||
client.BaseAddress = baseAddress;
|
||
|
||
List<DatiAziendaTable> modelList = new List<DatiAziendaTable>();
|
||
HttpResponseMessage response = client.GetAsync(baseAddress).Result;
|
||
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
string data = response.Content.ReadAsStringAsync().Result;
|
||
modelList = JsonConvert.DeserializeObject<List<DatiAziendaTable>>(data);
|
||
|
||
return View(modelList);
|
||
}
|
||
else
|
||
{
|
||
errMes = response.Content.ReadAsStringAsync().Result;
|
||
helper.SetStringValue("errMsg", errMes);
|
||
return RedirectToAction("Error");
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region CREATE
|
||
|
||
public IActionResult Create()
|
||
{
|
||
SessionHelper helper = new SessionHelper(this);
|
||
admin = helper.GetStringValue("admin");
|
||
ViewBag.Admin = admin;
|
||
ViewBag.AllTecnici = getTecnici();
|
||
return View();
|
||
}
|
||
|
||
[HttpPost]
|
||
public async Task<IActionResult> Create(DatiAzienda model)
|
||
{
|
||
SessionHelper helper = new SessionHelper(this);
|
||
string token = helper.GetStringValue("tok");
|
||
string tenant2 = helper.GetStringValue("tenant2"); // tenant = azienda
|
||
string apiUrl = helper.GetStringValue("apiUrl");
|
||
string admin = helper.GetStringValue("admin");
|
||
|
||
ViewBag.Admin = admin;
|
||
ViewBag.AllTecnici = getTecnici();
|
||
|
||
// ❌ Validazione fallita → restituisco errori in JSON
|
||
if (!ModelState.IsValid)
|
||
{
|
||
var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToList();
|
||
return BadRequest(string.Join("\n", errors));
|
||
}
|
||
|
||
string logoUrl = null;
|
||
|
||
// 1️⃣ Upload del logo tramite API UploadLogo
|
||
if (model.logo != null && model.logo.Length > 0)
|
||
{
|
||
string uploadUrl = $"{apiUrl}datiazienda/upload_logo?token={token}";
|
||
|
||
using (var httpClient = new HttpClient())
|
||
using (var form = new MultipartFormDataContent())
|
||
{
|
||
var fileContent = new StreamContent(model.logo.OpenReadStream());
|
||
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(
|
||
string.IsNullOrWhiteSpace(model.logo.ContentType) ? "application/octet-stream" : model.logo.ContentType
|
||
);
|
||
form.Add(fileContent, "file", model.logo.FileName);
|
||
|
||
HttpResponseMessage response = await httpClient.PostAsync(uploadUrl, form);
|
||
|
||
if (!response.IsSuccessStatusCode)
|
||
{
|
||
string err = await response.Content.ReadAsStringAsync();
|
||
return BadRequest("Errore upload logo: " + err);
|
||
}
|
||
|
||
dynamic result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
|
||
logoUrl = result.url;
|
||
}
|
||
}
|
||
|
||
// 2️⃣ Creo l'oggetto da inviare all'API
|
||
var dat = new DatiAziendaTable
|
||
{
|
||
azienda = tenant2,
|
||
tecnico = model.tecnico,
|
||
ragsoc = model.ragsoc,
|
||
testo_buono = model.testo_buono,
|
||
url_logo = logoUrl,
|
||
logo = model.logo != null ? await ConvertToByteArrayAsync(model.logo) : null
|
||
};
|
||
|
||
// 3️⃣ Invio dati all'API datiazienda/add
|
||
string apiAddUrl = apiUrl + "datiazienda/add?token=" + token;
|
||
using (var httpClient = new HttpClient())
|
||
{
|
||
string data = JsonConvert.SerializeObject(dat);
|
||
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
|
||
HttpResponseMessage saveResponse = await httpClient.PostAsync(apiAddUrl, content);
|
||
|
||
if (!saveResponse.IsSuccessStatusCode)
|
||
{
|
||
string err = await saveResponse.Content.ReadAsStringAsync();
|
||
return BadRequest("Errore salvataggio dati: " + err);
|
||
}
|
||
}
|
||
|
||
// ✅ Risposta JSON usata dalla view per aprire la finestra popup
|
||
return Json(new { success = true });
|
||
}
|
||
|
||
/// <summary>
|
||
/// Pagina popup mostrata dopo il salvataggio
|
||
/// </summary>
|
||
public IActionResult Dialog()
|
||
{
|
||
return View();
|
||
}
|
||
|
||
#endregion CREATE
|
||
|
||
#region EDIT
|
||
public IActionResult Edit(string azienda,string tecnico)
|
||
{
|
||
SessionHelper helper = new SessionHelper(this);
|
||
|
||
token = helper.GetStringValue("tok");
|
||
|
||
apiUrl = helper.GetStringValue("apiUrl");
|
||
admin = helper.GetStringValue("admin");
|
||
ViewBag.Admin = admin;
|
||
urlBase = apiUrl + "datiaziendaList";
|
||
urlBase = urlBase + "?token=" + token;
|
||
Uri baseAddress = new Uri(urlBase);
|
||
client = new HttpClient();
|
||
client.BaseAddress = baseAddress;
|
||
|
||
DatiAziendaTable dat = new DatiAziendaTable();
|
||
List<DatiAziendaTable> modelList = new List<DatiAziendaTable>();
|
||
HttpResponseMessage response = client.GetAsync(baseAddress).Result;
|
||
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
string data = response.Content.ReadAsStringAsync().Result;
|
||
modelList = JsonConvert.DeserializeObject<List<DatiAziendaTable>>(data);
|
||
dat = modelList.Where(t => t.azienda.Equals(azienda) && t.tecnico.Equals(tecnico)).First();
|
||
}
|
||
else
|
||
{
|
||
errMes = response.Content.ReadAsStringAsync().Result;
|
||
helper.SetStringValue("errMsg", errMes);
|
||
return RedirectToAction("Error");
|
||
}
|
||
|
||
|
||
|
||
ViewBag.AllTecnici = getTecnici();
|
||
return View(dat);
|
||
}
|
||
|
||
[HttpPost]
|
||
public async Task<IActionResult> Edit(DatiAziendaTable model)
|
||
{
|
||
SessionHelper helper = new SessionHelper(this);
|
||
|
||
string token = helper.GetStringValue("tok");
|
||
string tenant2 = helper.GetStringValue("tenant2");
|
||
|
||
if (string.IsNullOrEmpty(token))
|
||
return RedirectToAction("Login2", "Login");
|
||
|
||
string apiUrl = helper.GetStringValue("apiUrl");
|
||
|
||
// 1️⃣ Upload del logo tramite API UploadLogo
|
||
if (model.logo2 != null && model.logo2.Length > 0)
|
||
{
|
||
string uploadUrl = $"{apiUrl}datiazienda/upload_logo?token={token}";
|
||
|
||
using (var httpClient = new HttpClient())
|
||
using (var form = new MultipartFormDataContent())
|
||
{
|
||
var fileContent = new StreamContent(model.logo2.OpenReadStream());
|
||
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(
|
||
string.IsNullOrWhiteSpace(model.logo2.ContentType) ? "application/octet-stream" : model.logo2.ContentType
|
||
);
|
||
form.Add(fileContent, "file", model.logo2.FileName);
|
||
|
||
HttpResponseMessage response = await httpClient.PostAsync(uploadUrl, form);
|
||
if (!response.IsSuccessStatusCode)
|
||
{
|
||
string err = await response.Content.ReadAsStringAsync();
|
||
ModelState.AddModelError("", "Errore upload logo: " + err);
|
||
return View(model);
|
||
}
|
||
|
||
dynamic result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
|
||
model.url_logo = result.url;
|
||
}
|
||
|
||
// Salvo i byte del file nel modello se serve per il DB
|
||
using (MemoryStream ms = new MemoryStream())
|
||
{
|
||
await model.logo2.CopyToAsync(ms);
|
||
model.logo = ms.ToArray();
|
||
}
|
||
model.logo2 = null;
|
||
}
|
||
|
||
// 2️⃣ Invio dati all'API datiazienda/mod
|
||
string modUrl = $"{apiUrl}datiazienda/mod?token={token}";
|
||
using (var client = new HttpClient())
|
||
{
|
||
string data = JsonConvert.SerializeObject(model);
|
||
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
|
||
HttpResponseMessage response = await client.PostAsync(modUrl, content);
|
||
|
||
if (!response.IsSuccessStatusCode)
|
||
{
|
||
string errMes = await response.Content.ReadAsStringAsync();
|
||
helper.SetStringValue("errMsg", errMes);
|
||
return RedirectToAction("Error");
|
||
}
|
||
}
|
||
|
||
//return RedirectToAction("Index");
|
||
// ✅ Risposta OK per far apparire la dialog nella view
|
||
return Ok();
|
||
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region DETAIL
|
||
public IActionResult Detail(string azienda, string tecnico)
|
||
{
|
||
SessionHelper helper = new SessionHelper(this);
|
||
|
||
token = helper.GetStringValue("tok");
|
||
|
||
apiUrl = helper.GetStringValue("apiUrl");
|
||
admin = helper.GetStringValue("admin");
|
||
ViewBag.Admin = admin;
|
||
urlBase = apiUrl + "datiaziendaList";
|
||
urlBase = urlBase + "?token=" + token;
|
||
Uri baseAddress = new Uri(urlBase);
|
||
client = new HttpClient();
|
||
client.BaseAddress = baseAddress;
|
||
|
||
DatiAziendaTable dat = new DatiAziendaTable();
|
||
List<DatiAziendaTable> modelList = new List<DatiAziendaTable>();
|
||
HttpResponseMessage response = client.GetAsync(baseAddress).Result;
|
||
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
string data = response.Content.ReadAsStringAsync().Result;
|
||
modelList = JsonConvert.DeserializeObject<List<DatiAziendaTable>>(data);
|
||
dat = modelList.Where(t => t.azienda.Equals(azienda) && t.tecnico.Equals(tecnico)).First();
|
||
}
|
||
else
|
||
{
|
||
errMes = response.Content.ReadAsStringAsync().Result;
|
||
helper.SetStringValue("errMsg", errMes);
|
||
return RedirectToAction("Error");
|
||
}
|
||
|
||
|
||
|
||
ViewBag.AllTecnici = getTecnici();
|
||
return View(dat);
|
||
}
|
||
#endregion
|
||
|
||
#region DELETE
|
||
[HttpGet]
|
||
public IActionResult Delete(string azienda, string tecnico)
|
||
{
|
||
SessionHelper helper = new SessionHelper(this);
|
||
|
||
token = helper.GetStringValue("tok");
|
||
|
||
apiUrl = helper.GetStringValue("apiUrl");
|
||
admin = helper.GetStringValue("admin");
|
||
ViewBag.Admin = admin;
|
||
urlBase = apiUrl + "datiaziendaList";
|
||
urlBase = urlBase + "?token=" + token;
|
||
Uri baseAddress = new Uri(urlBase);
|
||
client = new HttpClient();
|
||
client.BaseAddress = baseAddress;
|
||
|
||
DatiAziendaTable dat = new DatiAziendaTable();
|
||
|
||
List<DatiAziendaTable> modelList = new List<DatiAziendaTable>();
|
||
|
||
HttpResponseMessage response = client.GetAsync(baseAddress).Result;
|
||
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
string data = response.Content.ReadAsStringAsync().Result;
|
||
modelList = JsonConvert.DeserializeObject<List<DatiAziendaTable>>(data);
|
||
dat = modelList.Where(x => x.azienda.Equals(azienda) && x.tecnico.Equals(tecnico)).First();
|
||
}
|
||
|
||
return View(dat);
|
||
}
|
||
|
||
[HttpPost, ActionName("DeleteConfirmed")]
|
||
public IActionResult DeleteConfirmed(string azienda, string tecnico)
|
||
{
|
||
SessionHelper helper = new SessionHelper(this);
|
||
|
||
token = helper.GetStringValue("tok");
|
||
tenant = helper.GetStringValue("tenant");
|
||
|
||
apiUrl = helper.GetStringValue("apiUrl");
|
||
admin = helper.GetStringValue("admin");
|
||
ViewBag.Admin = admin;
|
||
urlBase = apiUrl + "datiazienda/del";
|
||
urlBase = urlBase + "?azienda=" + azienda;
|
||
urlBase = urlBase + "&tecnico=" + tecnico;
|
||
Uri baseAddress = new Uri(urlBase);
|
||
client = new HttpClient();
|
||
client.BaseAddress = baseAddress;
|
||
|
||
string data = JsonConvert.SerializeObject(azienda);
|
||
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
|
||
HttpResponseMessage response = client.PostAsync(baseAddress, content).Result;
|
||
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
return RedirectToAction("Index");
|
||
}
|
||
else
|
||
{
|
||
errMes = response.Content.ReadAsStringAsync().Result;
|
||
helper.SetStringValue("errMsg", errMes);
|
||
return RedirectToAction("Error");
|
||
}
|
||
}
|
||
#endregion DELETE
|
||
|
||
#region ALTRI METODI
|
||
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
|
||
public IActionResult Error()
|
||
{
|
||
SessionHelper helper = new SessionHelper(this);
|
||
string e = helper.GetStringValue("errMsg");
|
||
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrMsg = e });
|
||
}
|
||
|
||
private List<SelectListItem> getTecnici()
|
||
{
|
||
SessionHelper helper = new SessionHelper(this);
|
||
token = helper.GetStringValue("tok");
|
||
apiUrl = helper.GetStringValue("apiUrl");
|
||
urlBase = apiUrl + "tecniciList";
|
||
urlBase = urlBase + "?token=" + token;
|
||
Uri baseAddress = new Uri(urlBase);
|
||
client = new HttpClient();
|
||
client.BaseAddress = baseAddress;
|
||
List<SelectListItem> selectItems = new List<SelectListItem>();
|
||
List<Tecnici> modelList = new List<Tecnici>();
|
||
HttpResponseMessage response = client.GetAsync(baseAddress).Result;
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
string data = response.Content.ReadAsStringAsync().Result;
|
||
modelList = JsonConvert.DeserializeObject<List<Tecnici>>(data);
|
||
modelList = modelList.Where(x => x.tcdatobs == null).ToList();
|
||
//per gestire primo elemento tendina (deve essere vuoto)
|
||
SelectListItem listItemFirst = new SelectListItem();
|
||
|
||
listItemFirst.Value = string.Empty;
|
||
listItemFirst.Text = " - Tecnico";
|
||
selectItems.Add(listItemFirst);
|
||
|
||
foreach (var role in modelList)
|
||
{
|
||
SelectListItem listItem = new SelectListItem();
|
||
|
||
string s = role.tccodice + " - " + role.tcdescri;
|
||
listItem.Value = role.tccodice;
|
||
listItem.Text = s;
|
||
selectItems.Add(listItem);
|
||
}
|
||
}
|
||
return selectItems;
|
||
}
|
||
|
||
|
||
// Metodo helper per convertire IFormFile in byte[]
|
||
private async Task<byte[]> ConvertToByteArrayAsync(IFormFile file)
|
||
{
|
||
using (var ms = new MemoryStream())
|
||
{
|
||
await file.CopyToAsync(ms);
|
||
return ms.ToArray();
|
||
}
|
||
}
|
||
#endregion ALTRI METODI
|
||
|
||
// Classe per deserializzare la risposta JSON dell'API
|
||
private class UploadResponse
|
||
{
|
||
public string? message { get; set; }
|
||
public string? url { get; set; }
|
||
public string? fileName { get; set; }
|
||
}
|
||
}
|
||
|
||
|
||
}
|