using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Comal.Classes;
using InABox.Clients;
using InABox.Core;
using InABox.Mobile;
using InABox.Rpc;
namespace comal.timesheets
{
public class GPSEventArgs : EventArgs
{
}
public delegate void GPSLocationUpdatedEvent(GPSEventArgs args);
public class BluetoothEventArgs : EventArgs
{
}
public delegate void BluetoothScanFinishedEvent(BluetoothEventArgs args);
public class TransportConnectedEventArgs : EventArgs
{
}
public delegate void TransportConnectedEvent(TransportConnectedEventArgs args);
public class TransportDisconnectedEventArgs : EventArgs
{
}
public delegate void TransportDisconnectedEvent(TransportDisconnectedEventArgs args);
public class DataModel : IModelHost
{
public event GPSLocationUpdatedEvent GPSLocationUpdated;
public event BluetoothScanFinishedEvent BluetoothScanFinished;
///
/// All Active Employees of the Company
///
public EmployeeModel Employees { get; private set; }
///
/// EmployeeDetails for Currently Logged in User
///
public EmployeeDetailModel Me { get; private set; }
///
/// All Employee Teams for the Company
/// Should this be just teams I am a part of, or all available teams
/// Need to implement a Security Token to differentiate
///
public EmployeeTeamModel EmployeeTeams { get; private set; }
///
/// All Available Contacts - used in Deliveries
///
public ContactModel Contacts { get; private set; }
///
/// All Defined Bluetooth-enabled Gates
///
public BluetoothGateModel BluetoothGates { get; private set; }
///
/// Unprocessed Timesheets for Currently Logged in User
///
public TimeSheetModel TimeSheets { get; private set; }
///
/// List of All active Jobs
///
public JobLookupModel JobLookups { get; private set; }
///
/// List of Jobs that Currently Logged in User has access To
///
public JobModel Jobs { get; private set; }
///
/// List of Assignments for ??? need to specify this.
/// Can I see other people's assignments? (Security Token)
/// How far back / forward can I look.
/// This smells Transient, or maybe split into lookups (for all)
/// and shells (for mine)
/// Possibly need a back/forward window as well?
///
public AssignmentModel Assignments { get; private set; }
///
/// Master Product Catalogue for the company
/// This should be split into Lookups and Shells
///
public ProductModel Products { get; private set; }
///
/// Master Product Groups List (Lookup?)
///
public ProductGroupLookupModel ProductGroupsLookup { get; private set; }
///
/// All GPS Tracker Devices registered by the company
///
public GPSTrackerModel GPSTrackers { get; private set; }
///
/// Master Equipment Register
///
public EquipmentModel Equipment { get; private set; }
///
/// Master List of Equipment Groups
///
public EquipmentGroupModel EquipmentGroups { get; private set; }
///
/// List of all Deliveries made in the last 90 days
/// hmmm.. should be configurable?
///
public DeliveryModel Deliveries { get; private set; }
///
/// My Notifications (open only?)
///
public NotificationModel Notifications { get; private set; }
///
/// All Open Kanbans
///
public KanbanLookupModel KanbanLookups { get; private set; }
///
/// All Tasks I am subscribed to
///
public KanbanModel Kanbans { get; private set; }
///
/// Available Form Library - this includes all "Applies To" values
/// You can filter to a specific type by using the "Search" function
///
public DigitalFormModel DigitalForms { get; private set; }
// The list of open task-kased forms for the current user
// Specifically for us in the "Forms" module
// This overlaps the "Task" module a fair amount, but it provides
// an alternative paradigm for tasks
public KanbanFormModel KanbanForms { get; private set; }
///
/// List of Employees, along with Clock on / off status
///
public InOutModel InOut { get; private set; }
///
/// List of all available Document Set Tags
///
public JobDocumentSetTagModel DocumentSetTags { get; private set; }
///
/// List of available Delivery Barcodes
///
public DeliveryItemLookupModel DeliveryItems { get; private set; }
public DataModel()
{
Me = new EmployeeDetailModel(this,
() => new Filter(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
);
Employees = new EmployeeModel(this,
() => LookupFactory.DefineFilter());
EmployeeTeams = new EmployeeTeamModel(this,
() => new Filter(x => x.EmployeeLink.ID)
.InQuery(LookupFactory.DefineFilter(), x => x.ID)
);
InOut = new InOutModel(this,
() => LookupFactory.DefineFilter()
.And(x=>x.ID).IsNotEqualTo(App.Data.Me.ID));
Jobs = new JobModel(this, MyJobsFilter);
JobLookups = new JobLookupModel(this,
() => LookupFactory.DefineFilter());
Products = new ProductModel(this,
() => LookupFactory.DefineFilter());
ProductGroupsLookup = new ProductGroupLookupModel(this,
() => LookupFactory.DefineFilter());
GPSTrackers = new GPSTrackerModel(this,
() => LookupFactory.DefineFilter());
Equipment = new EquipmentModel(this,
() =>
{
var filter = LookupFactory.DefineFilter();
var privfilter = new Filter(x => x.Private).IsEqualTo(false);
if (InABox.Core.Security.IsAllowed())
return filter;
return filter != null
? filter.And(privfilter)
: privfilter;
},
"equipment.index");
EquipmentGroups = new EquipmentGroupModel(this,
() => LookupFactory.DefineFilter());
Deliveries = new DeliveryModel(this,
() => new Filter(x => x.Completed).IsEqualTo(DateTime.MinValue)
.Or(x => x.Completed).IsGreaterThanOrEqualTo(DateTime.Today.AddDays(-90))
);
DeliveryItems = new DeliveryItemLookupModel(this,
() => LookupFactory.DefineFilter()
);
Notifications = new NotificationModel(this,
() => new Filter(x=>x.Closed).IsEqualTo(DateTime.MinValue)
.And(x=>x.Employee.ID).IsEqualTo(App.Data.Me.ID)
);
TimeSheets = new TimeSheetModel(this,
() => new Filter(x=>x.Processed).IsEqualTo(DateTime.MinValue)
.And(x=>x.EmployeeLink.ID).IsEqualTo(App.Data.Me.ID));
Assignments = new AssignmentModel(this,
() => new Filter(x => x.Date).IsGreaterThanOrEqualTo(DateTime.Today.AddDays(-90))
.And(x => x.Date).IsLessThanOrEqualTo(DateTime.Today.AddDays(90))
);
Contacts = new ContactModel(this,
() => LookupFactory.DefineFilter());
Kanbans = new KanbanModel(this,
() => new Filter(x => x.Employee.ID).IsEqualTo(App.Data.Me.ID));
KanbanLookups = new KanbanLookupModel(this,
() => new Filter(x => x.Completed).IsEqualTo(DateTime.MinValue));
BluetoothGates = new BluetoothGateModel(this,
() => new Filter(x => x.Active).IsEqualTo(true)
);
DigitalForms = new DigitalFormModel(this,
() => new Filter(x => x.Employee.ID).IsEqualTo(App.Data.Me.ID)
.And(x => x.Form.Active).IsEqualTo(true)
.And(x => x.Form.Secure).IsEqualTo(false)
);
KanbanForms = new KanbanFormModel(this,
() => new Filter(x=>x.Parent.EmployeeLink.ID).IsEqualTo(App.Data.Me.ID)
.And(x=>x.FormCompleted).IsEqualTo(DateTime.MinValue)
);
DocumentSetTags = new JobDocumentSetTagModel(this,
() => null
);
}
private static Filter MyJobsFilter()
{
return InABox.Core.Security.IsAllowed()
? new Filter(X => X.Completed).IsEqualTo(DateTime.MinValue)
.And(x => x.JobStatus.Active).IsEqualTo(true)
: new Filter(X => X.Completed).IsEqualTo(DateTime.MinValue)
.And(x => x.JobStatus.Active).IsEqualTo(true)
.And(x => x.ID).InQuery(
new Filter(x => x.EmployeeLink.ID).IsEqualTo(App.Data.Me.ID),
x => x.JobLink.ID
);
}
public void Setup()
{
_connected = true;
InABox.Core.Security.CheckTokens();
Me.Refresh(true);
Task[] _setuptasks = new Task[]
{
Task.Run(() => TimeSheets.Refresh(true)),
Task.Run(() => GPSTrackers.Refresh(true)),
Task.Run(() => BluetoothGates.Refresh(true)),
Task.Run(() => Notifications.Refresh(true)),
Task.Run(() => Kanbans.Refresh(true))
};
Task.WaitAll(_setuptasks);
App.Bluetooth.OnScanFinished += OnBluetoothScanFinished;
App.GPS.OnLocationFound += OnGPSLocationFound;
App.Transport.OnOpen += OnTransportConnected;
App.Transport.OnClose += OnTransportDisconnected;
}
public bool IsConnected() => _connected;
private bool _connected;
public event TransportDisconnectedEvent TransportDisconnected;
public event TransportConnectedEvent TransportConnected;
private void OnTransportDisconnected(IRpcTransport transport, RpcTransportCloseArgs e)
{
_connected = false;
TransportDisconnected?.Invoke(new TransportDisconnectedEventArgs());
Task.Run(() =>
{
while (!_connected)
App.Transport.Connect();
var status = ClientFactory.Validate(ClientFactory.SessionID);
});
}
private void OnTransportConnected(IRpcTransport transport, RpcTransportOpenArgs e)
{
_connected = true;
TransportConnected?.Invoke(new TransportConnectedEventArgs());
}
private GPSTrackerLocation GetGPSTrackerUpdate(string deviceid, InABox.Core.Location location,
TimeSpan threshold, double distance)
{
GPSTrackerShell tracker = GPSTrackers.FirstOrDefault(x => x.DeviceID.Equals(deviceid));
if (tracker != null)
{
if ((tracker.Timestamp < location.Timestamp.Subtract(threshold)) || (tracker.Location.DistanceTo(location, UnitOfLength.Kilometers) > distance))
{
GPSTrackerLocation gpsTrackerLocation = new GPSTrackerLocation();
gpsTrackerLocation.DeviceID = tracker.DeviceID;
gpsTrackerLocation.Tracker.ID = tracker.ID;
gpsTrackerLocation.Location = location;
return gpsTrackerLocation;
}
}
return null;
}
private InABox.Core.Location _lastgpslocation = new InABox.Core.Location();
private void OnGPSLocationFound(LocationServices sender)
{
if (_lastgpslocation.Timestamp < DateTime.Now.Subtract(TimeSpan.FromMinutes(2)))
{
var devicelocation = new InABox.Core.Location()
{
Latitude = App.GPS.Latitude,
Longitude = App.GPS.Longitude,
Timestamp = App.GPS.TimeStamp,
Address = App.GPS.Address
};
GPSTrackers.Refresh(false);
var update = GetGPSTrackerUpdate(MobileUtils.GetDeviceID(), devicelocation, TimeSpan.FromMinutes(2), 0.1);
if (update != null)
new Client().Save(update, "Updated via Mobile Device", (o, e) => { });
}
GPSLocationUpdated?.Invoke(new GPSEventArgs());
}
private void OnBluetoothScanFinished(Bluetooth sender)
{
UploadTiles();
BluetoothScanFinished?.Invoke(new BluetoothEventArgs());
}
private void UploadTiles()
{
try
{
if (App.GPS.Latitude.Equals(0.0F) && App.GPS.Longitude.Equals(0.0F))
return;
if (App.Bluetooth.DetectedBlueToothMACAddresses.Count == 0)
return;
var devicelocation = new InABox.Core.Location()
{
Latitude = App.GPS.Latitude,
Longitude = App.GPS.Longitude,
Timestamp = App.GPS.TimeStamp,
Address = App.GPS.Address
};
GPSTrackers.Refresh(true);
List updates = new List();
foreach (String deviceid in App.Bluetooth.DetectedBlueToothMACAddresses)
{
var update = GetGPSTrackerUpdate(deviceid, devicelocation, TimeSpan.FromMinutes(2), 0.1);
if (update != null)
updates.Add(update);
}
if (updates.Any())
new Client().Save(updates, $"Updated by Mobile {MobileUtils.GetDeviceID()}",
(o, e) => { });
}
catch (Exception ex)
{
MobileLogging.Log($"UploadTiles() {ex.Message} \n {ex.StackTrace}");
}
}
public int EmployeeFormsToDo { get; set; }
public int QualificationsNeedingAttention { get; set; }
public bool UpdateHRItemsNeedingAttention()
{
try
{
EmployeeFormsToDo = 0;
QualificationsNeedingAttention = 0;
CoreTable table = new Client().Query(
new Filter(x => x.Employee.ID).IsEqualTo(Me.ID),
new Columns(
x => x.ID, //0
x => x.Expiry, //1
x => x.FrontPhoto.ID //2
)
);
if (table.Rows.Any())
{
List IDs = new List();
foreach (CoreRow row in table.Rows)
{
List