Merge branch 'master' of bitbucket.org:bluetradesys/spark into pnl_nits2

This commit is contained in:
Jake Norbut committed 2018-07-12 12:07:08 -05:00
commit 07377b8cc9
66 files changed
+11090 -2657

No files matched your search

+2 -4
View File
@@ -47,7 +47,7 @@ namespace mbts.ui
//public static ImageSource Ticket { get { return load_image("Ticket.png"); } } // replaced with AddOrders
public static ImageSource Date { get { return load_image("Date.png"); } }
public static ImageSource Cube3d { get { return (DrawingImage)_resources["Cube"]; /*return load_image("Cube-Molecule.png");*/ } }
public static ImageSource Cube3d { get { return (DrawingImage)_resources["Cube"]; } }
public static ImageSource Algo { get { return Cube3d; } }
public static ImageSource Quote { get { return Math; } }
public static ImageSource Math { get { return (DrawingImage)_resources["Surface"]; } }
@@ -62,9 +62,7 @@ namespace mbts.ui
#pragma warning restore CS0618
// Vector icons
public static ImageSource Favorites { get { return Favorites_Gold; } }
public static ImageSource Favorites_Gold { get { return (DrawingImage)_resources["FavoritesGold"]; } }
public static ImageSource Favorites_White { get { return (DrawingImage)_resources["FavoritesWhite"]; } }
public static ImageSource Bookmarks { get { return (DrawingImage)_resources["Bookmarks"]; } }
public static ImageSource Window { get { return (DrawingImage)_resources["Window"]; } }
public static ImageSource ActiveWindow { get { return (DrawingImage)_resources["ActiveWindow"]; } }
public static ImageSource Trash { get { return (DrawingImage)_resources["Trash"]; } }
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

