Uniconta UserReportAPI (DevExpress reports)

Date: 2021-03-30
// using DevExpress.XtraReports.UI;
// using Uniconta.API.Service;
// using Uniconta.API.System;
// using Uniconta.ClientTools;
// using Uniconta.ClientTools.Controls;
// using Uniconta.ClientTools.DataModel;
// using Uniconta.ClientTools.Page;
// using Uniconta.DataModel;
// using Uniconta.Reports.Utilities;
// using UnicontaClient.Pages;

private static async Task<XtraReport> LoadReport<T>(CrudAPI api, string reportName) where T : UserReportDevExpressClient, UnicontaBaseEntity, new()
{
	var apiWrapper = new ApiWrapper<T>(api);

	var reportRow = (await apiWrapper.Filter()
	   .WhereEqual(x => x.Name, reportName)
	   .Run()).FirstOrDefault();

	return await GetReportInternal(api, reportName, reportRow);
}

private static async Task<byte[]> GetByteArrayFromReport(XtraReport report)
{
	var stream = new MemoryStream();
	await report.ExportToPdfAsync(stream, new PdfExportOptions());
	stream.Position = 0;
	return stream.ToArray();
}

private static async Task<XtraReport> GetReportInternal(CrudAPI api, string reportName, UserReportDevExpressClient reportRow)
{
	if (reportRow == null)
		throw new Exception($"Kon rapport '{reportName}' niet vinden!");
	// Load Layout bytes in repord
	_ = await api.Read(reportRow);
	var reportLayout = reportRow.Layout;
	if (reportLayout == null)
		throw new Exception($"Kon rapport '{reportName}' layout niet laden!");

	XtraReport report;
	try
	{
		report = ReportUtil.GetXtraReportFromLayout(reportLayout);
	}
	catch (Exception)
	{
		report = null;
	}

	if (report == null)
		throw new Exception($"Kon rapport '{reportName}' niet laden! (error while loading layout)");

	return report;
}

private static async Task<UserDocsClient> GetOfferReportBasedOnProjectType(CrudAPI api, GiftProject giftProject, string reportName)
{
	var report = await LoadReport<UserReportDevExpressClient>(api, reportName);
	var orderService = new OrderService();
	var projectConvertedToOrder = orderService.ConvertProjectToOrder<UniDebtorOffer>(giftProject);
	var lines = orderService.GetOrderlinesForProject<UniDebtorOfferLine>(giftProject);
	report.DataSource = ConvertToMasterDetailDataSource(projectConvertedToOrder, lines.ToArray());

	var reportAsByteArray = await GetByteArrayFromReport(report);

	return new UserDocsClient()
	{
		_Data = reportAsByteArray,
		_Text = $"Offerte {giftProject.Code}",
		_DocumentType = FileextensionsTypes.PDF
	};
}

public void ViewUserDoc(UserDocsClient attachment)
{
	ViewDocument("UserDocsPage3", attachment);
}



public class CustomPrintReport : IPrintReport
{
	public DevExpress.XtraReports.UI.XtraReport Report { get; set; }

	public Task InitializePrint()
	{
		return Task.FromResult(0);
	}
}

private void SetReportParameter(DevExpress.XtraReports.UI.XtraReport report, string name, object value)
{
	var p = report.Parameters
		.AsQueryable()
		.Cast<DevExpress.XtraReports.Parameters.Parameter>()
		.FirstOrDefault(x => string.Equals(x.Name, name));

	if (p == null)
	{
		p = new DevExpress.XtraReports.Parameters.Parameter
		{
			Name = name
		};
		report.Parameters.Add(p);
	}
	p.Value = value;
}


var reportApi = new UserReportAPI(api);
var reportName = "MyReportName";
var customReport = false;
if (!string.IsNullOrWhiteSpace(e.ArticleReport))
{
	customReport = true;
	reportName = e.ArticleReport;
}

byte[] reportLayout;
XtraReport report;

try
{
	reportLayout = ThreadsHelper.RunSync(() => reportApi.LoadForRun(reportName, 1));
	report = ReportUtil.GetXtraReportFromLayout(reportLayout);
}
catch (Exception ex)
{
	throw new Exception($"Kon rapport {reportName} niet laden!", ex);
}
if (report == null)
	throw new Exception($"Kon rapport {reportName} niet laden! (2)");

if (customReport)
{
	var dataSource = new List<UnicontaMasterDetail>();
	//var master = productionOrder;

	// #1. Laatste productie gereedmeld-regel opzoeken (productie artikel)
	var productionPostedClients = await api.Query<ProductionPostedClient>(productionOrder);
	var productionPostedClient = productionPostedClients.OrderByDescending(x => x.LineNumber).FirstOrDefault();
	if (productionPostedClient == null)
		return;

	// #2. Laatste gereedmeld-detailregel opzoeken
	var invTransClients = await api.Query<InvTransClient>(productionPostedClient);
	var invTransClient = invTransClients.Where(x => x.MovementTypeEnum == InvMovementType.ReportAsFinished).OrderByDescending(x => x.LineNumber).FirstOrDefault();

	//var filter = new List<PropValuePair>
	//{
	//    PropValuePair.GenereteWhereElements(nameof(InvSerieBatchClient.Number), e.BatchNumber, CompareOperator.Equal),
	//    PropValuePair.GenereteWhereElements(nameof(InvSerieBatchClient.Item), productionOrder.Item, CompareOperator.Equal),
	//};

	// #3. var de invTransClient de bijbehorende batchnummers opzoeken
	var batchNumbers = await api.Query<InvSerieBatchClient>(invTransClient);
	// Force re-check
	var specificBatchNumbers = batchNumbers.Where(x => x.Number == e.BatchNumber && x.Item == productionOrder.Item).ToArray();
	
	dataSource.Add(new UnicontaMasterDetail()
	{
		Master = invTransClient,
		Details = specificBatchNumbers
	});
	
	report.DataSource = dataSource;
}
else
{
	report.DataSource = new List<ProductionOrderClient>() { productionOrder };
}
SetReportParameter(report, "EmployeeNumber", employee.Number);
SetReportParameter(report, "EmployeeName", employee.Name);
SetReportParameter(report, "Quantity", e.Quantity);
SetReportParameter(report, "QuantityToBook", e.QuantityToBook);
SetReportParameter(report, "BatchNumber", e.BatchNumber);
SetReportParameter(report, "Date", e.Date);
SetReportParameter(report, "BatchExpiryDate", e.BatchExpiryDate);
SetReportParameter(report, "ArticleDescription", e.ArticleDescription);
SetReportParameter(report, "ArticleCode", e.ArticleCode);
SetReportParameter(report, "BookingDescription", e.BookingDescription);
SetReportParameter(report, "ProductionDate", ProductionOrderList.ProductionDate);
SetReportParameter(report, "ProductionOrderDescription", e.ProductionOrderDescription);

// Via GUI
Dispatcher.Invoke(() =>
{
	IPrintReport printReport = new CustomPrintReport() { Report = report };
	var dockName = $"{Localization.lookup("ProductionOrder")} {productionOrder.KeyStr}";
	AddDockItem(UnicontaTabs.StandardPrintReportPage, new object[] { new List<IPrintReport> { printReport }, reportName }, dockName);
});


// As stream / byte[]
var pdfOptions = new PdfExportOptions() { };
var stream = new MemoryStream();
await report.ExportToPdfAsync(stream, pdfOptions);
stream.Position = 0;
return stream.ToArray();
47970cookie-checkUniconta UserReportAPI (DevExpress reports)