+3 -19
View File
@@ -3,33 +3,17 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:mbts="clr-namespace:mbts.ui">
<DrawingImage x:Key="FavoritesGold">
<DrawingImage.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Geometry="M1540.22,2082.07L1546.95,2102.78 1568.73,2102.78 1551.11,2115.58 1557.84,2136.29 1540.22,2123.49 1522.6,2136.29 1529.33,2115.58 1511.71,2102.78 1533.49,2102.78 1540.22,2082.07z">
<GeometryDrawing.Pen>
<Pen Thickness="1" Brush="Black" />
</GeometryDrawing.Pen>
<GeometryDrawing.Brush>
<SolidColorBrush Color="#ffd932" />
</GeometryDrawing.Brush>
</GeometryDrawing>
</DrawingGroup.Children>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
<DrawingImage x:Key="FavoritesWhite">
<DrawingImage x:Key="Bookmarks">
<DrawingImage.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Geometry="M1540.22,2082.07L1546.95,2102.78 1568.73,2102.78 1551.11,2115.58 1557.84,2136.29 1540.22,2123.49 1522.6,2136.29 1529.33,2115.58 1511.71,2102.78 1533.49,2102.78 1540.22,2082.07z">
<GeometryDrawing.Pen>
<Pen Thickness="1" Brush="Black" />
<Pen Thickness="3" Brush="Black" />
</GeometryDrawing.Pen>
<GeometryDrawing.Brush>
<SolidColorBrush Color="#ffd932" />
<SolidColorBrush Color="Transparent" />
</GeometryDrawing.Brush>
</GeometryDrawing>
</DrawingGroup.Children>
@@ -0,0 +1,81 @@
using bts.spark;
using mbts.spark;
using mbts.ui;
using mbts.ui.settings;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
namespace bts.ui {
[Export(typeof(IShellModule))]
public class BookmarkShellModule : ILazyMenuModule {
readonly WindowManager _wm;
readonly IBookmarks _bookmarks;
readonly ISavedWindowFactory _window_factory;
readonly WorkspacesModel _workspaces;
[ImportingConstructor]
public BookmarkShellModule(
WorkspacesModel workspaces,
WindowManager wm,
IBookmarks bm,
ISavedWindowFactory swf) {
_workspaces = workspaces;
_wm = wm;
_bookmarks = bm;
_window_factory = swf;
}
public ImageSource icon => Icons.Bookmarks;
public string name => "My Windows";
public int priority => 35;
public IEnumerable<SparkCommand> actions {
get {
// The windows that are open
var open =
_wm.list_documents()
.Select(td => td.ViewModel)
.Where(vm => vm.HasCustomTitle)
.Select(vm =>
SparkCommand.create(vm.Title, vm.Icon, SparkTags.ActivateWindow, () => vm.Model))
.Cast<SparkCommand>();
var open_set = new HashSet<string>(open.Select(c => c.title));
// The windows that are not open
var closed =
_bookmarks.bookmarks
.Where(state => !open_set.Contains(state.title))
.Select(state =>
SparkCommand.create(state.title, Icons.Bookmarks, SparkTags.ShowWindowAsync,
() => {
_bookmarks.remove(state);
return _window_factory.restore(state);
}))
.Cast<SparkCommand>();
// todo: The windows that are closed
foreach (var w in open.Concat(closed).OrderBy(w => w.title)) {
yield return w;
}
}
}
public Task<IShellWindow> create(Stream load_stream) {
// This module shouldn't have any windows
throw new NotImplementedException();
}
public void Dispose() { }
}
}
@@ -0,0 +1,48 @@
using mbts.ui.settings;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mbts.ui.shell {
public interface IBookmarks {
void save_bookmark(IShellWindow window);
void save_bookmark(WindowState window);
void remove(WindowState window);
void clear();
IEnumerable<WindowState> bookmarks { get; }
}
[Export(typeof(IBookmarks))]
public class BookmarksModel : IBookmarks {
readonly ISettingsCollector _settings_collector;
readonly Dictionary<string, WindowState> _bookmarks = new Dictionary<string, WindowState>();
[ImportingConstructor]
public BookmarksModel(ISettingsCollector settings) {
_settings_collector = settings;
}
public void save_bookmark(IShellWindow window) {
var state = _settings_collector.get_window_state(window);
if (state != null) {
_bookmarks[state.title] = state;
}
}
public void save_bookmark(WindowState window) {
_bookmarks[window.title] = window;
}
public void clear() {
_bookmarks.Clear();
}
public void remove(WindowState window) {
_bookmarks.Remove(window.title);
}
public IEnumerable<WindowState> bookmarks => _bookmarks.Values;
}
}
@@ -34,7 +34,7 @@ namespace bts.ui {
public int priority => 40;
public IEnumerable<SparkCommand> actions => new []{
public IEnumerable<SparkCommand> actions => new SparkCommand[]{
SparkCommands.ShowWorkspaces
//SparkCommands.ShowSettings
};
@@ -75,7 +75,7 @@ namespace mbts.ui.tests
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Begin: test_windows_disposed");
// Make sure that an IShellWindow and ISlowWindow added to the Windows collection is eventually disposed
var thread_factory = new ShellThreadFactory();
IWindowManager wm = new WindowManager(thread_factory, new Lazy<ISettingsCollector>(() => new TestSettingsCollector()), new TestSavedWindowFactory(), new TestUndo(), new SimpleBus());
IWindowManager wm = new WindowManager(thread_factory, new Lazy<ISettingsCollector>(() => new TestSettingsCollector()), new TestSavedWindowFactory(), null, new SimpleBus());
Assert.IsNotNull(Application.Current);
Assert.IsNotNull(Application.Current.Windows);
Assert.AreEqual(Application.Current.Windows.Count, 0);
@@ -100,7 +100,7 @@ namespace mbts.ui.tests
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Begin: test_slow_windows_disposed");
// Make sure that an IShellWindow and ISlowWindow added to the Windows collection is eventually disposed
var thread_factory = new ShellThreadFactory();
IWindowManager wm = new WindowManager(thread_factory, new Lazy<ISettingsCollector>(() => new TestSettingsCollector()), new TestSavedWindowFactory(), new TestUndo(), new SimpleBus());
IWindowManager wm = new WindowManager(thread_factory, new Lazy<ISettingsCollector>(() => new TestSettingsCollector()), new TestSavedWindowFactory(), null, new SimpleBus());
Assert.AreEqual(Application.Current.Windows.Count, 0);
// an ISlowWindow gets its own thread
+3
View File
@@ -5,6 +5,7 @@ using bts.spark;
using mbts.ui;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using static mbts.spark.SparkBusData;
namespace mbts.spark
@@ -34,6 +35,8 @@ namespace mbts.spark
public static ITag<(PartialCommand<SecurityMD>, SecurityCriteria)> FilterPickOne { get; } = new SparkTag<(PartialCommand<SecurityMD>, SecurityCriteria)>("FilterPick1");
public static ITag<IShellWindow> ShowWindow { get; } = new SparkTag<IShellWindow>("Show Window");
public static ITag<Task<IShellWindow>> ShowWindowAsync { get; } = new SparkTag<Task<IShellWindow>>("ShowWindowAsync");
public static ITag<IShellWindow> ActivateWindow { get; } = new SparkTag<IShellWindow>("Activate Window");
public static ITag<Nothing> ShowWorkspaces { get; } = new SparkTag<Nothing>(nameof(ShowWorkspaces));
public static ITag<Nothing> ShowSettings { get; } = new SparkTag<Nothing>(nameof(ShowSettings));
public static ITag<Uri> ShowUri { get; } = new SparkTag<Uri>("ShowUri");
@@ -48,10 +48,10 @@ namespace System.Collections.Generic {
return rv;
}
public static IEnumerable<T> ToIEnumerable<T>(this T item) {
yield return item;
}
// use "new [] { item }" - avoid putting this on the intellisense for every item everywhere
//public static IEnumerable<T> ToIEnumerable<T>(this T item) {
// yield return item;
//}
public static IEnumerable<T> TakeWhile<T, TAccumulate>(this IEnumerable<T> source, TAccumulate seed, Func<TAccumulate, T, TAccumulate> accumulate, Func<TAccumulate, T, bool> predicate) {
TAccumulate a = seed;
@@ -69,16 +69,18 @@ namespace mbts.ui.settings
if (window == null || window.Owner == null) return null;
MemoryStream out_stream = new MemoryStream();
window.GetState(out_stream);
var pos = _interop.GetPosition(window);
var state = new WindowState() {
owner = window.Owner.key(),
app_data = out_stream.ToArray(),
position = _interop.GetPosition(window),
title = window.Title
position = pos,
title = string.IsNullOrEmpty(pos.custom_title) ? window.Title : pos.custom_title
};
return state;
}
catch (Exception e) {
Logger.log(bts.log.Level.Error, bts.log.Subsystem.Ui, "Error saving window state for type {0}.\n {1}".fmt(window.GetType(), e.Message));
Logger.log(Level.Error, Subsystem.Ui, "Error saving window state for type {0}.\n {1}".fmt(window.GetType(), e.Message));
}
return null;
}
@@ -39,6 +39,9 @@ namespace mbts.ui.shell {
[ProtoMember(102), DefaultValue(true)]
public bool always_on_top = true;
//[ProtoMember(103)] //used
[ProtoMember(104)]
public string custom_title;
}
[ProtoContract]
@@ -58,7 +61,7 @@ namespace mbts.ui.shell {
public WindowPosition position;
[ProtoMember(9)]
public string title;
public string title; // for debugging
}
[ProtoContract]
@@ -23,6 +23,9 @@ namespace mbts.ui
Task<IShellWindow> create(Stream load_stream);
}
// ILazyModule may also impement IShellMenu to get opening/closing notification
public interface ILazyMenuModule : IShellModule { }
public interface IPersistShellModule : IShellModule {
// Called at startup before the UI is shown
// This is an opportunity for you to kick off background services
@@ -17,5 +17,5 @@ namespace mbts.ui
WindowPosition GetPosition(IShellWindow window);
bool IsVisible(IShellWindow window);
void PinWindow(IShellWindow window);
}
}
}
@@ -10,9 +10,11 @@ namespace mbts.ui.controls {
static SparkMenu() =>
DefaultStyleKeyProperty.OverrideMetadata(typeof(SparkMenu), new FrameworkPropertyMetadata(typeof(SparkMenu)));
public SparkMenu() =>
public SparkMenu() {
SetCurrentValue(FocusableProperty, false);
}
public SparkMenu(IEnumerable<SparkCommand> commands, IBus bus) : this() =>
ItemsSource = commands.Select(c => new SparkCommandVM(c, bus)).ToList();
@@ -61,16 +61,16 @@ namespace mbts.ui
_source_window = window as FloatingWindow;
if (_source != null) {
_mouse_start = e.GetPosition(window);
if (!is_button_descendant((DependencyObject)e.OriginalSource)) {
if (!is_clickable_descendant((DependencyObject)e.OriginalSource)) {
Mouse.Capture(_source);
}
}
}
static bool is_button_descendant(DependencyObject target) {
static bool is_clickable_descendant(DependencyObject target) {
while (target != null && !(target is TabDocument)) {
target = VisualTreeHelper.GetParent(target);
if (target is Button) return true;
if (target is Button || target is TextBox) return true;
}
return false;
}
@@ -24,38 +24,7 @@ namespace mbts.ui
}
}
public static async Task FromEvent(this object target, string event_name) {
var evt = target.GetType().GetEvent(event_name);
var delegate_type = evt.EventHandlerType;
var tcs = new TaskCompletionSource<object>();
Action result = () => { tcs.TrySetResult(null); };
var d = Delegate.CreateDelegate(evt.EventHandlerType, result, "Invoke");
try {
evt.AddEventHandler(target, d);
await tcs.Task;
}
finally {
evt.RemoveEventHandler(target, d);
}
}
public static async Task<T> FromEvent<T>(this object target, string event_name) {
var evt = target.GetType().GetEvent(event_name);
var delegate_type = evt.EventHandlerType;
var tcs = new TaskCompletionSource<T>();
Action<T> result = (arg) => { tcs.TrySetResult(arg); };
var d = Delegate.CreateDelegate(evt.EventHandlerType, result, "Invoke");
try {
evt.AddEventHandler(target, d);
await tcs.Task;
return tcs.Task.Result;
}
finally {
evt.RemoveEventHandler(target, d);
}
}
public static async Task<Tuple<T1,T2>> FromEvent<T1,T2>(this object target, string event_name) {
public static async Task<Tuple<T1,T2>> FromEvent<T1,T2>(this DependencyObject target, string event_name) {
var evt = target.GetType().GetEvent(event_name);
var delegate_type = evt.EventHandlerType;
var tcs = new TaskCompletionSource<Tuple<T1,T2>>();
@@ -32,7 +32,7 @@ namespace mbts.ui {
#region TraverseOnEnter
public static readonly DependencyProperty TraverseOnEnterProperty = DependencyProperty.RegisterAttached("TraverseOnEnter", typeof(bool), typeof(TextBoxBehavior), new PropertyMetadata(false, OnTraverseOnEnterChanged));
public static readonly DependencyProperty TraverseOnEnterProperty = DependencyProperty.RegisterAttached("TraverseOnEnter", typeof(bool), typeof(TextBoxBehavior), new PropertyMetadata(false, OnTraverseOnEnterChanged));
private static void OnTraverseOnEnterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var text_box = (TextBox)d;
if ((bool)e.NewValue) text_box.PreviewKeyDown += commit_on_enter_PreviewKeyDownHandler;
@@ -67,6 +67,65 @@ namespace mbts.ui {
public static void SetCommitOnEnter(DependencyObject obj, bool value) => obj.SetValue(CommitOnEnterProperty, value);
#endregion
#region CancelOnEnter
public static readonly DependencyProperty CancelOnEscapeProperty =
DependencyProperty.RegisterAttached("CancelOnEscape", typeof(bool), typeof(TextBoxBehavior), new PropertyMetadata(false, cancel_on_escape_changed));
private static void cancel_on_escape_changed(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var tb = (TextBox)d;
if ((bool)e.NewValue) {
tb.KeyDown += tbx_keydown;
}
else {
tb.KeyDown += tbx_keydown;
}
}
static void tbx_keydown(object sender, KeyEventArgs e) {
if (e.Key == Key.Escape) {
abort_edit(sender as DependencyObject);
}
}
// Copy the binding value back and forth to generate a set to the source property with the original value
private static void abort_edit(DependencyObject sender) {
if (sender != null) {
var binding = BindingOperations.GetBindingExpression(sender, TextBox.TextProperty);
binding?.UpdateTarget();
binding?.UpdateSource();
}
}
public static bool GetCancelOnEscape(DependencyObject obj) => (bool)obj.GetValue(CancelOnEscapeProperty);
public static void SetCancelOnEscape(DependencyObject obj, bool value) => obj.SetValue(CancelOnEscapeProperty, value);
#endregion
#region TryCancelOnFocusLost
public static readonly DependencyProperty TryCancelOnFocusLostProperty =
DependencyProperty.RegisterAttached("TryCancelOnFocusLost", typeof(bool), typeof(TextBoxBehavior), new PropertyMetadata(false, cancel_on_focus_lost_changed));
private static void cancel_on_focus_lost_changed(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var tb = (TextBox)d;
if ((bool)e.NewValue) {
tb.LostFocus += tb_lostfocus;
}
else {
tb.LostFocus += tb_lostfocus;
}
}
static void tb_lostfocus(object sender, EventArgs e) {
abort_edit(sender as DependencyObject);
}
public static bool GetTryCancelOnFocusLost(DependencyObject obj) => (bool)obj.GetValue(TryCancelOnFocusLostProperty);
public static void SetTryCancelOnFocusLost(DependencyObject obj, bool value) => obj.SetValue(TryCancelOnFocusLostProperty, value);
#endregion
#region ReleaseOnEscape
public static readonly DependencyProperty ReleaseOnEscapeProperty = DependencyProperty.RegisterAttached(
"ReleaseOnEscape", typeof(bool), typeof(TextBoxBehavior), new PropertyMetadata(false, OnReleaseOnEscapeChanged));
@@ -79,7 +138,8 @@ namespace mbts.ui {
tb.ReleaseMouseCapture();
Keyboard.ClearFocus();
}));
} else {
}
else {
tb.ClearKeyBindings(Key.Escape, ModifierKeys.None);
tb.ClearCommandBindings(ReleaseCaptureCommand);
}
@@ -180,17 +240,18 @@ namespace mbts.ui {
"IncrementDecrementOnMouseClick", typeof(bool), typeof(TextBoxBehavior), new PropertyMetadata(false, IncrementDecrementOnMouseClickPropertyChanged)
);
public static bool GetIncrementDecrementOnMouseClick(TextBox element) { return (bool)element.GetValue(IncrementDecrementOnMouseClickProperty); }
public static bool GetIncrementDecrementOnMouseClick(TextBox element) { return (bool)element.GetValue(IncrementDecrementOnMouseClickProperty); }
public static void SetIncrementDecrementOnMouseClick(TextBox element, bool value) { element.SetValue(IncrementDecrementOnMouseClickProperty, value); }
private static void IncrementDecrementOnMouseClickPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var text_box = d as TextBox;
if(text_box != null) {
if (text_box != null) {
if ((bool)e.NewValue) {
text_box.PreviewMouseLeftButtonDown += OnMouseLeftButtonDownDecrementValue;
text_box.PreviewMouseRightButtonDown += OnMouseRightButtonDownIncrementValue;
} else {
}
else {
text_box.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDownDecrementValue;
text_box.PreviewMouseRightButtonDown -= OnMouseRightButtonDownIncrementValue;
}
@@ -201,7 +262,8 @@ namespace mbts.ui {
var text_box = sender as TextBox;
if (text_box == null || String.IsNullOrWhiteSpace(text_box.Text)) {
return;
} else {
}
else {
if (uint.TryParse(text_box.Text, out uint val)) {
if (val < uint.MaxValue) {
val++;
@@ -226,5 +288,6 @@ namespace mbts.ui {
}
}
#endregion
}
}
@@ -14,18 +14,19 @@ namespace mbts.ui.shell
public partial class FloatingWindow : Window
{
bool _closed = false;
private IUndoActions _undo;
readonly IBookmarks _bookmark;
private IWindowManager _wm;
private ISavedWindowFactory _window_factory;
private ISettingsCollector _window_settings;
private Stack<Action> _recently_closed_windows = new Stack<Action>();
// if is_loaded is true, will NOT set width/height
internal FloatingWindow(TabDocument document, IWindowManager wm, IUndoActions undo, ISettingsCollector settings, ISavedWindowFactory factory, bool is_loaded=false) {
internal FloatingWindow(TabDocument document,
IWindowManager wm, IBookmarks bookmarks, ISettingsCollector settings, ISavedWindowFactory factory, bool is_loaded=false) {
_wm = wm;
_undo = undo;
_window_settings = settings;
_window_factory = factory;
_bookmark = bookmarks;
InitializeComponent();
if (string.IsNullOrEmpty(document.ViewModel.host_id)) {
@@ -67,6 +68,7 @@ namespace mbts.ui.shell
private ItemCollection Items { get { return _tabs.Items; } }
public IEnumerable<TabDocument> Documents => _tabs.Items.OfType<TabDocument>();
public bool IsEmpty { get { return _tabs.Items.Count == 0; } }
public bool SingleChild { get { return _tabs.Items.Count == 1; } }
public string host_id { get; private set; }
@@ -88,10 +90,10 @@ namespace mbts.ui.shell
if (sender != this) {
var undoaction = create_undo_action(document);
if (undoaction != null) {
IDisposable undoitem = _undo.push("Restore Tab '{0}'".fmt(document.Title), undoaction);
_recently_closed_windows.Push(() => { undoaction(); undoitem.Dispose(); });
_recently_closed_windows.Push(() => { undoaction(); });
}
}
_bookmark.save_bookmark(document.Model);
}
public void remove_document(TabDocument document) {
@@ -144,22 +146,9 @@ namespace mbts.ui.shell
protected override void OnClosed(EventArgs e) {
_closed = true;
TabDocument[] items = _tabs.Items.OfType<TabDocument>().ToArray();
if (items.Length > 0) {
// If we're closing and still have Tabs open we save the whole "window" worth of state in the undo stack
// If the application is shutting down this might be unnecessary work but it's not too costly
var undo_actions = items.Select(t => create_undo_action(t.ViewModel)).Where(item => item != null).ToArray();
if (undo_actions.Length > 0) {
string name = "Restore Window: '{0}'".fmt(string.Join("', '", items.Select(t => t.ViewModel.Title)));
_undo.push(name, () => {
foreach (var u in undo_actions) { u(); }
});
}
}
base.OnClosed(e);
foreach (TabDocument document in items) {
foreach (TabDocument document in _tabs.Items.OfType<TabDocument>().ToList()) {
if (document != null && document.ViewModel.CloseCommand.CanExecute(this)) {
document.ViewModel.CloseCommand.Execute(this);
}
+40 -12
View File
@@ -3,7 +3,9 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Style="{StaticResource {x:Type TabItem}}" d:DesignWidth="125"
xmlns:ui="clr-namespace:mbts.ui"
xmlns:convert="clr-namespace:mbts.ui.converters"
mc:Ignorable="d" d:DesignWidth="125"
Header="{Binding}" Content="{Binding AppContent}"
Background="#e6e6e6">
@@ -18,6 +20,19 @@
<Storyboard x:Key="_slide_back">
<DoubleAnimation Storyboard.TargetName="translate_transform" Storyboard.TargetProperty="X" To="100" Duration="0:0:0.25" FillBehavior="Stop" />
</Storyboard>
<DataTemplate x:Key="_edit_template">
<TextBox Text="{Binding TitleOverride}"
ui:TextBoxBehavior.CommitOnEnter="True"
ui:TextBoxBehavior.FocusOnLoaded="True"
ui:TextBoxBehavior.SelectAllOnFocus="True"
ui:TextBoxBehavior.CancelOnEscape="True"
ui:TextBoxBehavior.TryCancelOnFocusLost="True"
Width="150" HorizontalAlignment="Left" VerticalAlignment="Stretch" Grid.Column="0" Margin="0,0,4,0" />
</DataTemplate>
<DataTemplate x:Key="_template">
<TextBlock Text="{Binding Title}" TextTrimming="CharacterEllipsis" HorizontalAlignment="Left" VerticalAlignment="Stretch" Grid.Column="0" Margin="0,0,4,0"></TextBlock>
</DataTemplate>
<convert:BooleanToObjectConverter x:Key="MenuHeaderConverter" ValueForTrue="Rename Window" ValueForFalse="Add to My Windows" />
</ResourceDictionary>
</TabItem.Resources>
<TabItem.LayoutTransform>
@@ -28,25 +43,32 @@
<TabItem.RenderTransform>
<TranslateTransform x:Name="translate_transform" X="0" />
</TabItem.RenderTransform>
<TabItem.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}" TextTrimming="CharacterEllipsis" HorizontalAlignment="Left" VerticalAlignment="Stretch" Grid.Column="0" Margin="0,0,4,0"> </TextBlock>
</DataTemplate>
</TabItem.HeaderTemplate>
<TabItem.Template>
<ControlTemplate TargetType="{x:Type TabItem}">
<Border x:Name="bd" BorderBrush="Black" BorderThickness="0,0,0.5,0" Background="#d6d6d6" Width="{DynamicResource TabWidth}" Height="{DynamicResource TabHeight}" MinWidth="40" Margin="0" SnapsToDevicePixels="True" DockPanel.Dock="Left">
<Border.ToolTip>
<TextBlock Text="{Binding Title}" />
</Border.ToolTip>
<Border.ContextMenu>
<ContextMenu>
<MenuItem Header="{Binding HasCustomTitle, Converter={StaticResource MenuHeaderConverter}}" Command="{Binding rename_command}">
<MenuItem.Icon>
<Image Source="{StaticResource Bookmarks}" />
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Remove from My Windows" Command="{Binding unrename_command}" IsEnabled="{Binding HasCustomTitle}" />
</ContextMenu>
</Border.ContextMenu>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Image SnapsToDevicePixels="True" MaxHeight="20" VerticalAlignment="Center" HorizontalAlignment="Left" Stretch="Uniform" Margin="5,0,5,0" Source="{Binding Icon, Mode=OneTime}" RenderOptions.BitmapScalingMode="HighQuality" />
<Image SnapsToDevicePixels="True" MaxHeight="20" VerticalAlignment="Center" HorizontalAlignment="Left" Stretch="Uniform" Margin="5,0,5,0"
Source="{Binding Icon, Mode=OneTime}" RenderOptions.BitmapScalingMode="HighQuality" />
<!--<Image MaxHeight="10" HorizontalAlignment="Left" VerticalAlignment="Bottom" Stretch="Uniform" Margin="5"
Source="{StaticResource Bookmarks}" Visibility="{Binding HasCustomTitle, Converter={StaticResource BoolToVisibility}}" />-->
<ContentPresenter Grid.Column="1" x:Name="content" ContentSource="Header" TextBlock.Foreground="#666"
RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
HorizontalAlignment="Left"
@@ -62,12 +84,18 @@
<Setter Property="Panel.ZIndex" Value="1" />
<Setter Property="Background" TargetName="bd" Value="#F9F9F9" />
<Setter Property="TextBlock.Foreground" TargetName="content" Value="black" />
<!--<Setter Property="BorderThickness" TargetName="bd" Value="0,4,0.5,0" />-->
<!--<Setter Property="Margin" Value="-2,-2,-2,-1" />
<Setter Property="Margin" TargetName="content" Value="0,0,0,1" />
<Setter Property="Margin" TargetName="bd" Value="0,0,0,0" />-->
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</TabItem.Template>
<TabItem.Style>
<Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
<Setter Property="HeaderTemplate" Value="{StaticResource _template}" />
<Style.Triggers>
<DataTrigger Binding="{Binding EditMode}" Value="True">
<Setter Property="HeaderTemplate" Value="{StaticResource _edit_template}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TabItem.Style>
</TabItem>
@@ -18,8 +18,15 @@ namespace mbts.ui.shell {
public ImageSource IconSource { get { return _module.icon; } }
public UIElement MenuContent => new SparkMenu(_module.actions, _bus);
public void opening() { }
public void opening() {
(_module as IShellMenu)?.opening();
if (_module is ILazyMenuModule) {
RaisePropertyChanged(nameof(MenuContent));
}
}
public void closing() { }
public void closing() {
(_module as IShellMenu)?.closing();
}
}
}
@@ -24,10 +24,11 @@ namespace mbts.ui.shell
Dispatcher _dispatcher;
HwndContentHost _hwnd_host;
public ShellWindowVM(IShellWindow model, IWindowManager wm, IShellThreadFactory threads, string host = "") {
Logger.assert(model != null);
_model = model;
_model.TitleChanged += () => RaisePropertyChanged("Title");
_model.TitleChanged += () => { if (!HasCustomTitle) RaisePropertyChanged("Title"); };
_model.IconChanged += () => { _icon = null; RaisePropertyChanged("Icon"); };
_wm = wm;
host_id = host;
@@ -40,13 +41,55 @@ namespace mbts.ui.shell
if (HasTabAffinity) {
this.host_id = ((ITabAffineWindow)model).tab_group;
}
_edit_mode = backing(nameof(EditMode), false);
}
public string host_id { get; set; }
public Dispatcher Dispatcher { get { return _dispatcher; } }
public string Title { get { return _model.Title; } }
public string Title { get { return HasCustomTitle? TitleOverride : _model.Title; } }
string _title_override;
public string TitleOverride {
get => _title_override;
set {
if (_title_override != value) {
if (value == _model.Title) {
_title_override = null;
}
else {
_title_override = value;
}
RaisePropertyChanged(nameof(TitleOverride), nameof(Title), nameof(HasCustomTitle));
}
_edit_mode.set(false);
}
}
public bool HasCustomTitle => !string.IsNullOrWhiteSpace(TitleOverride);
Property<bool> _edit_mode;
public bool EditMode => _edit_mode.Value;
public ICommand rename_command => new DelegateCommand(begin_rename);
public ICommand unrename_command => new DelegateCommand(remove_custom);
private void begin_rename() {
if (string.IsNullOrEmpty(TitleOverride)) {
_title_override = Title;
}
_edit_mode.set(true);
}
private void remove_custom() {
TitleOverride = string.Empty;
//begin_close(this);
}
public string OwnerName { get { return _model.Owner == null ? "" : _model.Owner.name; } }
public ICommand CloseCommand { get { return new DelegateCommand(begin_close); } }
public double InitialWidth { get; private set; }
public double InitialHeight { get; private set; }
@@ -155,18 +198,14 @@ namespace mbts.ui.shell
}
}
public byte[] GetSaveState() {
MemoryStream stream = new MemoryStream();
_model.GetState(stream);
return stream.ToArray();
}
public IShellWindow Model { get { return _model; } }
public bool IsSlow { get { return _model is ISlowWindow; } }
public bool IsShared { get { return _model is ISharedWindow; } }
public bool HasTabAffinity { get { return _model is ITabAffineWindow; } }
public void Dispose() {
if (IsShared) {
// Shared threads continue running
+26 -13
View File
@@ -20,25 +20,31 @@ namespace mbts.ui.shell {
[Export(typeof(IWindowManager))]
[Export(typeof(IWindowsInterop))]
[Export]
public class WindowManager : IWindowManager, IWindowsInterop, IDisposable {
Dictionary<IShellWindow, TabDocument> _documents = new Dictionary<IShellWindow, TabDocument>();
Dictionary<string, FloatingWindow> _windows = new Dictionary<string, FloatingWindow>();
IShellThreadFactory _threads;
readonly IShellThreadFactory _threads;
Lazy<ISettingsCollector> _window_settings;
ISavedWindowFactory _window_factory;
IUndoActions _undo;
readonly ISavedWindowFactory _window_factory;
readonly Lazy<IBookmarks> _bookmarks;
IDisposable _dispose;
object _lock = new object();
[ImportingConstructor]
public WindowManager(
IShellThreadFactory threads, Lazy<ISettingsCollector> settings,
ISavedWindowFactory factory, IUndoActions undo, IBus bus) {
ISavedWindowFactory factory, Lazy<IBookmarks> bookmarks, IBus bus) {
_threads = threads;
_window_settings = settings;
_window_factory = factory;
_undo = undo;
_dispose = bus.subscribe(SparkTags.ShowWindow).OnDispatcher().Subscribe(w => add(w).ignore());
_bookmarks = bookmarks;
_dispose =
Disposable.Create(
bus.subscribe(SparkTags.ShowWindow).OnDispatcher().Subscribe(w => add(w).ignore()),
bus.subscribe(SparkTags.ShowWindowAsync).OnDispatcher().Subscribe(w => add(w).ignore()),
bus.subscribe(SparkTags.ActivateWindow).OnDispatcher().Subscribe(MakeVisible)
);
}
#region Window creation
@@ -48,6 +54,7 @@ namespace mbts.ui.shell {
var state = model.start_position();
if (state != null) {
viewmodel.host_id = state.host_id ?? "";
viewmodel.TitleOverride = state.custom_title;
}
var window = CreateWindow(content, state);
@@ -66,10 +73,10 @@ namespace mbts.ui.shell {
}
} else {
if (position != null) {
window = new FloatingWindow(document, this, _undo, _window_settings.Value, _window_factory, true);
window = new FloatingWindow(document, this, _bookmarks.Value, _window_settings.Value, _window_factory, true);
window.set_position(position);
} else
window = new FloatingWindow(document, this, _undo, _window_settings.Value, _window_factory);
window = new FloatingWindow(document, this, _bookmarks.Value, _window_settings.Value, _window_factory);
_windows.Add(window.host_id, window);
window.Closed += (o, e) => _windows.Remove(window.host_id);
}
@@ -81,12 +88,19 @@ namespace mbts.ui.shell {
public IReadOnlyList<IShellWindow> list_windows() =>
_documents.Keys.ToList();
public IReadOnlyList<TabDocument> list_documents() => _documents.Values.ToList();
public async Task add(IShellWindow window) {
if (!Application.Current.Dispatcher.CheckAccess())
await Application.Current.Dispatcher.InvokeAsync(() => add(window));
Logger.info(bts.log.Subsystem.Ui, $"Opening window {window.diagnostic_name()}.");
lock (_lock)
lock (_lock) {
_documents[window] = _create_document(window);
}
}
public async Task add(Task<IShellWindow> window) {
await add(await window);
}
public void remove(IShellWindow window) {
@@ -139,14 +153,13 @@ namespace mbts.ui.shell {
#region IWindowsInterop
public WindowPosition GetPosition(IShellWindow shell_window) {
return GetPosition(shell_window, null);
}
public WindowPosition GetPosition(IShellWindow shell_window, FloatingWindow owning_window) {
FloatingWindow window = owning_window == null ? window_for(shell_window) : owning_window;
FloatingWindow window = window_for(shell_window);
var doc = window.Documents.FirstOrDefault(td => td.ViewModel.Model == shell_window);
if (window != null) {
WindowPosition pos = window.get_position();
pos.tab_index = window.document_index(shell_window);
pos.host_id = window.host_id;
pos.custom_title = doc?.ViewModel?.TitleOverride;
return pos;
}
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.Ui, "IShellWindow '{0}' does not have a valid position. It may not be displayed".fmt(shell_window.Title));
@@ -19,6 +19,7 @@ using mbts.persist;
namespace mbts.ui.shell
{
[Export]
public class WorkspacesModel : ViewModelBaseWithValidation
{
@@ -35,10 +36,11 @@ namespace mbts.ui.shell
private bool _closing = false;
private ILauncher _launcher;
private IUndoActions _undo;
readonly IBookmarks _bookmarks;
[ImportingConstructor]
public WorkspacesModel(ISettingsCollector settings, ISavedWindowFactory window_restore,
IWindowManager windows, ObservableCollection<IShellModule> modules, IPersist persist,
IWindowManager windows, ObservableCollection<IShellModule> modules, IPersist persist, IBookmarks bm,
IUserPersist user_persist, ILauncher launcher, IUndoActions undo, [Import("workspace")]string initial_workspace) {
_settings_collector = settings;
_window_restore = window_restore;
@@ -48,6 +50,7 @@ namespace mbts.ui.shell
_modules = modules;
_launcher = launcher;
_undo = undo;
_bookmarks = bm;
_launcher.closing += _launcher_closing;
Workspaces = new ObservableCollection<WorkspaceViewModel>();
init(initial_workspace).ignore();
@@ -150,6 +153,7 @@ namespace mbts.ui.shell
workspace.windows = _settings_collector.get_window_state().ToList();
workspace.modules = _settings_collector.get_module_state().ToList();
workspace.launcher_state = _settings_collector.get_launcher_state();
workspace.named_windows = _bookmarks.bookmarks.ToList();
return workspace;
}
@@ -166,6 +170,7 @@ namespace mbts.ui.shell
await Task.Yield();
}
workspace.launcher_state = _settings_collector.get_launcher_state();
workspace.named_windows = _bookmarks.bookmarks.ToList();
return workspace;
}
@@ -226,10 +231,15 @@ namespace mbts.ui.shell
}
}
// Notify workspace changed
if (WorkspaceLoaded != null) {
WorkspaceLoaded(name);
_bookmarks.clear();
if (def.named_windows != null) {
foreach (var window in def.named_windows) {
_bookmarks.save_bookmark(window);
}
}
// Notify workspace changed
WorkspaceLoaded?.Invoke(name);
}
public Task delete_workspace(string name, WorkspaceDefinition def) {
@@ -244,18 +254,20 @@ namespace mbts.ui.shell
}
return (def.is_shared ? _public : _private).clear(WORKSPACE_NAMESPACE, name);
}
}
// The serialized data for the Workspace
[ProtoContract(Name = "WorkspaceDefinition")]
public class WorkspaceDefinition
{
// Converted the protobuf type ShellSettings to c#
// Avoid re-using id: 1,3,4,5,6,7
[ProtoMember(2, IsRequired = false)]
public List<WindowState> windows { get; set; }
// named windows which are not currently open
[ProtoMember(3)]
public List<WindowState> named_windows { get; set; }
[ProtoMember(9, IsRequired = false)]
public List<ModuleState> modules { get; set; }
@@ -37,13 +37,13 @@ namespace bts.spark
if (this.IsRoot) {
return Enumerable.Empty<OrderNode>();
}
return this.Parent.ToIEnumerable().Concat(this.Parent.Ancestors);
return new[] { this.Parent }.Concat(this.Parent.Ancestors);
}
}
public IEnumerable<OrderNode> MeAndDescedants {
get {
return this.ToIEnumerable().Concat(this.children.SelectMany(c => c.MeAndDescedants));
return new[] { this }.Concat(this.children.SelectMany(c => c.MeAndDescedants));
}
}
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
syntax='proto2';
package bts.config;
message CppConfig {
map<string, double> cpp_entry = 1;
}
+2 -5
View File
@@ -89,7 +89,7 @@ size_t load_securities(
void store_if_new(const std::vector<Security*>& securities) {
auto dbptr = open_db();
auto insert = utils::prepare_query(dbptr, "insert into securities (key, symbol, venue, type, security_blob, expiration) values (?,?,?,?,?,?)");
auto insert = utils::prepare_query(dbptr, "insert or ignore into securities (key, symbol, venue, type, security_blob, expiration) values (?,?,?,?,?,?)");
sqlite3_exec_nofail(dbptr, "BEGIN TRANSACTION");
std::string buffer;
for (const api::Security* psecurity : securities) {
@@ -100,10 +100,7 @@ void store_if_new(const std::vector<Security*>& securities) {
SQLITE_CHK(sqlite3_bind_int(insert.get(), 4, securitytype_of(*psecurity)), dbptr);
SQLITE_CHK(sqlite3_bind_blob(insert.get(), 5, buffer.c_str(), buffer.size(), SQLITE_STATIC), dbptr);
SQLITE_CHK(sqlite3_bind_int(insert.get(), 6, expiration(*psecurity).to_short()), dbptr);
auto result = sqlite3_step(insert.get());
if (result != SQLITE_DONE) {
LOG(md, Warn, "Failed to insert security into security db. key={}", psecurity->id());
}
sqlite3_step(insert.get());
sqlite3_reset(insert.get());
}
}
+13 -3
View File
@@ -133,6 +133,8 @@ void SecurityIDRecorder::work_db() {
// Once a security has a key it is public so record it in the security database
std::shared_ptr<SecurityIDEntry> temp;
vector<std::shared_ptr<SecurityIDEntry>> new_entries;
// SPARK-1446 Need to try to add existing securities to the db in case we deleted them by hand
vector<std::shared_ptr<SecurityIDEntry>> existing_securities;
vector<std::shared_ptr<SecurityIDEntry>> defer;
vector<string> new_descriptors;
size_t count = 0;
@@ -150,6 +152,7 @@ void SecurityIDRecorder::work_db() {
if (key != invalid_security_key) {
temp->security.set_id(key);
temp->callback(temp->security);
existing_securities.push_back(move(temp));
}
else {
// always push in parallel
@@ -168,7 +171,7 @@ void SecurityIDRecorder::work_db() {
}
if (new_entries.size() > 0) {
if (!new_entries.empty()) {
sqlite3_exec_nofail(_self->db.get(), "BEGIN TRANSACTION");
for (size_t x = 0; x < new_entries.size(); ++x) {
@@ -179,15 +182,22 @@ void SecurityIDRecorder::work_db() {
}
sqlite3_exec_nofail(_self->db.get(), "COMMIT TRANSACTION");
}
// record the securities
// record the securities
if (!new_entries.empty() || !existing_securities.empty()) {
std::vector<Security*> save_these;
save_these.reserve(new_entries.size());
save_these.reserve(new_entries.size() + existing_securities.size());
for (const auto& e : new_entries) {
save_these.push_back(&e->security);
}
for (const auto& e : existing_securities) {
save_these.push_back(&e->security);
}
db::store_if_new(save_these);
}
if (!new_entries.empty()) {
for (size_t x = 0; x < new_entries.size(); ++x) {
Security& security = new_entries[x]->security;
new_entries[x]->callback(security);
-11
View File
@@ -1,11 +0,0 @@
#!/bin/bash
g++ -isystem include/externals/linux/include \
-I include \
-I include/spark \
-o example \
example.cpp \
-Wl,-rpath,lib \
-L lib \
-l spark
-15
View File
@@ -1,15 +0,0 @@
#include "spark/lib/logging/logging.h"
#include "spark/lib/utils/init_spark_lib.h"
#include "spark/lib/utils/bts_chrono.h"
int main()
{
using namespace bts;
utils::init_spark_lib();
LOG(md, Info, "Hello world");
sleep_for(5s);
utils::finit_spark_lib();
return 0;
}
+1 -1
View File
@@ -1,6 +1,6 @@
#!/bin/bash
g++ -isystem ../include/externals/linux/include \
g++ -isystem ../externals/include \
-I ../include \
-I ../include/spark \
-o example \
+26 -32
View File
@@ -5,44 +5,38 @@
#include "spark/lib/utils/PBUtils.h"
using namespace bts;
using namespace bts::md;
void produce()
{
md::MDProducer producer(co2::PLATFORM_SIM);
auto s = utils::pb::from_string<api::Security> (
"id: 16\n"
"symbol: \"ZF\"\n"
"exchange: VENUE_GLBX\n"
"contract_spec {\n"
"low_tick: 0.0078125\n"
"high_tick: 0.0078125\n"
"cash_per_point: 0.012799999999999999\n"
"price_multiplier: 1\n"
"}\n"
"future {\n"
"expiration_year: 2018\n"
"expiration_month: 9\n"
"expiration_day: 28\n"
"}\n"
"glbx {\n"
"exchange_id: 164760\n"
"security_desc: \"ZFU8\"\n"
"cfi_code: \"FFDXSX\"\n"
"cme_symbol: \"ZF\"\n"
"main_fraction: 32\n"
"sub_fraction: 4\n"
"price_display_format: 3\n"
"market_segment_id: 84\n"
"}\n"
);
// Create temporary security (on the stack)
md::FixedFutureSecurity fsec;
fsec.numeric_id = 12345; // Exchange ID
fsec.symbol("ZF");
fsec.exchange = api::VENUE_GLBX;
fsec.low_tick = 0.0078125;
fsec.high_tick = 0.0078125;
fsec.cash_per_point = 0.0128;
// display price is price * pow10(display_factor)
fsec.display_factor = 0;
fsec.expiration_year = 2018;
fsec.expiration_month = 9;
fsec.expiration_day = 28;
fsec.security_desc("ZFU8");
fsec.cfi_code("FFDXSX");
fsec.alt_symbol("ZF");
fsec.cme_main_fraction = 32;
fsec.cme_sub_fraction = 4;
fsec.cme_price_display_format = 3;
fsec.cme_market_segment_id = 84;
// create security and obtain handle so we can update it later
std::vector<md::MDProducerHandle> producer_handles;
md::with_security_like(s, [&s,&producer,&producer_handles](auto &fs) {
md::convert_security(s, fs, true);
producer_handles.push_back(producer.add_security(fs));
});
// Add the security to the producer (this copies fsec) and get a handle to update it
// This call is thread safe and may take a symbol specific lock internally
producer_handles.push_back(producer.add_security(fsec));
// initialized bid side book data
std::array<md::PriceSize, md::COCONUT_MAX_DEPTH> bids = {
@@ -72,7 +66,7 @@ void produce()
md::PriceSize::from_double<7> (10.0,100)
};
// update book
// Update book - this call does not use locks so should not be called concurrently
producer_handles[0].update_book(utils::TimeStamp::now(), bids, asks);
}
+4 -2
View File
@@ -9,7 +9,7 @@ mkdir -p $1/sdk
rm -rf $1/sdk/*
mkdir -p $1/sdk/include/spark
mkdir -p $1/sdk/include/externals/linux/
mkdir -p $1/sdk/externals/
# lib headers
(cd $2/.. && find lib -type f -name "*.h" -exec cp --parents \{\} $1/sdk/include/spark/ \;)
@@ -18,7 +18,9 @@ mkdir -p $1/sdk/include/externals/linux/
(cd $1/src && find lib -type f -name "*.h" -exec cp --parents \{\} $1/sdk/include/spark/ \;)
(cd $1/src && find lib -type f -name "*.cc" -exec cp --parents \{\} $1/sdk/include/spark/ \;)
ln -sf $2/../../externals/linux/include $1/sdk/include/externals/linux
ln -sf $2/../../externals/linux/include $1/sdk/externals/include
ln -sf $2/../../externals/linux/lib/Release $1/sdk/externals/lib
ln -sf $1/server $1/sdk/lib
mkdir $1/sdk/example
cp $2/example/* $1/sdk/example
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
if [ ! -f spark_sdk.tgz ]; then
wget http://jenkins/job/Spark_Server/lastSuccessfulBuild/artifact/spark_sdk_1909.tgz -O spark_sdk.tgz
fi
if [ ! -d spark_sdk ]; then
git clone git@bitbucket.org:bluetradesys/spark_sdk.git
else
(cd spark_sdk && git pull)
fi
rm -rf new_sdk
mkdir new_sdk
(cd new_sdk && tar -xvzf ../spark_sdk.tgz)
cp -R new_sdk/* spark_sdk
# http://jenkins/job/Spark_Server/lastSuccessfulBuild/artifact/spark_server_1909.tgz
# http://jenkins/job/Spark_Server/lastSuccessfulBuild/artifact/spark_sdk_1909.tgz
+1 -1
View File
@@ -1 +1 @@
set(sources cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/Help.cpp;cmds/Md.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/RunSim.cpp;cmds/Span.cpp;cmds/Test.cpp;cmds/TestCeloxica.cpp;cmds/Web.cpp;dspark/mirage.cpp;dspark/mirage/routing/Router.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/WebServer.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;main.cpp;md/platforms/celoxica/CXListener.cpp;md/platforms/celoxica/CXMain.cpp;md/platforms/celoxica/tests/cx_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/MDP3Utils.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;mercury/actors/Actor.cpp;mercury/broker/AsyncEventBroker.cpp;mercury/broker/CoreEventBroker.cpp;mercury/broker/IEventBroker.cpp;mercury/events/TimerEvent.cpp;mercury/mercury_utils/Executor.cpp;mercury/mercury_utils/IPollableActor.cpp;mercury/mercury_utils/mercury_common.cpp;mercury/synopsis/SynopsisBuilder.cpp;mercury/topics/ITopic.cpp;orderman/actors/AsyncFactory.cpp;orderman/actors/ExecutionGateway.cpp;orderman/actors/FillStore.cpp;orderman/actors/OrderStore.cpp;orderman/actors/SecuritySrc.cpp;orderman/actors/ServiceBridge.cpp;orderman/actors/order_manager/OrderBuilder.cpp;orderman/actors/order_manager/OrderManager.cpp;orderman/actors/order_manager/OrderServicesData.cpp;orderman/events/CancelRejectEvent.cpp;orderman/events/NewExecutionReportEvent.cpp;orderman/limiter/LimitStore.cpp;orderman/limiter/Limiter.cpp;orderman/limiter/ProductLimitNode.cpp;orderman/limiter/ProductLimitTree.cpp;orderman/limiter/SecurityLimitNode.cpp;orderman/limiter/SecurityLimitTree.cpp;orderman/limiter/tests/limit_tests.cpp;orderman/order_factory/OrderFactory.cpp;orderman/order_router/OrderRouter.cpp;orderman/orderman_utils/fix_order_codec.cpp;orderman/orders/IcebergOrder.cpp;orderman/orders/NativeOrder.cpp;orderman/orders/Order.cpp;orderman/orders/TimeBoxOrder.cpp;orderman/orders/book_algos/BookAlgo.cpp;orderman/orders/book_algos/JoinOrder.cpp;orderman/orders/book_algos/LeanOrder.cpp;orderman/orders/book_algos/TickOrder.cpp;orderman/orders/book_algos/TopOrder.cpp;orderman/orders/spreader_orders/SpreaderOrder.cpp;orderman/orders/spreader_orders/spreader/LegPropertyData.cpp;orderman/orders/spreader_orders/spreader/QuoteLegPriceQuantityState.cpp;orderman/orders/spreader_orders/spreader/SingleFillHedger.cpp;orderman/orders/spreader_orders/spreader/SingleLegQuoter.cpp;orderman/orders/spreader_orders/spreader/SpreaderBookkeepingData.cpp;orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.cpp;orderman/orders/spreader_orders/spreader/SpreaderLegData.cpp;orderman/orders/spreader_orders/spreader/SpreaderUtils.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderServices.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderPreActivationOrderServices.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.Line truncated
set(sources cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/Help.cpp;cmds/Md.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/RunSim.cpp;cmds/Span.cpp;cmds/Test.cpp;cmds/TestCeloxica.cpp;cmds/Web.cpp;dspark/mirage.cpp;dspark/mirage/routing/Router.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/WebServer.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;main.cpp;md/platforms/celoxica/CXListener.cpp;md/platforms/celoxica/CXMain.cpp;md/platforms/celoxica/tests/cx_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/MDP3Utils.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;mercury/actors/Actor.cpp;mercury/broker/AsyncEventBroker.cpp;mercury/broker/CoreEventBroker.cpp;mercury/broker/IEventBroker.cpp;mercury/events/TimerEvent.cpp;mercury/mercury_utils/Executor.cpp;mercury/mercury_utils/IPollableActor.cpp;mercury/mercury_utils/mercury_common.cpp;mercury/synopsis/SynopsisBuilder.cpp;mercury/topics/ITopic.cpp;orderman/actors/AsyncFactory.cpp;orderman/actors/ExecutionGateway.cpp;orderman/actors/FillStore.cpp;orderman/actors/OrderStore.cpp;orderman/actors/SecuritySrc.cpp;orderman/actors/ServiceBridge.cpp;orderman/actors/order_manager/OrderBuilder.cpp;orderman/actors/order_manager/OrderManager.cpp;orderman/actors/order_manager/OrderServicesData.cpp;orderman/events/CancelRejectEvent.cpp;orderman/events/NewExecutionReportEvent.cpp;orderman/limiter/LimitStore.cpp;orderman/limiter/Limiter.cpp;orderman/limiter/ProductLimitNode.cpp;orderman/limiter/ProductLimitTree.cpp;orderman/limiter/SecurityLimitNode.cpp;orderman/limiter/SecurityLimitTree.cpp;orderman/limiter/tests/limit_tests.cpp;orderman/order_factory/OrderFactory.cpp;orderman/order_router/OrderRouter.cpp;orderman/orderman_utils/fix_order_codec.cpp;orderman/orders/IcebergOrder.cpp;orderman/orders/NativeOrder.cpp;orderman/orders/Order.cpp;orderman/orders/TimeBoxOrder.cpp;orderman/orders/book_algos/BookAlgo.cpp;orderman/orders/book_algos/JoinOrder.cpp;orderman/orders/book_algos/LeanOrder.cpp;orderman/orders/book_algos/TickOrder.cpp;orderman/orders/book_algos/TopOrder.cpp;orderman/orders/spreader_orders/SpreaderOrder.cpp;orderman/orders/spreader_orders/spreader/LegPropertyData.cpp;orderman/orders/spreader_orders/spreader/QuoteLegPriceQuantityState.cpp;orderman/orders/spreader_orders/spreader/SingleFillHedger.cpp;orderman/orders/spreader_orders/spreader/SingleLegQuoter.cpp;orderman/orders/spreader_orders/spreader/SpreaderBookkeepingData.cpp;orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.cpp;orderman/orders/spreader_orders/spreader/SpreaderLegData.cpp;orderman/orders/spreader_orders/spreader/SpreaderUtils.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderServices.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderPreActivationOrderServices.cpp;orderman/orders/spreader_orders/spreader/hedger/UnhedgedDelta.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSet.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSetHistory.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteLegDriver.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp;ordermanLine truncated
@@ -54,15 +54,15 @@ TEST_CASE("JetFIX FIX Encoding","[jetfix_encoding]")
stream.close ();
auto str = stream.to_human_str ();
REQUIRE (str.compare (0,strlen ("8=FIX.4.2|9=000102|"), "8=FIX.4.2|9=000102|")==0);
REQUIRE (str.compare (0,strlen ("8=FIX.4.2|9=000092|"), "8=FIX.4.2|9=000092|")==0);
}
SECTION("checksum_is_correct")
{
char target [] =
"8=FIX.4.2\0019=000102\00135=i\00134=000000000\001369=000000000\001"
"8=FIX.4.2\0019=000092\00135=i\00134=000000000\001369=000000000\001"
"52=20150427-19:05:18.923\00149=O2TESTER\00156=BTS\00157=BTS\001"
"142=US,NC\00158=hello\001";
"58=hello\001";
uint32_t byte_sum = 0;
for (auto c : target)
@@ -74,7 +74,8 @@ TEST_CASE("JetFIX FIX Encoding","[jetfix_encoding]")
stream.close ();
// std::string human_target(target);
// std::replace(human_target.begin(), human_target.end(),'\001','|');
// REQUIRE(stream.to_human_str() == human_target);
// std::cout << human_target << "\n";
// std::cout << stream.to_human_str() << "\n";
auto chk = stream.msg_map ()[0].checksum;
REQUIRE (chk==byte_sum);
}
@@ -88,9 +89,9 @@ TEST_CASE("JetFIX FIX Encoding","[jetfix_encoding]")
stream.stamp (1,1000,"20150427-19:05:18.922");
std::string lit =
"8=FIX.4.2\0019=000102\00135=i\00134=000000002\001369=000001000\001"
"8=FIX.4.2\0019=000092\00135=i\00134=000000002\001369=000001000\001"
"52=20150427-19:05:18.922\00149=O2TESTER\00156=BTS\00157=BTS\001"
"142=US,NC\00158=hello\001";
"58=hello\001";
uint32_t lit_checksum = 0;
for (auto c : lit)
lit_checksum += c;
@@ -308,7 +308,6 @@ public:
double& out_new_price){
int64_t time_diff = ms_diff (now_time, order_time);
if (time_diff > time_based_forced_cross.time_in_ms_threshold()){
LOG(OrderMan, Info, "SpreaderUtils::post_hedge_time_based_forced_cross order_time: {} now_time: {} ms_time_diff: {} threshold: {}", order_time, now_time, time_diff, time_based_forced_cross.time_in_ms_threshold());
if (hedge_side == api::SIDE_BUY){
const md::PriceSize& opp_inside_price_size = book.side(api::Side::SIDE_SELL)[0];
if (opp_inside_price_size.size() > 0){
@@ -5,10 +5,9 @@ namespace bts {
namespace orderman {
QuoteDriverSetHistory::QuoteDriverSetHistory(size_t n_legs,
size_t cache_size,
double tick_size)
size_t cache_size,
double tick_size)
:
_n_legs(n_legs),
_cache_size(cache_size),
_tick_size(tick_size),
_quote_seq_no(0),
@@ -7,7 +7,8 @@ namespace orderman {
class QuoteDriverSetHistory{
private:
const size_t _n_legs, _cache_size;
// const size_t _n_legs; // THIS IS NOT USED
const size_t _cache_size;
const double _tick_size;
uint16_t _quote_seq_no;
std::vector<QuoteDriverSet> _driver_sets;
@@ -16,11 +17,11 @@ private:
const QuoteDriverSet* _find_driver_set(Price quote_price) const;
public:
QuoteDriverSetHistory(size_t n_legs,
size_t cache_size,
double tick_size);
size_t cache_size,
double tick_size);
void add(const std::vector<QuoteLegDriver>& drivers,
Price quote_price);
const QuoteLegDriver* find_driver(Price quote_price, size_t leg_index) const;
};
}}
}}
+1 -1
View File
@@ -1 +1 @@
set(sources ../../externals/linux/include/google/protobuf/descriptor.proto;../../externals/linux/include/google/protobuf/timestamp.proto;../lib/api/apicore.proto;../lib/api/apigateway.proto;../lib/api/apioptions.proto;../lib/api/services/AdminService.proto;../lib/api/services/ApiUnitTestService.proto;../lib/api/services/ErrorReportService.proto;../lib/api/services/HelloService.proto;../lib/api/services/MarketDataRelay.proto;../lib/api/services/OrderService.proto;../lib/api/services/OutOfProcessURLListener.proto;../lib/api/services/PersistenceService.proto;../lib/api/services/ShellDiagnosticService.proto;../lib/api/services/ShellLatencyService.proto;../lib/api/services/SyntheticSecurityService.proto;../lib/api/services/UserService.proto;../lib/domain_model/Security.proto;../lib/md/protos/co2.proto;../lib/sparkproto/SparkProtos.proto;api/build.sh;api/node_modules/cssstyle/scripts/run_tests.sh;api/node_modules/exit/test/fixtures/create-files.sh;api/node_modules/protobufjs/cli/node_modules/acorn-jsx/node_modules/acorn/bin/update_authors.sh;api/node_modules/watch/release.sh;api/quiet_build.sh;api/src/DynamicService.ts;api/src/ServiceContext.ts;api/src/bts_assert.ts;ui/src/Access.fs;ui/src/Accounts/ClipLimits.fs;ui/src/Accounts/ProductLimits.fs;ui/src/Accounts/SecurityLimits.fs;ui/src/Accounts/State.fs;ui/src/Accounts/Types.fs;ui/src/Accounts/View.fs;ui/src/App.fs;ui/src/Cmd.fs;ui/src/Controls/Button.fs;ui/src/Controls/DataGrid.fs;ui/src/Controls/Fields.fs;ui/src/Controls/Modal.fs;ui/src/Controls/ReactGrid.fs;ui/src/Controls/Table.fs;ui/src/Controls/nbsp.fs;ui/src/Global.fs;ui/src/Imports.fs;ui/src/Lens.fs;ui/src/Login/Login.fs;ui/src/Navbar/View.fs;ui/src/State.fs;ui/src/Types.fs;ui/src/Users/State.fs;ui/src/Users/Types.fs;ui/src/Users/View.fs;ui/src/Util/EnumUtils.fs;ui/src/Util/JSMap.fs)
set(sources ../../externals/linux/include/google/protobuf/descriptor.proto;../../externals/linux/include/google/protobuf/timestamp.proto;../lib/api/apicore.proto;../lib/api/apigateway.proto;../lib/api/apioptions.proto;../lib/api/services/AdminService.proto;../lib/api/services/ApiUnitTestService.proto;../lib/api/services/ErrorReportService.proto;../lib/api/services/HelloService.proto;../lib/api/services/MarketDataRelay.proto;../lib/api/services/OrderService.proto;../lib/api/services/OutOfProcessURLListener.proto;../lib/api/services/PersistenceService.proto;../lib/api/services/ShellDiagnosticService.proto;../lib/api/services/ShellLatencyService.proto;../lib/api/services/SyntheticSecurityService.proto;../lib/api/services/UserService.proto;../lib/domain_model/Security.proto;../lib/md/protos/co2.proto;../lib/sparkproto/SparkProtos.proto;api/build.sh;api/node_modules/cssstyle/scripts/run_tests.sh;api/node_modules/exit/test/fixtures/create-files.sh;api/node_modules/protobufjs/cli/node_modules/acorn-jsx/node_modules/acorn/bin/update_authors.sh;api/node_modules/watch/release.sh;api/quiet_build.sh;api/src/DynamicService.ts;api/src/ServiceContext.ts;api/src/bts_assert.ts;ui/src/Access.fs;ui/src/Accounts/ClipLimits.fs;ui/src/Accounts/ProductLimits.fs;ui/src/Accounts/SecurityLimits.fs;ui/src/Accounts/State.fs;ui/src/Accounts/Types.fs;ui/src/Accounts/View.fs;ui/src/App.fs;ui/src/Cmd.fs;ui/src/Controls/Button.fs;ui/src/Controls/DataGrid.fs;ui/src/Controls/Fields.fs;ui/src/Controls/Modal.fs;ui/src/Controls/ReactGrid.fs;ui/src/Controls/Table.fs;ui/src/Controls/nbsp.fs;ui/src/Global.fs;ui/src/Imports.fs;ui/src/Lens.fs;ui/src/Login/Login.fs;ui/src/Nav.fs;ui/src/State.fs;ui/src/Types.fs;ui/src/Users/State.fs;ui/src/Users/Types.fs;ui/src/Users/View.fs;ui/src/Util/EnumUtils.fs;ui/src/Util/JSMap.fs)
+3621 -1776
View File
File diff suppressed because it is too large. Load diff
+11 -11
View File
@@ -2,7 +2,7 @@
"name": "ui",
"version": "1.0.0",
"description": "Simple Fable App",
"repository": { },
"repository": {},
"scripts": {
"build": "webpack -p",
"start": "webpack-dev-server",
@@ -15,26 +15,26 @@
"babel-runtime": "^6.26.0",
"protobufjs": "^6.8.6",
"react": "^15.6.2",
"react-data-grid": "^4.0.7",
"react-data-grid-addons": "^4.0.7",
"react-data-grid": "^4.0.8",
"react-data-grid-addons": "^4.0.8",
"react-dom": "^15.6.2",
"remotedev": "^0.2.7",
"tslib": "~1.9.0"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"bulma": "^0.5.2",
"bulma": "^0.5.3",
"css-loader": "^0.28.7",
"fable-loader": "^1.1.2",
"fable-loader": "^1.1.6",
"fable-utils": "^1.0.6",
"loglevel": "^1.5.0",
"loglevel": "^1.6.1",
"node-sass": "^4.9.0",
"sass-loader": "^6.0.6",
"sass-loader": "^6.0.7",
"style-loader": "^0.18.2",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.8.2"
"webpack": "^3.12.0",
"webpack-dev-server": "^2.11.2"
}
}
+4
View File
@@ -0,0 +1,4 @@
/*! bulmaswatch v0.6.2 | MIT License */
@import "variables";
@import "../node_modules/bulma/bulma";
@import "overrides";
-87
View File
@@ -1,87 +0,0 @@
// Colors
$brand_primary: #0086bf
$primary: $brand_primary
$shell_gray: #f6f6f6
$table-background-color: $shell_gray
//$table-cell-border: 0
$table-row-hover-background-color: $shell_gray
$navbar-background-color: $brand_primary
$navbar-item-color: #fff
$navbar-item-hover-color: #ffffff
$navbar-item-hover-background-color: lighten($brand_primary, 5%)
$navbar-item-active-color: #333333
$navbar-item-active-background-color: $shell_gray
@import '../node_modules/bulma/bulma'
html
background-color: $shell_gray
.navbar-bg
background-color: $primary
.nav
background-color: $primary
color: #ffffff
.title
color: #ffffff
font-weight: 600
.tabs ul
//border: 0
.tabBox
border: 1px solid $border
border-width: 0 0 0 1px
border-image: linear-gradient(to bottom, $border, rgba(0, 0, 0, 0)) 1 100%
margin-top: -1.5rem
padding-top: 1.5rem
padding-left: 1.5rem
padding-bottom: 1.5rem
padding-right: 1.5rem
min-height: 30rem
.plus-margin-top
margin-top: 1em
input[type=text], input[type=password]
width: 20rem
input[type=text].login-input, input[type=password].login-input
width: 100%
.table-bordered
border: 1px solid $border
thead th
background-color: $brand_primary
color: $white
font-weight: normal
.btstable td
vertical-align: middle
table .fabutton
margin-top: 0.9ex
.no-border
border: 0
td
border: 0
th
border: 0
.selector-button
width: 100%
margin-top: 1ex
text-align: left
justify-content: left
.contrast-button
background-color: #ebebeb
border-color: #ccc
&:hover
background-color: #dbdbdb
.has-text-grey-mid
color: #999
+235
View File
@@ -0,0 +1,235 @@
@import 'bulmaswatch';
html
{
background-color: $shell_gray;
min-height: 100vh;
max-height: 100vh;
height: 100vh;
}
body {
min-height: 100vh;
max-height: 100vh;
height: 100vh;
height:100%;
}
.is-sidebar-menu {
padding: 2.5rem;
background: $grey-lighter;
border-right: 0.6px solid $border;
min-width: 12rem;
li {
a {
color: $grey-dark
}
}
}
.is-launcher-sidebar-menu {
padding: 0;
background: $primary;
max-width: 7rem;
.menu-list a.is-active {
background: lighten($primary, 30);
color: $black-ter;
}
li {
width: 100%;
a {
color: $white;
}
}
}
.launcher-item {
text-align:center;
width:100%;
a {
padding:1ex 1.5em;
}
}
.is-main-content {
padding:0;
height: 100vh;
}
.is-main-control-bar {
width:100%;
height:$tabs-height;
background:$grey-lighter;
overflow: hidden;
.is-light {
background:$grey-lighter;
border-right: 1px solid $grey-light;
&:hover {
background:$grey-light;
}
}
}
.is-danger-hover {
margin: 1rem 0;
&:hover {
background: $red;
color: $white;
}
}
.is-round {
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-moz-appearance: none;
-webkit-appearance: none;
background-color: transparent;
//color: $white;
border: none;
border-radius: 50%;
cursor: pointer;
display: inline-block;
flex-grow: 0;
flex-shrink: 0;
font-size: 14px;
height: 21px;
max-height: 21px;
max-width: 21px;
min-height: 21px;
min-width: 21px;
width: 21px;
line-height:14px;
outline: none;
position: relative;
vertical-align: middle;
text-align: center;
padding: 0.275em 0 0 0.07em;
padding: auto;
&:hover {
background-color: $shell_gray;
}
.icon {
&.is-small{
height:14px;
width:14px;
}
}
i {
font-weight: normal;
}
}
.is-tab-content {
$tab-content-left-margin: 3rem;
padding: 0.5rem 0.2rem 1.5rem $tab-content-left-margin;
height: calc(100% - #{$tabs-height} - #{$tabs-height} - 1.6rem);
overflow: auto;
input[type=text], input[type=password] {
max-width: 43rem;
}
.columns {
max-width:100%;
}
}
.has-background-primary {
background: $primary;
}
.columns {
&.is-fullheight {
min-height: 100vh;
max-height: 100vh;
height: 100vh;
margin:0;
padding:0;
display: flex;
flex-direction: row;
justify-content: stretch;
.column {
overflow-y: auto;
}
}
}
.has-text-grey-mid {
color: #999
}
.limits-container {
//max-width: 60rem;
}
.is-help-text {
max-width: 40em;
}
.bts-selector-table {
width: calc(100% - 5rem);
margin: 2.5rem 2.5rem 2.5rem 0;
background: $background;
td, th {
height:2.5rem;
vertical-align: middle;
}
.is-checkbox-cell {
width: 3rem;
}
}
.bts-data-table-container {
display:inline-block;
margin-bottom:2rem;
}
.bts-data-table {
background: $white;
border: 1px solid $grey-lighter;
td {
height:2.7rem;
overflow:hidden;
padding: 1px;
vertical-align: middle;
}
thead th {
padding: 0.4rem 2rem 0.4rem 0.625em;
background: $primary;
border: 0;
color:$white;
vertical-align: middle;
font-weight: normal;
}
tr {
&:hover {
background-color: $table-row-hover-background-color;
}
}
.control, .select {
width:100%;
height: 2.5rem;
}
select, input {
width:100%;
border-color: transparent;
height: 2.5rem;
background-color: transparent;
&:focus {
background-color: $white;
}
}
.is-checkbox-cell {
width: 3rem;
}
.delete {
margin:.6rem .4rem;
}
.table-buttons {
width:auto;
}
}
+197
View File
@@ -0,0 +1,197 @@
// Overrides
@import url(https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700);
@import 'tabs';
.button,
.control.has-icons-left .icon,
.control.has-icons-right .icon,
.input,
.pagination-ellipsis,
.pagination-link,
.pagination-next,
.pagination-previous,
.select,
.select select,
.textarea {
height: 2.6667em;
}
.button {
&.is-active,
&.is-focused,
&:active,
&:focus {
box-shadow: inset 1px 1px 4px rgba($grey-darker, 0.3);
}
@each $name,
$pair in $colors {
$color: nth($pair, 1);
$color-invert: nth($pair, 2);
&.is-#{$name} {
&.is-hovered,
&:hover {
background-color: darken($color, 10);
}
&.is-active,
&.is-focused,
&:active,
&:focus {
box-shadow: inset 1px 0 3px rgba($grey-darker, 0.3);
background-color: darken($color, 10);
}
}
}
}
.input,
.textarea {
box-shadow: none;
}
.box,
.card {
box-shadow: 0 0 0 1px $border;
}
.notification {
@each $name,
$pair in $colors {
$color: nth($pair, 1);
$color-invert: nth($pair, 2);
&.is-#{$name} {
a:not(.button) {
color: $color-invert;
text-decoration: underline;
}
}
}
}
.progress {
height: $size-small;
}
.progress,
.tag {
border-radius: $radius;
}
.navbar:not(.is-transparent) {
background-color: $black-ter;
.navbar-menu {
background-color: $black-ter;
}
.navbar-item,
.navbar-link {
color: $white;
&.has-dropdown:hover .navbar-link,
&:hover {
background-color: rgba($white, 0.05);
}
&.is-active,
&:active {
background-color: rgba($black-ter, 0.05);
color: $primary;
}
}
.navbar-burger:hover {
background-color: rgba($black-ter, 0.05);
}
.navbar-link::after {
border-color: $white;
}
@include desktop {
.navbar-dropdown .navbar-item {
color: $grey-dark;
&:hover {
background-color: rgba($black-ter, 0.05);
}
&.is-active,
&:active {
color: $primary;
}
strong {
color: $grey;
}
}
}
.navbar-burger {
span {
background-color: $white;
}
}
strong {
color: $white-ter;
}
@each $name,
$pair in $colors {
$color: nth($pair, 1);
$color-invert: nth($pair, 2);
&.is-#{$name} {
background-color: $color;
.navbar-menu {
background-color: $color;
}
.navbar-item,
.navbar-link {
@media (max-width: $desktop) {
color: $color-invert;
}
&.is-active,
&:active {
color: $color-invert;
}
}
.navbar-burger {
&:hover {
background-color: darken($color, 5);
}
span {
background-color: $color-invert;
}
}
}
}
}
.hero {
// Colors
.navbar:not(.is-transparent) {
background-color: $black-ter;
}
@each $name,
$pair in $colors {
$color: nth($pair, 1);
$color-invert: nth($pair, 2);
&.is-#{$name} {
.navbar {
background: none;
}
.navbar-item,
.navbar-link {
color: $color-invert;
&.is-active,
&:hover {
background-color: darken($color, 10);
color: $color-invert;
}
&:after {
border-color: $color-invert;
}
}
.navbar-menu {
background-color: $color;
}
.navbar-burger {
span {
background-color: $color-invert;
}
}
@include desktop {
.navbar-dropdown a.navbar-item {
color: $grey-dark;
}
}
}
}
}
+198
View File
@@ -0,0 +1,198 @@
.tabs {
@include block;
@include overflow-touch;
@include unselectable;
align-items: stretch;
display: flex;
font-size: $size-normal;
justify-content: space-between;
overflow: hidden;
overflow-x: auto;
white-space: nowrap;
height: $tabs-height;
border-bottom-color: $tabs-border-bottom-color;
border-bottom-style: $tabs-border-bottom-style;
border-bottom-width: $tabs-border-bottom-width;
a {
align-items: center;
border-bottom-color: $tabs-border-bottom-color;
border-bottom-style: $tabs-border-bottom-style;
border-bottom-width: $tabs-border-bottom-width;
color: $tabs-link-color;
display: flex;
justify-content: center;
margin-bottom: 0;//-#{$tabs-border-bottom-width};
padding: $tabs-link-padding;
vertical-align: top;
&:hover {
border-bottom-color: $tabs-link-hover-border-bottom-color;
color: $tabs-link-hover-color;
}
}
li {
display: block;
&.is-active {
a {
border-bottom-color: $tabs-link-active-border-bottom-color;
color: $tabs-link-active-color;
}
}
}
ul {
align-items: center;
display: flex;
flex-grow: 1;
flex-shrink: 0;
justify-content: flex-start;
&.is-left {
padding-right: 0.75em;
}
&.is-center {
flex: none;
justify-content: center;
padding-left: 0.75em;
padding-right: 0.75em;
}
&.is-right {
justify-content: flex-end;
padding-left: 0.75em;
}
}
.icon {
&:first-child {
margin-right: 0.5em;
}
&:last-child {
margin-left: 0.5em;
}
}
// Alignment
&.is-centered {
ul {
justify-content: center;
}
}
&.is-right {
ul {
justify-content: flex-end;
}
}
// Styles
&.is-boxed {
a {
border: 1px solid $border-dark;
border-width: 0 0.6px 0 0;
border-radius: $tabs-boxed-link-radius $tabs-boxed-link-radius 0 0;
background-color: $tabs-boxed-link-background-background-color;
&:hover {
background-color: $tabs-boxed-link-hover-background-color;
//border-bottom-color: $tabs-boxed-link-hover-border-bottom-color;
}
}
li {
&.is-active {
a {
background-color: $tabs-boxed-link-active-background-color;
border-color: $border-dark;
//border-bottom-color: $tabs-boxed-link-active-border-bottom-color !important;
}
}
}
}
&.is-fullwidth {
li {
flex-grow: 1;
flex-shrink: 0;
}
}
&.is-toggle {
a {
border-color: $tabs-toggle-link-border-color;
border-style: $tabs-toggle-link-border-style;
border-width: $tabs-toggle-link-border-width;
margin-bottom: 0;
position: relative;
&:hover {
background-color: $tabs-toggle-link-hover-background-color;
border-color: $tabs-toggle-link-hover-border-color;
z-index: 2;
}
}
li {
& + li {
margin-left: -#{$tabs-toggle-link-border-width};
}
&:first-child a {
border-radius: $tabs-toggle-link-radius 0 0 $tabs-toggle-link-radius;
}
&:last-child a {
border-radius: 0 $tabs-toggle-link-radius $tabs-toggle-link-radius 0;
}
&.is-active {
a {
background-color: $tabs-toggle-link-active-background-color;
border-color: $tabs-toggle-link-active-border-color;
color: $tabs-toggle-link-active-color;
z-index: 1;
}
}
}
ul {
border-bottom: none;
}
&.is-toggle-rounded {
li {
&:first-child a {
border-bottom-left-radius: $radius-rounded;
border-top-left-radius: $radius-rounded;
padding-left: 1.25em;
}
&:last-child a {
border-bottom-right-radius: $radius-rounded;
border-top-right-radius: $radius-rounded;
padding-right: 1.25em;
}
}
}
}
// Sizes
&.is-small {
font-size: $size-small;
}
&.is-medium {
font-size: $size-medium;
}
&.is-large {
font-size: $size-large;
}
}
+87
View File
@@ -0,0 +1,87 @@
////////////////////////////////////////////////
// COSMO
////////////////////////////////////////////////
$white: #fff;
$grey-light: hsl(0, 0%, 71%);
$grey-lighter: hsl(0, 0%, 86%);
$grey-darker: #333;
$black-ter: #222;
$orange: #FF7518;
$yellow: #f4db00;
$green: #3FB618;
$turquoise: #00ABA9;
$blue: #1FAEFF;
$purple: #AA40FF;
$red: #FF2E12;
$brand_primary: #0086bf;
$shell_primary: #4169AA;
$shell_gray: #f6f6f6;
$primary: $shell_primary !default;
$primary-dark: darken($shell_primary, 20%);
$warning: $orange;
$info: $purple;
$orange-invert: #fff;
$warning-invert: $orange-invert;
$text: #222;
$text-strong: hsl(0, 0%, 21%);
$background: $shell_gray;
$border: hsl(0, 0%, 66%);
$border-dark: $text;
$border-hover: hsl(0, 0%, 71%);
$family-sans-serif: "Source Sans Pro", "Segoe UI", Calibri, Candara, Arial, sans-serif;
$body-size: 13px;
$body-line-height: 1.6;
$radius: 0;
$radius-small: 0;
$radius-large: 0;
$radius-rounded: 0;
$link: $primary;
$link-invert: $white;
$link-hover: $primary-dark;
$link-focus: $primary-dark;
$link-active: $primary-dark;
$button-hover-color: $grey-darker;
$button-focus: $black-ter;
$button-active-color: $black-ter;
//$table-background-color: $shell_gray;
//$table-cell-border: 0
$table-row-hover-background-color: #f2f7ff;
$table-striped-row-even-hover-background-color: $table-row-hover-background-color;
$table-striped-row-even-background-color: #e6efff;
$tabs-height: 2.5rem;
$tabs-border-bottom-color: $border;
$tabs-border-bottom-width: 1px;
$tabs-link-color: $text;
$tabs-link-hover-border-bottom-color: $text-strong;
$tabs-link-hover-color: $text-strong;
$tabs-link-active-border-bottom-color: $link;
$tabs-link-active-color: $link;
$tabs-link-padding: 0.5em 1em;
$tabs-boxed-link-radius: $radius;
$tabs-boxed-link-background-background-color: hsl(0, 0%, 85%);
$tabs-boxed-link-hover-background-color: #dcecfc;
$tabs-boxed-link-hover-border-bottom-color: $border;
$tabs-boxed-link-active-background-color: $white;
$tabs-boxed-link-active-border-color: $border;
$tabs-boxed-link-active-border-bottom-color: transparent;
$tabs-toggle-link-border-color: $border;
$tabs-toggle-link-border-width: 1px;
$tabs-toggle-link-hover-background-color: $background;
$tabs-toggle-link-hover-border-color: $border-hover;
$tabs-toggle-link-active-background-color: $link;
$tabs-toggle-link-active-border-color: $link;
$tabs-toggle-link-active-color: $link-invert;
+10 -10
View File
@@ -19,16 +19,16 @@ module Lens =
module SecurityScope =
let exchangeString ex =
match ex with
| Venue.UNSET -> "*"
let exchangeString ex =
match ex with
| Venue.UNSET -> "*"
| x -> unbox x
let securityTypeString st =
match st with
| SecurityType.UNSET -> "*"
| x -> unbox x
let create exchange securityType symbol id =
{ exchange = exchange
securityType = securityType
@@ -44,25 +44,25 @@ module SecurityScope =
module Accounts =
let empty : BTSAccount =
let empty : BTSAccount =
{
isPresent = true
id = 0u
parentAccountId = 0u
name = "New Account"
name = ""
description = ""
isActive = false
productPositionLimits = [||]
securityPositionLimits = [||]
marginLimit =
marginLimit =
{ enforceMargin = false
cashBalance = 0.
leverageFactorPercentage = 0. }
securityClipLimits = { limit = [||] }
// Array.empty<int> gets compiled to Int32Array instead of []
connections = { exchangeConnections = unbox Array.empty<obj>; exchangeConnectionNames = Array.empty}
exchangeAccountData =
{ cmeAccountData =
exchangeAccountData =
{ cmeAccountData =
{ cti = CTICode.CtiCodeUndefined
origin = CustomerOrFirm.CustomerOrFirmCustomer
takeupMemberCode = ""
@@ -76,7 +76,7 @@ module Accounts =
clientId = ""
miscTags = JSMap.empty<string>
}
iceAccountData =
iceAccountData =
{ nybitHouse=""
wceHouse=0
clearingAccountOverride=""
+25 -24
View File
@@ -7,8 +7,10 @@ open Fable.PowerPack.PromiseImpl
open Fable.Import
open bts.co2
let isNewAccount (account:BTSAccount) =
account.id = 0u
let isNewAccount (account:BTSAccount) =
account.id = 0u && account.isPresent
let currentAccountIsDefault (account:BTSAccount) = (account.id = 0u)
let init (context:ServiceContext.ServiceContext) =
let admin = AdminService.Create context ""
@@ -18,7 +20,7 @@ let init (context:ServiceContext.ServiceContext) =
adminData = None
mdRelay = mdr
mdRelayProductData = [||]
mdRelayExpNameData = Array.empty<ExpirationNameList>
mdRelayExpNameData = Array.empty<ExpirationNameList>
scratch = emptyAccount
previousScratch = emptyAccount
AllValue = "*"
@@ -27,8 +29,8 @@ let init (context:ServiceContext.ServiceContext) =
let existingSelection (scratch:BTSAccount) (previousScratch:BTSAccount) (data:AdminData) =
List.choose id [
data.accounts |> Array.tryFind (fun a -> a.name = scratch.name)
data.accounts |> Array.tryFind (fun a -> a.name = previousScratch.name)
data.accounts |> Array.tryFind (fun a -> a.id = scratch.id || (scratch.id = 0u && a.name = scratch.name))
data.accounts |> Array.tryFind (fun a -> a.id = previousScratch.id || (scratch.id = 0u && a.name = previousScratch.name))
data.accounts |> Array.tryHead
Some emptyAccount]
|> List.head
@@ -67,7 +69,7 @@ let saveAccount (admin:IAdminService) (account:BTSAccount) = promise {
let createAccount (admin:IAdminService) (account:BTSAccount) = promise {
let args = { parentAccountId = 0u; accountName = account.name; description = account.description }
let! result = admin.create_account args
if result.isSuccess then
if result.isSuccess then
return! saveAccount admin { account with id = result.newId }
else
return ErrorOccured (sprintf "Error creating account: %s" result.errorText)
@@ -97,26 +99,25 @@ let erase (arr:'a[]) i =
let right = arr.[1+i..]
Array.concat [left;right]
let update msg (model:Model) : Model * Cmd<Msg> =
let update msg (model:Model) : Model * Cmd<Msg> =
match msg with
| UpdateAdminData data ->
| UpdateAdminData data ->
let presentAccounts = data.accounts |> Array.filter (fun a -> a.isPresent) |> Array.sortBy (fun a -> a.name.ToLower())
let data = { data with accounts = presentAccounts }
{ model with adminData = Some data }
|> preserveSelection data, Cmd.ofExistingPromise (requestProducts model.mdRelay) id (box>>ErrorOccured)
| NoAdminData msg ->
| NoAdminData msg ->
Global.alert Global.Info msg
model, Cmd.Empty
| SelectAccount account ->
// When an account is selected 'scratch' account is discarded
| SelectAccount account ->
{ model with previousScratch = model.scratch; scratch = account }, Cmd.Empty
| DeleteAccount account ->
| DeleteAccount account ->
match Fable.Import.Browser.window.confirm (sprintf "Are you sure you want to delete '%s'" account.name) with
| true -> model, Cmd.ofExistingPromise (deleteAccount model.admin account) id (box>>ErrorOccured)
| false -> model, Cmd.Empty
| AddAccount ->
| AddAccount ->
// Create a new scratch account. Send to server after user has filled in details
{ model with previousScratch = model.scratch; scratch = emptyAccount }, Cmd.ofMsg <| SelectTab General
{ model with previousScratch = model.scratch; scratch = { emptyAccount with name = "New Account" } }, Cmd.ofMsg <| SelectTab General
| SaveScratch ->
match isNewAccount model.scratch with
| true -> model, Cmd.ofExistingPromise (createAccount model.admin model.scratch) id (box>>ErrorOccured)
@@ -125,23 +126,23 @@ let update msg (model:Model) : Model * Cmd<Msg> =
Global.alert Global.Error (string msg)
Browser.console.log msg
model,Cmd.Empty
| SelectTab tab ->
| SelectTab tab ->
{ model with tab = tab }, Cmd.Empty
| Update field ->
{ model with scratch = applyUpdate model.scratch field }, Cmd.Empty
| ClipLimits limits ->
| ClipLimits limits ->
{ model with scratch = { model.scratch with securityClipLimits = { limit = limits } } }, Cmd.Empty
| DeleteClipLimit i ->
let limits = erase model.scratch.securityClipLimits.limit i
{ model with scratch = { model.scratch with securityClipLimits = { limit = limits } } }, Cmd.Empty
| ProductLimits limits ->
| ProductLimits limits ->
{ model with scratch = { model.scratch with productPositionLimits = limits } }, Cmd.Empty
| DeleteProductLimit i ->
| DeleteProductLimit i ->
let limits = erase model.scratch.productPositionLimits i
{ model with scratch = { model.scratch with productPositionLimits = limits } }, Cmd.Empty
| SecurityLimits limits ->
| SecurityLimits limits ->
{ model with scratch = { model.scratch with securityPositionLimits = limits } }, Cmd.Empty
| DeleteSecurityLimit i ->
| DeleteSecurityLimit i ->
let limits = erase model.scratch.securityPositionLimits i
{ model with scratch = { model.scratch with securityPositionLimits = limits } }, Cmd.Empty
| AddConnection conId ->
@@ -162,11 +163,11 @@ let update msg (model:Model) : Model * Cmd<Msg> =
let newCme = applyCMEUpdate model.scratch.exchangeAccountData.cmeAccountData field
let scratch = { model.scratch with exchangeAccountData = { cmeAccountData = newCme; iceAccountData = model.scratch.exchangeAccountData.iceAccountData } }
{ model with scratch = scratch }, Cmd.Empty
| RequestProducts ->
| RequestProducts ->
model, Cmd.ofExistingPromise (requestProducts model.mdRelay) id (box>>ErrorOccured)
| UpdateProducts data ->
| UpdateProducts data ->
{ model with mdRelayProductData = data}, Cmd.ofExistingPromise (requestExpNames model.mdRelay) id (box>>ErrorOccured)
| RequestExpirationNames ->
| RequestExpirationNames ->
model, Cmd.ofExistingPromise (requestExpNames model.mdRelay) id (box>>ErrorOccured)
| UpdateExpirationNames (data:ExpirationNameList[]) ->
| UpdateExpirationNames (data:ExpirationNameList[]) ->
{ model with mdRelayExpNameData = data }, Cmd.Empty
+2 -3
View File
@@ -1,7 +1,6 @@
module Accounts.Types
open bts.api.admin
open Fable.Core
open bts.api
open bts.api.orderman
open JSMap
@@ -9,8 +8,8 @@ open bts.co2
type Tab =
| General
| ClipLimitsTab
| PositionLimitsTab
//| ClipLimitsTab
| LimitsTab
| CreditLimitsTab
| ExchangeSettingsTab
| ConnectionsTab
+274 -206
View File
@@ -15,8 +15,8 @@ open bts.co2
let selectedAccount model =
match model.adminData with
| Some data ->
data.accounts |>
| Some data ->
data.accounts |>
Array.tryFind (fun a -> a.id = model.scratch.id)
| None -> None
@@ -38,7 +38,7 @@ let mappedDataGridWithAddDelete<'a,'r> title (descriptor:MappedDataGridDescripto
let addRow _ = Array.append rows [| descriptor.emptyRow |] |> dispatch
// Why can't `erase` have the same signature as dispatch?
// Because the react Column is the one invoking erase and it doesn't really understand equality
// so when rows is updated this column probably *won't be* so it **cannot** close over rows
// so when rows is updated this column probably *won't be* so it **cannot** close over rows
// If it closes over rows the grid will reset to the first visible state (when the tab was made visible)
let deleteColumn = ReactGrid.buttonColumn erase "" "times" (box rows)
let descriptor' = { descriptor with columns = Array.append [| deleteColumn |] descriptor.columns }
@@ -46,7 +46,7 @@ let mappedDataGridWithAddDelete<'a,'r> title (descriptor:MappedDataGridDescripto
h5 [ClassName "title is-5"] [ str title ]
mappedDataGrid descriptor' props rows dispatch
div [ClassName "level"] [
div [ClassName "level-left"] []
div [ClassName "level-left"] []
div [ClassName "level-right"] [
div [ClassName "level-item"] [
Button.addButton Button.Enabled addRow
@@ -57,17 +57,22 @@ let mappedDataGridWithAddDelete<'a,'r> title (descriptor:MappedDataGridDescripto
*)
//
// General
//
let generalView model dispatch =
//
let generalView model dispatch =
let account = model.scratch
let revertFun =
let remButton =
match selectedAccount model with
| None -> Button.button "Remove Account" "is-danger-hover" "times" Disabled ignore
| Some acc -> Button.button "Remove Account" "is-danger-hover" "times" Enabled (fun _ -> dispatch <| DeleteAccount acc)
let revertFun =
match model.adminData with
| Some data -> fun _ -> (dispatch <| SelectAccount (State.existingSelection model.scratch model.previousScratch data))
| None -> fun _ -> (dispatch <| SelectAccount emptyAccount)
let modal = Modal.showCreate
"Create Account"
let modal = Modal.showCreate
"Create Account"
(div [] [
Fields.text "Name" account.name [] (AccountName >> Update >> dispatch)
Fields.text "Description" account.description [] (Description >> Update >> dispatch)
@@ -75,20 +80,21 @@ let generalView model dispatch =
])
(fun _ -> dispatch SaveScratch)
revertFun
div [] [
p [ Style [FontWeight "Bold"] ] [ str ("ID: " + (string account.id))]
br []
Fields.text "Name" account.name [] (AccountName >> Update >> dispatch)
Fields.text "Description" account.description [] (Description >> Update >> dispatch)
Fields.checkbox "Active" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
remButton
(if State.isNewAccount account then modal else span[][])
]
let clipLimitsView model dispatch =
let headerRow:TableControl.row =
let clipLimitsView model dispatch =
let headerRow:TableControl.row =
{
cells =
cells =
[
TableControl.Cell (str "")
TableControl.Cell (str "Exchange")
@@ -101,25 +107,25 @@ let clipLimitsView model dispatch =
header = None
}
let symbolArray = [|
[| model.AllValueDisplay |];
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|]
let symbolArray = [|
[| model.AllValueDisplay |];
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|]
|> Array.concat
|> Array.distinct
let getSecurityMap (limit:AccountSecurityClipLimitUnit) =
let getSecurityMap (limit:AccountSecurityClipLimitUnit) =
let allOption = {
product = {
exchange = bts.api.Venue.UNSET
``type`` = bts.api.SecurityType.UNSET
symbol = model.AllValueDisplay
};
names = (JSMap.add<string> "0" model.AllValueDisplay JSMap.empty<string>)
};
names = (JSMap.add<string> "0" model.AllValueDisplay JSMap.empty<string>)
}:ExpirationNameList
Array.concat [ [| allOption |]; model.mdRelayExpNameData]
|> Array.filter (fun (x:bts.co2.ExpirationNameList) -> (
|> Array.filter (fun (x:bts.co2.ExpirationNameList) -> (
((x.product.exchange = limit.security.exchange) || (x.product.exchange = bts.api.Venue.UNSET))
&& ((x.product.``type`` = limit.security.securityType) || (x.product.``type`` = bts.api.SecurityType.UNSET))
&& ((x.product.symbol = limit.security.securitySymbol) || (x.product.symbol = model.AllValueDisplay))
@@ -127,7 +133,7 @@ let clipLimitsView model dispatch =
)
|> Seq.map (fun x -> x.names ) |> JSMap.concat
let modifyRow (oldRow:AccountSecurityClipLimitUnit) (newRow:AccountSecurityClipLimitUnit) =
let modifyRow (oldRow:AccountSecurityClipLimitUnit) (newRow:AccountSecurityClipLimitUnit) =
let i = Array.findIndex (fun l -> oldRow = l) model.scratch.securityClipLimits.limit
let left = Array.append (model.scratch.securityClipLimits.limit.[..i-1]) [| newRow |]
let right = model.scratch.securityClipLimits.limit.[1+i..]
@@ -135,12 +141,12 @@ let clipLimitsView model dispatch =
let changeVenue (oldRow:AccountSecurityClipLimitUnit) (value:string) =
let venueValue = EnumUtils.fromHuman<bts.api.Venue> venues value
let newRow = { oldRow with security = { oldRow.security with exchange = venueValue } }
let newRow = { oldRow with security = { oldRow.security with exchange = venueValue } }
modifyRow oldRow newRow
let changeType (oldRow:AccountSecurityClipLimitUnit) (value:string) =
let typeValue = EnumUtils.fromHuman<bts.api.SecurityType> securityTypes value
let newRow = { oldRow with security = { oldRow.security with securityType = typeValue } }
let newRow = { oldRow with security = { oldRow.security with securityType = typeValue } }
modifyRow oldRow newRow
let changeSymbol (oldRow:AccountSecurityClipLimitUnit) (value:string) =
@@ -155,43 +161,43 @@ let clipLimitsView model dispatch =
let changeClipSize (oldRow:AccountSecurityClipLimitUnit) (value:string) =
modifyRow oldRow { oldRow with clipSize = (uint32 value) }
let rws:TableControl.row list =
let rws:TableControl.row list =
[ for limit in model.scratch.securityClipLimits.limit do yield {
cells =
cells =
[
TableControl.Cell (Button.removeButton Button.Enabled (fun _ -> (Array.findIndex (fun l -> limit = l) model.scratch.securityClipLimits.limit) |> DeleteClipLimit |> dispatch))
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.Venue> false venues limit.security.exchange)
(EnumUtils.allToHuman<bts.api.Venue> false venues)
[]
TableControl.controlCell (Button.deleteButton Button.Enabled (fun _ -> (Array.findIndex (fun l -> limit = l) model.scratch.securityClipLimits.limit) |> DeleteClipLimit |> dispatch))
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.Venue> false venues limit.security.exchange)
(EnumUtils.allToHuman<bts.api.Venue> false venues)
[Class ""]
((changeVenue limit) >> ClipLimits >> dispatch)
)
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.SecurityType> false securityTypes limit.security.securityType)
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.SecurityType> false securityTypes limit.security.securityType)
(EnumUtils.allToHuman<bts.api.SecurityType> false (Array.filter (fun a -> a <> bts.api.SecurityType.SYNTHETIC) securityTypes))
[]
[]
((changeType limit) >> ClipLimits >> dispatch)
)
TableControl.Cell (Fields.enumSelect<string>
""
TableControl.Cell (Fields.enumSelect<string>
""
limit.security.securitySymbol
symbolArray
[]
symbolArray
[]
((changeSymbol limit) >> ClipLimits >> dispatch)
)
TableControl.Cell (Fields.mapSelect
""
(JSMap.toMap (getSecurityMap limit))
TableControl.Cell (Fields.mapSelect
""
(JSMap.toMap (getSecurityMap limit))
None
(Some (sprintf "%i" limit.security.securityId))
((changeSecurityId limit) >> ClipLimits >> dispatch)
)
TableControl.Cell (Fields.text
""
(sprintf "%i" limit.clipSize)
[ Style [Width "10em"]]
TableControl.Cell (Fields.text
""
(sprintf "%i" limit.clipSize)
[ ]
((changeClipSize limit) >> ClipLimits >> dispatch)
)
]
@@ -207,20 +213,18 @@ let clipLimitsView model dispatch =
let addRow _ = Array.append model.scratch.securityClipLimits.limit [| emptyLimit |] |> (ClipLimits >> dispatch)
div []
[
div [ ClassName "columns" ][
div [ ClassName "column is-size-7 has-text-grey-mid" ]
div [ ClassName "columns" ][
h1 [ ClassName "is-size-3 column is-narrow" ][str "Clip Limits" ]
div [ ClassName "column is-size-7 has-text-grey-mid is-help-text"; ]
[str "Clip limits can be set for one security, for all securities in a product (by selecting \"All\" for securities), or for all products within a security type (by selecting \"All\" for both symbol and security)"]
div [ ClassName "column" ][]
]
TableControl.createTableWithStyle (Some headerRow) rws "table-bordered" [Width "100%"]
span [ClassName "is-pulled-right"] [ Button.button "Add" "contrast-button" "plus" Button.Enabled addRow ]
span [ClassName "is-clearfix"][]
TableControl.createDataTable (Some headerRow) rws (Button.button "Add" "" "plus" Button.Enabled addRow)
]
let productLimits model dispatch =
let headerRow:TableControl.row =
let headerRow:TableControl.row =
{
cells =
cells =
[
TableControl.Cell (str "")
TableControl.Cell (str "Exchange")
@@ -233,27 +237,27 @@ let productLimits model dispatch =
header = None
}
let symbolArray = [|
[| model.AllValueDisplay |];
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|]
let symbolArray = [|
[| model.AllValueDisplay |];
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|]
|> Array.concat
|> Array.distinct
let modifyRow (oldRow:AccountProductPositionLimitUnit) (newRow:AccountProductPositionLimitUnit) =
let modifyRow (oldRow:AccountProductPositionLimitUnit) (newRow:AccountProductPositionLimitUnit) =
let i = Array.findIndex (fun l -> oldRow = l) model.scratch.productPositionLimits
let left = Array.append (model.scratch.productPositionLimits.[..i-1]) [| newRow |]
let right = model.scratch.productPositionLimits.[1+i..]
Array.concat [left; right]
let changeVenue (oldRow:AccountProductPositionLimitUnit) (value:string) =
let venueValue = EnumUtils.fromHuman<bts.api.Venue> venues value
let newRow = { oldRow with product = { oldRow.product with exchange = venueValue } }
let newRow = { oldRow with product = { oldRow.product with exchange = venueValue } }
modifyRow oldRow newRow
let changeType (oldRow:AccountProductPositionLimitUnit) (value:string) =
let typeValue = EnumUtils.fromHuman<bts.api.SecurityType> securityTypes value
let newRow = { oldRow with product = { oldRow.product with securityType = typeValue } }
let newRow = { oldRow with product = { oldRow.product with securityType = typeValue } }
modifyRow oldRow newRow
let changeSymbol (oldRow:AccountProductPositionLimitUnit) (value:string) =
@@ -268,42 +272,42 @@ let productLimits model dispatch =
let changeShortPositionLimit (oldRow:AccountProductPositionLimitUnit) (value:string) =
modifyRow oldRow { oldRow with shortPositionLimit = (uint32 value) }
let rws:TableControl.row list =
let rws:TableControl.row list =
[ for limit in model.scratch.productPositionLimits do yield {
cells =
cells =
[
TableControl.Cell (Button.removeButton Button.Enabled (fun _ -> (Array.findIndex (fun l -> limit = l) model.scratch.productPositionLimits) |> DeleteProductLimit |> dispatch))
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.Venue> false venues limit.product.exchange)
(EnumUtils.allToHuman<bts.api.Venue> false venues)
[]
TableControl.Cell (Button.deleteButton Button.Enabled (fun _ -> (Array.findIndex (fun l -> limit = l) model.scratch.productPositionLimits) |> DeleteProductLimit |> dispatch))
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.Venue> false venues limit.product.exchange)
(EnumUtils.allToHuman<bts.api.Venue> false venues)
[]
((changeVenue limit) >> ProductLimits >> dispatch)
)
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.SecurityType> false securityTypes limit.product.securityType)
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.SecurityType> false securityTypes limit.product.securityType)
(EnumUtils.allToHuman<bts.api.SecurityType> false (Array.filter (fun a -> a <> bts.api.SecurityType.SYNTHETIC) securityTypes))
[]
[]
((changeType limit) >> ProductLimits >> dispatch)
)
TableControl.Cell (Fields.enumSelect<string>
""
TableControl.Cell (Fields.enumSelect<string>
""
limit.product.securitySymbol
symbolArray
[]
[]
((changeSymbol limit) >> ProductLimits >> dispatch)
)
TableControl.Cell (Fields.text
""
(sprintf "%i" limit.longPositionLimit)
[ Style [Width "10em"]]
TableControl.Cell (Fields.text
""
(sprintf "%i" limit.longPositionLimit)
[ ]
((changeLongPositionLimit limit) >> ProductLimits >> dispatch)
)
TableControl.Cell (Fields.text
""
(sprintf "%i" limit.shortPositionLimit)
[ Style [Width "10em"]]
TableControl.Cell (Fields.text
""
(sprintf "%i" limit.shortPositionLimit)
[ ]
((changeShortPositionLimit limit) >> ProductLimits >> dispatch)
)
]
@@ -325,22 +329,20 @@ let productLimits model dispatch =
let addRow _ = Array.append model.scratch.productPositionLimits [| emptyLimit |] |> (ProductLimits >> dispatch)
div []
[
div [ ClassName "columns" ][
h1 [ ClassName "is-size-4 column is-narrow" ][str "Product Limits" ]
div [ ClassName "column is-size-7 has-text-grey-mid" ]
div [ ClassName "columns" ][
h1 [ ClassName "is-size-3 column is-narrow" ][str "Product Limits" ]
div [ ClassName "column is-size-7 has-text-grey-mid is-help-text" ]
[str "This limits the net position for a product (i.e. accumulated position over all securities belonging to a product). This can be set for one product, or for all products within a security type by selecting \"All\" for symbol"]
]
TableControl.createTableWithStyle (Some headerRow) rws "table-bordered" [Width "100%"]
span [ClassName "is-pulled-right"] [ Button.button "Add" "contrast-button" "plus" Button.Enabled addRow ]
span [ClassName "is-clearfix"][]
TableControl.createDataTable (Some headerRow) rws (Button.button "Add" "" "plus" Button.Enabled addRow)
br []
]
let securityLimits model dispatch =
let headerRow:TableControl.row =
let headerRow:TableControl.row =
{
cells =
cells =
[
TableControl.Cell (str "")
TableControl.Cell (str "Exchange")
@@ -354,25 +356,25 @@ let securityLimits model dispatch =
header = None
}
let symbolArray = [|
[| model.AllValueDisplay |];
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|]
let symbolArray = [|
[| model.AllValueDisplay |];
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|]
|> Array.concat
|> Array.distinct
let getSecurityMap (limit:AccountSecurityPositionLimitUnit) =
let getSecurityMap (limit:AccountSecurityPositionLimitUnit) =
let allOption = {
product = {
exchange = bts.api.Venue.UNSET
``type`` = bts.api.SecurityType.UNSET
symbol = model.AllValueDisplay
};
names = (JSMap.add<string> "0" model.AllValueDisplay JSMap.empty<string>)
};
names = (JSMap.add<string> "0" model.AllValueDisplay JSMap.empty<string>)
}:ExpirationNameList
Array.concat [ [| allOption |]; model.mdRelayExpNameData]
|> Array.filter (fun (x:bts.co2.ExpirationNameList) -> (
|> Array.filter (fun (x:bts.co2.ExpirationNameList) -> (
((x.product.exchange = limit.security.exchange) || (x.product.exchange = bts.api.Venue.UNSET))
&& ((x.product.``type`` = limit.security.securityType) || (x.product.``type`` = bts.api.SecurityType.UNSET))
&& ((x.product.symbol = limit.security.securitySymbol) || (x.product.symbol = model.AllValueDisplay))
@@ -380,20 +382,20 @@ let securityLimits model dispatch =
)
|> Seq.map (fun x -> x.names ) |> JSMap.concat
let modifyRow (oldRow:AccountSecurityPositionLimitUnit) (newRow:AccountSecurityPositionLimitUnit) =
let modifyRow (oldRow:AccountSecurityPositionLimitUnit) (newRow:AccountSecurityPositionLimitUnit) =
let i = Array.findIndex (fun l -> oldRow = l) model.scratch.securityPositionLimits
let left = Array.append (model.scratch.securityPositionLimits.[..i-1]) [| newRow |]
let right = model.scratch.securityPositionLimits.[1+i..]
Array.concat [left; right]
let changeVenue (oldRow:AccountSecurityPositionLimitUnit) (value:string) =
let venueValue = EnumUtils.fromHuman<bts.api.Venue> venues value
let newRow = { oldRow with security = { oldRow.security with exchange = venueValue } }
let newRow = { oldRow with security = { oldRow.security with exchange = venueValue } }
modifyRow oldRow newRow
let changeType (oldRow:AccountSecurityPositionLimitUnit) (value:string) =
let typeValue = EnumUtils.fromHuman<bts.api.SecurityType> securityTypes value
let newRow = { oldRow with security = { oldRow.security with securityType = typeValue } }
let newRow = { oldRow with security = { oldRow.security with securityType = typeValue } }
modifyRow oldRow newRow
let changeSymbol (oldRow:AccountSecurityPositionLimitUnit) (value:string) =
@@ -411,49 +413,49 @@ let securityLimits model dispatch =
let changeShortPositionLimit (oldRow:AccountSecurityPositionLimitUnit) (value:string) =
modifyRow oldRow { oldRow with shortPositionLimit = (uint32 value) }
let rws:TableControl.row list =
let rws:TableControl.row list =
[ for limit in model.scratch.securityPositionLimits do yield {
cells =
cells =
[
TableControl.Cell (Button.removeButton Button.Enabled (fun _ -> (Array.findIndex (fun l -> limit = l) model.scratch.securityPositionLimits) |> DeleteSecurityLimit |> dispatch))
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.Venue> false venues limit.security.exchange)
(EnumUtils.allToHuman<bts.api.Venue> false venues)
[]
TableControl.Cell (Button.deleteButton Button.Enabled (fun _ -> (Array.findIndex (fun l -> limit = l) model.scratch.securityPositionLimits) |> DeleteSecurityLimit |> dispatch))
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.Venue> false venues limit.security.exchange)
(EnumUtils.allToHuman<bts.api.Venue> false venues)
[]
((changeVenue limit) >> SecurityLimits >> dispatch)
)
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.SecurityType> false securityTypes limit.security.securityType)
TableControl.Cell (Fields.enumSelect<string>
""
(EnumUtils.toHuman<bts.api.SecurityType> false securityTypes limit.security.securityType)
(EnumUtils.allToHuman<bts.api.SecurityType> false (Array.filter (fun a -> a <> bts.api.SecurityType.SYNTHETIC) securityTypes))
[]
[]
((changeType limit) >> SecurityLimits >> dispatch)
)
TableControl.Cell (Fields.enumSelect<string>
""
TableControl.Cell (Fields.enumSelect<string>
""
limit.security.securitySymbol
symbolArray
[]
[]
((changeSymbol limit) >> SecurityLimits >> dispatch)
)
TableControl.Cell (Fields.mapSelect
""
(JSMap.toMap (getSecurityMap limit))
TableControl.Cell (Fields.mapSelect
""
(JSMap.toMap (getSecurityMap limit))
None
(Some (sprintf "%i" limit.security.securityId))
((changeSecurityId limit) >> SecurityLimits >> dispatch)
)
TableControl.Cell (Fields.text
""
(sprintf "%i" limit.longPositionLimit)
[ Style [Width "10em"]]
TableControl.Cell (Fields.text
""
(sprintf "%i" limit.longPositionLimit)
[ ]
((changeLongPositionLimit limit) >> SecurityLimits >> dispatch)
)
TableControl.Cell (Fields.text
""
(sprintf "%i" limit.shortPositionLimit)
[ Style [Width "10em"]]
TableControl.Cell (Fields.text
""
(sprintf "%i" limit.shortPositionLimit)
[ ]
((changeShortPositionLimit limit) >> SecurityLimits >> dispatch)
)
]
@@ -471,61 +473,65 @@ let securityLimits model dispatch =
let addRow _ = Array.append model.scratch.securityPositionLimits [| emptyLimit |] |> (SecurityLimits >> dispatch)
div []
[
div [ ClassName "columns" ][
h1 [ ClassName "is-size-4 column is-narrow" ][str "Security Limits" ]
div [ ClassName "column is-size-7 has-text-grey-mid" ]
div [ ClassName "columns" ][
h1 [ ClassName "is-size-3 column is-narrow" ][str "Security Limits" ]
div [ ClassName "column is-size-7 has-text-grey-mid is-help-text" ]
[str "Optionally, the net position for one or more securities can also be limited. For example, the Product Limits can be set to restrict the Max Net Long Position across all ES futures to 10,000 contracts, but Security Limits can be used to restrict the ES Jun future to 500 only"]
]
TableControl.createTableWithStyle (Some headerRow) rws "table-bordered" [Width "100%"]
span [ClassName "is-pulled-right"] [ Button.button "Add" "contrast-button" "plus" Button.Enabled addRow ]
span [ClassName "is-clearfix"][]
TableControl.createDataTable (Some headerRow) rws (Button.button "Add" "" "plus" Button.Enabled addRow)
]
let positionLimitsView model dispatch =
div [] [
let LimitsView model dispatch =
div [ Class "limits-container"] [
clipLimitsView model dispatch
productLimits model dispatch
securityLimits model dispatch
]
let ConnectionsView (model:Accounts.Types.Model) dispatch =
let ConnectionsView (model:Accounts.Types.Model) dispatch =
let conNames = model.scratch.connections.exchangeConnectionNames
let rws:TableControl.row list =
[for name in conNames do yield {
cells = [
(TableControl.Cell (Button.removeButton Button.Enabled (fun _ -> name |> ( RemoveConnection >> dispatch))))
(TableControl.Cell (str name))
]
className="no-border"
header = None
}
]
let cons = match model.adminData with
| None -> Array.empty<ExchangeConnection>
| Some data -> data.connections
let conMap =
let conMap =
cons
|> Array.filter (fun a -> not <| (Array.contains a.name conNames))
|> Array.map (fun a -> a.id.ToString(), a.name)
|> Map.ofArray
let rows =
rws @ [{cells = [ {content = Fields.mapSelect "" conMap (Some "Add Connection") None (fun v -> v |> (AddConnection >> dispatch)); className = ""; isHeader = true; colSpan = 2 } ]; className = "no-border"; header = None }]
let rows:TableControl.row list =
[for c in conMap do yield {
cells = [
{ content = (Fields.checkbox "" "" (
Array.contains c.Value conNames)
[]
(fun _ -> (match (Array.contains c.Value conNames) with | true -> c.Value |> (RemoveConnection >> dispatch) | false -> c.Key |> (AddConnection>> dispatch)))
);
className = "is-checkbox-cell";
isHeader = false;
colSpan = 0
}
(TableControl.Cell (str c.Value))
]
className=""
header = None
}
]
div []
[
TableControl.createTable None rows
TableControl.createSelectorTable None rows
]
let creditLimitsView model dispatch = div [] [str "lorem ipsum"]
let exchangeSettings model dispatch =
let exchangeSettings model dispatch =
let cme = model.scratch.exchangeAccountData.cmeAccountData
let send = UpdateCME>>dispatch
div [] [
Fields.simpleSelect "" ["CME"] "CME" ignore
h2 [Class "is-size-3"] [ str "CME" ]
Fields.enumSelect "CTI" (toHuman false CTICode.values cme.cti) (allToHuman false CTICode.values) [] (fromHuman CTICode.values>>CTI>>send)
Fields.enumSelect "Origin" (toHuman false CustomerOrFirm.values cme.origin) (allToHuman false CustomerOrFirm.values) [] (fromHuman CustomerOrFirm.values>>Origin>>send)
//Fields.text "Takeup Member Code" cme.takeupMemberCode [] (TakeupMember>>send)
@@ -538,30 +544,26 @@ let exchangeSettings model dispatch =
let tabContent model dispatch =
div [Key (string model.scratch.id); ClassName "tabBox"] [
div [Key (string model.scratch.id); ClassName "is-tab-content"] [
(match model.tab with
| General -> generalView model dispatch
| ClipLimitsTab -> clipLimitsView model dispatch
| PositionLimitsTab -> positionLimitsView model dispatch
//| ClipLimitsTab -> clipLimitsView model dispatch
| LimitsTab -> LimitsView model dispatch
| ConnectionsTab -> ConnectionsView model dispatch
| CreditLimitsTab -> creditLimitsView model dispatch
| ExchangeSettingsTab -> exchangeSettings model dispatch)
]
let accountControls selected (dispatch:Msg->unit) =
let remButton =
match selected with
| None -> Button.button "Remove" "contrast-button selector-button" "times" Disabled ignore
| Some acc -> Button.button "Remove" "contrast-button selector-button" "times" Enabled (fun _ -> dispatch <| DeleteAccount acc)
div [ClassName "is-clearfix plus-margin-top"] [
p [ ClassName "" ][
Button.button "Add" "contrast-button selector-button" "plus" Enabled (fun _ -> dispatch AddAccount)
//nbsp.element
br []
remButton
]
let accountControls model (dispatch:Msg->unit) =
let revertFun =
match (selectedAccount model) with
| Some acc -> fun _ -> (dispatch <| SelectAccount acc)
| None -> ignore
div [ClassName "is-main-control-bar"] [
saveButton model dispatch
Button.button "Revert" "is-light" "" (if isDirty model then Enabled else Disabled) revertFun
]
let isActive account = function
@@ -585,13 +587,90 @@ let accountsMenu (accounts:BTSAccount[]) selectedAccount dispatch =
str account.name]
]
]
accountControls selectedAccount dispatch
]
]
let accountSelectionGrid (accountList:BTSAccount list) (currentAccount:BTSAccount) (dispatch:Msg->Unit) =
let activeAccounts =
accountList |> List.sortBy (fun u -> u.name.ToLower())
let headerRow:TableControl.row =
{
cells =
[
TableControl.Cell (str "Account Name")
TableControl.Cell (str "Active")
TableControl.Cell (str "Description")
]
className = ""
header = None
}
let rws:TableControl.row list =
[ for acc in activeAccounts do yield {
cells =
[
TableControl.Cell (a [ OnClick (fun _ -> (acc |> SelectAccount |> dispatch))][
str acc.name
])
TableControl.Cell (str (sprintf "%b" acc.isActive))
TableControl.Cell (str acc.description)
]
className = ""
header = None
}
]
div[][
TableControl.createSelectorTable (Some headerRow) rws
]
let selectionPageContent (adminData:AdminData) (model:Model) (dispatch:Msg->Unit) =
let account = model.scratch
let revertFun =
match model.adminData with
| Some data -> fun _ -> (dispatch <| SelectAccount (State.existingSelection model.scratch model.previousScratch data))
| None -> fun _ -> (dispatch <| SelectAccount emptyAccount)
let modal = Modal.showCreate
"Create Account"
(div [] [
Fields.text "Name" account.name [] (AccountName >> Update >> dispatch)
Fields.text "Description" account.description [] (Description >> Update >> dispatch)
Fields.checkbox "Active" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
])
(fun _ -> dispatch SaveScratch)
revertFun
div [] [
accountSelectionGrid (Array.toList adminData.accounts) model.scratch dispatch
//NavRoot data.accounts (selectedAccount model) dispatch
(if State.isNewAccount model.scratch then modal else span[][])
]
let NavRoot (accounts:BTSAccount[]) selectedAccount dispatch =
div [ Class "column is-narrow is-sidebar-menu" ]
[ aside [ Class "menu" ]
[ div [ Class "has-text-right" ]
[ Button.faRoundButton "Add Account" "plus" Enabled (fun _ -> dispatch AddAccount) ]
ul [ Class "menu-list" ]
[
for account in accounts do
yield li [] [
a [
ClassName (isActive account selectedAccount)
OnClick (fun _ -> SelectAccount account |> dispatch) ] [
str account.name]
]
]
]
]
let tabName = function
| ClipLimitsTab -> "Clip Limits"
| PositionLimitsTab -> "Position Limits"
//| ClipLimitsTab -> "Clip Limits"
| LimitsTab -> "Limits"
| CreditLimitsTab -> "Credit Limits"
| ConnectionsTab -> "Connections"
| ExchangeSettingsTab -> "Exchange Settings"
@@ -603,36 +682,25 @@ let tabHeader tab currentTab dispatch =
]
let root (model:Model) dispatch =
let revertFun =
match (selectedAccount model) with
| Some acc -> fun _ -> (dispatch <| SelectAccount acc)
| None -> ignore
match model.adminData with
| None -> div[][str "Loading account list..."]
| Some data ->
div [ClassName "columns"] [
accountsMenu data.accounts (selectedAccount model) dispatch
div [ ClassName "column" ] [
div [ ClassName "columns" ][
div [ ClassName "column" ]
| Some data ->
div
[ Class "columns is-fullheight" ]
[ NavRoot data.accounts (selectedAccount model) dispatch
div [ Class "column is-main-content" ]
[
div [ ClassName "tabs is-boxed" ] [
ul [] [
tabHeader General model.tab dispatch
tabHeader ClipLimitsTab model.tab dispatch
tabHeader PositionLimitsTab model.tab dispatch
//tabHeader ClipLimitsTab model.tab dispatch
tabHeader LimitsTab model.tab dispatch
tabHeader ConnectionsTab model.tab dispatch
// tabHeader CreditLimits model.tab dispatch
tabHeader ExchangeSettingsTab model.tab dispatch
]
]
tabContent model dispatch
accountControls model dispatch
]
div [ ClassName "column is-narrow" ] [
yield saveButton model dispatch
yield Button.button "Revert" "is-light" "" (if isDirty model then Enabled else Disabled) revertFun
]
]
tabContent model dispatch
]
]
+13 -82
View File
@@ -11,97 +11,28 @@ open App.State
open App.Types
open Global
importAll "../sass/main.sass"
importAll "../sass/main.scss"
open Fable.Helpers.React
open Fable.Helpers.React.Props
open Elmish.React.Common
let isCurrentPage page currentPage =
match page, currentPage with
| UsersModel _, UsersModel _ -> true
| AccountsModel _, AccountsModel _ -> true
| _ -> false
open ServiceContext
let navButton classy href faClass txt =
p
[ ClassName "control" ]
[ a
[ ClassName (sprintf "button %s" classy)
Href href ]
[ span
[ ClassName "icon" ]
[ i
[ ClassName (sprintf "fa %s" faClass) ]
[ ] ]
span
[ ]
[ str txt ] ] ]
let navButtons =
span
[ ClassName "nav-item" ]
[ div
[ ClassName "field is-grouped" ]
[ navButton "" "/" "fa-sign-out" "Logout"
]
]
let navItem label icon state currentPage dispatch =
a [
OnClick (fun _ -> Navigate state |> dispatch)
classList [ "navbar-item", true; "is-active", isCurrentPage (fst state) currentPage ]
]
[
Button.faIcon icon
nbsp.element
str label
]
let navRoot currentPage sc dispatch =
let tmap (a,b) (fa,fb) = (fa a, fb b)
nav
[ ClassName "navbar" ]
[
div [ ClassName "navbar-brand" ]
[
h1
[ ClassName "navbar-item" ]
[
span [Style [ FontSize "1.5rem";]] [ str "BTS Spark Admin" ]
span [ Style [ CSSProp.Color "#fff"; FontSize "0.7rem"; Margin ".5ex 0 0 0"; Transform "rotate(90deg)"] ] [ str "beta" ]
]
navItem "Users" "users" (tmap (Users.State.init sc) (UsersModel, Cmd.map UsersMsg)) currentPage dispatch
navItem "Accounts" "server" (tmap (Accounts.State.init sc) (AccountsModel,Cmd.map AccountsMsg)) currentPage dispatch
]
div [ ClassName "nav-right" ]
[ navButtons ]
]
let nav' = lazyView3With (fun a b -> isCurrentPage (fst a) (fst b)) navRoot
let topLevel sc currentPage dispatch content =
let topLevel (sc:ServiceContext.ServiceContext) currentPage dispatch content =
div
[]
[ div
[ Class "columns is-fullheight" ]
[ Nav.root currentPage sc dispatch
div [ Class "column is-main-content" ]
[ content]
(*
div
[ ClassName "navbar-bg" ]
[ div
[ ClassName "container" ]
[ nav' currentPage sc dispatch ] ]
div
[ ClassName "section" ]
[ div
[ ClassName "container" ]
[ div []
[ content ]
]
]
]
[(App.Nav.navRoot currentPage sc dispatch) ] ]
//[(App.Nav.nav' currentPage sc dispatch) ] ]*)
]
let root model dispatch =
match model with
@@ -110,7 +41,7 @@ let root model dispatch =
match model.page with
| UsersModel m -> Users.View.root m (UsersMsg>>dispatch) |> topLevel model.context model.page dispatch
| AccountsModel m -> Accounts.View.root m (AccountsMsg>>dispatch) |> topLevel model.context model.page dispatch
open Elmish.React
open Elmish.Debug
open Elmish.HMR
+29 -13
View File
@@ -4,7 +4,7 @@ open Fable.Core
open Fable.Helpers.React
open Fable.Helpers.React.Props
type IsDisabled =
type IsDisabled =
| Disabled
| Enabled
@@ -12,53 +12,69 @@ let isDisabled = function
| Disabled -> true
| Enabled -> false
let addButton disabled click =
let addButton disabled click =
a [ ClassName "button fabutton "
HTMLAttr.Disabled (isDisabled disabled)
Title "Add"
OnClick click ] [
span [ ClassName "icon is-small has-text-success" ] [
span [ ClassName "icon is-small has-text-success" ] [
i [ ClassName "fa fa-plus"] [ ] ]
]
let removeButton disabled click =
a [ ClassName "button fabutton"
let removeButton disabled click =
a [ ClassName "button fabutton"
Style []
HTMLAttr.Disabled (isDisabled disabled)
Title "Remove"
OnClick click ] [
span [ ClassName "icon has-text-danger" ] [
span [ ClassName "icon has-text-danger" ] [
i [ ClassName "fa fa-times"] [ ] ]
]
let deleteButton disabled click =
a [ ClassName "delete is-small"
Style []
HTMLAttr.Disabled (isDisabled disabled)
Title "Remove"
OnClick click ] []
let fabutton title icon disabled click =
let faRoundButton title icon disabled click =
a [ ClassName "button fabutton is-round"
HTMLAttr.Disabled (isDisabled disabled)
Title title
OnClick click ] [
span [ ClassName "icon is-small" ] [
i [ ClassName (sprintf "fa fa-%s" icon)] [ ] ]
]
let fabutton title icon disabled click =
a [ ClassName "button fabutton"
HTMLAttr.Disabled (isDisabled disabled)
Title title
OnClick click ] [
span [ ClassName "icon is-small" ] [
span [ ClassName "icon is-small" ] [
i [ ClassName (sprintf "fa fa-%s" icon)] [ ] ]
]
let falink title icon disabled click =
span [
let falink title icon disabled click =
span [
HTMLAttr.Disabled (isDisabled disabled)
Title title
OnClick click ] [
span [ ClassName "icon is-small" ] [
span [ ClassName "icon is-small" ] [
i [ ClassName (sprintf "fa fa-%s" icon)] [ ] ]
]
let button text flavor icon disabled click =
let button text flavor icon disabled click =
a [ ClassName (sprintf "button %s" flavor)
HTMLAttr.Disabled (isDisabled disabled)
//Title text
OnClick click] [
(match icon with
| "" -> str text
| _ ->
| _ ->
span [][
span [ ClassName "icon is-small" ] [i [ ClassName (sprintf "fa fa-%s" icon)][] ]
nbsp.element
+73 -67
View File
@@ -9,13 +9,20 @@ open Global
open Fable
open JSMap
let text (lbl:string) (dv:string) (attrs:IHTMLProp list) onchange =
let Label (lbl:string) =
match lbl with
| "" -> str ""
| _ ->
label [ ClassName "label" ]
[ str lbl ]
let text (lbl:string) (dv:string) (attrs:IHTMLProp list) onchange =
div [ ClassName "field" ]
[
label [ ClassName "label" ]
[ str lbl ]
[
Label lbl
div [ ClassName "control" ]
[ input ([
[ input ([
ClassName "input"
Type "text"
Value dv
@@ -24,13 +31,13 @@ let text (lbl:string) (dv:string) (attrs:IHTMLProp list) onchange =
]
]
let textPair (v:string*string) (keyAttrs:IHTMLProp list) (valueAttrs:IHTMLProp list) (thirdCol:ReactElement list) (onchange: (string*string) -> string -> string -> unit) =
let textPair (v:string*string) (keyAttrs:IHTMLProp list) (valueAttrs:IHTMLProp list) (thirdCol:ReactElement list) (onchange: (string*string) -> string -> string -> unit) =
div [ ClassName "columns" ]
[
[
div [ ClassName "column is-3" ]
[
input (
[
[
ClassName "input"
Type "text"
Value (fst v)
@@ -43,9 +50,9 @@ let textPair (v:string*string) (keyAttrs:IHTMLProp list) (valueAttrs:IHTMLProp l
str ":"
]
div [ ClassName "column is-3" ]
[
[
input (
[
[
ClassName "input"
Type "text"
Value (snd v)
@@ -56,19 +63,19 @@ let textPair (v:string*string) (keyAttrs:IHTMLProp list) (valueAttrs:IHTMLProp l
div [ ClassName "column" ] thirdCol
]
let map (lbl:string) (dv:JSMap<string>) (attrs:IHTMLProp list) (onchange: JSMap<string> -> unit) =
let remove (item: string*string) =
let map (lbl:string) (dv:JSMap<string>) (attrs:IHTMLProp list) (onchange: JSMap<string> -> unit) =
let remove (item: string*string) =
let mp = JSMap.remove (fst item) dv
onchange (mp)
let newEntry (value:string) =
let newEntry (value:string) =
let origin = "", value
let newValue = value, ""
let rmp = JSMap.remove (fst origin) dv
let mp = JSMap.add (fst newValue) (snd newValue) rmp
onchange (mp)
let change (origin: string*string) (name:string) (value:string) =
let change (origin: string*string) (name:string) (value:string) =
let newValue = match name with
| "key" -> value, snd origin
| "value" -> fst origin, value
@@ -76,46 +83,45 @@ let map (lbl:string) (dv:JSMap<string>) (attrs:IHTMLProp list) (onchange: JSMap<
let rmp = JSMap.remove (fst origin) dv
let mp = JSMap.add (fst newValue) (snd newValue) rmp
onchange (mp)
let sortedSeq = Seq.sortBy (fst) (Seq.ofArray (JSMap.toArray dv))
let elementList:ReactElement list =
[for i in sortedSeq do yield
let elementList:ReactElement list =
[for i in sortedSeq do yield
(
match (fst i) with
| "" ->
textPair
("", (snd i) )
[HTMLAttr.Disabled true; Placeholder "Enter New Item Name:"; ]
[ OnBlur ((fun ev -> !!ev.target?value |> newEntry )) ]
[
Button.fabutton "" "" Button.Enabled ignore
Button.fabutton "Add" "check" Button.Enabled ignore
]
| "" ->
textPair
("", (snd i) )
[HTMLAttr.Disabled true; Placeholder "Enter New Item Name:"; ]
[ OnBlur ((fun ev -> !!ev.target?value |> newEntry )) ]
[
Button.fabutton "" "" Button.Enabled ignore
Button.fabutton "Add" "check" Button.Enabled ignore
]
change
| _ ->
textPair
i
[HTMLAttr.Disabled true]
[]
[Button.fabutton "Delete" "times" Button.Enabled (fun _ -> (remove i))]
| _ ->
textPair
i
[HTMLAttr.Disabled true]
[]
[Button.fabutton "Delete" "times" Button.Enabled (fun _ -> (remove i))]
change
)]
div [ ClassName "field" ]
[
label [ ClassName "label" ] [ str lbl ]
[
Label lbl
div [] elementList
Button.fabutton "Add" "plus" Button.Enabled ((fun _ -> change ("","") "" ""))
Button.fabutton "Add" "plus" Button.Enabled ((fun _ -> change ("","") "" ""))
]
let password (lbl:string) (dv:string) (attrs:IHTMLProp list) onchange =
let password (lbl:string) (dv:string) (attrs:IHTMLProp list) onchange =
div [ ClassName "field" ]
[
label [ ClassName "label" ]
[ str lbl ]
[
Label lbl
div [ ClassName "control" ]
[ input ([
[ input ([
ClassName "input"
Type "password"
Value dv
@@ -130,7 +136,7 @@ let number (lbl:string) (dv:int) (attrs:IHTMLProp list) onchange =
let enumSelect<'a> (lbl:string) (dv:'a) (values:'a[]) (attrs:IHTMLProp list) (onchange:'a->unit) =
div [ClassName "field"] [
label [ClassName "label"] [str lbl]
Label lbl
div [ClassName "control"] [
div [ClassName "select"] [
select ([
@@ -144,13 +150,13 @@ let enumSelect<'a> (lbl:string) (dv:'a) (values:'a[]) (attrs:IHTMLProp list) (on
]
]
let checkbox (lbl:string) (description:string) (dv:bool) (attrs:IHTMLProp list) (onchange:bool->unit) =
let checkbox (lbl:string) (description:string) (dv:bool) (attrs:IHTMLProp list) (onchange:bool->unit) =
div [ ClassName "field" ]
[
[
div [ ClassName "control" ]
[
[
label [ ] [
input ([
input ([
ClassName "checkbox"
Type "checkbox"
Checked dv
@@ -162,49 +168,49 @@ let checkbox (lbl:string) (description:string) (dv:bool) (attrs:IHTMLProp list)
span [ClassName "is-size-7 has-text-grey-mid"][ str description]
]
]
let mapSelect (lbl:string) (options:Map<string,string>) (defaultText:string option) (defaultValue:string option) (onchange:'a->unit) =
let optList:ReactElement list =
let mapSelect (lbl:string) (options:Map<string,string>) (defaultText:string option) (defaultValue:string option) (onchange:'a->unit) =
let optList:ReactElement list =
match defaultText with
| None -> ([ for opt in options do yield option [ Value opt.Key ] [ str (opt.Value) ] ])
| Some dt -> (option [] [str dt]) :: ([ for opt in options do yield option [ Value opt.Key ] [ str (opt.Value) ] ])
let dv = match defaultValue with
| Some d ->
let dv = match defaultValue with
| Some d ->
d
| None -> ""
div [ ClassName "field" ]
[
label [ ClassName "label" ] [ str lbl ]
[
Label lbl
div [ ClassName "control" ]
[
[
div [ ClassName "select" ]
[
[
select [
Value dv
OnChange (fun ev -> !!ev.target?value |> onchange)
]
optList
]
]
]
]
]
let simpleSelect (lbl:string) (options:string list) (defaultValue:string) (onchange:'a->unit) =
let simpleSelect (lbl:string) (options:string list) (defaultValue:string) (onchange:'a->unit) =
div [ ClassName "field" ]
[
label [ ClassName "label" ] [ str lbl ]
[
Label lbl
div [ ClassName "control" ]
[
[
div [ ClassName "select" ]
[
select [
[
select [
Value defaultValue
OnChange (fun ev -> !!ev.target?value |> onchange)
]
[ for opt in options do yield option [ Value opt ] [ str (opt) ] ]
]
]
[ for opt in options do yield option [ Value opt ] [ str (opt) ] ]
]
]
]
+63 -17
View File
@@ -6,9 +6,21 @@ open Fable.Helpers.React
open Fable.Helpers.React.Props
open Fable.Import.React
type cell = { content:ReactElement; className:string; isHeader:bool; colSpan:int }
type cell = { content:ReactElement; className:string; isHeader:bool; colSpan:int }
let Cell (content:ReactElement) = { content = content; className = ""; isHeader = false; colSpan = 1 }
let controlCell (content:ReactElement) =
{ content = div [ Class "field" ]
[ div [ Class "control" ]
[
content
]
]
className = ""
isHeader = false
colSpan = 1
}
let Cell (content:ReactElement) = { content = content; className = ""; isHeader = false; colSpan = 0 }
type row = {
cells:cell list
@@ -16,12 +28,12 @@ type row = {
header:string option
}
let createCell (inHeaderRow:bool) (c:cell) =
let createCell (inHeaderRow:bool) (c:cell) =
match c.isHeader || inHeaderRow with
| false -> td [ ClassName c.className; ColSpan (float c.colSpan) ] [ c.content ]
| true -> th [ ClassName c.className; ColSpan (float c.colSpan) ] [ c.content ]
let createRow (isHeaderRow:bool) (r:row) =
let createRow (isHeaderRow:bool) (r:row) =
match r.header, isHeaderRow with
| None, false -> tr [ ClassName r.className ] (List.map<cell, ReactElement> (createCell isHeaderRow) r.cells)
| None, true -> tr [ ClassName r.className ] (List.map<cell, ReactElement> (createCell isHeaderRow) r.cells)
@@ -29,16 +41,50 @@ let createRow (isHeaderRow:bool) (r:row) =
| Some h, false -> tr [ ClassName r.className ] (th [] [str h] :: (List.map<cell, ReactElement> (createCell isHeaderRow) r.cells ))
let createTableWithStyle (headers:row option) (rl:row list) className styles =
let rws = List.map<row,ReactElement> (createRow false) rl
let tbl = match headers with
| Some h ->
[
thead [] [ createRow true h]
tbody [] rws
]
| None ->
[ tbody [] rws ]
table [ ClassName (sprintf "table is-narrow btstable %s" className); Style styles ] tbl
let createTable (headers:row option) (rl:row list) = createTableWithStyle headers rl "" []
let rws = List.map<row,ReactElement> (createRow false) rl
let tbl = match headers with
| Some h ->
[
thead [] [ createRow true h]
tbody [] rws
]
| None ->
[ tbody [] rws ]
table [ ClassName (sprintf "table %s" className); Style styles ] tbl
let createTable (headers:row option) (rl:row list) = createTableWithStyle headers rl "" []
let createDataTable (headers:row option) (rl:row list) (buttons:ReactElement) =
let rws = List.map<row,ReactElement> (createRow false) rl
let tbl = match headers with
| Some h ->
[
thead [] [ createRow true h]
tbody [] rws
]
| None ->
[ tbody [] rws ]
div [ Class "bts-data-table-container" ][
table [ ClassName (sprintf "table bts-data-table") ] tbl
div [Class "is-pulled-right table-buttons"] [ buttons ]
div [Class "is-clearfix "] []
]
let createSelectorTableWithStyle (headers:row option) (rl:row list) className styles =
let rws = List.map<row,ReactElement> (createRow false) rl
let tbl = match headers with
| Some h ->
[
thead [] [ createRow true h]
tbody [] rws
]
| None ->
[ tbody [] rws ]
table [ ClassName (sprintf "table bts-selector-table %s" className); Style styles ] tbl
(*
If a callback is provided add a checkbox as the first column and set a background color if it is checked... in addition to the callback
*)
let createSelectorTable (headers:row option) (rl:row list) = createSelectorTableWithStyle headers rl "" []
+60
View File
@@ -0,0 +1,60 @@
module App.Nav
open Elmish
open Elmish.Browser.Navigation
open Fable.Core
open Fable.Core.JsInterop
open Fable.Import
open Fable.Import.Browser
open Types
open App.State
open App.Types
open Global
open Fable.Helpers.React
open Fable.Helpers.React.Props
open Elmish.React.Common
open ServiceContext
open Fable.Helpers
let isCurrentPage page currentPage =
match page, currentPage with
| UsersModel _, UsersModel _ -> true
| AccountsModel _, AccountsModel _ -> true
| _ -> false
let navItem label icon state currentPage dispatch =
a [
OnClick (fun _ -> Navigate state |> dispatch)
classList [ "is-active", isCurrentPage (fst state) currentPage ]
]
[
div [ ClassName "icon is-large" ] [
i [ ClassName (sprintf "fa fa-2x fa-%s" icon) ] []
]
div [] [str label]
]
let root (currentPage:Page) (sc:ServiceContext) dispatch =
let tmap (a,b) (fa,fb) = (fa a, fb b)
div [ Class "column is-narrow is-launcher-sidebar-menu" ]
[ aside [ Class "menu" ]
[ ul [ Class "menu-list" ]
[ li [ Class "launcher-item" ]
[ navItem "Users" "users" (tmap (Users.State.init sc) (UsersModel, Cmd.map UsersMsg)) currentPage dispatch ]
li [ Class "launcher-item" ]
[ navItem "Accounts" "server" (tmap (Accounts.State.init sc) (AccountsModel,Cmd.map AccountsMsg)) currentPage dispatch ]
li [ Class "launcher-item" ]
[ a [ Href "/" ]
[ div [ ClassName "icon is-large" ] [
i [ ClassName "fa fa-3x fa-sign-out" ] []
]
div [] [str "Logout"]
]
]
]
]
]
//let navRoot = lazyView3With (fun a b -> isCurrentPage (fst a) (fst b)) root
-7
View File
@@ -1,7 +0,0 @@
module Navbar.View
open Fable.Helpers.React
open Fable.Helpers.React.Props
open System.Drawing
+13 -9
View File
@@ -12,8 +12,8 @@ open Fable.PowerPack.PromiseImpl
open bts.api.admin
open Global
let isNewAccount (user:BTSUser) =
user.id = 0u
let isNewUser (user:BTSUser) =
user.id = 0u && user.isPresent
let getAdminData (admin:IAdminService) =
Cmd.ofPromise
@@ -98,17 +98,17 @@ let rec removeUser (user:BTSUser) (userList:BTSUser list) =
| hd::tl -> hd::removeUser user tl
| _ -> []
let getFirstUser usrlst =
let getFirstUser usrlst =
let head = (List.sortBy (fun (u:BTSUser) -> u.name.ToLower()) usrlst) |> List.tryHead
match head with
| None -> defaultScratchUser
| Some hd -> hd
let findUserInList (user:BTSUser) (userList:BTSUser list) =
List.tryFind (fun (x:BTSUser) ->
let findUserInList (user:BTSUser) (userList:BTSUser list) =
List.tryFind (fun (x:BTSUser) ->
x.id = user.id
|| (user.id = 0u && x.name = user.name)
)
)
userList
let getCurrentOrFirstUser (model:Model) (userList:BTSUser list) =
@@ -116,11 +116,12 @@ let getCurrentOrFirstUser (model:Model) (userList:BTSUser list) =
| Some cu, _ -> cu
| None, Some pu -> pu
| None, None -> getFirstUser userList
//| None, None -> defaultScratchUser
let getCurrentUser (model:Model) = getCurrentOrFirstUser model model.userList
let currentUserIsDefault model = ((getCurrentUser model).id = 0u)
let userIsdirty (initialState:BTSUser) (scratch:BTSUser) (existing:BTSUser) = (scratch <> existing) && (scratch <> initialState)
@@ -167,6 +168,7 @@ let applyUpdate (field:UserField) (user:BTSUser) =
| OperatorID oid -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with operatorId = oid }}}}
| ATSOperatorID atsoid -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with atsOperatorId = atsoid }}}}
| SMPID smpid -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with smpId = smpid }}}}
| Location loc -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with location = loc }}}}
| SMPInstruction smpi -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with smpInstruction = smpi }}}}
| MaxOrderRatePerConnection morpc -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with maxOrderRatePerConnection = morpc }}}}
| MiscTags map ->
@@ -228,7 +230,9 @@ let update msg (model:Users.Types.Model) : Model * Cmd<Msg> =
| false -> model, Cmd.Empty
| AddUser ->
{ model with PreviousScratchUser = model.scratchUser; scratchUser = { defaultScratchUser with name = "New User" } }, Cmd.ofMsg (SwitchTab General)
{ model with PreviousScratchUser = model.scratchUser; scratchUser = { defaultScratchUser with name = "New User" }}, Cmd.ofMsg (SwitchTab General)
| CancelAddUser ->
{ model with scratchUser = { model.PreviousScratchUser with name = "New User" }}, Cmd.ofMsg (SwitchTab General)
| SwitchTab tb ->
{model with currentTab = tb}, Cmd.Empty
+5 -3
View File
@@ -16,16 +16,17 @@ type Model = {
PreviousScratchUser:BTSUser
currentTab:Tab
admin : IAdminService
adminData : AdminData option
adminData : AdminData option
}
type UserField =
type UserField =
| Name of string
| Password of string
| IsActive of bool
| OperatorID of string
| ATSOperatorID of string
| SMPID of string
| Location of string
| SMPInstruction of string
| MaxOrderRatePerConnection of string
| MiscTags of JSMap<string>
@@ -47,8 +48,9 @@ type Msg =
| CopyFrom of BTSUser * BTSUser
| Delete of BTSUser
| AddUser
| CancelAddUser
| SwitchTab of Tab
| SwitchUser of BTSUser
| SaveUser
| ErrorOccured of obj
+188 -111
View File
@@ -10,8 +10,8 @@ open Types
open Users
open bts.api.admin
open Users
let isActiveTab tab currentTab =
let isActiveTab tab currentTab =
let ia = "is-active"
match tab, currentTab with
| Tab.General, Tab.General -> ia
@@ -20,21 +20,21 @@ let isActiveTab tab currentTab =
| Tab.OrderRouting, Tab.OrderRouting -> ia
| _ -> ""
let isActiveUser id (currentUser:BTSUser) =
let isActiveUser id (currentUser:BTSUser) =
match id = currentUser.id with
| true -> "is-active"
| false -> ""
let saveButton (model:Users.Types.Model) dispatch =
let buttonText = if State.isNewAccount model.scratchUser then "Create" else "Save"
let buttonText = if State.isNewUser model.scratchUser then "Create" else "Save"
let dirty = State.userIsdirty State.defaultScratchUser model.scratchUser (State.getCurrentUser model)
let enabled = if dirty then Button.Enabled else Button.Disabled
let flavor = if dirty then "is-success" else "is-light"
Button.button buttonText flavor "" enabled (fun _ -> dispatch SaveUser)
let generalTabContent (model:Model) (dispatch:Msg->Unit) =
let modal = Modal.showCreate
"Create User"
let generalTabContent (model:Model) (dispatch:Msg->Unit) =
let modal = Modal.showCreate
"Create User"
(div [][
Fields.text "Name" model.scratchUser.name [ ] (Name >> UpdateField >> dispatch)
Fields.password "Password" model.scratchUser.password [ ] (Password >> UpdateField >> dispatch)
@@ -48,25 +48,35 @@ let generalTabContent (model:Model) (dispatch:Msg->Unit) =
Fields.text "Name" model.scratchUser.name [ ] (Name >> UpdateField >> dispatch)
Fields.password "Password" model.scratchUser.password [ ] (Password >> UpdateField >> dispatch)
Fields.checkbox "Active" "Unchecking this stops the user from entering orders" model.scratchUser.isActive [] (IsActive >> UpdateField >> dispatch)
(if State.isNewAccount model.scratchUser then modal else span[][])
(if State.isNewUser model.scratchUser then modal else span[][])
Button.button "Remove User" "is-danger-hover" "times" Button.Enabled (fun _ -> dispatch <| Delete model.scratchUser)
]
let accountNameLookup (accountsList:BTSAccount list) (id:string) =
let accountNameLookup (accountsList:BTSAccount list) (id:string) =
match (List.tryFind<BTSAccount> (fun a -> a.id.ToString() = id) accountsList) with
| Some acnt -> acnt.name
| None -> "Account Not Found"
let accountsTabContent (model:Model) (dispatch:Msg->Unit) =
let accountsTabContent (model:Model) (dispatch:Msg->Unit) =
let accountPermissions = model.scratchUser.userData.accountPermissions.accountPermissions
let keys =
Global.Reflection.keys accountPermissions
let keys =
Global.Reflection.keys accountPermissions
|> Array.map (fun i -> i, accountNameLookup model.accountsList i)
let headerRow:TableControl.row =
let keymap =
keys |> Array.map snd |> Set.ofArray
let accMap =
model.accountsList
|> List.filter (fun a -> a.isPresent)
|> List.map (fun a -> a.id.ToString(), a.name)
|> Map.ofList
let headerRow:TableControl.row =
{
cells =
cells =
[
TableControl.Cell(str "")
TableControl.Cell(str "Account")
TableControl.Cell(str "Trading Permission")
TableControl.Cell(str "Admin Permission")
@@ -74,42 +84,46 @@ let accountsTabContent (model:Model) (dispatch:Msg->Unit) =
className = ""
header = None
}
let rws:TableControl.row list =
[for (key,name) in keys do yield {
cells = [
TableControl.Cell(Button.removeButton Button.Enabled (fun _ -> key |> (RemoveAccount >> UpdateField >> dispatch)))
TableControl.Cell(str name)
TableControl.Cell( str "Full")
TableControl.Cell(str "Full")
let rows:TableControl.row list =
[for acc in accMap do yield {
cells = [
//TableControl.Cell(Button.removeButton Button.Enabled (fun _ -> key |> (RemoveAccount >> UpdateField >> dispatch)))
TableControl.Cell(str acc.Value)
{ content = (Fields.checkbox "" "" (
keymap.Contains <| acc.Value)
[]
(fun _ -> acc.Key |> ((match (keymap.Contains <| acc.Value) with | true -> RemoveAccount | false -> AddAccount) >> UpdateField >> dispatch))
);
className = "";
isHeader = false;
colSpan = 0
}
{ content = (Fields.checkbox "" "" (
model.scratchUser.name.Contains "bts" || model.scratchUser.name.Contains "admin")
[Disabled true]
ignore
);
className = "";
isHeader = false;
colSpan = 0
}
]
className=""
header = None
}
]
let keymap =
keys |> Array.map snd |> Set.ofArray
let accMap =
model.accountsList
|> List.filter (fun a -> a.isPresent && not <| keymap.Contains a.name)
|> List.map (fun a -> a.id.ToString(), a.name)
|> Map.ofList
let rows =
rws @ [{cells = [
{ content = Fields.mapSelect "" accMap (Some "Add Account") None (AddAccount >> UpdateField >> dispatch); className = ""; isHeader = false; colSpan = 4 }
]; className = ""; header = None }]
div []
[
TableControl.createTableWithStyle (Some headerRow) rows "table-bordered" []
TableControl.createSelectorTable (Some headerRow) rows
]
let mdEntitlementsTabContent (model:Model) (dispatch:Msg->Unit) =
let mdEntitlementsTabContent (model:Model) (dispatch:Msg->Unit) =
let cmeData = model.scratchUser.userData.exchangeMdEntitlementData.cmeData
div []
[
Fields.simpleSelect "" ["CME"] "CME" ignore
div []
div []
[
h2 [Class "is-size-3"] [ str "CME" ]
div []
[
Fields.checkbox "CBOT" "" cmeData.cbotEntitlement.canView [] (CBOTEntitlement >> UpdateField >> dispatch)
Fields.checkbox "CME" "" cmeData.cmeEntitlement.canView [] (CMEEntitlement >> UpdateField >> dispatch)
@@ -117,27 +131,28 @@ let mdEntitlementsTabContent (model:Model) (dispatch:Msg->Unit) =
Fields.checkbox "BMANDF" "" cmeData.bmandfEntitlement.canView [] (BMANDFEntitlement >> UpdateField >> dispatch)
Fields.checkbox "COMEX" "" cmeData.comexEntitlement.canView [] (COMEXEntitlement >> UpdateField >> dispatch)
Fields.checkbox "CME Europe" "" cmeData.cmeEuropeEntitlement.canView [] (CMEEuropeEntitlement >> UpdateField >> dispatch)
]
]
]
let orderRoutingTabContent (model:Model) (dispatch:Msg->Unit) =
let orderRoutingTabContent (model:Model) (dispatch:Msg->Unit) =
let cmeData = model.scratchUser.userData.exchangeUserData.cmeData
div []
[
Fields.simpleSelect "" ["CME"] "CME" ignore
div []
div []
[
h2 [Class "is-size-3"] [ str "CME" ]
div []
[
Fields.text "Operator ID" cmeData.operatorId [] (OperatorID >> UpdateField >> dispatch)
//Fields.text "ATS Operator ID" cmeData.atsOperatorId [] (ATSOperatorID >> UpdateField >> dispatch)
//Fields.text "SMP ID" cmeData.smpId [] (SMPID >> UpdateField >> dispatch)
//Fields.text "SMP Instruction" cmeData.smpInstruction [] (SMPInstruction >> UpdateField >> dispatch)
Fields.text "SMP Instruction" cmeData.smpInstruction [] (SMPInstruction >> UpdateField >> dispatch)
Fields.text "Location" cmeData.location [] (Location >> UpdateField >> dispatch)
//Fields.text "Max Order Rate Per Connection" cmeData.maxOrderRatePerConnection [] (MaxOrderRatePerConnection >> UpdateField >> dispatch)
//Fields.map "Misc Tag Mapping" cmeData.miscTags [] (MiscTags >> UpdateField >> dispatch)
]
]
let tabContent (model:Model) (dispatch:Msg->Unit) =
div [Key (string model.scratchUser.id); ClassName "tabBox"] [
let tabContent (model:Model) (dispatch:Msg->Unit) =
div [Key (string model.scratchUser.id); ClassName "is-tab-content"] [
(match model.currentTab, (State.userIsSelected model.scratchUser State.defaultScratchUser) with
| _, false -> p [Style [ Color "Red" ]] [ str "Select a User" ]
| Tab.General, true -> generalTabContent model dispatch
@@ -146,15 +161,15 @@ let tabContent (model:Model) (dispatch:Msg->Unit) =
| Tab.OrderRouting, true -> orderRoutingTabContent model dispatch)
]
let userControls (usersList:BTSUser list) (currentUser:BTSUser) (dispatch:Msg->Unit) (disabled:bool)=
div [ ClassName "is-clearfix plus-margin-top" ]
[
p [ ClassName "" ][
Button.button "Add" "contrast-button selector-button" "plus" Button.Enabled (fun _ -> dispatch <| AddUser)
//nbsp.element
br []
Button.button "Remove" "contrast-button selector-button" "times" Button.Enabled (fun _ -> dispatch <| Delete currentUser)
]
let userControls (model:Model) (dispatch:Msg->Unit) =
let currentUser = State.getCurrentUser model
let dirty = State.userIsdirty State.defaultScratchUser model.scratchUser (State.getCurrentUser model)
div [ ClassName "is-main-control-bar" ]
[
nbsp.element
saveButton model dispatch
Button.button "Revert" "is-light" "" (if dirty then Button.Enabled else Button.Disabled) (fun _ -> SwitchUser (currentUser) |> dispatch)
(*p [ ClassName "control" ]
[ a [ ClassName "button is-light"
Title "Clone"
@@ -164,91 +179,153 @@ let userControls (usersList:BTSUser list) (currentUser:BTSUser) (dispatch:Msg->U
[ span [ ClassName "icon is-small" ]
[ i [ ClassName "fa fa-clone" ]
[ ] ]
]
]
]*)
(*p [ ClassName "control" ]
[ a [ ClassName "button is-light" ]
[ span [ ClassName "icon is-small"
Title "Copy from user 1 ..."
Title "Copy from user 1 ..."
OnClick (fun _ -> dispatch <| CopyFrom (usersList.Head, currentUser))
]
[ i [ ClassName "fa fa-copy" ]
[ ] ]
]
]*)
]
]*)
]
let usersMenu (usersList:BTSUser list) (currentUser:BTSUser) (dispatch:Msg->Unit) =
let activeUsers =
let usersMenu (usersList:BTSUser list) (currentUser:BTSUser) (dispatch:Msg->Unit) =
let activeUsers =
usersList |> List.sortBy (fun u -> u.name.ToLower())
div
[ ClassName "column is-narrow" ]
[
[
aside [ ClassName "menu box" ]
[
[
p [ ClassName "menu-label has-text-centered" ] [
str "Select User"
]
ul [ ClassName "menu-list" ]
[ for u in activeUsers do yield li []
[ for u in activeUsers do yield li []
[
a [
ClassName (isActiveUser u.id currentUser)
a [
ClassName (isActiveUser u.id currentUser)
OnClick (fun _ -> (u |> SwitchUser |> dispatch))
]
[
[
str u.name
]
]
]
userControls usersList currentUser dispatch (not (State.userIsSelected currentUser State.defaultScratchUser))
]
]
]
]
let userSelectionGrid (usersList:BTSUser list) (currentUser:BTSUser) (dispatch:Msg->Unit) =
let activeUsers =
usersList |> List.sortBy (fun u -> u.name.ToLower())
let headerRow:TableControl.row =
{
cells =
[
TableControl.Cell (str "")
TableControl.Cell (str "Username")
TableControl.Cell (str "Active")
]
className = ""
header = None
}
let rws:TableControl.row list =
[ for u in activeUsers do yield {
cells =
[
{ content = (Fields.checkbox "" "" false [] ignore); className = "is-checkbox-cell"; isHeader = false; colSpan = 0 }
TableControl.Cell (a [ OnClick (fun _ -> (u |> SwitchUser |> dispatch))][
str u.name
])
TableControl.Cell (str (sprintf "%b" u.isActive))
]
className = ""
header = None
}
]
div[][
TableControl.createSelectorTable (Some headerRow) rws
]
let NavRoot (usersList:BTSUser list) (currentUser:BTSUser) (dispatch:Msg->Unit) =
let activeUsers =
usersList |> List.sortBy (fun u -> u.name.ToLower())
div [ Class "column is-narrow is-sidebar-menu" ]
[ aside [ Class "menu" ]
[ div [ Class "has-text-right" ]
[
Button.faRoundButton "Add User" "plus" Button.Enabled (fun _ -> dispatch <| AddUser)
]
ul [ Class "menu-list" ]
[
for u in activeUsers do yield li []
[ a [
ClassName (isActiveUser u.id currentUser)
OnClick (fun _ -> (u |> SwitchUser |> dispatch))
]
[
str u.name
]
]
]
]
]
let selectionPageContent (model:Model) (dispatch:Msg->Unit) =
let modal = Modal.showCreate
"Create User"
(div [][
Fields.text "Name" model.scratchUser.name [ ] (Name >> UpdateField >> dispatch)
Fields.password "Password" model.scratchUser.password [ ] (Password >> UpdateField >> dispatch)
Fields.checkbox "Active" "Unchecking this stops the user from entering orders" model.scratchUser.isActive [] (IsActive >> UpdateField >> dispatch)
])
(fun _ -> dispatch SaveUser)
//(fun _ -> SwitchUser (State.getCurrentUser model) |> dispatch)
(fun _ -> CancelAddUser |> dispatch)
div [] [
userSelectionGrid model.userList model.scratchUser dispatch
(if State.isNewUser model.scratchUser then modal else span[][])
]
let root (model:Model) (dispatch:Msg->Unit) =
let dirty = State.userIsdirty State.defaultScratchUser model.scratchUser (State.getCurrentUser model)
(match model.adminData with
| None -> div[][str "Loading user list..."]
| Some data ->
div [ ClassName "columns" ]
[
usersMenu model.userList model.scratchUser dispatch
div [ ClassName "column" ]
[
div [ ClassName "columns" ]
[
div [ ClassName "column" ]
| None -> div[][str "Loading user list..."]
| Some data ->
div
[ Class "columns is-fullheight" ]
[ NavRoot model.userList model.scratchUser dispatch
div [ Class "column is-main-content" ]
[
div [ ClassName "tabs is-boxed" ]
[ ul [ ]
[
div [ ClassName "tabs is-boxed" ]
[ ul [ ]
[
li [ ClassName (isActiveTab Tab.General model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.General)) ]
[ str "General" ] ]
li [ ClassName (isActiveTab Tab.Accounts model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.Accounts)) ]
[ str "Account Permissions" ] ]
li [ ClassName (isActiveTab Tab.MDEntitlements model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.MDEntitlements)) ]
[ str "Market Data Entitlements" ] ]
li [ ClassName (isActiveTab Tab.OrderRouting model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.OrderRouting)) ]
[ str "Order Routing" ] ]
]
]
]
div [ ClassName "column is-narrow" ]
[
yield saveButton model dispatch
yield Button.button "Revert" "is-light" "" (if dirty then Button.Enabled else Button.Disabled) (fun _ -> SwitchUser (State.getCurrentUser model) |> dispatch)
li [ ClassName (isActiveTab Tab.General model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.General)) ]
[ str "General" ] ]
li [ ClassName (isActiveTab Tab.Accounts model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.Accounts)) ]
[ str "Account Permissions" ] ]
li [ ClassName (isActiveTab Tab.MDEntitlements model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.MDEntitlements)) ]
[ str "Market Data Entitlements" ] ]
li [ ClassName (isActiveTab Tab.OrderRouting model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.OrderRouting)) ]
[ str "Order Routing" ] ]
]
]
tabContent model dispatch
]
]
userControls model dispatch
]
]
)
+1 -2
View File
@@ -55,11 +55,10 @@
<Compile Include="Users/Types.fs" />
<Compile Include="Users/State.fs" />
<Compile Include="Users/View.fs" />
<!-- Navbar -->
<Compile Include="Navbar/View.fs" />
<!-- App -->
<Compile Include="Types.fs" />
<Compile Include="State.fs" />
<Compile Include="Nav.fs" />
<Compile Include="App.fs" />
</ItemGroup>
<Import Project="..\.paket\Paket.Restore.targets" />
+1 -1
View File
@@ -64,7 +64,7 @@ module.exports = env => {
},
},
{
test: /\.sass$/,
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
+1 -1
View File
@@ -4,7 +4,7 @@ SETLOCAL
if "%SPARKVM_PORT%"=="" set SPARKVM_PORT=22
if "%1" == "" goto :err
echo.
ssh bts@sparkvm -p %SPARKVM_PORT% -o StrictHostKeyChecking=no -t "cd /home/bts/spark && git checkout %1 && git reset --hard && git clean -fd && git pull && git submodule update"
ssh bts@sparkvm -p %SPARKVM_PORT% -o StrictHostKeyChecking=no -t "cd /home/bts/spark ; git reset --hard ; git clean -fd ; git checkout %1 ; git pull ; git submodule update"
ENDLOCAL
goto :eof