code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Samba.Modules.SettingsModule")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.Modules.SettingsModule")] [assembly: AssemblyCopyright("Copyright © 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0acad2b8-c1d7-435a-a332-7e244839fe70")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/Properties/AssemblyInfo.cs
C#
gpl3
1,468
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain.Models.Tickets; using Samba.Localization.Properties; using Samba.Persistance.Data; using Samba.Presentation.Common; using Samba.Presentation.Common.ModelBase; using Samba.Presentation.Common.Services; using Samba.Services; namespace Samba.Modules.SettingsModule { public class GiftReasonListViewModel : EntityCollectionViewModelBase<GiftReasonViewModel, Reason> { public ICaptionCommand CreateBatchGiftReasons { get; set; } public GiftReasonListViewModel() { CreateBatchGiftReasons = new CaptionCommand<string>(Resources.BatchCreateGiftReasons, OnCreateBatchGiftReasons); CustomCommands.Add(CreateBatchGiftReasons); } private void OnCreateBatchGiftReasons(string obj) { var values = InteractionService.UserIntraction.GetStringFromUser( Resources.BatchCreateGiftReasons, Resources.BatchCreateReasonsHint); var createdItems = new DataCreationService().BatchCreateReasons(values, 1, Workspace); Workspace.CommitChanges(); foreach (var mv in createdItems.Select(CreateNewViewModel)) { mv.Init(Workspace); Items.Add(mv); } } protected override GiftReasonViewModel CreateNewViewModel(Reason model) { return new GiftReasonViewModel(model); } protected override Reason CreateNewModel() { return new Reason { ReasonType = 1 }; } protected override System.Collections.ObjectModel.ObservableCollection<GiftReasonViewModel> GetItemsList() { return BuildViewModelList(Workspace.All<Reason>(x => x.ReasonType == 1)); } protected override string CanDeleteItem(Reason model) { var gifts = Dao.Count<TicketItem>(x => x.Gifted && x.ReasonId == model.Id); return gifts > 0 ? Resources.DeleteErrorGiftReasonInUse : ""; } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/GiftReasonListViewModel.cs
C#
gpl3
2,168
using System; using Samba.Domain.Models.Settings; using Samba.Localization.Properties; using Samba.Presentation.Common.ModelBase; namespace Samba.Modules.SettingsModule { public class NumeratorViewModel : EntityViewModelBase<Numerator> { public string NumberFormat { get { return Model.NumberFormat; } set { Model.NumberFormat = value; } } public NumeratorViewModel(Numerator model) : base(model) { } public override Type GetViewType() { return typeof(NumeratorView); } public override string GetModelTypeString() { return Resources.Numerator; } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/NumeratorViewModel.cs
C#
gpl3
756
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Modules.SettingsModule { /// <summary> /// Interaction logic for GiftReasonView.xaml /// </summary> public partial class GiftReasonView : UserControl { public GiftReasonView() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/GiftReasonView.xaml.cs
C#
gpl3
666
using System.Windows.Controls; namespace Samba.Modules.SettingsModule { /// <summary> /// Interaction logic for VoidReasonView.xaml /// </summary> public partial class VoidReasonView : UserControl { public VoidReasonView() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/VoidReasonView.xaml.cs
C#
gpl3
333
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Samba.Domain.Models.Menus; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Tickets; using Samba.Infrastructure.Data; using Samba.Localization.Properties; using Samba.Persistance.Data; using Samba.Presentation.Common; using Samba.Presentation.Common.ModelBase; using Samba.Presentation.Common.Services; using Samba.Services; namespace Samba.Modules.SettingsModule { class PrintJobViewModel : EntityViewModelBase<PrintJob> { public PrintJobViewModel(PrintJob model) : base(model) { _newPrinterMaps = new List<PrinterMap>(); AddPrinterMapCommand = new CaptionCommand<string>(Resources.Add, OnAddPrinterMap); DeletePrinterMapCommand = new CaptionCommand<string>(Resources.Delete, OnDelete, CanDelete); } private IWorkspace _workspace; public ICaptionCommand AddPrinterMapCommand { get; set; } public ICaptionCommand DeletePrinterMapCommand { get; set; } private readonly IList<string> _whenToPrintTypes = new[] { Resources.Manual, Resources.WhenNewLinesAddedToTicket, Resources.WhenTicketPaid }; private readonly IList<string> _whatToPrintTypes = new[] { Resources.AllLines, Resources.OnlyNewLines, Resources.LinesGroupedByBarcode, Resources.LinesGroupedByGroupCode, Resources.LinesGroupedByTag, Resources.LastLinesByPrinterLineCount, Resources.LastPaidLines }; public IList<string> WhenToPrintTypes { get { return _whenToPrintTypes; } } public IList<string> WhatToPrintTypes { get { return _whatToPrintTypes; } } public IEnumerable<Department> Departments { get { return GetAllDepartments(); } } public IEnumerable<Printer> Printers { get { return _workspace.All<Printer>(); } } public IEnumerable<PrinterTemplate> PrinterTemplates { get { return _workspace.All<PrinterTemplate>(); } } private readonly IList<PrinterMap> _newPrinterMaps; private ObservableCollection<PrinterMapViewModel> _printerMaps; public ObservableCollection<PrinterMapViewModel> PrinterMaps { get { return _printerMaps ?? (_printerMaps = GetPrinterMaps()); } } public PrinterMapViewModel SelectedPrinterMap { get; set; } public string ButtonText { get { return Model.ButtonText; } set { Model.ButtonText = value; } } public string WhenToPrint { get { return _whenToPrintTypes[Model.WhenToPrint]; } set { Model.WhenToPrint = _whenToPrintTypes.IndexOf(value); } } public string WhatToPrint { get { return _whatToPrintTypes[Model.WhatToPrint]; } set { Model.WhatToPrint = _whatToPrintTypes.IndexOf(value); } } public bool LocksTicket { get { return Model.LocksTicket; } set { Model.LocksTicket = value; } } public bool CloseTicket { get { return Model.CloseTicket; } set { Model.CloseTicket = value; } } public bool UseFromPos { get { return Model.UseFromPos; } set { Model.UseFromPos = value; } } public bool UseFromPaymentScreen { get { return Model.UseFromPaymentScreen; } set { Model.UseFromPaymentScreen = value; } } public bool UseFromTerminal { get { return Model.UseFromTerminal; } set { Model.UseFromTerminal = value; } } public bool UseForPaidTickets { get { return Model.UseForPaidTickets; } set { Model.UseForPaidTickets = value; } } public bool ExcludeVat { get { return Model.ExcludeVat; } set { Model.ExcludeVat = value; } } public string PrintJobHint { get { if (Model.Id > 0 && !AppServices.Terminals.Any(x => x.PrintJobs.Any(y => y.Id == Model.Id))) { if (Dao.Count<Terminal>(x => x.PrintJobs.Count(y => y.Id == Model.Id) > 0) > 0) return ""; return Resources.PrintJobHint; } return ""; } } public bool AutoPrintIfCash { get { return Model.AutoPrintIfCash; } set { Model.AutoPrintIfCash = value; RaisePropertyChanged("AutoPrintIfCash"); } } public bool AutoPrintIfCreditCard { get { return Model.AutoPrintIfCreditCard; } set { Model.AutoPrintIfCreditCard = value; RaisePropertyChanged("AutoPrintIfCreditCard"); } } public bool AutoPrintIfTicket { get { return Model.AutoPrintIfTicket; } set { Model.AutoPrintIfTicket = value; RaisePropertyChanged("AutoPrintIfTicket"); } } private IEnumerable<Department> GetAllDepartments() { IList<Department> result = new List<Department>(_workspace.All<Department>().OrderBy(x => x.Name)); result.Insert(0, Department.All); return result; } private ObservableCollection<PrinterMapViewModel> GetPrinterMaps() { return new ObservableCollection<PrinterMapViewModel>( Model.PrinterMaps.Select( printerMap => new PrinterMapViewModel(printerMap, _workspace))); } public override Type GetViewType() { return typeof(PrintJobView); } public override string GetModelTypeString() { return Resources.PrintJob; } protected override void Initialize(IWorkspace workspace) { _workspace = workspace; } protected override void OnSave(string value) { foreach (var printerMap in _printerMaps) { if (printerMap.Department == Department.All) printerMap.Department = null; if (printerMap.MenuItem == MenuItem.All) printerMap.MenuItem = null; if (printerMap.MenuItemGroupCode == "*") printerMap.MenuItemGroupCode = null; if (printerMap.TicketTag == "*") printerMap.TicketTag = null; } foreach (var newPrinterMap in _newPrinterMaps) { if (newPrinterMap.Printer != null) { if (newPrinterMap.Department == Department.All) newPrinterMap.Department = null; if (newPrinterMap.MenuItem == MenuItem.All) newPrinterMap.MenuItem = null; if (newPrinterMap.MenuItemGroupCode == "*") newPrinterMap.MenuItemGroupCode = null; if (newPrinterMap.TicketTag == "*") newPrinterMap.TicketTag = null; _workspace.Add(newPrinterMap); } } base.OnSave(value); _newPrinterMaps.Clear(); } private void OnDelete(string obj) { if (InteractionService.UserIntraction.AskQuestion(Resources.DeleteSelectedMappingQuestion)) { var map = SelectedPrinterMap.Model; PrinterMaps.Remove(SelectedPrinterMap); Model.PrinterMaps.Remove(map); if (_newPrinterMaps.Contains(map)) _newPrinterMaps.Remove(map); else { _workspace.Delete(map); _workspace.CommitChanges(); } } } private bool CanDelete(string arg) { return SelectedPrinterMap != null; } private void OnAddPrinterMap(object obj) { var map = new PrinterMap { Department = Department.All, MenuItem = MenuItem.All, MenuItemGroupCode = "*" }; var mapModel = new PrinterMapViewModel(map, _workspace); Model.PrinterMaps.Add(map); PrinterMaps.Add(mapModel); _newPrinterMaps.Add(map); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/PrintJobViewModel.cs
C#
gpl3
8,112
using System.Windows.Controls; namespace Samba.Modules.SettingsModule { /// <summary> /// Interaction logic for SettingsView.xaml /// </summary> public partial class SettingsView : UserControl { public SettingsView() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/SettingsView.xaml.cs
C#
gpl3
332
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Modules.SettingsModule { /// <summary> /// Interaction logic for RuleView.xaml /// </summary> public partial class RuleView : UserControl { public RuleView() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/RuleView.xaml.cs
C#
gpl3
648
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Samba.Domain.Models.Actions; using Samba.Persistance.Data; using Samba.Presentation.Common; using Samba.Services; namespace Samba.Modules.SettingsModule { public class ActionParameterValue : ObservableObject { public string Name { get; set; } private string _value; public string Value { get { return _value; } set { _value = value; ActionContainer.UpdateParameters(); } } public IEnumerable<string> ParameterValues { get; set; } public ActionContainerViewModel ActionContainer { get; set; } public ActionParameterValue(ActionContainerViewModel actionContainer, string name, string value, IEnumerable<string> parameterValues) { Name = name; _value = value; ActionContainer = actionContainer; ParameterValues = parameterValues.Select(x => string.Format("[{0}]", x)); } } public class ActionContainerViewModel : ObservableObject { public ActionContainerViewModel(ActionContainer model, RuleViewModel ruleViewModel) { Model = model; _ruleViewModel = ruleViewModel; } private readonly RuleViewModel _ruleViewModel; private AppAction _action; public AppAction Action { get { return _action ?? (_action = Dao.Single<AppAction>(x => x.Id == Model.AppActionId)); } set { _action = value; } } public ActionContainer Model { get; set; } private ObservableCollection<ActionParameterValue> _parameterValues; public ObservableCollection<ActionParameterValue> ParameterValues { get { return _parameterValues ?? (_parameterValues = GetParameterValues()); } } private ObservableCollection<ActionParameterValue> GetParameterValues() { IEnumerable<ActionParameterValue> result; if (!string.IsNullOrEmpty(_ruleViewModel.EventName)) { if (string.IsNullOrEmpty(Model.ParameterValues)) { result = Regex.Matches(Action.Parameter, "\\[([^\\]]+)\\]") .Cast<Match>() .Select(match => new ActionParameterValue(this, match.Groups[1].Value, "", RuleActionTypeRegistry.GetParameterNames(_ruleViewModel.EventName))); } else { result = Model.ParameterValues.Split('#').Select( x => new ActionParameterValue(this, x.Split('=')[0], x.Split('=')[1], RuleActionTypeRegistry.GetParameterNames(_ruleViewModel.EventName))); } } else result = new List<ActionParameterValue>(); return new ObservableCollection<ActionParameterValue>(result); } public string Name { get { return Model.Name; } set { Model.Name = value; } } public void UpdateParameters() { Model.ParameterValues = string.Join("#", ParameterValues.Select(x => x.Name + "=" + x.Value)); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/ActionContainerViewModel.cs
C#
gpl3
3,418
using System; using Samba.Domain.Models.Tickets; using Samba.Localization.Properties; using Samba.Presentation.Common.ModelBase; namespace Samba.Modules.SettingsModule { public class VoidReasonViewModel : EntityViewModelBase<Reason> { public VoidReasonViewModel(Reason model) : base(model) { } public override Type GetViewType() { return typeof(VoidReasonView); } public override string GetModelTypeString() { return Resources.VoidReason; } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/VoidReasonViewModel.cs
C#
gpl3
598
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Presentation.Common.ModelBase; namespace Samba.Modules.SettingsModule { class BrowserViewModel : VisibleViewModelBase { public BrowserViewModel() { ActiveUrl = new Uri("about:Blank"); EventServiceFactory.EventService.GetEvent<GenericEvent<Uri>>().Subscribe(OnBrowseUri); } private void OnBrowseUri(EventParameters<Uri> obj) { if (obj.Topic == EventTopicNames.BrowseUrl) ActiveUrl = obj.Value; } private Uri _activeUrl; public Uri ActiveUrl { get { return _activeUrl; } set { _activeUrl = value; RaisePropertyChanged("ActiveUrl"); } } protected override string GetHeaderInfo() { return Resources.InternetBrowser; } public override Type GetViewType() { return typeof(BrowserView); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/BrowserViewModel.cs
C#
gpl3
1,203
using Samba.Domain.Models.Actions; using Samba.Presentation.Common.ModelBase; namespace Samba.Modules.SettingsModule { class RuleActionListViewModel: EntityCollectionViewModelBase<RuleActionViewModel, AppAction> { protected override RuleActionViewModel CreateNewViewModel(AppAction model) { return new RuleActionViewModel(model); } protected override AppAction CreateNewModel() { return new AppAction(); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/RuleActionListViewModel.cs
C#
gpl3
517
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain.Models.Actions; using Samba.Presentation.Common.ModelBase; namespace Samba.Modules.SettingsModule { class RuleListViewModel : EntityCollectionViewModelBase<RuleViewModel, AppRule> { protected override RuleViewModel CreateNewViewModel(AppRule model) { return new RuleViewModel(model); } protected override AppRule CreateNewModel() { return new AppRule(); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/RuleListViewModel.cs
C#
gpl3
576
using System; using System.Collections.Generic; using Samba.Domain.Models.Settings; using Samba.Localization.Properties; using Samba.Presentation.Common.ModelBase; using Samba.Services; namespace Samba.Modules.SettingsModule { public class PrinterViewModel : EntityViewModelBase<Printer> { public PrinterViewModel(Printer model) : base(model) { } public IList<string> PrinterTypes { get { return new[] { Resources.TicketPrinter, Resources.Text, Resources.Html, Resources.PortPrinter, Resources.DemoPrinter }; } } public string ShareName { get { return Model.ShareName; } set { Model.ShareName = value; } } public string PrinterType { get { return PrinterTypes[Model.PrinterType]; } set { Model.PrinterType = PrinterTypes.IndexOf(value); } } public int CodePage { get { return Model.CodePage; } set { Model.CodePage = value; } } public int CharsPerLine { get { return Model.CharsPerLine; } set { Model.CharsPerLine = value; } } public int PageHeight { get { return Model.PageHeight; } set { Model.PageHeight = value; } } public string ReplacementPattern { get { return Model.ReplacementPattern; } set { Model.ReplacementPattern = value; } } private IEnumerable<string> _printerNames; public IEnumerable<string> PrinterNames { get { return _printerNames ?? (_printerNames = GetPrinterNames()); } } private static IEnumerable<string> GetPrinterNames() { return AppServices.PrintService.GetPrinterNames(); } public override Type GetViewType() { return typeof(PrinterView); } public override string GetModelTypeString() { return Resources.Printer; } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/PrinterViewModel.cs
C#
gpl3
1,922
using Samba.Domain.Models.Settings; using Samba.Localization.Properties; using Samba.Presentation.Common.ModelBase; namespace Samba.Modules.SettingsModule { public class TerminalListViewModel : EntityCollectionViewModelBase<TerminalViewModel, Terminal> { protected override TerminalViewModel CreateNewViewModel(Terminal model) { return new TerminalViewModel(model); } protected override Terminal CreateNewModel() { return new Terminal(); } protected override string CanDeleteItem(Terminal model) { var count = Workspace.Count<Terminal>(); if (count == 1) return Resources.DeleteErrorShouldHaveAtLeastOneTerminal; return base.CanDeleteItem(model); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/TerminalListViewModel.cs
C#
gpl3
829
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Modules.SettingsModule { /// <summary> /// Interaction logic for MenuItemSettingsView.xaml /// </summary> public partial class ProgramSettingsView : UserControl { public ProgramSettingsView() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/ProgramSettingsView.xaml.cs
C#
gpl3
682
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain.Models.Settings; using Samba.Presentation.Common.ModelBase; using Samba.Presentation.Common.Services; using Samba.Services; namespace Samba.Modules.SettingsModule { class TriggerListViewModel : EntityCollectionViewModelBase<TriggerViewModel, Trigger> { protected override TriggerViewModel CreateNewViewModel(Trigger model) { return new TriggerViewModel(model); } protected override Trigger CreateNewModel() { return new Trigger(); } protected override void OnDeleteItem(object obj) { base.OnDeleteItem(obj); MethodQueue.Queue("UpdateCronObjects", TriggerService.UpdateCronObjects); } } }
zzgaminginc-pointofssale
Samba.Modules.SettingsModule/TriggerListViewModel.cs
C#
gpl3
861
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new MainWindowViewModel(); #if !DEBUG WindowStyle = WindowStyle.None; WindowState = WindowState.Maximized; #endif } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/MainWindow.xaml.cs
C#
gpl3
817
using System; using System.Collections.Generic; using Microsoft.Practices.Prism.Events; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Tickets; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Presentation.ViewModels; using Samba.Services; using System.Linq; namespace Samba.Presentation.Terminal { public delegate void TicketItemSelectedEventHandler(TicketItemViewModel item); public class TicketEditorViewModel : ObservableObject { public event EventHandler OnAddMenuItemsRequested; public event EventHandler OnCloseTicketRequested; public event EventHandler OnSelectTableRequested; public event EventHandler OnTicketNoteEditorRequested; public event EventHandler OnTicketTagEditorRequested; public void InvokeOnTicketTagEditorRequested(TicketTagGroup tag) { EventHandler handler = OnTicketTagEditorRequested; if (handler != null) handler(tag, EventArgs.Empty); } public void InvokeOnTicketNoteEditorRequested(EventArgs e) { EventHandler handler = OnTicketNoteEditorRequested; if (handler != null) handler(this, e); } public void InvokeOnSelectTableRequested(EventArgs e) { EventHandler handler = OnSelectTableRequested; if (handler != null) handler(this, e); } public void InvokeCloseTicketRequested(EventArgs e) { EventHandler handler = OnCloseTicketRequested; if (handler != null) handler(this, e); } public void InvokeOnAddMenuItemsRequested(EventArgs e) { EventHandler handler = OnAddMenuItemsRequested; if (handler != null) handler(this, e); } public TicketViewModel SelectedTicket { get { return DataContext.SelectedTicket; } } private string _selectedTicketTitle; public string SelectedTicketTitle { get { return _selectedTicketTitle; } set { _selectedTicketTitle = value; RaisePropertyChanged("SelectedTicketTitle"); } } public bool IsTicketTotalVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketTotalVisible; } } public bool IsTicketPaymentVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketPaymentVisible; } } public bool IsTicketRemainingVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketRemainingVisible; } } public bool IsTicketDiscountVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketDiscountVisible; } } private bool? _isTableButtonVisible; public bool? IsTableButtonVisible { get { return _isTableButtonVisible ?? (_isTableButtonVisible = AppServices.MainDataContext.SelectedDepartment != null && AppServices.MainDataContext.SelectedDepartment.TerminalTableScreenId > 0); } } public string Note { get { if (SelectedTicket != null) { var result = SelectedTicket.Note; if (SelectedTicket.IsTagged) if (!string.IsNullOrEmpty(result)) result = Resources.Note + ": " + result + "\r"; result += SelectedTicket.TagDisplay; return result; } return ""; } } public bool IsTicketNoteVisible { get { return SelectedTicket != null && (SelectedTicket.IsTicketNoteVisible || SelectedTicket.IsTagged); } } public TicketItemViewModel LastSelectedTicketItem { get; set; } public CaptionCommand<string> AddMenuItemsCommand { get; set; } public CaptionCommand<string> PrintTicketCommand { get; set; } public CaptionCommand<string> DeleteSelectedItemsCommand { get; set; } public CaptionCommand<string> ChangeTableCommand { get; set; } public CaptionCommand<string> IncSelectedQuantityCommand { get; set; } public CaptionCommand<string> DecSelectedQuantityCommand { get; set; } public CaptionCommand<string> MoveSelectedItemsCommand { get; set; } public CaptionCommand<string> EditTicketNoteCommand { get; set; } public CaptionCommand<PrintJob> PrintJobCommand { get; set; } public CaptionCommand<TicketTagGroup> TicketTagCommand { get; set; } public IEnumerable<PrintJobButton> PrintJobButtons { get { return SelectedTicket != null ? SelectedTicket.PrintJobButtons.Where(x => x.Model.UseFromTerminal) : null; } } public IEnumerable<TicketTagButton> TicketTagButtons { get { return SelectedTicket != null ? AppServices.MainDataContext.SelectedDepartment.TicketTagGroups .Where(x => x.ActiveOnTerminalClient) .OrderBy(x => x.Order) .Select(x => new TicketTagButton(x, SelectedTicket)) : null; } } public TicketEditorViewModel() { AddMenuItemsCommand = new CaptionCommand<string>(Resources.Add, OnAddMenuItems, CanAddMenuItems); DeleteSelectedItemsCommand = new CaptionCommand<string>(Resources.Delete_ab, OnDeleteSelectedItems, CanDeleteSelectedItems); ChangeTableCommand = new CaptionCommand<string>(Resources.Table, OnChangeTable, CanChangeTable); IncSelectedQuantityCommand = new CaptionCommand<string>("+", OnIncSelectedQuantity, CanIncSelectedQuantity); DecSelectedQuantityCommand = new CaptionCommand<string>("-", OnDecSelectedQuantity, CanDecSelectedQuantity); MoveSelectedItemsCommand = new CaptionCommand<string>(Resources.Divide_ab, OnMoveSelectedItems, CanMoveSelectedItems); EditTicketNoteCommand = new CaptionCommand<string>(Resources.Note, OnEditTicketNote); PrintJobCommand = new CaptionCommand<PrintJob>(Resources.Print_ab, OnPrintJobExecute, CanExecutePrintJob); TicketTagCommand = new CaptionCommand<TicketTagGroup>("Tag", OnTicketTagExecute, CanTicketTagExecute); EventServiceFactory.EventService.GetEvent<GenericEvent<TicketItemViewModel>>().Subscribe( x => { if (SelectedTicket != null && x.Topic == EventTopicNames.SelectedItemsChanged) { LastSelectedTicketItem = x.Value.Selected ? x.Value : null; foreach (var item in SelectedTicket.SelectedItems) { item.IsLastSelected = item == LastSelectedTicketItem; } } }); EventServiceFactory.EventService.GetEvent<GenericEvent<EventAggregator>>().Subscribe( x => { if (x.Topic == EventTopicNames.RefreshSelectedTicket) { DataContext.RefreshSelectedTicket(); Refresh(); } }); } private bool CanExecutePrintJob(PrintJob arg) { return arg != null && SelectedTicket != null && (!SelectedTicket.IsLocked || SelectedTicket.Model.GetPrintCount(arg.Id) == 0); } private void OnPrintJobExecute(PrintJob printJob) { var message = SelectedTicket.GetPrintError(); if (!string.IsNullOrEmpty(message)) { MainWindowViewModel.ShowFeedback(message); return; } if (SelectedTicket.Id == 0) { var result = DataContext.CloseSelectedTicket(); DataContext.OpenTicket(result.TicketId); } AppServices.PrintService.ManualPrintTicket(SelectedTicket.Model, printJob); InvokeCloseTicketRequested(EventArgs.Empty); } private bool CanTicketTagExecute(TicketTagGroup arg) { return SelectedTicket != null && (!SelectedTicket.IsLocked || !SelectedTicket.IsTaggedWith(arg.Name)); } private void OnTicketTagExecute(TicketTagGroup obj) { InvokeOnTicketTagEditorRequested(obj); } private void OnEditTicketNote(string obj) { InvokeOnTicketNoteEditorRequested(EventArgs.Empty); } private void OnMoveSelectedItems(string obj) { InvokeOnSelectTableRequested(EventArgs.Empty); } private bool CanMoveSelectedItems(string arg) { return SelectedTicket != null && SelectedTicket.SelectedItems.Count > 0 && SelectedTicket.CanMoveSelectedItems(); } private bool CanDecSelectedQuantity(string arg) { return LastSelectedTicketItem != null && LastSelectedTicketItem.Quantity > 1 && !LastSelectedTicketItem.IsGifted && !LastSelectedTicketItem.IsVoided; } private void OnDecSelectedQuantity(string obj) { if (LastSelectedTicketItem.IsLocked) LastSelectedTicketItem.DecSelectedQuantity(); else LastSelectedTicketItem.Quantity--; } private bool CanIncSelectedQuantity(string arg) { return LastSelectedTicketItem != null && (LastSelectedTicketItem.Quantity > 1 || !LastSelectedTicketItem.IsLocked) && !LastSelectedTicketItem.IsGifted && !LastSelectedTicketItem.IsVoided; } private void OnIncSelectedQuantity(string obj) { if (LastSelectedTicketItem.IsLocked) LastSelectedTicketItem.IncSelectedQuantity(); else LastSelectedTicketItem.Quantity++; } private bool CanChangeTable(string arg) { if (SelectedTicket != null && !SelectedTicket.IsLocked) return SelectedTicket.CanChangeTable(); return true; } private void OnChangeTable(string obj) { SelectedTicket.ClearSelectedItems(); InvokeOnSelectTableRequested(EventArgs.Empty); } private bool CanDeleteSelectedItems(string arg) { return SelectedTicket != null && SelectedTicket.CanCancelSelectedItems(); } private void OnDeleteSelectedItems(string obj) { SelectedTicket.CancelSelectedItems(); } public void UpdateSelectedTicketTitle() { SelectedTicketTitle = SelectedTicket == null ? Resources.NewTicket : SelectedTicket.Title; } public void Refresh() { RaisePropertyChanged("SelectedTicket"); RaisePropertyChanged("IsTicketRemainingVisible"); RaisePropertyChanged("IsTicketPaymentVisible"); RaisePropertyChanged("IsTicketTotalVisible"); RaisePropertyChanged("IsTicketDiscountVisible"); RaisePropertyChanged("PrintJobButtons"); RaisePropertyChanged("TicketTagButtons"); RaisePropertyChanged("Note"); RaisePropertyChanged("IsTicketNoteVisible"); RaisePropertyChanged("IsTableButtonVisible"); UpdateSelectedTicketTitle(); } private void OnAddMenuItems(string obj) { InvokeOnAddMenuItemsRequested(EventArgs.Empty); } private bool CanAddMenuItems(string arg) { if (SelectedTicket != null && SelectedTicket.IsLocked) return AppServices.IsUserPermittedFor(PermissionNames.AddItemsToLockedTickets); return true; } public void ResetCache() { _isTableButtonVisible = null; } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/TicketEditorViewModel.cs
C#
gpl3
12,561
using System.Collections.ObjectModel; using System.Linq; using Microsoft.Practices.Prism.Commands; using Samba.Domain.Models.Menus; using Samba.Localization.Properties; using Samba.Presentation.ViewModels; using Samba.Services; using Samba.Presentation.Common; namespace Samba.Presentation.Terminal { public class MenuItemSelectorViewModel : ObservableObject { public event TicketItemSelectedEventHandler OnTicketItemSelected; public void InvokeOnTicketItemSelected(TicketItemViewModel ticketItem) { TicketItemSelectedEventHandler handler = OnTicketItemSelected; if (handler != null) handler(ticketItem); } public ScreenMenu CurrentScreenMenu { get; set; } public ScreenMenuCategory MostUsedItemsCategory { get; set; } public ObservableCollection<ScreenMenuItemButton> MostUsedMenuItems { get; set; } public ObservableCollection<ScreenCategoryButton> Categories { get; set; } public ObservableCollection<ScreenMenuItemButton> MenuItems { get; set; } public DelegateCommand<ScreenMenuCategory> CategorySelectionCommand { get; set; } public DelegateCommand<ScreenMenuItem> MenuItemSelectionCommand { get; set; } public DelegateCommand<TicketItemViewModel> ItemSelectedCommand { get; set; } public ObservableCollection<TicketItemViewModel> AddedMenuItems { get; set; } private ScreenMenuCategory _selectedCategory; public ScreenMenuCategory SelectedCategory { get { return _selectedCategory; } set { _selectedCategory = value; if (IsQuickNumeratorVisible) { QuickNumeratorValues = string.IsNullOrEmpty(value.NumeratorValues) ? new[] { "1", "2", "3", "4", "5" } : value.NumeratorValues.Split(','); NumeratorValue = QuickNumeratorValues[0]; } else NumeratorValue = ""; RaisePropertyChanged("IsQuickNumeratorVisible"); RaisePropertyChanged("QuickNumeratorValues"); RaisePropertyChanged("IsPageNumberNavigatorVisible"); RaisePropertyChanged("SelectedCategory"); } } private string _numeratorValue; public string NumeratorValue { get { return _numeratorValue; } set { _numeratorValue = value; RaisePropertyChanged("NumeratorValue"); } } public string[] QuickNumeratorValues { get; set; } public bool IsQuickNumeratorVisible { get { return SelectedCategory != null && SelectedCategory.IsQuickNumeratorVisible; } } public bool IsPageNumberNavigatorVisible { get { return SelectedCategory != null && SelectedCategory.PageCount > 1; } } public ICaptionCommand IncPageNumberCommand { get; set; } public ICaptionCommand DecPageNumberCommand { get; set; } public int CurrentPageNo { get; set; } public string CurrentTag { get; set; } public MenuItemSelectorViewModel() { MostUsedMenuItems = new ObservableCollection<ScreenMenuItemButton>(); Categories = new ObservableCollection<ScreenCategoryButton>(); MenuItems = new ObservableCollection<ScreenMenuItemButton>(); AddedMenuItems = new ObservableCollection<TicketItemViewModel>(); CategorySelectionCommand = new DelegateCommand<ScreenMenuCategory>(OnCategorySelected); MenuItemSelectionCommand = new DelegateCommand<ScreenMenuItem>(OnMenuItemSelected); ItemSelectedCommand = new DelegateCommand<TicketItemViewModel>(OnItemSelected); IncPageNumberCommand = new CaptionCommand<string>(Resources.Next + " >>", OnIncPageNumber, CanIncPageNumber); DecPageNumberCommand = new CaptionCommand<string>("<< " + Resources.Previous, OnDecPageNumber, CanDecPageNumber); } private void OnDecPageNumber(string obj) { CurrentPageNo--; UpdateMenuButtons(SelectedCategory); } private bool CanDecPageNumber(string arg) { return CurrentPageNo > 0; } private bool CanIncPageNumber(object arg) { return SelectedCategory != null && CurrentPageNo < SelectedCategory.PageCount - 1; } private void OnIncPageNumber(object obj) { CurrentPageNo++; UpdateMenuButtons(SelectedCategory); } private void OnItemSelected(TicketItemViewModel obj) { InvokeOnTicketItemSelected(obj); } private void OnMenuItemSelected(ScreenMenuItem obj) { if (DataContext.SelectedTicket.IsLocked && !AppServices.IsUserPermittedFor(PermissionNames.AddItemsToLockedTickets)) return; decimal selectedMultiplier = 1; if (!string.IsNullOrEmpty(NumeratorValue)) decimal.TryParse(NumeratorValue, out selectedMultiplier); if (IsQuickNumeratorVisible) NumeratorValue = QuickNumeratorValues[0]; if (selectedMultiplier > 0) { if ((QuickNumeratorValues == null || selectedMultiplier.ToString() == QuickNumeratorValues[0]) && obj.Quantity > 1) selectedMultiplier = obj.Quantity; } var item = DataContext.SelectedTicket.AddNewItem(obj.MenuItemId, selectedMultiplier, obj.Gift, obj.DefaultProperties, obj.ItemPortion); if (item != null) AddedMenuItems.Add(item); if (obj.AutoSelect) InvokeOnTicketItemSelected(item); } private void OnCategorySelected(ScreenMenuCategory obj) { UpdateMenuButtons(obj); } private void UpdateMenuButtons(ScreenMenuCategory category) { SelectedCategory = category; CreateMenuItemButtons(MenuItems, category, CurrentPageNo, CurrentTag); } public void Refresh() { AddedMenuItems.Clear(); if (CurrentScreenMenu == null) { CurrentScreenMenu = AppServices.MainDataContext.SelectedDepartment != null ? AppServices.DataAccessService.GetScreenMenu(AppServices.MainDataContext.SelectedDepartment.TerminalScreenMenuId) : null; if (CurrentScreenMenu != null) { Categories.Clear(); Categories.AddRange(CurrentScreenMenu.Categories.OrderBy(x => x.Order) .Where(x => !x.MostUsedItemsCategory) .Select(x => new ScreenCategoryButton(x, CategorySelectionCommand))); MostUsedItemsCategory = CurrentScreenMenu.Categories.FirstOrDefault(x => x.MostUsedItemsCategory); if (MostUsedItemsCategory != null) CreateMenuItemButtons(MostUsedMenuItems, MostUsedItemsCategory, CurrentPageNo, CurrentTag); if (Categories.Count > 0) { UpdateMenuButtons(Categories[0].Category); } } } } private void CreateMenuItemButtons(ObservableCollection<ScreenMenuItemButton> itemButtons, ScreenMenuCategory category, int pageNo, string tag) { itemButtons.Clear(); if (category == null) return; itemButtons.AddRange(AppServices.DataAccessService.GetMenuItems(category, pageNo, tag) .Select(x => new ScreenMenuItemButton(x, MenuItemSelectionCommand, category))); } public void CloseView() { AddedMenuItems.Clear(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/MenuItemSelectorViewModel.cs
C#
gpl3
7,964
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Samba.Presentation.Common; using Samba.Presentation.ViewModels; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for TicketEditorView.xaml /// </summary> public partial class TicketEditorView : UserControl { public TicketEditorView() { InitializeComponent(); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { Scroller.ScrollToEnd(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/TicketEditorView.xaml.cs
C#
gpl3
879
using System.Collections.ObjectModel; using System.Linq; using System.Windows; using Microsoft.Practices.Prism.Commands; using Samba.Domain.Models.Tables; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Presentation.ViewModels; using Samba.Services; namespace Samba.Presentation.Terminal { public delegate void TableSelectionEventHandler(Table selectedTable); public class TableScreenViewModel : ObservableObject { public int CurrentPageNo { get; set; } public ObservableCollection<TableScreenItemViewModel> Tables { get; set; } public TableScreen SelectedTableScreen { get { return AppServices.MainDataContext.SelectedTableScreen; } } public ICaptionCommand IncPageNumberCommand { get; set; } public ICaptionCommand DecPageNumberCommand { get; set; } public DelegateCommand<Table> SelectTableCommand { get; set; } public DelegateCommand<string> TypeValueCommand { get; set; } public DelegateCommand<string> FindTableCommand { get; set; } public event TableSelectionEventHandler TableSelectedEvent; public VerticalAlignment TableScreenAlignment { get { return SelectedTableScreen != null && SelectedTableScreen.ButtonHeight > 0 ? VerticalAlignment.Top : VerticalAlignment.Stretch; } } private bool _fullScreenNumerator; public void DisplayFullScreenNumerator() { _fullScreenNumerator = true; RaisePropertyChanged("NavigatorHeight"); RaisePropertyChanged("IsTablesVisible"); NumeratorHeight = double.NaN; } public void HideFullScreenNumerator() { NumeratorValue = ""; _fullScreenNumerator = false; if (SelectedTableScreen != null) NumeratorHeight = SelectedTableScreen.NumeratorHeight; RaisePropertyChanged("NavigatorHeight"); RaisePropertyChanged("NumeratorHeight"); RaisePropertyChanged("IsTablesVisible"); } public bool IsTablesVisible { get { return !_fullScreenNumerator; } } private double _numeratorHeight; public double NumeratorHeight { get { return _numeratorHeight; } set { _numeratorHeight = value; RaisePropertyChanged("NumeratorHeight"); } } private string[] _alphaButtonValues; public string[] AlphaButtonValues { get { return _alphaButtonValues; } set { _alphaButtonValues = value; RaisePropertyChanged("AlphaButtonValues"); } } private string _numeratorValue; public string NumeratorValue { get { return _numeratorValue; } set { _numeratorValue = value; RaisePropertyChanged("NumeratorValue"); } } public TableScreenViewModel() { Tables = new ObservableCollection<TableScreenItemViewModel>(); IncPageNumberCommand = new CaptionCommand<string>(Resources.NextPage, OnIncPageNumber, CanIncPageNumber); DecPageNumberCommand = new CaptionCommand<string>(Resources.PreviousPage, OnDecPageNumber, CanDecPageNumber); SelectTableCommand = new DelegateCommand<Table>(OnSelectTable); TypeValueCommand = new DelegateCommand<string>(OnTypeValueExecute); FindTableCommand = new DelegateCommand<string>(OnFindTableExecute); } public void InvokeOnTableSelected(Table table) { var handler = TableSelectedEvent; if (handler != null) handler(table); } private void OnFindTableExecute(string obj) { if (!string.IsNullOrEmpty(NumeratorValue)) { var table = AppServices.DataAccessService.GetTable(NumeratorValue); if (table != null) { InvokeOnTableSelected(table); } } HideFullScreenNumerator(); } private void OnTypeValueExecute(string obj) { if (obj == "\r") FindTableCommand.Execute(""); else if (obj == "\b" && !string.IsNullOrEmpty(NumeratorValue)) NumeratorValue = NumeratorValue.Substring(0, NumeratorValue.Length - 1); else NumeratorValue = obj == "clear" ? "" : Helpers.AddTypedValue(NumeratorValue, obj, "#0."); } private void OnSelectTable(Table obj) { InvokeOnTableSelected(obj); } public string NavigatorHeight { get { return SelectedTableScreen != null && !_fullScreenNumerator && SelectedTableScreen.PageCount > 1 ? "25" : "0"; } } private bool CanDecPageNumber(string arg) { return CurrentPageNo > 0; } private void OnDecPageNumber(string obj) { CurrentPageNo--; UpdateTables(); } private bool CanIncPageNumber(string arg) { return SelectedTableScreen != null && CurrentPageNo < SelectedTableScreen.PageCount - 1; } private void OnIncPageNumber(string obj) { CurrentPageNo++; UpdateTables(); } public void Refresh() { UpdateTables(); } private void UpdateTables() { Tables.Clear(); Tables.AddRange(AppServices.DataAccessService.GetCurrentTables(AppServices.MainDataContext.SelectedDepartment.TerminalTableScreenId, CurrentPageNo) .Select(x => new TableScreenItemViewModel(x, AppServices.MainDataContext.SelectedTableScreen))); if (SelectedTableScreen != null) { AlphaButtonValues = !string.IsNullOrEmpty(SelectedTableScreen.AlphaButtonValues) ? SelectedTableScreen.AlphaButtonValues.Split(',') : new string[0]; NumeratorHeight = SelectedTableScreen.NumeratorHeight; } else { NumeratorHeight = 0; AlphaButtonValues = new string[0]; } RaisePropertyChanged("Tables"); RaisePropertyChanged("NavigatorHeight"); RaisePropertyChanged("SelectedTableScreen"); RaisePropertyChanged("NumeratorHeight"); RaisePropertyChanged("TableScreenAlignment"); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/TableScreenViewModel.cs
C#
gpl3
6,780
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for DepartmentSelectorView.xaml /// </summary> public partial class DepartmentSelectorView : UserControl { public DepartmentSelectorView() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/DepartmentSelectorView.xaml.cs
C#
gpl3
689
using System; using System.Diagnostics; using System.Windows; using Samba.Domain.Models.Tables; using Samba.Domain.Models.Tickets; using Samba.Domain.Models.Users; using Samba.Infrastructure; using Samba.Infrastructure.Settings; using Samba.Localization.Engine; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Presentation.Common.Services; using Samba.Presentation.ViewModels; using Samba.Services; using System.Linq; namespace Samba.Presentation.Terminal { public class MainWindowViewModel : ObservableObject { public MainWindowViewModel() { //TODO: Para birimi servisinden al. LocalizeDictionary.ChangeLanguage(LocalSettings.CurrentLanguage); LocalSettings.SetTraceLogPath("term"); LocalSettings.DefaultCurrencyFormat = "#,#0.00"; LocalSettings.AppPath = System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location); AppServices.MainDispatcher = Application.Current.Dispatcher; GenericRuleRegistator.RegisterOnce(); TriggerService.UpdateCronObjects(); LoggedInUserViewModel = new LoggedInUserViewModel(); LoggedInUserViewModel.CloseButtonClickedEvent += LoggedInUserViewModelCloseButtonClickedEvent; LoginViewModel = new LoginViewModel(); LoginViewModel.PinSubmitted += LoginViewModelPinSubmitted; TableScreenViewModel = new TableScreenViewModel(); TableScreenViewModel.TableSelectedEvent += TableScreenViewModelTableSelectedEvent; TicketScreenViewModel = new TicketScreenViewModel(); TicketScreenViewModel.TicketSelectedEvent += TicketScreenViewModelTicketSelectedEvent; DepartmentSelectorViewModel = new DepartmentSelectorViewModel(); DepartmentSelectorViewModel.DepartmentSelected += DepartmentSelectorViewModelDepartmentSelected; TicketEditorViewModel = new TicketEditorViewModel(); TicketEditorViewModel.OnAddMenuItemsRequested += TicketEditorViewModel_OnAddMenuItemsRequested; TicketEditorViewModel.OnCloseTicketRequested += TicketEditorViewModel_OnCloseTicketRequested; TicketEditorViewModel.OnSelectTableRequested += TicketEditorViewModel_OnSelectTableRequested; TicketEditorViewModel.OnTicketNoteEditorRequested += TicketEditorViewModel_OnTicketNoteEditorRequested; TicketEditorViewModel.OnTicketTagEditorRequested += TicketEditorViewModel_OnTicketTagEditorRequested; MenuItemSelectorViewModel = new MenuItemSelectorViewModel(); MenuItemSelectorViewModel.OnTicketItemSelected += MenuItemSelectorViewModel_OnTicketItemSelected; SelectedTicketItemEditorViewModel = new SelectedTicketItemEditorViewModel(); SelectedTicketItemEditorViewModel.TagUpdated += SelectedTicketItemEditorViewModelTagUpdated; PermissionRegistry.RegisterPermission(PermissionNames.AddItemsToLockedTickets, PermissionCategories.Ticket, "Kilitli adisyona ekleme yapabilir"); PermissionRegistry.RegisterPermission(PermissionNames.GiftItems, PermissionCategories.Ticket, "İkram yapabilir"); PermissionRegistry.RegisterPermission(PermissionNames.VoidItems, PermissionCategories.Ticket, "İade alabilir"); PermissionRegistry.RegisterPermission(PermissionNames.MoveTicketItems, PermissionCategories.Ticket, "Adisyon satırlarını taşıyabilir"); PermissionRegistry.RegisterPermission(PermissionNames.MoveUnlockedTicketItems, PermissionCategories.Ticket, "Kilitlenmemiş adisyon satırlarını taşıyabilir"); PermissionRegistry.RegisterPermission(PermissionNames.ChangeExtraProperty, PermissionCategories.Ticket, "Ekstra özellik girebilir"); AppServices.MessagingService.RegisterMessageListener(new MessageListener()); if (LocalSettings.StartMessagingClient) AppServices.MessagingService.StartMessagingClient(); EventServiceFactory.EventService.GetEvent<GenericEvent<Message>>().Subscribe( x => { if (SelectedIndex == 2 && x.Topic == EventTopicNames.MessageReceivedEvent && x.Value.Command == Messages.TicketRefreshMessage) { TableScreenViewModel.Refresh(); } }); } void SelectedTicketItemEditorViewModelTagUpdated(TicketTagGroup item) { Debug.Assert(DataContext.SelectedTicket != null); if (DataContext.SelectedTicket.Items.Count == 0) { ActivateMenuItemSelector(); } else if (item.Action > 0) { CloseSelectedTicket(); ActivateTableView(); } else { ActivateTicketView(null); } } private int _selectedIndex; public int SelectedIndex { get { return _selectedIndex; } set { _selectedIndex = value; RaisePropertyChanged("SelectedIndex"); RaisePropertyChanged("IsLoggedUserVisible"); } } private int _selectedTicketViewIndex; public int SelectedTicketViewIndex { get { return _selectedTicketViewIndex; } set { _selectedTicketViewIndex = value; RaisePropertyChanged("SelectedTicketViewIndex"); } } public bool IsLoggedUserVisible { get { return SelectedIndex != 0; } } public LoggedInUserViewModel LoggedInUserViewModel { get; set; } public LoginViewModel LoginViewModel { get; set; } public TableScreenViewModel TableScreenViewModel { get; set; } public TicketScreenViewModel TicketScreenViewModel { get; set; } public DepartmentSelectorViewModel DepartmentSelectorViewModel { get; set; } public TicketEditorViewModel TicketEditorViewModel { get; set; } public MenuItemSelectorViewModel MenuItemSelectorViewModel { get; set; } public SelectedTicketItemEditorViewModel SelectedTicketItemEditorViewModel { get; set; } void LoginViewModelPinSubmitted(object sender, string pinValue) { if (pinValue == "065058") { Application.Current.Shutdown(); } var user = AppServices.LoginUser(pinValue); LoggedInUserViewModel.Refresh(); if (user != User.Nobody) { if (user.UserRole.DepartmentId != 0 && !AppServices.IsUserPermittedFor(PermissionNames.ChangeDepartment)) { AppServices.MainDataContext.SelectedDepartment = AppServices.MainDataContext.Departments.Single(x => x.Id == user.UserRole.DepartmentId); ActivateTableView(); } else if (AppServices.MainDataContext.PermittedDepartments.Count() == 1) { AppServices.MainDataContext.SelectedDepartment = AppServices.MainDataContext.PermittedDepartments.First(); ActivateTableView(); } else ActivateDepartmentSelector(); } TicketEditorViewModel.ResetCache(); } void TicketScreenViewModelTicketSelectedEvent(int selectedTicketId) { if (!AppServices.MainDataContext.IsCurrentWorkPeriodOpen) { ShowFeedback(Resources.WorkPeriodEnded); return; } DataContext.OpenTicket(selectedTicketId); if (selectedTicketId > 0) { ActivateTicketView(null); } else { if (ShouldSelectTag()) return; ActivateMenuItemSelector(); } } void TableScreenViewModelTableSelectedEvent(Table selectedTable) { //Id #10: Gün sonu yapıldıysa iptal et. if (!AppServices.MainDataContext.IsCurrentWorkPeriodOpen) { ShowFeedback(Resources.WorkPeriodEnded); return; } if (DataContext.SelectedTicket != null) { if (DataContext.SelectedTicket.SelectedItems.Count == 0) { TicketViewModel.AssignTableToSelectedTicket(selectedTable.Id); //AppServices.MainDataContext.AssignTableToSelectedTicket(selectedTable.Id); //{LocText TicketMovedToTable_f} ShowFeedback(string.Format(Resources.TicketMovedToTable_f, "", selectedTable.Name)); } else { MoveSelectedItems(selectedTable.Id); ShowFeedback(string.Format(Resources.ItemsMovedToTable_f, selectedTable.Name)); } CloseSelectedTicket(); ActivateTableView(); } else ActivateTicketView(selectedTable); } void LoggedInUserViewModelCloseButtonClickedEvent(object sender, EventArgs e) { if (SelectedIndex == 5) { if (SelectedTicketItemEditorViewModel.SelectedTicketTag != null && DataContext.SelectedTicket.Items.Count == 0) { DataContext.CloseSelectedTicket(); ActivateTableView(); } else if (MenuItemSelectorViewModel.AddedMenuItems.Count > 0) SelectedIndex = 4; else ActivateTicketView(null); SelectedTicketItemEditorViewModel.CloseView(); } else if (SelectedIndex == 4) { if (DataContext.SelectedTicket.Items.Count > 0) { DataContext.SelectedTicket.MergeLines(); MenuItemSelectorViewModel.CloseView(); ActivateTicketView(null); } else { CloseSelectedTicket(); ActivateTableView(); } } else if (SelectedIndex == 3) { if (CanCloseSelectedTicket()) { CloseSelectedTicket(); ActivateTableView(); } } else if (SelectedIndex == 2 && AppServices.MainDataContext.SelectedTicket != null) { SelectedIndex = 3; } else { TableScreenViewModel.CurrentPageNo = 0; TableScreenViewModel.HideFullScreenNumerator(); MenuItemSelectorViewModel.CurrentScreenMenu = null; AppServices.LogoutUser(); ActivateLoginView(); } } void DepartmentSelectorViewModelDepartmentSelected(object sender, EventArgs e) { AppServices.MainDataContext.SelectedTableScreen = null; AppServices.MainDataContext.SelectedDepartment = DepartmentSelectorViewModel.SelectedDepartment; TicketEditorViewModel.ResetCache(); ActivateTableView(); } void TicketEditorViewModel_OnTicketTagEditorRequested(object sender, EventArgs e) { ActivateSelectedTicketItemEditorView(null, sender as TicketTagGroup); } void TicketEditorViewModel_OnTicketNoteEditorRequested(object sender, EventArgs e) { ActivateSelectedTicketItemEditorView(null, null); } void TicketEditorViewModel_OnSelectTableRequested(object sender, EventArgs e) { if (CanCloseSelectedTicket()) ActivateTableView(); } private void TicketEditorViewModel_OnCloseTicketRequested(object sender, EventArgs e) { CloseSelectedTicket(); ActivateTableView(); } private static void CloseSelectedTicket() { var result = DataContext.CloseSelectedTicket(); if (!string.IsNullOrEmpty(result.ErrorMessage)) ShowFeedback(result.ErrorMessage); } private void TicketEditorViewModel_OnAddMenuItemsRequested(object sender, EventArgs e) { ActivateMenuItemSelector(); } void MenuItemSelectorViewModel_OnTicketItemSelected(TicketItemViewModel item) { ActivateSelectedTicketItemEditorView(item, null); } private void ActivateSelectedTicketItemEditorView(TicketItemViewModel item, TicketTagGroup selectedTicketTag) { SelectedIndex = 5; SelectedTicketItemEditorViewModel.Refresh(item, selectedTicketTag); } private void ActivateLoginView() { SelectedIndex = 0; } private void ActivateTableView() { SelectedIndex = 2; if (AppServices.MainDataContext.SelectedDepartment.TerminalTableScreenId > 0) { SelectedTicketViewIndex = 0; TableScreenViewModel.Refresh(); } else { if (DataContext.SelectedTicket != null) { if (DataContext.SelectedTicket.SelectedItems.Count > 0) { MoveSelectedItems(0); if (ShouldSelectTag()) return; } ActivateTicketView(null); } else { SelectedTicketViewIndex = 1; TicketScreenViewModel.Refresh(); } } LoggedInUserViewModel.Refresh(); } private void ActivateTicketView(Table table) { if (table != null) { DataContext.UpdateSelectedTicket(table); if (table.TicketId == 0) { ActivateMenuItemSelector(); return; } } LoggedInUserViewModel.Refresh(); TicketEditorViewModel.Refresh(); SelectedIndex = 3; } private void ActivateDepartmentSelector() { SelectedIndex = 1; DepartmentSelectorViewModel.Refresh(); } private void ActivateMenuItemSelector() { SelectedIndex = 4; LoggedInUserViewModel.Refresh(); MenuItemSelectorViewModel.Refresh(); } internal static void ShowFeedback(string message) { var window = new FeedbackWindow { Message = { Text = message } }; window.ShowDialog(); } static bool CanCloseSelectedTicket() { var err = DataContext.SelectedTicket.GetPrintError(); if (!string.IsNullOrEmpty(err)) { ShowFeedback(err); return false; } return true; } private static void MoveSelectedItems(int tableId) { Debug.Assert(DataContext.SelectedTicket != null); Debug.Assert(DataContext.SelectedTicket.SelectedItems.Count > 0); DataContext.SelectedTicket.FixSelectedItems(); var newTicketId = DataContext.MoveSelectedTicketItemsToNewTicket(); DataContext.OpenTicket(newTicketId); if (tableId > 0) TicketViewModel.AssignTableToSelectedTicket(tableId); //AppServices.MainDataContext.AssignTableToSelectedTicket(tableId); } private bool ShouldSelectTag() { if (!string.IsNullOrEmpty(AppServices.MainDataContext.SelectedDepartment.TerminalDefaultTag)) { var tg = AppServices.MainDataContext.SelectedDepartment.TicketTagGroups.FirstOrDefault(x => x.Name == AppServices.MainDataContext.SelectedDepartment.TerminalDefaultTag); if (tg != null) { ActivateSelectedTicketItemEditorView(null, tg); return true; } } return false; } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/MainWindowViewModel.cs
C#
gpl3
17,055
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Presentation.Common; using Samba.Services; namespace Samba.Presentation.Terminal { public class LoggedInUserViewModel : ObservableObject { public event EventHandler CloseButtonClickedEvent; public void InvokeCloseButtonClickedEvent(EventArgs e) { EventHandler handler = CloseButtonClickedEvent; if (handler != null) handler(this, e); } public string GetLocation() { var result = ""; if (DataContext.SelectedTicket != null) { if (!string.IsNullOrEmpty(DataContext.SelectedTicket.Model.TicketNumber)) result += "#" + DataContext.SelectedTicket.Model.TicketNumber + " - "; if (!string.IsNullOrEmpty(DataContext.SelectedTicket.Location)) result += DataContext.SelectedTicket.Location + " - "; } return result; } public string LoggedInUserName { get { return GetLocation() + AppServices.CurrentLoggedInUser.Name; } } public ICaptionCommand CloseScreenCommand { get; set; } public LoggedInUserViewModel() { CloseScreenCommand = new CaptionCommand<string>("Close", OnCloseScreen); } private void OnCloseScreen(string obj) { RaisePropertyChanged("LoggedInUserName"); InvokeCloseButtonClickedEvent(EventArgs.Empty); } public void Refresh() { RaisePropertyChanged("LoggedInUserName"); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/LoggedInUserViewModel.cs
C#
gpl3
1,701
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Samba.Presentation.Common; using Samba.Presentation.ViewModels; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for MenuItemSelectorView.xaml /// </summary> public partial class MenuItemSelectorView : UserControl { public MenuItemSelectorView() { InitializeComponent(); EventServiceFactory.EventService.GetEvent<GenericEvent<TicketItemViewModel>>().Subscribe( x => { if (x.Topic == EventTopicNames.TicketItemAdded) Scroller.ScrollToEnd(); }); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { Scroller.ScrollToEnd(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/MenuItemSelectorView.xaml.cs
C#
gpl3
1,174
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for FeedbackWindow.xaml /// </summary> public partial class FeedbackWindow : Window { public FeedbackWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Close(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/FeedbackWindow.xaml.cs
C#
gpl3
741
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Samba.Presentation.Common; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for SelectedTicketItemEditorView.xaml /// </summary> public partial class SelectedTicketItemEditorView : UserControl { public SelectedTicketItemEditorView() { InitializeComponent(); } private void ExtraPropertyName_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { ExtraPropertyName.BackgroundSelectAll(); (DataContext as SelectedTicketItemEditorViewModel).ShowKeyboard(); } private void ExtraPropertyName_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { (DataContext as SelectedTicketItemEditorViewModel).HideKeyboard(); } private void ExtraPropertyPrice_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { ExtraPropertyPrice.BackgroundSelectAll(); (DataContext as SelectedTicketItemEditorViewModel).ShowKeyboard(); } private void ExtraPropertyPrice_LostFocus(object sender, RoutedEventArgs e) { (DataContext as SelectedTicketItemEditorViewModel).HideKeyboard(); } private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e) { ExtraPropertyName.Focus(); } private void TextBlock_MouseDown_1(object sender, MouseButtonEventArgs e) { ExtraPropertyPrice.Focus(); } private void TextBox_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (NoteEditor.Visibility == Visibility.Visible) { NoteEditor.BackgroundFocus(); NoteEditor.BackgroundSelectAll(); } } private void FreeTagEditor_GotFocus(object sender, RoutedEventArgs e) { (DataContext as SelectedTicketItemEditorViewModel).IsKeyboardVisible = true; } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/SelectedTicketItemEditorView.xaml.cs
C#
gpl3
2,468
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Microsoft.Practices.EnterpriseLibrary.Common.Utility; using Microsoft.Practices.Prism.Commands; using Samba.Domain.Models.Tickets; using Samba.Localization.Properties; using Samba.Persistance.Data; using Samba.Presentation.Common; using Samba.Presentation.ViewModels; using Samba.Services; namespace Samba.Presentation.Terminal { public delegate void TicketSelectionEventHandler(int selectedTicketId); public class TicketScreenViewModel : ObservableObject { public event TicketSelectionEventHandler TicketSelectedEvent; public DelegateCommand<TerminalOpenTicketView> SelectTicketCommand { get; set; } public ICaptionCommand CreateNewTicketCommand { get; set; } public IEnumerable<TerminalOpenTicketView> OpenTickets { get; set; } private IEnumerable<TicketTagFilterViewModel> _openTicketTags; public IEnumerable<TicketTagFilterViewModel> OpenTicketTags { get { return _openTicketTags; } set { _openTicketTags = value; RaisePropertyChanged("OpenTicketTags"); } } public TicketScreenViewModel() { SelectTicketCommand = new DelegateCommand<TerminalOpenTicketView>(OnSelectTicket); CreateNewTicketCommand = new CaptionCommand<string>(Resources.NewTicket, OnCreateNewTicket); } private void OnCreateNewTicket(string obj) { InvokeTicketSelectedEvent(0); } public void InvokeTicketSelectedEvent(int ticketId) { TicketSelectionEventHandler handler = TicketSelectedEvent; if (handler != null) handler(ticketId); } private void OnSelectTicket(TerminalOpenTicketView obj) { InvokeTicketSelectedEvent(obj.Id); } public void Refresh() { UpdateOpenTickets(AppServices.MainDataContext.SelectedDepartment, AppServices.MainDataContext.SelectedDepartment.TerminalDefaultTag); RaisePropertyChanged("OpenTickets"); } public void UpdateOpenTickets(Department department, string selectedTag) { Expression<Func<Ticket, bool>> prediction; if (department != null) prediction = x => !x.IsPaid && x.DepartmentId == department.Id; else prediction = x => !x.IsPaid; OpenTickets = Dao.Select(x => new TerminalOpenTicketView { Id = x.Id, TicketNumber = x.TicketNumber, LocationName = x.LocationName, CustomerName = x.CustomerName, IsLocked = x.Locked, TicketTag = x.Tag }, prediction).OrderBy(x => x.Title); if (!string.IsNullOrEmpty(selectedTag)) { var tag = selectedTag.ToLower() + ":"; var cnt = OpenTickets.Count(x => string.IsNullOrEmpty(x.TicketTag) || !x.TicketTag.ToLower().Contains(tag)); OpenTickets = OpenTickets.Where(x => !string.IsNullOrEmpty(x.TicketTag) && x.TicketTag.ToLower().Contains(tag)); var opt = OpenTickets.SelectMany(x => x.TicketTag.Split('\r')) .Where(x => x.ToLower().Contains(tag)) .Distinct() .Select(x => x.Split(':')).Select(x => new TicketTagFilterViewModel { TagGroup = x[0], TagValue = x[1] }).OrderBy(x => x.TagValue).ToList(); opt.Insert(0, new TicketTagFilterViewModel { TagGroup = selectedTag, TagValue = "*", ButtonColor = "Blue" }); if (cnt > 0) opt.Insert(0, new TicketTagFilterViewModel { Count = cnt, TagGroup = selectedTag, ButtonColor = "Red" }); OpenTicketTags = opt.Count() > 1 ? opt : null; OpenTickets.ForEach(x => x.Info = x.TicketTag.Split('\r').Where(y => y.ToLower().StartsWith(tag)).Single().Split(':')[1]); } else { OpenTicketTags = null; } } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/TicketScreenViewModel.cs
C#
gpl3
4,309
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Samba.Domain.Models.Tables; using Samba.Infrastructure; using Samba.Presentation.Common; using Samba.Presentation.ViewModels; using Samba.Services; namespace Samba.Presentation.Terminal { public static class DataContext { public static TicketViewModel SelectedTicket { get; private set; } private static TicketViewModel CreateSelectedTicket() { return new TicketViewModel(AppServices.MainDataContext.SelectedTicket, false); } public static TicketItemViewModel SelectedTicketItem { get; set; } public static void UpdateSelectedTicket(Table table) { Debug.Assert(SelectedTicket == null); if (table.TicketId == 0) TicketViewModel.AssignTableToSelectedTicket(table.Id); //AppServices.MainDataContext.AssignTableToSelectedTicket(table.Id);); else AppServices.MainDataContext.OpenTicket(table.TicketId); RefreshSelectedTicket(); } public static void OpenTicket(int ticketId) { Debug.Assert(SelectedTicket == null); if (ticketId == 0) TicketViewModel.CreateNewTicket(); else AppServices.MainDataContext.OpenTicket(ticketId); RefreshSelectedTicket(); } public static TicketCommitResult CloseSelectedTicket() { Debug.Assert(SelectedTicket != null); SelectedTicket = null; var result = AppServices.MainDataContext.CloseTicket(); AppServices.MessagingService.SendMessage(Messages.TicketRefreshMessage, result.TicketId.ToString()); return result; } internal static int MoveSelectedTicketItemsToNewTicket() { var result= AppServices.MainDataContext.MoveTicketItems(SelectedTicket.SelectedItems.Select(x => x.Model), 0).TicketId; SelectedTicket = null; return result; } public static void RefreshSelectedTicket() { SelectedTicket = CreateSelectedTicket(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/DataContext.cs
C#
gpl3
2,258
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for LoggedInUserView.xaml /// </summary> public partial class LoggedInUserView : UserControl { public LoggedInUserView() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/LoggedInUserView.xaml.cs
C#
gpl3
671
using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using Microsoft.Practices.Prism.Commands; using Samba.Domain.Models.Tickets; using Samba.Localization.Properties; using Samba.Persistance.Data; using Samba.Presentation.Common; using Samba.Presentation.ViewModels; using Samba.Services; namespace Samba.Presentation.Terminal { public delegate void TagUpdatedEventHandler(TicketTagGroup item); public class SelectedTicketItemEditorViewModel : ObservableObject { public event TagUpdatedEventHandler TagUpdated; public TicketItemViewModel SelectedItem { get { return DataContext.SelectedTicketItem; } private set { DataContext.SelectedTicketItem = value; } } public DelegateCommand<MenuItemPortionViewModel> PortionSelectedCommand { get; set; } public DelegateCommand<MenuItemPropertyViewModel> PropertySelectedCommand { get; set; } public DelegateCommand<MenuItemGroupedPropertyItemViewModel> PropertyGroupSelectedCommand { get; set; } public DelegateCommand<TicketTagViewModel> TicketTagSelectedCommand { get; set; } public ICaptionCommand AddTicketTagCommand { get; set; } public ObservableCollection<MenuItemPortionViewModel> SelectedItemPortions { get; set; } public ObservableCollection<MenuItemPropertyGroupViewModel> SelectedItemPropertyGroups { get; set; } public ObservableCollection<MenuItemGroupedPropertyViewModel> SelectedItemGroupedPropertyItems { get; set; } public ObservableCollection<TicketTagViewModel> TicketTags { get; set; } private string _customTag; public string CustomTag { get { return _customTag; } set { _customTag = value; RaisePropertyChanged("CustomTag"); } } public int TagColumnCount { get { return TicketTags.Count % 7 == 0 ? TicketTags.Count / 7 : (TicketTags.Count / 7) + 1; } } public SelectedTicketItemEditorViewModel() { SelectedItemPortions = new ObservableCollection<MenuItemPortionViewModel>(); SelectedItemPropertyGroups = new ObservableCollection<MenuItemPropertyGroupViewModel>(); SelectedItemGroupedPropertyItems = new ObservableCollection<MenuItemGroupedPropertyViewModel>(); TicketTags = new ObservableCollection<TicketTagViewModel>(); PortionSelectedCommand = new DelegateCommand<MenuItemPortionViewModel>(OnPortionSelected); PropertySelectedCommand = new DelegateCommand<MenuItemPropertyViewModel>(OnPropertySelected); PropertyGroupSelectedCommand = new DelegateCommand<MenuItemGroupedPropertyItemViewModel>(OnPropertyGroupSelected); TicketTagSelectedCommand = new DelegateCommand<TicketTagViewModel>(OnTicketTagSelected); AddTicketTagCommand = new CaptionCommand<string>(Resources.AddTag, OnTicketTagAdded, CanAddTicketTag); } public void InvokeTagUpdated(TicketTagGroup item) { TagUpdatedEventHandler handler = TagUpdated; if (handler != null) handler(item); } private bool CanAddTicketTag(string arg) { return !string.IsNullOrEmpty(CustomTag); } private void OnTicketTagAdded(string obj) { var cachedTag = AppServices.MainDataContext.SelectedDepartment.TicketTagGroups.Single( x => x.Id == SelectedTicketTag.Id); Debug.Assert(cachedTag != null); var ctag = cachedTag.TicketTags.SingleOrDefault(x => x.Name.ToLower() == CustomTag.ToLower()); if (ctag == null && cachedTag.SaveFreeTags) { using (var workspace = WorkspaceFactory.Create()) { var tt = workspace.Single<TicketTagGroup>(x => x.Id == SelectedTicketTag.Id); Debug.Assert(tt != null); var tag = tt.TicketTags.SingleOrDefault(x => x.Name.ToLower() == CustomTag.ToLower()); if (tag == null) { tag = new TicketTag() { Name = CustomTag }; tt.TicketTags.Add(tag); workspace.Add(tag); workspace.CommitChanges(); } } } DataContext.SelectedTicket.UpdateTag(SelectedTicketTag, new TicketTag { Name = CustomTag }); CustomTag = string.Empty; InvokeTagUpdated(SelectedTicketTag); } public string TicketNote { get { return DataContext.SelectedTicket != null ? DataContext.SelectedTicket.Note : ""; } set { DataContext.SelectedTicket.Note = value; } } public bool IsTicketNoteVisible { get { return SelectedTicketTag == null && SelectedItem == null && DataContext.SelectedTicket != null; } } public bool IsTagEditorVisible { get { return TicketTags.Count > 0 && SelectedItem == null && DataContext.SelectedTicket != null; } } public bool IsFreeTagEditorVisible { get { return SelectedTicketTag != null && SelectedTicketTag.FreeTagging; } } public bool IsEditorsVisible { get { return SelectedItem != null; } } public bool IsPortionsVisible { get { return SelectedItem != null && !SelectedItem.IsVoided && !SelectedItem.IsLocked && SelectedItem.Model.PortionCount > 1; } } private bool _isKeyboardVisible; public bool IsKeyboardVisible { get { return _isKeyboardVisible; } set { _isKeyboardVisible = value; RaisePropertyChanged("IsKeyboardVisible"); } } public TicketTagGroup SelectedTicketTag { get; set; } public void ShowKeyboard() { IsKeyboardVisible = true; } public void HideKeyboard() { IsKeyboardVisible = false; } public void Refresh(TicketItemViewModel ticketItem, TicketTagGroup selectedTicketTag) { HideKeyboard(); SelectedTicketTag = null; SelectedItemPortions.Clear(); SelectedItemPropertyGroups.Clear(); SelectedItemGroupedPropertyItems.Clear(); TicketTags.Clear(); SelectedItem = ticketItem; if (ticketItem != null) { var mi = AppServices.DataAccessService.GetMenuItem(ticketItem.Model.MenuItemId); if (mi.Portions.Count > 1) SelectedItemPortions.AddRange(mi.Portions.Select(x => new MenuItemPortionViewModel(x))); SelectedItemGroupedPropertyItems.AddRange(mi.PropertyGroups.Where(x => !string.IsNullOrEmpty(x.GroupTag)) .GroupBy(x => x.GroupTag) .Select(x => new MenuItemGroupedPropertyViewModel(SelectedItem, x))); SelectedItemPropertyGroups.AddRange(mi.PropertyGroups .Where(x => string.IsNullOrEmpty(x.GroupTag)) .Select(x => new MenuItemPropertyGroupViewModel(x))); foreach (var ticketItemPropertyViewModel in ticketItem.Properties.ToList()) { var tip = ticketItemPropertyViewModel; var mig = SelectedItemPropertyGroups.Where(x => x.Model.Id == tip.Model.PropertyGroupId).SingleOrDefault(); if (mig != null) mig.Properties.SingleOrDefault(x => x.Name == tip.Model.Name).TicketItemProperty = ticketItemPropertyViewModel.Model; var sig = SelectedItemGroupedPropertyItems.SelectMany(x => x.Properties).Where( x => x.MenuItemPropertyGroup.Id == tip.Model.PropertyGroupId).FirstOrDefault(); if (sig != null) sig.TicketItemProperty = ticketItemPropertyViewModel.Model; } } else { if (selectedTicketTag != null) { SelectedTicketTag = selectedTicketTag; if (selectedTicketTag.FreeTagging) { TicketTags.AddRange(Dao.Query<TicketTagGroup>(x => x.Id == selectedTicketTag.Id, x => x.TicketTags).SelectMany(x => x.TicketTags).OrderBy(x => x.Name).Select(x => new TicketTagViewModel(x))); } else { TicketTags.AddRange(selectedTicketTag.TicketTags.Select(x => new TicketTagViewModel(x))); } RaisePropertyChanged("TicketTags"); } else { RaisePropertyChanged("TicketNote"); ShowKeyboard(); } } RaisePropertyChanged("SelectedItem"); RaisePropertyChanged("IsPortionsVisible"); RaisePropertyChanged("IsEditorsVisible"); RaisePropertyChanged("IsTicketNoteVisible"); RaisePropertyChanged("IsTagEditorVisible"); RaisePropertyChanged("IsFreeTagEditorVisible"); RaisePropertyChanged("TagColumnCount"); } public void CloseView() { SelectedItem = null; SelectedItemPortions.Clear(); SelectedItemPropertyGroups.Clear(); SelectedItemGroupedPropertyItems.Clear(); TicketTags.Clear(); SelectedTicketTag = null; } private void OnPortionSelected(MenuItemPortionViewModel obj) { SelectedItem.UpdatePortion(obj.Model, AppServices.MainDataContext.SelectedDepartment.PriceTag); foreach (var model in SelectedItemPortions) { model.Refresh(); } } private void OnPropertySelected(MenuItemPropertyViewModel obj) { var mig = SelectedItemPropertyGroups.FirstOrDefault(propertyGroup => propertyGroup.Properties.Contains(obj)); Debug.Assert(mig != null); SelectedItem.ToggleProperty(mig.Model, obj.Model); foreach (var model in SelectedItemPropertyGroups) { model.Refresh(SelectedItem.Properties); } } private void OnPropertyGroupSelected(MenuItemGroupedPropertyItemViewModel obj) { obj.TicketItemProperty = SelectedItem.ToggleProperty(obj.MenuItemPropertyGroup, obj.NextProperty); obj.UpdateNextProperty(obj.NextProperty); } private void OnTicketTagSelected(TicketTagViewModel obj) { if (DataContext.SelectedTicket != null && SelectedTicketTag != null) { DataContext.SelectedTicket.UpdateTag(SelectedTicketTag, obj.Model); foreach (var model in TicketTags) { model.Refresh(); } InvokeTagUpdated(SelectedTicketTag); } } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/SelectedTicketItemEditorViewModel.cs
C#
gpl3
11,517
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for TicketScreenView.xaml /// </summary> public partial class TicketScreenView : UserControl { public TicketScreenView() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/TicketScreenView.xaml.cs
C#
gpl3
671
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Windows.Data; using System.Windows.Media; using Samba.Domain.Models.Tickets; using Samba.Presentation.ViewModels; namespace Samba.Presentation.Terminal { public class TagColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (DataContext.SelectedTicket != null) if (DataContext.SelectedTicket.TagDisplay.Contains(": " + value)) return Brushes.Red; return Brushes.Transparent; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException("This method should never be called"); } } public class PortionColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (DataContext.SelectedTicketItem != null) if (DataContext.SelectedTicketItem.Description.EndsWith(value.ToString())) return Brushes.Red; return Brushes.Transparent; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException("This method should never be called"); } } public class PropertyColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (DataContext.SelectedTicketItem != null) { var val = value as TicketItemProperty; if (val != null) return Brushes.Red; } return Brushes.Transparent; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException("This method should never be called"); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/PortionColorConverter.cs
C#
gpl3
2,212
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; using Samba.Infrastructure; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private void Application_Exit(object sender, ExitEventArgs e) { if (MessagingClient.IsConnected) MessagingClient.Disconnect(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/App.xaml.cs
C#
gpl3
544
using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace Samba.Presentation.Terminal { public class VisibilityConverter : IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture) { //bool visibility = (bool)value; //return visibility ? Visibility.Visible : Visibility.Collapsed; bool param = parameter != null ? bool.Parse(parameter as string) : true; bool val = (bool)value; return val == param ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture) { Visibility visibility = (Visibility)value; return (visibility == Visibility.Visible); } } //public class BoolToVisibilityConverter : IValueConverter //{ // public object Convert(object value, Type targetType, // object parameter, System.Globalization.CultureInfo culture) // { // bool param = bool.Parse(parameter as string); // bool val = (bool)value; // return val == param ? // Visibility.Visible : Visibility.Hidden; // } // public object ConvertBack(object value, Type targetType, // object parameter, System.Globalization.CultureInfo culture) // { // throw new NotImplementedException(); // } //} }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/VisibilityConverter.cs
C#
gpl3
1,701
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Samba.Presentation.Terminal")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.Presentation.Terminal")] [assembly: AssemblyCopyright("Copyright © 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzgaminginc-pointofssale
Samba.Presentation.Terminal/Properties/AssemblyInfo.cs
C#
gpl3
2,318
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for TableView.xaml /// </summary> public partial class TableScreenView : UserControl { public TableScreenView() { InitializeComponent(); } private void TextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var ts = (DataContext as TableScreenViewModel); if (ts != null) { if (ts.SelectedTableScreen.NumeratorHeight < 30) ts.DisplayFullScreenNumerator(); } } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/TableScreenView.xaml.cs
C#
gpl3
1,024
using System; using System.Collections.Generic; using Microsoft.Practices.Prism.Commands; using Samba.Domain.Models.Tickets; using Samba.Presentation.Common; using Samba.Services; namespace Samba.Presentation.Terminal { public class DepartmentSelectorViewModel : ObservableObject { public event EventHandler DepartmentSelected; public void InvokeDepartmentSelected(EventArgs e) { EventHandler handler = DepartmentSelected; if (handler != null) handler(this, e); } public IEnumerable<Department> Departments { get { return AppServices.MainDataContext.PermittedDepartments; } } public Department SelectedDepartment { get { return AppServices.MainDataContext.SelectedDepartment; } set { AppServices.MainDataContext.SelectedDepartment = value; RaisePropertyChanged("SelectedDepartment"); } } public DelegateCommand<Department> SelectDepartmentCommand { get; set; } public DepartmentSelectorViewModel() { SelectDepartmentCommand = new DelegateCommand<Department>(OnDepartmentSelected); } private void OnDepartmentSelected(Department obj) { SelectedDepartment = obj; InvokeDepartmentSelected(EventArgs.Empty); } public void Refresh() { RaisePropertyChanged("Departments"); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/DepartmentSelectorViewModel.cs
C#
gpl3
1,540
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Presentation.Terminal { /// <summary> /// Interaction logic for LoginView.xaml /// </summary> public partial class LoginView : UserControl { public LoginView() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/LoginView.xaml.cs
C#
gpl3
650
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Localization.Properties; using Samba.Presentation.Common; namespace Samba.Presentation.Terminal { public delegate void PinSubmittedEventHandler(object sender, string pinValue); public class LoginViewModel : ObservableObject { public event PinSubmittedEventHandler PinSubmitted; public void InvokePinSubmitted(string pinvalue) { var handler = PinSubmitted; if (handler != null) handler(this, pinvalue); } private string _pin = ""; public string PinDisplay { get { return !string.IsNullOrEmpty(_pin) ? "*".PadLeft(_pin.Length, '*') : Resources.EnterPin; } set { _pin = value; } } public ICaptionCommand EnterValueCommand { get; set; } public ICaptionCommand SubmitPinCommand { get; set; } public LoginViewModel() { EnterValueCommand = new CaptionCommand<string>("Cmd", OnEnterValue); SubmitPinCommand = new CaptionCommand<string>("Gir", OnPinSubmitted); } private void OnPinSubmitted(string obj) { InvokePinSubmitted(_pin); _pin = ""; RaisePropertyChanged("PinDisplay"); } private void OnEnterValue(string obj) { if (!string.IsNullOrEmpty(obj)) _pin += obj; else _pin = ""; RaisePropertyChanged("PinDisplay"); } } }
zzgaminginc-pointofssale
Samba.Presentation.Terminal/LoginViewModel.cs
C#
gpl3
1,623
using System.ComponentModel; namespace Samba.Modules.CreditCardModule.SimpleProcessor { public class SimpleCreditCardProcessorSettings { [DisplayName("Display Message"), Category("Settings")] public string DisplayMessage { get; set; } } }
zzgaminginc-pointofssale
Samba.Modules.CreditCardModule/SimpleProcessor/SimpleCreditCardProcessorSettings.cs
C#
gpl3
281
using System; using System.ComponentModel.Composition; using Samba.Presentation.Common; using Samba.Presentation.Common.Services; using Samba.Services; namespace Samba.Modules.CreditCardModule.SimpleProcessor { [Export(typeof(ICreditCardProcessor))] public class SimpleCreditCardProcessor : ICreditCardProcessor { private readonly SimpleCreditCardProcessorSettings _settings; private const string DmSettingName = "SCCP_DisplayMessage"; public SimpleCreditCardProcessor() { _settings = new SimpleCreditCardProcessorSettings(); _settings.DisplayMessage = AppServices.SettingService.ReadGlobalSetting(DmSettingName).StringValue; } public string Name { get { return "Simple Credit Card Processor"; } } public void Process(CreditCardProcessingData creditCardProcessingData) { // get operator response var userEntry = InteractionService.UserIntraction.GetStringFromUser(Name, _settings.DisplayMessage); // publish processing result var result = new CreditCardProcessingResult() { Amount = creditCardProcessingData.TenderedAmount, ProcessType = userEntry.Length > 0 ? ProcessType.Force : ProcessType.Cancel }; result.PublishEvent(EventTopicNames.PaymentProcessed); } public bool ForcePayment(int ticketId) { return false; } public void EditSettings() { // displays generic property editor InteractionService.UserIntraction.EditProperties(_settings); // saves values to global custom setting table AppServices.SettingService.ReadGlobalSetting(DmSettingName).StringValue = _settings.DisplayMessage; AppServices.SettingService.SaveChanges(); } } }
zzgaminginc-pointofssale
Samba.Modules.CreditCardModule/SimpleProcessor/SimpleCreditCardProcessor.cs
C#
gpl3
2,020
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using Microsoft.Practices.Prism.MefExtensions.Modularity; using Samba.Presentation.Common; using Samba.Services; namespace Samba.Modules.CreditCardModule { [ModuleExport(typeof(CreditCardModule))] class CreditCardModule : ModuleBase { [ImportMany] public IEnumerable<ICreditCardProcessor> CreditCardProcessors { get; set; } protected override void OnInitialization() { foreach (var creditCardProcessor in CreditCardProcessors) { CreditCardProcessingService.RegisterCreditCardProcessor(creditCardProcessor); } } } }
zzgaminginc-pointofssale
Samba.Modules.CreditCardModule/CreditCardModule.cs
C#
gpl3
781
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Samba.Modules.CreditCardModule")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.Modules.CreditCardModule")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d2d0f83f-859a-49c0-92c0-81e9cb46edba")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzgaminginc-pointofssale
Samba.Modules.CreditCardModule/Properties/AssemblyInfo.cs
C#
gpl3
1,472
using System.Windows; using Samba.Presentation.Common; namespace Samba.Modules.CreditCardModule.ExternalProcessor { /// <summary> /// Interaction logic for ExternalProcessorView.xaml /// </summary> public partial class ExternalProcessorView : Window { public ExternalProcessorView(ExternalProcessorViewModel viewModel) { DataContext = viewModel; InitializeComponent(); } private void ExternalProcessorWindow_Loaded(object sender, RoutedEventArgs e) { SwipeDataBox.BackgroundFocus(); } } }
zzgaminginc-pointofssale
Samba.Modules.CreditCardModule/ExternalProcessor/ExternalProcessorView.xaml.cs
C#
gpl3
626
using System.ComponentModel.Composition; using Microsoft.Practices.Prism.Commands; using Samba.Presentation.Common; using Samba.Services; namespace Samba.Modules.CreditCardModule.ExternalProcessor { public class OnProcessedArgs { public ProcessType ProcessType { get; set; } } [Export] public class ExternalProcessorViewModel : ObservableObject { public delegate void OnProcessed(object sender, OnProcessedArgs args); public event OnProcessed Processed; private void InvokeProcessed(OnProcessedArgs args) { OnProcessed handler = Processed; if (handler != null) handler(this, args); } [ImportingConstructor] public ExternalProcessorViewModel() { ForceCommand = new DelegateCommand(OnForce); PreAuthCommand = new DelegateCommand(OnPreAuth, CanPreAuthExecute); CancelCommand = new DelegateCommand(OnCancel); } private bool CanPreAuthExecute() { return CanPreAuth; } private void OnPreAuth() { var args = new OnProcessedArgs { ProcessType = ProcessType.PreAuth }; InvokeProcessed(args); } private void OnCancel() { InvokeProcessed(new OnProcessedArgs { ProcessType = ProcessType.Cancel }); } private void OnForce() { InvokeProcessed(new OnProcessedArgs { ProcessType = ProcessType.Force }); } public DelegateCommand PreAuthCommand { get; set; } public DelegateCommand ForceCommand { get; set; } public DelegateCommand CancelCommand { get; set; } public decimal TenderedAmount { get; set; } public decimal Gratuity { get; set; } public string AuthCode { get; set; } public string CardholderName { get; set; } public bool CanPreAuth { get; set; } } }
zzgaminginc-pointofssale
Samba.Modules.CreditCardModule/ExternalProcessor/ExternalProcessorViewModel.cs
C#
gpl3
2,012
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Security; using Microsoft.Practices.Prism.Regions; using Samba.Domain.Models.Tickets; using Samba.Infrastructure; using Samba.Presentation.Common; using Samba.Presentation.Common.Services; using Samba.Services; namespace Samba.Modules.CreditCardModule.ExternalProcessor { internal class PreauthData { public SecureString SwipeData { get; set; } public decimal TenderedAmount { get; set; } public decimal Gratuity { get; set; } public string MerchantAuthCode { get; set; } } [Export(typeof(ICreditCardProcessor))] class ExternalCreditCardProcessor : ICreditCardProcessor { private readonly ExternalProcessorViewModel _viewModel; private ExternalProcessorView _view; private static readonly ExternalProcessorSettings Settings = new ExternalProcessorSettings(); private static readonly IDictionary<int, PreauthData> PreauthDataCache = new Dictionary<int, PreauthData>(); public Ticket SelectedTicket { get; set; } [ImportingConstructor] public ExternalCreditCardProcessor(IRegionManager regionManager, ExternalProcessorViewModel viewModel) { _viewModel = viewModel; _viewModel.Processed += ViewModelProcessed; Settings.Load(); } public string Name { get { return "External Credit Card Processor"; } } public void EditSettings() { InteractionService.UserIntraction.EditProperties(Settings); Settings.Save(); } public void Process(CreditCardProcessingData creditCardProcessingData) { InteractionService.UserIntraction.BlurMainWindow(); SelectedTicket = creditCardProcessingData.Ticket; _viewModel.CanPreAuth = !PreauthDataCache.ContainsKey(SelectedTicket.Id); _viewModel.TenderedAmount = creditCardProcessingData.TenderedAmount; _viewModel.Gratuity = (creditCardProcessingData.TenderedAmount * Settings.GratuityRate) / 100; _viewModel.AuthCode = ""; _view = new ExternalProcessorView(_viewModel); _view.ShowDialog(); } public bool ForcePayment(int ticketId) { return PreauthDataCache.ContainsKey(ticketId); } void ViewModelProcessed(object sender, OnProcessedArgs args) { var processType = args.ProcessType; var gratuity = _viewModel.Gratuity; var ticket = SelectedTicket; InteractionService.UserIntraction.DeblurMainWindow(); _view.Close(); var result = new CreditCardProcessingResult { ProcessType = processType }; if (processType == ProcessType.PreAuth) result.Amount = Preauth(_view.SwipeDataBox.SecurePassword, ticket, _viewModel.TenderedAmount, gratuity); if (processType == ProcessType.Force) result.Amount = Force(_view.SwipeDataBox.SecurePassword, ticket, _viewModel.TenderedAmount, gratuity); result.PublishEvent(EventTopicNames.PaymentProcessed); } static void AddPreauthData(int ticketId, SecureString swipeData, string authCode, decimal tenderedAmount, decimal gratuity) { Debug.Assert(!PreauthDataCache.ContainsKey(ticketId)); PreauthDataCache.Add(ticketId, new PreauthData { MerchantAuthCode = authCode, SwipeData = swipeData, TenderedAmount = tenderedAmount, Gratuity = gratuity }); } static PreauthData GetPreauthData(int ticketId) { if (PreauthDataCache.ContainsKey(ticketId)) { var result = PreauthDataCache[ticketId]; PreauthDataCache.Remove(ticketId); return result; } return null; } private static decimal Force(SecureString swipeData, Ticket ticket, decimal tenderedAmount, decimal gratuity) { var result = tenderedAmount; if (!PreauthDataCache.ContainsKey(ticket.Id)) result = Preauth(swipeData, ticket, tenderedAmount, gratuity); ForceWithPreauth(ticket.Id); return result; } private static void ForceWithPreauth(int ticketId) { // Force preauth payment Debug.Assert(PreauthDataCache.ContainsKey(ticketId)); var preauthData = GetPreauthData(ticketId); using (var sm = new SecureStringToStringMarshaler(preauthData.SwipeData)) { // access swipedata as demonstrated here InteractionService.UserIntraction.GiveFeedback("Force:\r" + sm.String); // *------------------------ // force with preauth data; // *------------------------ } preauthData.SwipeData.Clear(); // we don't need swipedata anymore... } private static decimal Preauth(SecureString swipeData, Ticket ticket, decimal tenderedAmount, decimal gratuity) { // preauthPayment if (gratuity > 0 && Settings.GratuityService != null) // add gratuity amount to ticket ticket.AddTaxService(Settings.GratuityService.Id, Settings.GratuityService.CalculationMethod, gratuity); using (var sm = new SecureStringToStringMarshaler(swipeData)) { // access swipedata as demonstrated here InteractionService.UserIntraction.GiveFeedback(string.Format("Amount:{0}\r\rPreauth:\r{1}", ticket.GetRemainingAmount(), sm.String)); // *------------------------ // Preauth Here // *------------------------ } AddPreauthData(ticket.Id, swipeData, "SAMPLE MERCHANT AUTH CODE", tenderedAmount, gratuity); return tenderedAmount + gratuity; } } }
zzgaminginc-pointofssale
Samba.Modules.CreditCardModule/ExternalProcessor/ExternalCreditCardProcessor.cs
C#
gpl3
6,316
using System.ComponentModel; using System.Linq; using Samba.Domain.Models.Menus; using Samba.Services; namespace Samba.Modules.CreditCardModule.ExternalProcessor { public class ExternalProcessorSettings { [DisplayName("Gratuity"), Category("Settings")] public decimal GratuityRate { get; set; } [DisplayName("Gratuity Template Name"), Category("Settings")] public string GratuityTemplateName { get; set; } [Browsable(false)] public TaxServiceTemplate GratuityService { get; set; } public void Load() { GratuityRate = AppServices.SettingService.ReadGlobalSetting("EXCCS_GRATUITYRATE").DecimalValue; GratuityTemplateName = AppServices.SettingService.ReadGlobalSetting("EXCCS_GRATUITYTEMPLATE").StringValue; GratuityService = AppServices.MainDataContext.TaxServiceTemplates.FirstOrDefault(x => x.Name == GratuityTemplateName); } public void Save() { AppServices.SettingService.ReadGlobalSetting("EXCCS_GRATUITYRATE").DecimalValue = GratuityRate; AppServices.SettingService.ReadGlobalSetting("EXCCS_GRATUITYTEMPLATE").StringValue = GratuityTemplateName; AppServices.SettingService.SaveChanges(); GratuityService = AppServices.MainDataContext.TaxServiceTemplates.FirstOrDefault(x => x.Name == GratuityTemplateName); } } }
zzgaminginc-pointofssale
Samba.Modules.CreditCardModule/ExternalProcessor/ExternalProcessorSettings.cs
C#
gpl3
1,449
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.IO.Packaging; using System.Linq; using System.Windows; using System.ComponentModel; using System.Windows.Documents; using System.Windows.Markup; using System.Windows.Threading; using System.Windows.Xps.Packaging; using System.Windows.Xps.Serialization; using Microsoft.Win32; using Samba.Domain.Models.Settings; using Samba.Infrastructure.Settings; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Presentation.Common.ErrorReport; using Samba.Services; namespace Samba.Modules.BasicReports { public abstract class ReportViewModelBase : ObservableObject { private readonly List<string> _links; public string Header { get { return GetHeader(); } } private bool _selected; public bool Selected { get { return _selected; } set { _selected = value; RaisePropertyChanged("Selected"); RaisePropertyChanged("Background"); RaisePropertyChanged("Foreground"); } } public string Background { get { return Selected ? "Orange" : "White"; } } public string Foreground { get { return Selected ? "White" : "Black"; } } public ObservableCollection<FilterGroup> FilterGroups { get; set; } public string StartDateString { get { return ReportContext.StartDateString; } set { ReportContext.StartDateString = value; } } public string EndDateString { get { return ReportContext.EndDateString; } set { ReportContext.EndDateString = value; } } public ICaptionCommand PrintDocumentCommand { get; set; } public ICaptionCommand RefreshFiltersCommand { get; set; } public ICaptionCommand SaveDocumentCommand { get; set; } public FlowDocument Document { get; set; } public bool CanUserChangeDates { get { return AppServices.IsUserPermittedFor(PermissionNames.ChangeReportDate); } } protected ReportViewModelBase() { _links = new List<string>(); PrintDocumentCommand = new CaptionCommand<string>(Resources.Print, OnPrintDocument); RefreshFiltersCommand = new CaptionCommand<string>(Resources.Refresh, OnRefreshFilters, CanRefreshFilters); SaveDocumentCommand = new CaptionCommand<string>(Resources.Save, OnSaveDocument); FilterGroups = new ObservableCollection<FilterGroup>(); } private void OnSaveDocument(string obj) { var fn = AskFileName("Report", ".xps"); if (!string.IsNullOrEmpty(fn)) { try { SaveAsXps(fn, Document); } catch (Exception e) { AppServices.LogError(e); } } } public static void SaveAsXps(string path, FlowDocument document) { using (Package package = Package.Open(path, FileMode.Create)) { using (var xpsDoc = new XpsDocument( package, CompressionOption.Maximum)) { var xpsSm = new XpsSerializationManager( new XpsPackagingPolicy(xpsDoc), false); var dp = ((IDocumentPaginatorSource)document).DocumentPaginator; xpsSm.SaveAsXaml(dp); } } } internal string AskFileName(string defaultName, string extenstion) { defaultName = defaultName.Replace(" ", "_"); defaultName = defaultName.Replace(".", "_"); var saveFileDialog = new SaveFileDialog { InitialDirectory = LocalSettings.DocumentPath, FileName = defaultName, Filter = string.Format("{0} file (*.{1})|*.{1}", extenstion.Trim('.').ToUpper(), extenstion.Trim('.')), DefaultExt = extenstion }; var result = saveFileDialog.ShowDialog(); return result.GetValueOrDefault(false) ? saveFileDialog.FileName : ""; } public void HandleLink(string text) { if (!_links.Contains(text)) _links.Add(text); } protected virtual void OnRefreshFilters(string obj) { var sw = FilterGroups[0].SelectedValue as WorkPeriod; if (sw == null) return; if (ReportContext.CurrentWorkPeriod != null && (ReportContext.StartDate != sw.StartDate || ReportContext.EndDate != sw.EndDate)) { ReportContext.CurrentWorkPeriod = ReportContext.CreateCustomWorkPeriod("", ReportContext.StartDate, ReportContext.EndDate); } else ReportContext.CurrentWorkPeriod = FilterGroups[0].SelectedValue as WorkPeriod; RefreshReport(); } protected abstract void CreateFilterGroups(); protected FilterGroup CreateWorkPeriodFilterGroup() { var wpList = ReportContext.GetWorkPeriods(ReportContext.StartDate, ReportContext.EndDate).ToList(); wpList.Insert(0, ReportContext.ThisMonthWorkPeriod); wpList.Insert(0, ReportContext.LastMonthWorkPeriod); wpList.Insert(0, ReportContext.ThisWeekWorkPeriod); wpList.Insert(0, ReportContext.LastWeekWorkPeriod); wpList.Insert(0, ReportContext.YesterdayWorkPeriod); wpList.Insert(0, ReportContext.TodayWorkPeriod); if (!wpList.Contains(ReportContext.CurrentWorkPeriod)) { wpList.Insert(0, ReportContext.CurrentWorkPeriod); } if (!wpList.Contains(AppServices.MainDataContext.CurrentWorkPeriod)) wpList.Insert(0, AppServices.MainDataContext.CurrentWorkPeriod); return new FilterGroup { Values = wpList, SelectedValue = ReportContext.CurrentWorkPeriod }; } private bool CanRefreshFilters(string arg) { return FilterGroups.Count > 0; } private void OnPrintDocument(string obj) { AppServices.PrintService.PrintSlipReport(Document); } public void RefreshReport() { Document = null; RaisePropertyChanged("Document"); //Program ilk yüklendiğinde aktif gün başı işlemi yoktur. if (ReportContext.CurrentWorkPeriod == null) return; var memStream = new MemoryStream(); using (var worker = new BackgroundWorker()) { worker.DoWork += delegate { LocalSettings.UpdateThreadLanguage(); var doc = GetReport(); XamlWriter.Save(doc, memStream); memStream.Position = 0; }; worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs eventArgs) { if (eventArgs.Error != null) { ExceptionReporter.Show(eventArgs.Error); return; } Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action( delegate { Document = (FlowDocument)XamlReader.Load(memStream); foreach (var link in _links) { var hp = Document.FindName(link.Replace(" ", "_")) as Hyperlink; if (hp != null) hp.Click += (s, e) => HandleClick(((Hyperlink)s).Name.Replace("_", " ")); } RaisePropertyChanged("Document"); RaisePropertyChanged("StartDateString"); RaisePropertyChanged("EndDateString"); CreateFilterGroups(); foreach (var filterGroup in FilterGroups) { var group = filterGroup; filterGroup.ValueChanged = delegate { var sw = group.SelectedValue as WorkPeriod; if (sw != null) { ReportContext.StartDate = sw.StartDate; ReportContext.EndDate = sw.EndDate; RefreshFiltersCommand.Execute(""); } }; } })); }; worker.RunWorkerAsync(); } } protected abstract FlowDocument GetReport(); protected abstract string GetHeader(); protected virtual void HandleClick(string text) { // override if needed. } public FlowDocument GetReportDocument() { return GetReport(); } public void AddDefaultReportHeader(SimpleReport report, WorkPeriod workPeriod, string caption) { report.AddHeader("Samba POS"); report.AddHeader(caption); if (workPeriod.EndDate > workPeriod.StartDate) report.AddHeader(workPeriod.StartDate.ToString("dd MMMM yyyy HH:mm") + " - " + workPeriod.EndDate.ToString("dd MMMM yyyy HH:mm")); else { report.AddHeader(workPeriod.StartDate.ToString("dd MMMM yyyy HH:mm") + " - " + DateTime.Now.ToString("dd MMMM yyyy HH:mm")); } if (!string.IsNullOrEmpty(workPeriod.Description)) report.AddHeader(workPeriod.Description); } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/ReportViewModelBase.cs
C#
gpl3
10,676
using System; using System.Collections.Generic; namespace Samba.Modules.BasicReports { public class FilterGroup { public string Name { get; set; } public IEnumerable<object> Values { get; set; } private object _selectedValue; public object SelectedValue { get { return _selectedValue; } set { if (value != _selectedValue) { _selectedValue = value; if (ValueChanged != null) ValueChanged(); } } } public Action ValueChanged { get; set; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/FilterGroup.cs
C#
gpl3
674
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; namespace Samba.Modules.BasicReports { public class SimpleReport { private readonly LengthConverter _lengthConverter = new LengthConverter(); private readonly GridLengthConverter _gridLengthConverter = new GridLengthConverter(); public FlowDocument Document { get; set; } public Paragraph Header { get; set; } public IDictionary<string, Table> Tables { get; set; } public IDictionary<string, GridLength[]> ColumnLengths { get; set; } public IDictionary<string, TextAlignment[]> ColumnTextAlignments { get; set; } public SimpleReport(string pageWidth) { Tables = new Dictionary<string, Table>(); ColumnLengths = new Dictionary<string, GridLength[]>(); ColumnTextAlignments = new Dictionary<string, TextAlignment[]>(); Header = new Paragraph { TextAlignment = TextAlignment.Center, FontSize = 14 }; Document = new FlowDocument(Header) { ColumnGap = 20.0, ColumnRuleBrush = Brushes.DodgerBlue, ColumnRuleWidth = 2.0, PageWidth = StringToLength("10cm"), //ColumnWidth = StringToLength("6cm"), FontFamily = new FontFamily("Segoe UI") }; } public void AddColumnLength(string tableName, params string[] values) { if (!ColumnLengths.ContainsKey(tableName)) ColumnLengths.Add(tableName, new GridLength[0]); ColumnLengths[tableName] = values.Select(StringToGridLength).ToArray(); } public void AddColumTextAlignment(string tableName, params TextAlignment[] values) { if (!ColumnTextAlignments.ContainsKey(tableName)) ColumnTextAlignments.Add(tableName, new TextAlignment[0]); ColumnTextAlignments[tableName] = values; } public void AddTable(string tableName, params string[] headers) { var table = new Table { CellSpacing = 0, BorderThickness = new Thickness(0.5, 0.5, 0, 0), BorderBrush = Brushes.Black }; Document.Blocks.Add(table); Tables.Add(tableName, table); var lengths = ColumnLengths.ContainsKey(tableName) ? ColumnLengths[tableName] : new[] { GridLength.Auto, GridLength.Auto, new GridLength(1, GridUnitType.Star) }; for (var i = 0; i < headers.Count(); i++) { var c = new TableColumn { Width = lengths[i] }; table.Columns.Add(c); } var rows = new TableRowGroup(); table.RowGroups.Add(rows); rows.Rows.Add(CreateRow(headers, new[] { TextAlignment.Center }, true)); } public void AddHeader(string text) { AddNewLine(Header, text, true); } public void AddRow(string tableName, params object[] values) { Tables[tableName].RowGroups[0].Rows.Add(CreateRow(values, ColumnTextAlignments.ContainsKey(tableName) ? ColumnTextAlignments[tableName] : new[] { TextAlignment.Left }, false)); } public void AddBoldRow(string tableName, params object[] values) { Tables[tableName].RowGroups[0].Rows.Add(CreateRow(values, ColumnTextAlignments.ContainsKey(tableName) ? ColumnTextAlignments[tableName] : new[] { TextAlignment.Left }, true)); } private static void AddNewLine(Paragraph p, string text, bool bold) { p.Inlines.Add(new Run(text) { FontWeight = bold ? FontWeights.Bold : FontWeights.Normal }); p.Inlines.Add(new LineBreak()); } public void AddLink(string text) { var hp = new Hyperlink(new Run(text)) { Name = text.Replace(" ", "_") }; Header.Inlines.Add(hp); Header.Inlines.Add(new LineBreak()); } public TableRow CreateRow(object[] values, TextAlignment[] alignment, bool bold) { var row = new TableRow(); TableCell lastCell = null; int index = 0; foreach (var value in values) { var val = value ?? ""; var r = new Run(val.ToString()) { FontWeight = bold ? FontWeights.Bold : FontWeights.Normal }; if (string.IsNullOrEmpty(val.ToString()) && lastCell != null) lastCell.ColumnSpan++; else { var p = new Paragraph(r); p.FontSize = 14; p.TextAlignment = alignment.Length <= index ? alignment[alignment.Length - 1] : alignment[index]; lastCell = new TableCell(p) { BorderBrush = Brushes.Black, BorderThickness = new Thickness(0, 0, 0.5, 0.5), Padding = new Thickness(3), Background = Brushes.Snow }; if (bold) { lastCell.Foreground = Brushes.White; lastCell.Background = Brushes.Gray; } row.Cells.Add(lastCell); } index++; } return row; } private GridLength StringToGridLength(string value) { return (GridLength)_gridLengthConverter.ConvertFromString(value); } private double StringToLength(string value) { return (double)_lengthConverter.ConvertFromString(value); } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/SimpleReport.cs
C#
gpl3
6,389
using System; using System.ComponentModel.Composition; using System.Linq; using Microsoft.Practices.Prism.MefExtensions.Modularity; using Microsoft.Practices.Prism.Regions; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Services; namespace Samba.Modules.BasicReports { [ModuleExport(typeof(BasicReportModule))] public class BasicReportModule : ModuleBase { private readonly IRegionManager _regionManager; private readonly ICategoryCommand _navigateReportsCommand; private readonly BasicReportView _basicReportView; [ImportingConstructor] public BasicReportModule(IRegionManager regionManager, BasicReportView basicReportView) { _regionManager = regionManager; _basicReportView = basicReportView; _navigateReportsCommand = new CategoryCommand<string>(Resources.Reports, Resources.Common, "Images/Ppt.png", OnNavigateReportModule, CanNavigateReportModule) { Order = 80 }; PermissionRegistry.RegisterPermission(PermissionNames.OpenReports, PermissionCategories.Navigation, Resources.CanDisplayReports); PermissionRegistry.RegisterPermission(PermissionNames.ChangeReportDate, PermissionCategories.Report, Resources.CanChangeReportFilter); RuleActionTypeRegistry.RegisterActionType("SaveReportToFile", Resources.SaveReportToFile, new { ReportName = "", FileName = "" }); RuleActionTypeRegistry.RegisterParameterSoruce("ReportName", () => ReportContext.Reports.Select(x => x.Header)); EventServiceFactory.EventService.GetEvent<GenericEvent<ActionData>>().Subscribe(x => { if (x.Value.Action.ActionType == "SaveReportToFile") { var reportName = x.Value.GetAsString("ReportName"); var fileName = x.Value.GetAsString("FileName"); if (!string.IsNullOrEmpty(reportName)) { var report = ReportContext.Reports.Where(y => y.Header == reportName).FirstOrDefault(); if (report != null) { ReportContext.CurrentWorkPeriod = AppServices.MainDataContext.CurrentWorkPeriod; var document = report.GetReportDocument(); try { ReportViewModelBase.SaveAsXps(fileName, document); } catch (Exception e) { AppServices.LogError(e); } } } } }); } private static bool CanNavigateReportModule(string arg) { return (AppServices.IsUserPermittedFor(PermissionNames.OpenReports) && AppServices.MainDataContext.CurrentWorkPeriod != null); } private void OnNavigateReportModule(string obj) { _regionManager.Regions[RegionNames.MainRegion].Activate(_basicReportView); ReportContext.ResetCache(); ReportContext.CurrentWorkPeriod = AppServices.MainDataContext.CurrentWorkPeriod; } protected override void OnInitialization() { _regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(BasicReportView)); } protected override void OnPostInitialization() { CommonEventPublisher.PublishNavigationCommandEvent(_navigateReportsCommand); } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/BasicReportModule.cs
C#
gpl3
3,726
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Samba.Modules.BasicReports.Reports.AccountReport { public class AccountData { public int Id { get; set; } public string PhoneNumber { get; set; } public string CustomerName { get; set; } public decimal Amount { get; set; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/AccountReport/AccountData.cs
C#
gpl3
386
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Documents; using Samba.Localization.Properties; namespace Samba.Modules.BasicReports.Reports.AccountReport { class InternalAccountsViewModel : AccountReportViewModelBase { protected override FlowDocument GetReport() { return CreateReport(Resources.InternalAccounts, null, true); } protected override string GetHeader() { return Resources.InternalAccounts; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/AccountReport/InternalAccountsViewModel.cs
C#
gpl3
580
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Documents; using Samba.Domain.Models.Tickets; using Samba.Localization.Properties; using Samba.Persistance.Data; namespace Samba.Modules.BasicReports.Reports.AccountReport { class LiabilityReportViewModel : AccountReportViewModelBase { protected override FlowDocument GetReport() { return CreateReport(Resources.AccountsLiability, false, false); } protected override string GetHeader() { return Resources.AccountsLiability; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/AccountReport/LiabilityReportViewModel.cs
C#
gpl3
650
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Documents; using Samba.Domain.Models.Customers; using Samba.Domain.Models.Tickets; using Samba.Domain.Models.Transactions; using Samba.Localization.Properties; using Samba.Persistance.Data; namespace Samba.Modules.BasicReports.Reports.AccountReport { public abstract class AccountReportViewModelBase : ReportViewModelBase { protected override void CreateFilterGroups() { FilterGroups.Clear(); FilterGroups.Add(CreateWorkPeriodFilterGroup()); } protected IEnumerable<AccountData> GetBalancedAccounts(bool selectInternalAccounts) { var tickets = Dao.Query<Ticket>(x => x.CustomerId > 0, x => x.Payments); var paymentSum = tickets.GroupBy(x => x.CustomerId).Select(x => new { CustomerId = x.Key, Amount = x.Sum(k => k.Payments.Where(y => y.PaymentType == 3).Sum(j => j.Amount)) }).ToList(); var transactions = Dao.Query<CashTransaction>().Where(x => x.CustomerId > 0); var transactionSum = transactions.GroupBy(x => x.CustomerId).Select( x => new { CustomerId = x.Key, Amount = x.Sum(y => y.TransactionType == 1 ? y.Amount : 0 - y.Amount) }).ToList(); var accountTransactions = Dao.Query<AccountTransaction>().Where(x => x.CustomerId > 0); var accountTransactionSum = accountTransactions.GroupBy(x => x.CustomerId).Select( x => new { CustomerId = x.Key, Amount = x.Sum(y => y.TransactionType == 3 ? y.Amount : 0 - y.Amount) }).ToList(); var customerIds = paymentSum.Select(x => x.CustomerId).Distinct(); customerIds = customerIds.Union(transactionSum.Select(x => x.CustomerId).Distinct()); customerIds = customerIds.Union(accountTransactionSum.Select(x => x.CustomerId).Distinct()); var list = (from customerId in customerIds let amount = transactionSum.Where(x => x.CustomerId == customerId).Sum(x => x.Amount) let account = accountTransactionSum.Where(x => x.CustomerId == customerId).Sum(x => x.Amount) let payment = paymentSum.Where(x => x.CustomerId == customerId).Sum(x => x.Amount) select new { CustomerId = customerId, Amount = (amount + account + payment) }) .Where(x => x.Amount != 0).ToList(); var cids = list.Select(x => x.CustomerId).ToList(); var accounts = Dao.Select<Customer, AccountData>( x => new AccountData { Id = x.Id, CustomerName = x.Name, PhoneNumber = x.PhoneNumber, Amount = 0 }, x => cids.Contains(x.Id) && x.InternalAccount == selectInternalAccounts); foreach (var accountData in accounts) { accountData.Amount = list.SingleOrDefault(x => x.CustomerId == accountData.Id).Amount; } return accounts; } public FlowDocument CreateReport(string reportHeader, bool? returnReceivables, bool selectInternalAccounts) { var report = new SimpleReport("8cm"); report.AddHeader("Samba POS"); report.AddHeader(reportHeader); report.AddHeader(string.Format(Resources.As_f, DateTime.Now)); var accounts = GetBalancedAccounts(selectInternalAccounts); if (returnReceivables != null) accounts = returnReceivables.GetValueOrDefault(false) ? accounts.Where(x => x.Amount < 0) : accounts.Where(x => x.Amount > 0); report.AddColumTextAlignment("Tablo", TextAlignment.Left, TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("Tablo", "35*", "35*", "30*"); if (accounts.Count() > 0) { report.AddTable("Tablo", Resources.Accounts, "", ""); var total = 0m; foreach (var account in accounts) { total += Math.Abs(account.Amount); report.AddRow("Tablo", account.PhoneNumber, account.CustomerName, Math.Abs(account.Amount).ToString(ReportContext.CurrencyFormat)); } report.AddRow("Tablo", Resources.GrandTotal, "", total); } else { report.AddHeader(string.Format(Resources.NoTransactionsFoundFor_f, reportHeader)); } return report.Document; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/AccountReport/AccountReportViewModelBase.cs
C#
gpl3
5,008
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Documents; using Samba.Localization.Properties; namespace Samba.Modules.BasicReports.Reports.AccountReport { public class ReceivableReportViewModel : AccountReportViewModelBase { protected override FlowDocument GetReport() { return CreateReport(Resources.AccountsReceivable, true, false); } protected override string GetHeader() { return Resources.AccountsReceivable; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/AccountReport/ReceivableReportViewModel.cs
C#
gpl3
592
namespace Samba.Modules.BasicReports.Reports { internal class TenderedAmount { public int PaymentType { get; set; } public decimal Amount { get; set; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/TenderedAmount.cs
C#
gpl3
193
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Samba.Modules.BasicReports.Reports { internal class MenuItemSellInfo { public string Name { get; set; } public decimal Quantity { get; set; } public decimal Amount { get; set; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/MenuItemSellInfo.cs
C#
gpl3
332
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Documents; using Samba.Domain; using Samba.Domain.Models.Settings; using Samba.Localization.Properties; using Samba.Services; namespace Samba.Modules.BasicReports.Reports.CashReport { public class CashReportViewModel : ReportViewModelBase { protected override void CreateFilterGroups() { FilterGroups.Clear(); FilterGroups.Add(CreateWorkPeriodFilterGroup()); } private static string GetPaymentString(int paymentType) { if (paymentType == (int)PaymentType.Cash) return Resources.Cash; if (paymentType == (int)PaymentType.CreditCard) return Resources.CreditCard_ab; return Resources.Voucher_ab; } private static string Fs(decimal amount) { return amount.ToString(ReportContext.CurrencyFormat); } protected override FlowDocument GetReport() { var report = new SimpleReport("8cm"); AddDefaultReportHeader(report, ReportContext.CurrentWorkPeriod, Resources.CashReport); if (ReportContext.CurrentWorkPeriod.Id == 0) { report.AddHeader(" "); report.AddHeader(Resources.DateRangeIsNotActiveWorkPeriod); report.AddHeader(Resources.ReportDoesNotContainsCashState); } var cashExpenseTotal = ReportContext.CashTransactions .Where(x => x.PaymentType == (int)PaymentType.Cash && x.TransactionType == (int)TransactionType.Expense) .Sum(x => x.Amount); var creditCardExpenseTotal = ReportContext.CashTransactions .Where(x => x.PaymentType == (int)PaymentType.CreditCard && x.TransactionType == (int)TransactionType.Expense) .Sum(x => x.Amount); var ticketExpenseTotal = ReportContext.CashTransactions .Where(x => x.PaymentType == (int)PaymentType.Ticket && x.TransactionType == (int)TransactionType.Expense) .Sum(x => x.Amount); var cashIncomeTotal = ReportContext.CashTransactions .Where(x => x.PaymentType == (int)PaymentType.Cash && x.TransactionType == (int)TransactionType.Income) .Sum(x => x.Amount); var ticketIncomeTotal = ReportContext.CashTransactions .Where(x => x.PaymentType == (int)PaymentType.Ticket && x.TransactionType == (int)TransactionType.Income) .Sum(x => x.Amount); var creditCardIncomeTotal = ReportContext.CashTransactions .Where(x => x.PaymentType == (int)PaymentType.CreditCard && x.TransactionType == (int)TransactionType.Income) .Sum(x => x.Amount); var expenseTransactions = ReportContext.CashTransactions.Where(x => x.TransactionType == (int)TransactionType.Expense); if (expenseTransactions.Count() > 0) { report.AddColumTextAlignment("Gider", TextAlignment.Left, TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("Gider", "15*", "Auto", "25*"); report.AddTable("Gider", Resources.Expenses, "", ""); report.AddBoldRow("Gider", Resources.CashTransactions.ToUpper(), "", ""); foreach (var cashTransaction in expenseTransactions) { report.AddRow("Gider", GetPaymentString(cashTransaction.PaymentType), Fct(cashTransaction), Fs(cashTransaction.Amount)); } report.AddBoldRow("Gider", Resources.Totals.ToUpper(), "", ""); report.AddRow("Gider", GetPaymentString(0), Resources.TotalExpense, Fs(cashExpenseTotal)); report.AddRow("Gider", GetPaymentString(1), Resources.TotalExpense, Fs(creditCardExpenseTotal)); report.AddRow("Gider", GetPaymentString(2), Resources.TotalExpense, Fs(ticketExpenseTotal)); report.AddRow("Gider", Resources.GrandTotal.ToUpper(), "", Fs(cashExpenseTotal + creditCardExpenseTotal + ticketExpenseTotal)); } var ac = ReportContext.GetOperationalAmountCalculator(); report.AddColumTextAlignment("Gelir", TextAlignment.Left, TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("Gelir", "15*", "Auto", "25*"); report.AddTable("Gelir", Resources.Incomes, "", ""); if (ReportContext.CurrentWorkPeriod.Id > 0) //devreden rakamları aktif çalışma dönemlerinden biri seçildiyse çalışır { var total = ReportContext.CurrentWorkPeriod.CashAmount + ReportContext.CurrentWorkPeriod.CreditCardAmount + ReportContext.CurrentWorkPeriod.TicketAmount; if (total > 0) { report.AddBoldRow("Gelir", Resources.StartAmount.ToUpper(), "", ""); if (ReportContext.CurrentWorkPeriod.CashAmount > 0) report.AddRow("Gelir", GetPaymentString(0) + " " + Resources.StartAmount, "", Fs(ReportContext.CurrentWorkPeriod.CashAmount)); if (ReportContext.CurrentWorkPeriod.CreditCardAmount > 0) report.AddRow("Gelir", GetPaymentString(1) + " " + Resources.StartAmount, "", Fs(ReportContext.CurrentWorkPeriod.CreditCardAmount)); if (ReportContext.CurrentWorkPeriod.TicketAmount > 0) report.AddRow("Gelir", GetPaymentString(2) + " " + Resources.StartAmount, "", Fs(ReportContext.CurrentWorkPeriod.TicketAmount)); report.AddRow("Gelir", Resources.Total.ToUpper(), "", Fs(total)); } } var incomeTransactions = ReportContext.CashTransactions.Where(x => x.TransactionType == (int)TransactionType.Income); if (incomeTransactions.Count() > 0) { report.AddBoldRow("Gelir", Resources.SalesIncome.ToUpper(), "", ""); if (ac.CashTotal > 0) report.AddRow("Gelir", GetPaymentString(0) + " " + Resources.SalesIncome, "", Fs(ac.CashTotal)); if (ac.CreditCardTotal > 0) report.AddRow("Gelir", GetPaymentString(1) + " " + Resources.SalesIncome, "", Fs(ac.CreditCardTotal)); if (ac.TicketTotal > 0) report.AddRow("Gelir", GetPaymentString(2) + " " + Resources.SalesIncome, "", Fs(ac.TicketTotal)); report.AddRow("Gelir", Resources.Total.ToUpper(), "", Fs(ac.CashTotal + ac.CreditCardTotal + ac.TicketTotal)); report.AddBoldRow("Gelir", Resources.CashTransactions.ToUpper(), "", ""); var it = 0m; foreach (var cashTransaction in incomeTransactions) { it += cashTransaction.Amount; report.AddRow("Gelir", GetPaymentString(cashTransaction.PaymentType), Fct(cashTransaction), Fs(cashTransaction.Amount)); } report.AddRow("Gelir", Resources.Total.ToUpper(), "", Fs(it)); } var totalCashIncome = cashIncomeTotal + ac.CashTotal + ReportContext.CurrentWorkPeriod.CashAmount; var totalCreditCardIncome = creditCardIncomeTotal + ac.CreditCardTotal + ReportContext.CurrentWorkPeriod.CreditCardAmount; var totalTicketIncome = ticketIncomeTotal + ac.TicketTotal + ReportContext.CurrentWorkPeriod.TicketAmount; report.AddBoldRow("Gelir", Resources.Income.ToUpper() + " " + Resources.Totals.ToUpper(), "", ""); report.AddRow("Gelir", GetPaymentString(0), Resources.TotalIncome, Fs(totalCashIncome)); report.AddRow("Gelir", GetPaymentString(1), Resources.TotalIncome, Fs(totalCreditCardIncome)); report.AddRow("Gelir", GetPaymentString(2), Resources.TotalIncome, Fs(totalTicketIncome)); report.AddRow("Gelir", Resources.GrandTotal.ToUpper(), "", Fs(totalCashIncome + totalCreditCardIncome + totalTicketIncome)); //-------------------- report.AddColumTextAlignment("Toplam", TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("Toplam", "Auto", "25*"); report.AddTable("Toplam", Resources.CashStatus, ""); report.AddRow("Toplam", Resources.Cash, Fs(totalCashIncome - cashExpenseTotal)); report.AddRow("Toplam", Resources.CreditCard, Fs(totalCreditCardIncome - creditCardExpenseTotal)); report.AddRow("Toplam", Resources.Voucher, Fs(totalTicketIncome - ticketExpenseTotal)); report.AddRow("Toplam", Resources.GrandTotal.ToUpper(), Fs((totalCashIncome - cashExpenseTotal) + (totalCreditCardIncome - creditCardExpenseTotal) + (totalTicketIncome - ticketExpenseTotal))); return report.Document; } private static string Fct(CashTransactionData data) { var cn = !string.IsNullOrEmpty(data.CustomerName) ? data.CustomerName + " " : ""; return data.Date.ToShortDateString() + " " + cn + data.Name; } protected override string GetHeader() { return Resources.CashReport; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/CashReport/CashReportViewModel.cs
C#
gpl3
9,801
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Localization.Properties; namespace Samba.Modules.BasicReports.Reports { internal class TicketTagInfo { public decimal Amount { get; set; } public int TicketCount { get; set; } private string _tagName; public string TagName { get { return !string.IsNullOrEmpty(_tagName) ? _tagName.Trim() : Resources.TicketWithBrackets; } set { _tagName = value; } } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/TicketTagInfo.cs
C#
gpl3
560
using System; using System.Linq; using System.Windows; using System.Windows.Documents; using Samba.Domain.Models.Tickets; using Samba.Localization.Properties; namespace Samba.Modules.BasicReports.Reports.ProductReport { public class ProductReportViewModel : ReportViewModelBase { protected override FlowDocument GetReport() { var report = new SimpleReport("8cm"); AddDefaultReportHeader(report, ReportContext.CurrentWorkPeriod, Resources.ItemSalesReport); var menuGroups = MenuGroupBuilder.CalculateMenuGroups(ReportContext.Tickets, ReportContext.MenuItems); report.AddColumTextAlignment("ÜrünGrubu", TextAlignment.Left, TextAlignment.Right, TextAlignment.Right); report.AddColumnLength("ÜrünGrubu", "40*", "Auto", "35*"); report.AddTable("ÜrünGrubu", Resources.SalesByItemGroup, "", ""); foreach (var menuItemInfo in menuGroups) { report.AddRow("ÜrünGrubu", menuItemInfo.GroupName, string.Format("%{0:0.00}", menuItemInfo.Rate), menuItemInfo.Amount.ToString(ReportContext.CurrencyFormat)); } report.AddRow("ÜrünGrubu", Resources.Total, "", menuGroups.Sum(x => x.Amount).ToString(ReportContext.CurrencyFormat)); //---------------------- report.AddColumTextAlignment("ÜrünGrubuMiktar", TextAlignment.Left, TextAlignment.Right, TextAlignment.Right); report.AddColumnLength("ÜrünGrubuMiktar", "40*", "Auto", "35*"); report.AddTable("ÜrünGrubuMiktar", Resources.QuantitiesByItemGroup, "", ""); foreach (var menuItemInfo in menuGroups) { report.AddRow("ÜrünGrubuMiktar", menuItemInfo.GroupName, string.Format("%{0:0.00}", menuItemInfo.QuantityRate), menuItemInfo.Quantity.ToString("#")); } report.AddRow("ÜrünGrubuMiktar", Resources.Total, "", menuGroups.Sum(x => x.Quantity).ToString("#")); //---------------------- var menuItems = MenuGroupBuilder.CalculateMenuItems(ReportContext.Tickets, ReportContext.MenuItems) .OrderByDescending(x => x.Quantity); report.AddColumTextAlignment("ÜrünTablosu", TextAlignment.Left, TextAlignment.Right, TextAlignment.Right); report.AddColumnLength("ÜrünTablosu", "50*", "Auto", "25*"); report.AddTable("ÜrünTablosu", Resources.MenuItem, Resources.Quantity, Resources.Amount); foreach (var menuItemInfo in menuItems) { report.AddRow("ÜrünTablosu", menuItemInfo.Name, string.Format("{0:0.##}", menuItemInfo.Quantity), menuItemInfo.Amount.ToString(ReportContext.CurrencyFormat)); } report.AddRow("ÜrünTablosu", Resources.Total, "", menuItems.Sum(x => x.Amount).ToString(ReportContext.CurrencyFormat)); //---------------------- PrepareModificationTable(report, x => x.Voided, Resources.Voids); PrepareModificationTable(report, x => x.Gifted, Resources.Gifts); var discounts = ReportContext.Tickets .SelectMany(x => x.Discounts.Select(y => new { x.TicketNumber, y.UserId, Amount = y.DiscountAmount })) .GroupBy(x => new { x.TicketNumber, x.UserId }).Select(x => new { x.Key.TicketNumber, x.Key.UserId, Amount = x.Sum(y => y.Amount) }); if (discounts.Count() > 0) { report.AddColumTextAlignment("İskontolarTablosu", TextAlignment.Left, TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("İskontolarTablosu", "20*", "Auto", "35*"); report.AddTable("İskontolarTablosu", Resources.Discounts, "", ""); foreach (var discount in discounts.OrderByDescending(x => x.Amount)) { report.AddRow("İskontolarTablosu", discount.TicketNumber, ReportContext.GetUserName(discount.UserId), discount.Amount.ToString(ReportContext.CurrencyFormat)); } if (discounts.Count() > 1) report.AddRow("İskontolarTablosu", Resources.Total, "", discounts.Sum(x => x.Amount).ToString(ReportContext.CurrencyFormat)); } //---------------------- var ticketGroups = ReportContext.Tickets .GroupBy(x => new { x.DepartmentId }) .Select(x => new { x.Key.DepartmentId, TicketCount = x.Count(), Amount = x.Sum(y => y.GetSumWithoutTax()) }); if (ticketGroups.Count() > 0) { report.AddColumTextAlignment("AdisyonlarTablosu", TextAlignment.Left, TextAlignment.Right, TextAlignment.Right); report.AddColumnLength("AdisyonlarTablosu", "40*", "20*", "40*"); report.AddTable("AdisyonlarTablosu", Resources.Tickets, "", ""); foreach (var ticketGroup in ticketGroups) { report.AddRow("AdisyonlarTablosu", ReportContext.GetDepartmentName(ticketGroup.DepartmentId), ticketGroup.TicketCount.ToString("#.##"), ticketGroup.Amount.ToString(ReportContext.CurrencyFormat)); } if (ticketGroups.Count() > 1) report.AddRow("AdisyonlarTablosu", Resources.Total, ticketGroups.Sum(x => x.TicketCount).ToString("#.##"), ticketGroups.Sum(x => x.Amount).ToString(ReportContext.CurrencyFormat)); } //---------------------- var properties = ReportContext.Tickets .SelectMany(x => x.TicketItems.Where(y => y.Properties.Count > 0)) .SelectMany(x => x.Properties.Where(y => y.MenuItemId == 0).Select(y => new { y.Name, x.Quantity })) .GroupBy(x => new { x.Name }) .Select(x => new { x.Key.Name, Quantity = x.Sum(y => y.Quantity) }); if (properties.Count() > 0) { report.AddColumTextAlignment("ÖzelliklerTablosu", TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("ÖzelliklerTablosu", "60*", "40*"); report.AddTable("ÖzelliklerTablosu", Resources.Properties, ""); foreach (var property in properties.OrderByDescending(x => x.Quantity)) { report.AddRow("ÖzelliklerTablosu", property.Name, property.Quantity.ToString("#.##")); } } return report.Document; } private static void PrepareModificationTable(SimpleReport report, Func<TicketItem, bool> predicate, string title) { var modifiedItems = ReportContext.Tickets .SelectMany(x => x.TicketItems.Where(predicate) .OrderBy(y => y.ModifiedDateTime) .Select(y => new { Ticket = x, UserId = y.ModifiedUserId, MenuItem = y.MenuItemName, y.Quantity, y.ReasonId, y.ModifiedDateTime, Amount = y.GetItemValue() })); if (modifiedItems.Count() == 0) return; report.AddColumTextAlignment(title, TextAlignment.Left, TextAlignment.Left, TextAlignment.Left, TextAlignment.Left); report.AddColumnLength(title, "14*", "45*", "28*", "13*"); report.AddTable(title, title, "", "", ""); foreach (var voidItem in modifiedItems.GroupBy(x => x.ReasonId)) { if (voidItem.Key > 0) report.AddRow(title, ReportContext.GetReasonName(voidItem.Key), "", "", ""); foreach (var vi in voidItem) { report.AddRow(title, vi.Ticket.TicketNumber, vi.Quantity.ToString("#.##") + " " + vi.MenuItem, ReportContext.GetUserName(vi.UserId), vi.ModifiedDateTime.ToShortTimeString()); } } var voidGroups = from c in modifiedItems group c by c.UserId into grp select new { UserId = grp.Key, Amount = grp.Sum(x => x.Amount) }; report.AddColumTextAlignment("Personel" + title, TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("Personel" + title, "60*", "40*"); report.AddTable("Personel" + title, string.Format(Resources.ByPersonnel_f, title), ""); foreach (var voidItem in voidGroups.OrderByDescending(x => x.Amount)) { report.AddRow("Personel" + title, ReportContext.GetUserName(voidItem.UserId), voidItem.Amount.ToString(ReportContext.CurrencyFormat)); } if (voidGroups.Count() > 1) report.AddRow("Personel" + title, Resources.Total, voidGroups.Sum(x => x.Amount).ToString(ReportContext.CurrencyFormat)); } protected override void CreateFilterGroups() { FilterGroups.Clear(); FilterGroups.Add(CreateWorkPeriodFilterGroup()); } protected override string GetHeader() { return Resources.ItemSalesReport; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/ProductReport/ProductReportViewModel.cs
C#
gpl3
9,854
using System.Linq; namespace Samba.Modules.BasicReports.Reports { internal class UserInfo { public int UserId { get; set; } public string UserName { get { var user = ReportContext.Users.SingleOrDefault(x => x.Id == UserId); return user != null ? user.Name : Localization.Properties.Resources.UndefinedWithBrackets; } } public decimal Amount { get; set; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/UserInfo.cs
C#
gpl3
499
using System.Collections.Generic; using System.Linq; using Samba.Domain.Models.Menus; using Samba.Domain.Models.Tickets; namespace Samba.Modules.BasicReports.Reports { internal static class MenuGroupBuilder { public static IEnumerable<MenuItemGroupInfo> CalculateMenuGroups(IEnumerable<Ticket> tickets, IEnumerable<MenuItem> menuItems) { var menuItemInfoGroups = from c in tickets.SelectMany(x => x.TicketItems.Select(y => new { Ticket = x, TicketItem = y })) join menuItem in menuItems on c.TicketItem.MenuItemId equals menuItem.Id group c by menuItem.GroupCode into grp select new MenuItemGroupInfo { GroupName = grp.Key, Quantity = grp.Sum(y => y.TicketItem.Quantity), Amount = grp.Sum(y => CalculateTicketItemTotal(y.Ticket, y.TicketItem)) }; var result = menuItemInfoGroups.ToList().OrderByDescending(x => x.Amount); var sum = menuItemInfoGroups.Sum(x => x.Amount); foreach (var menuItemInfoGroup in result) { if (sum > 0) menuItemInfoGroup.Rate = (menuItemInfoGroup.Amount * 100) / sum; if (string.IsNullOrEmpty(menuItemInfoGroup.GroupName)) menuItemInfoGroup.GroupName = Localization.Properties.Resources.UndefinedWithBrackets; } var qsum = menuItemInfoGroups.Sum(x => x.Quantity); foreach (var menuItemInfoGroup in result) { if (qsum > 0) menuItemInfoGroup.QuantityRate = (menuItemInfoGroup.Quantity * 100) / qsum; if (string.IsNullOrEmpty(menuItemInfoGroup.GroupName)) menuItemInfoGroup.GroupName = Localization.Properties.Resources.UndefinedWithBrackets; } return result; } public static IEnumerable<MenuItemSellInfo> CalculateMenuItems(IEnumerable<Ticket> tickets, IEnumerable<MenuItem> menuItems) { var menuItemSellInfos = from c in tickets.SelectMany(x => x.TicketItems.Where(y => !y.Voided).Select(y => new { Ticket = x, TicketItem = y })) join menuItem in menuItems on c.TicketItem.MenuItemId equals menuItem.Id group c by menuItem.Name into grp select new MenuItemSellInfo { Name = grp.Key, Quantity = grp.Sum(y => y.TicketItem.Quantity), Amount = grp.Sum(y => CalculateTicketItemTotal(y.Ticket, y.TicketItem)) }; var result = menuItemSellInfos.ToList().OrderByDescending(x => x.Quantity); return result; } public static decimal CalculateTicketItemTotal(Ticket ticket, TicketItem ticketItem) { var discount = ticket.GetDiscountAndRoundingTotal(); if (discount != 0) { var tsum = ticket.GetSumWithoutTax() + discount; var rate = tsum > 0 ? (discount * 100) / tsum : 100; var tiTotal = ticketItem.GetTotal(); var itemDiscount = (tiTotal * rate) / 100; return tiTotal - itemDiscount; } return ticketItem.GetTotal(); } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/MenuGroupBuilder.cs
C#
gpl3
3,378
using System; using System.Globalization; using System.IO; using System.Linq; using System.Windows; using System.Windows.Documents; using Samba.Localization.Properties; using Samba.Presentation.Common; namespace Samba.Modules.BasicReports.Reports.CSVBuilder { class CsvBuilderViewModel : ReportViewModelBase { protected override void CreateFilterGroups() { FilterGroups.Clear(); FilterGroups.Add(CreateWorkPeriodFilterGroup()); } protected override FlowDocument GetReport() { var currentPeriod = ReportContext.CurrentWorkPeriod; var report = new SimpleReport("8cm"); AddDefaultReportHeader(report, currentPeriod, Resources.CsvBuilder); report.Header.TextAlignment = TextAlignment.Left; report.AddHeader(""); report.AddHeader(Resources.ClickLinksToExportData); report.AddHeader(""); report.AddLink(Resources.ExportSalesData); HandleLink(Resources.ExportSalesData); return report.Document; } protected override void HandleClick(string text) { if (text == Resources.ExportSalesData) { ExportSalesData(); } } private void ExportSalesData() { var fileName = AskFileName(Resources.ExportSalesData + "_" + String.Format("{0:yyyy-MM-dd_hh-mm-ss}.txt", DateTime.Now), ".csv"); if (string.IsNullOrEmpty(fileName)) return; var lines = ReportContext.Tickets.SelectMany(x => x.TicketItems, (t, ti) => new { Ticket = t, TicketItem = ti }); var data = lines.Select(x => new { DateTime = x.TicketItem.CreatedDateTime, Date = x.TicketItem.CreatedDateTime.ToShortDateString(), Time = x.TicketItem.CreatedDateTime.ToShortTimeString(), x.Ticket.TicketNumber, UserName = ReportContext.GetUserName(x.TicketItem.CreatingUserId), Account = x.Ticket.CustomerName, Location = x.Ticket.LocationName, x.TicketItem.DepartmentId, x.TicketItem.OrderNumber, x.TicketItem.Voided, x.TicketItem.Gifted, Name = x.TicketItem.MenuItemName, Portion = x.TicketItem.PortionName, x.TicketItem.Quantity, Price = x.TicketItem.GetItemPrice(), Value = x.TicketItem.GetItemValue(), Discount = x.Ticket.GetPlainSum() > 0 ? x.Ticket.GetDiscountTotal() / x.Ticket.GetPlainSum() : 0, Rounding = x.Ticket.GetRoundingTotal(), Total = MenuGroupBuilder.CalculateTicketItemTotal(x.Ticket, x.TicketItem), } ); var csv = data.AsCsv(); File.WriteAllText(fileName, csv); } protected override string GetHeader() { return Resources.CsvBuilder; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/CSVBuilder/CsvBuilderViewModel.cs
C#
gpl3
3,322
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Documents; using Samba.Localization.Properties; using Samba.Persistance.Data; namespace Samba.Modules.BasicReports.Reports.InventoryReports { class PurchaseReportViewModel : ReportViewModelBase { protected override void CreateFilterGroups() { FilterGroups.Clear(); FilterGroups.Add(CreateWorkPeriodFilterGroup()); } protected override FlowDocument GetReport() { var report = new SimpleReport("8cm"); AddDefaultReportHeader(report, ReportContext.CurrentWorkPeriod, Resources.InventoryPurchaseReport); var transactionGroups = ReportContext.Transactions.SelectMany(x => x.TransactionItems) .GroupBy(x => new { x.InventoryItem.GroupCode }) .Select(x => new { ItemName = x.Key.GroupCode, Total = x.Sum(y => (y.Price * y.Quantity)) }); if (transactionGroups.Count() > 0) { report.AddColumTextAlignment("GrupToplam", TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("GrupToplam", "60*", "40*"); report.AddTable("GrupToplam", Resources.InventoryGroup, Resources.Total); if (transactionGroups.Count() > 1) { foreach (var transactionItem in transactionGroups) { report.AddRow("GrupToplam", !string.IsNullOrEmpty(transactionItem.ItemName) ? transactionItem.ItemName : Resources.UndefinedWithBrackets, transactionItem.Total.ToString(ReportContext.CurrencyFormat)); } } report.AddRow("GrupToplam", Resources.Total, transactionGroups.Sum(x => x.Total).ToString(ReportContext.CurrencyFormat)); } var transactionItems = ReportContext.Transactions.SelectMany(x => x.TransactionItems) .GroupBy(x => new { x.InventoryItem.Name, x.Unit }) .Select(x => new { ItemName = x.Key.Name, Quantity = x.Sum(y => y.Quantity), x.Key.Unit, Total = x.Sum(y => y.Price * y.Quantity) }); if (transactionItems.Count() > 0) { report.AddColumTextAlignment("Alımlar", TextAlignment.Left, TextAlignment.Right, TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("Alımlar", "40*", "20*", "15*", "25*"); report.AddTable("Alımlar", Resources.InventoryItem, Resources.Quantity, Resources.Unit, Resources.AveragePrice_ab); foreach (var transactionItem in transactionItems) { report.AddRow("Alımlar", transactionItem.ItemName, transactionItem.Quantity.ToString("#,#0.##"), transactionItem.Unit, (transactionItem.Total / transactionItem.Quantity).ToString(ReportContext.CurrencyFormat)); } } else { report.AddHeader(""); report.AddHeader(Resources.NoPurchaseTransactionInCurrentDateRange); } return report.Document; } protected override string GetHeader() { return Resources.InventoryPurchaseReport; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/InventoryReports/PurchaseReportViewModel.cs
C#
gpl3
3,585
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Documents; using Samba.Localization.Properties; namespace Samba.Modules.BasicReports.Reports.InventoryReports { class CostReportViewModel : ReportViewModelBase { protected override void CreateFilterGroups() { FilterGroups.Clear(); FilterGroups.Add(CreateWorkPeriodFilterGroup()); } protected override FlowDocument GetReport() { var report = new SimpleReport("8cm"); AddDefaultReportHeader(report, ReportContext.CurrentWorkPeriod, Resources.CostReport); var costItems = ReportContext.PeriodicConsumptions.SelectMany(x => x.CostItems) .GroupBy(x => new { ItemName = x.Name, PortionName = x.Portion.Name }) .Select(x => new { x.Key.ItemName, x.Key.PortionName, TotalQuantity = x.Sum(y => y.Quantity), TotalCost = x.Sum(y => y.Cost * y.Quantity) }); if (costItems.Count() > 0) { report.AddColumTextAlignment("Maliyet", TextAlignment.Left, TextAlignment.Left, TextAlignment.Right, TextAlignment.Right); report.AddColumnLength("Maliyet", "38*", "20*", "17*", "25*"); report.AddTable("Maliyet", Resources.MenuItem, Resources.Portion, Resources.Quantity, Resources.AverageCost); foreach (var costItem in costItems) { report.AddRow("Maliyet", costItem.ItemName, costItem.PortionName, costItem.TotalQuantity.ToString("#,#0.##"), (costItem.TotalCost / costItem.TotalQuantity).ToString(ReportContext.CurrencyFormat)); } report.AddRow("Maliyet", Resources.Total, "", "", costItems.Sum(x => x.TotalCost).ToString(ReportContext.CurrencyFormat)); } else report.AddHeader(Resources.ThereAreNoCostTransactionsInThisPeriod); return report.Document; } protected override string GetHeader() { return Resources.CostReport; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/InventoryReports/CostReportViewModel.cs
C#
gpl3
2,278
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Documents; using Samba.Localization.Properties; using Samba.Services; namespace Samba.Modules.BasicReports.Reports.InventoryReports { class InventoryReportViewModel : ReportViewModelBase { protected override void CreateFilterGroups() { FilterGroups.Clear(); FilterGroups.Add(CreateWorkPeriodFilterGroup()); } protected override FlowDocument GetReport() { var report = new SimpleReport("8cm"); report.AddHeader("Samba POS"); report.AddHeader(Resources.InventoryReport); report.AddHeader(string.Format(Resources.As_f, DateTime.Now)); var lastPeriodicConsumption = ReportContext.GetCurrentPeriodicConsumption(); var consumptionItems = lastPeriodicConsumption.PeriodicConsumptionItems; if (consumptionItems.Count() > 0) { report.AddColumTextAlignment("InventoryTable", TextAlignment.Left, TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("InventoryTable", "45*", "30*", "35*"); report.AddTable("InventoryTable", Resources.InventoryItem, Resources.Unit, Resources.Quantity); foreach (var costItem in consumptionItems) { report.AddRow("InventoryTable", costItem.InventoryItem.Name, costItem.InventoryItem.TransactionUnit??costItem.InventoryItem.BaseUnit, costItem.GetPhysicalInventory().ToString("#,#0.##")); } } else report.AddHeader(Resources.ThereAreNoCostTransactionsInThisPeriod); return report.Document; } protected override string GetHeader() { return Resources.InventoryReport; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/InventoryReports/InventoryReportViewModel.cs
C#
gpl3
2,037
using System.Linq; namespace Samba.Modules.BasicReports.Reports { internal class DepartmentInfo { public int DepartmentId { get; set; } public decimal Amount { get; set; } public decimal Vat { get; set; } public decimal TaxServices { get; set; } public int TicketCount { get; set; } public string DepartmentName { get { var d = ReportContext.Departments.SingleOrDefault(x => x.Id == DepartmentId); return d != null ? d.Name : Localization.Properties.Resources.UndefinedWithBrackets; } } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/DepartmentInfo.cs
C#
gpl3
658
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Samba.Modules.BasicReports.Reports { internal class AmountCalculator { private readonly IEnumerable<TenderedAmount> _amounts; public AmountCalculator(IEnumerable<TenderedAmount> amounts) { _amounts = amounts; } internal decimal GetAmount(int paymentType) { var r = _amounts.SingleOrDefault(x => x.PaymentType == paymentType); return r != null ? r.Amount : 0; } internal string GetPercent(int paymentType) { return TotalAmount > 0 ? string.Format("%{0:0.00}", (GetAmount(paymentType) * 100) / TotalAmount) : "%0"; } public decimal CashTotal { get { return GetAmount(0); } } public decimal CreditCardTotal { get { return GetAmount(1); } } public decimal TicketTotal { get { return GetAmount(2); } } public decimal AccountTotal { get { return GetAmount(3); } } public decimal GrandTotal { get { return _amounts.Where(x => x.PaymentType != 3).Sum(x => x.Amount); } } public decimal TotalAmount { get { return _amounts.Sum(x => x.Amount); } } public string CashPercent { get { return GetPercent(0); } } public string CreditCardPercent { get { return GetPercent(1); } } public string TicketPercent { get { return GetPercent(2); } } public string AccountPercent { get { return GetPercent(3); } } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/AmountCalculator.cs
C#
gpl3
1,556
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Documents; using Microsoft.Practices.EnterpriseLibrary.Common.Utility; using Samba.Domain.Models.Tickets; using Samba.Localization.Properties; namespace Samba.Modules.BasicReports.Reports.EndOfDayReport { public class EndDayReportViewModel : ReportViewModelBase { protected override void CreateFilterGroups() { FilterGroups.Clear(); FilterGroups.Add(CreateWorkPeriodFilterGroup()); } protected override FlowDocument GetReport() { var currentPeriod = ReportContext.CurrentWorkPeriod; var report = new SimpleReport("8cm"); AddDefaultReportHeader(report, currentPeriod, Resources.WorkPeriodReport); //--------------- report.AddColumTextAlignment("Departman", TextAlignment.Left, TextAlignment.Right); report.AddTable("Departman", Resources.Sales, ""); var ticketGropus = ReportContext.Tickets .GroupBy(x => new { x.DepartmentId }) .Select(x => new DepartmentInfo { DepartmentId = x.Key.DepartmentId, TicketCount = x.Count(), Amount = x.Sum(y => y.GetSumWithoutTax()), Vat = x.Sum(y => y.CalculateTax()), TaxServices = x.Sum(y => y.GetTaxServicesTotal()) }); report.AddRow("Departman", Resources.TotalSales.ToUpper(), ticketGropus.Sum(x => x.Amount).ToString(ReportContext.CurrencyFormat)); var vatSum = ticketGropus.Sum(x => x.Vat); var serviceSum = ticketGropus.Sum(x => x.TaxServices); if (vatSum > 0 || serviceSum > 0) { if (vatSum > 0) report.AddRow("Departman", Resources.VatTotal.ToUpper(), vatSum.ToString(ReportContext.CurrencyFormat)); if (serviceSum > 0) { ReportContext.Tickets.SelectMany(x => x.TaxServices).GroupBy(x => x.TaxServiceId).ForEach( x => { var template = ReportContext.TaxServiceTemplates.SingleOrDefault(y => y.Id == x.Key); var title = template != null ? template.Name : Resources.UndefinedWithBrackets; report.AddRow("Departman", title, x.Sum(y => y.CalculationAmount).ToString(ReportContext.CurrencyFormat)); }); } report.AddRow("Departman", Resources.GrandTotal.ToUpper(), ticketGropus.Sum(x => x.Amount + x.Vat + x.TaxServices).ToString(ReportContext.CurrencyFormat)); } //--------------- if (ReportContext.Departments.Count() > 1) { var showDepartmentTotals = false; report.AddColumnLength("CrossSales", "65*", "40*"); report.AddColumTextAlignment("CrossSales", TextAlignment.Left, TextAlignment.Right); report.AddTable("CrossSales", Resources.DepartmentSales, ""); foreach (var departmentInfo in ticketGropus) { var info = departmentInfo; var crossSales = ReportContext.Tickets.Where(x => x.DepartmentId == info.DepartmentId) .SelectMany(ticket => ticket.TicketItems.Select(ticketItem => new { Ticket = ticket, TicketItem = ticketItem })) .Where(x => x.TicketItem.DepartmentId != x.Ticket.DepartmentId) .GroupBy(x => new { x.TicketItem.DepartmentId }) .Select(x => new DepartmentInfo { DepartmentId = x.Key.DepartmentId, Amount = x.Sum(y => MenuGroupBuilder.CalculateTicketItemTotal(y.Ticket, y.TicketItem)) }); report.AddRow("CrossSales", string.Format("{0} {1}", departmentInfo.DepartmentName, Resources.Sales), (departmentInfo.Amount).ToString(ReportContext.CurrencyFormat)); if (crossSales.Count() > 0) { showDepartmentTotals = true; report.AddRow("CrossSales", " -" + departmentInfo.DepartmentName, (departmentInfo.Amount - crossSales.Sum(x => x.Amount)).ToString(ReportContext.CurrencyFormat)); foreach (var crossSale in crossSales) { var cs = crossSale; report.AddRow("CrossSales", " -" + cs.DepartmentName, cs.Amount.ToString(ReportContext.CurrencyFormat)); } } } if (showDepartmentTotals) { report.AddBoldRow("CrossSales", Resources.Department + " " + Resources.Totals, ""); var salesByOrder = ReportContext.Tickets.SelectMany(ticket => ticket.TicketItems.Select(ticketItem => new { Ticket = ticket, TicketItem = ticketItem })) .GroupBy(x => new { x.TicketItem.DepartmentId }) .Select(x => new DepartmentInfo { DepartmentId = x.Key.DepartmentId, Amount = x.Sum(y => MenuGroupBuilder.CalculateTicketItemTotal(y.Ticket, y.TicketItem)) }); foreach (var sale in salesByOrder) { var cs = sale; report.AddRow("CrossSales", cs.DepartmentName, cs.Amount.ToString(ReportContext.CurrencyFormat)); } } } //--------------- var ac = ReportContext.GetOperationalAmountCalculator(); report.AddColumnLength("GelirlerTablosu", "45*", "Auto", "35*"); report.AddColumTextAlignment("GelirlerTablosu", TextAlignment.Left, TextAlignment.Right, TextAlignment.Right); report.AddTable("GelirlerTablosu", Resources.Incomes, "", ""); report.AddRow("GelirlerTablosu", Resources.Cash, ac.CashPercent, ac.CashTotal.ToString(ReportContext.CurrencyFormat)); report.AddRow("GelirlerTablosu", Resources.CreditCard, ac.CreditCardPercent, ac.CreditCardTotal.ToString(ReportContext.CurrencyFormat)); report.AddRow("GelirlerTablosu", Resources.Voucher, ac.TicketPercent, ac.TicketTotal.ToString(ReportContext.CurrencyFormat)); report.AddRow("GelirlerTablosu", Resources.AccountBalance, ac.AccountPercent, ac.AccountTotal.ToString(ReportContext.CurrencyFormat)); report.AddRow("GelirlerTablosu", Resources.TotalIncome.ToUpper(), "", ac.TotalAmount.ToString(ReportContext.CurrencyFormat)); //--------------- //Kasa raporu eklendiği için kasa özeti bu rapordan kaldırıldı. Başka bir rapora taşınabilir şimdilik bıraktım. //var cashTransactionTotal = ReportContext.GetCashTotalAmount(); //var creditCardTransactionTotal = ReportContext.GetCreditCardTotalAmount(); //var ticketTransactionTotal = ReportContext.GetTicketTotalAmount(); //report.AddColumnLength("Kasa", "25*", "18*", "18*", "18*", "21*"); //report.AddColumTextAlignment("Kasa", TextAlignment.Left, TextAlignment.Right, TextAlignment.Right, TextAlignment.Right, TextAlignment.Right); //report.AddTable("Kasa", "Kasa", "Nakit", "K.Kartı", "Y.Çeki", "Toplam"); //report.AddRow("Kasa", "Gün Başı", // currentPeriod.CashAmount.ToString(ReportContext.CurrencyFormat), // currentPeriod.CreditCardAmount.ToString(ReportContext.CurrencyFormat), // currentPeriod.TicketAmount.ToString(ReportContext.CurrencyFormat), // (currentPeriod.CashAmount + currentPeriod.CreditCardAmount + currentPeriod.TicketAmount).ToString(ReportContext.CurrencyFormat)); //report.AddRow("Kasa", "Faaliyet", // ac.CashTotal.ToString(ReportContext.CurrencyFormat), // ac.CreditCardTotal.ToString(ReportContext.CurrencyFormat), // ac.TicketTotal.ToString(ReportContext.CurrencyFormat), // ac.GrandTotal.ToString(ReportContext.CurrencyFormat)); //report.AddRow("Kasa", "Hareketler", // cashTransactionTotal.ToString(ReportContext.CurrencyFormat), // creditCardTransactionTotal.ToString(ReportContext.CurrencyFormat), // ticketTransactionTotal.ToString(ReportContext.CurrencyFormat), // (cashTransactionTotal + creditCardTransactionTotal + ticketTransactionTotal).ToString(ReportContext.CurrencyFormat)); //var totalCash = currentPeriod.CashAmount + ac.CashTotal + cashTransactionTotal; //var totalCreditCard = currentPeriod.CreditCardAmount + ac.CreditCardTotal + creditCardTransactionTotal; //var totalTicket = currentPeriod.TicketAmount + ac.TicketTotal + ticketTransactionTotal; //report.AddRow("Kasa", "TOPLAM", // totalCash.ToString(ReportContext.CurrencyFormat), // totalCreditCard.ToString(ReportContext.CurrencyFormat), // totalTicket.ToString(ReportContext.CurrencyFormat), // (totalCash + totalCreditCard + totalTicket).ToString(ReportContext.CurrencyFormat)); //--------------- var propertySum = ReportContext.Tickets .SelectMany(x => x.TicketItems) .Sum(x => x.GetPropertyPrice() * x.Quantity); var voids = ReportContext.Tickets .SelectMany(x => x.TicketItems) .Where(x => x.Voided) .Sum(x => x.GetItemValue()); var discounts = ReportContext.Tickets .SelectMany(x => x.Discounts) .Sum(x => x.DiscountAmount); var gifts = ReportContext.Tickets .SelectMany(x => x.TicketItems) .Where(x => x.Gifted) .Sum(x => x.GetItemValue()); report.AddColumTextAlignment("Bilgi", TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("Bilgi", "65*", "35*"); report.AddTable("Bilgi", Resources.GeneralInformation, ""); report.AddRow("Bilgi", Resources.ItemProperties, propertySum.ToString(ReportContext.CurrencyFormat)); report.AddRow("Bilgi", Resources.VoidsTotal, voids.ToString(ReportContext.CurrencyFormat)); report.AddRow("Bilgi", Resources.DiscountsTotal, discounts.ToString(ReportContext.CurrencyFormat)); report.AddRow("Bilgi", Resources.GiftsTotal, gifts.ToString(ReportContext.CurrencyFormat)); if (ticketGropus.Count() > 1) foreach (var departmentInfo in ticketGropus) { report.AddRow("Bilgi", departmentInfo.DepartmentName, departmentInfo.TicketCount); } var ticketCount = ticketGropus.Sum(x => x.TicketCount); report.AddRow("Bilgi", Resources.TicketCount, ticketCount); report.AddRow("Bilgi", Resources.SalesDivTicket, ticketCount > 0 ? (ticketGropus.Sum(x => x.Amount) / ticketGropus.Sum(x => x.TicketCount)).ToString(ReportContext.CurrencyFormat) : "0"); if (ticketGropus.Count() > 1) { foreach (var departmentInfo in ticketGropus) { var dPayments = ReportContext.Tickets .SelectMany(x => x.Payments) .Where(x => x.DepartmentId == departmentInfo.DepartmentId) .GroupBy(x => new { x.PaymentType }) .Select(x => new TenderedAmount { PaymentType = x.Key.PaymentType, Amount = x.Sum(y => y.Amount) }); report.AddColumnLength(departmentInfo.DepartmentName + Resources.Incomes, "40*", "Auto", "35*"); report.AddColumTextAlignment(departmentInfo.DepartmentName + Resources.Incomes, TextAlignment.Left, TextAlignment.Right, TextAlignment.Right); report.AddTable(departmentInfo.DepartmentName + Resources.Incomes, string.Format(Resources.Incomes_f, departmentInfo.DepartmentName), "", ""); report.AddRow(departmentInfo.DepartmentName + Resources.Incomes, Resources.Cash, GetPercent(0, dPayments), GetAmount(0, dPayments).ToString(ReportContext.CurrencyFormat)); report.AddRow(departmentInfo.DepartmentName + Resources.Incomes, Resources.CreditCard, GetPercent(1, dPayments), GetAmount(1, dPayments).ToString(ReportContext.CurrencyFormat)); report.AddRow(departmentInfo.DepartmentName + Resources.Incomes, Resources.Voucher, GetPercent(2, dPayments), GetAmount(2, dPayments).ToString(ReportContext.CurrencyFormat)); report.AddRow(departmentInfo.DepartmentName + Resources.Incomes, Resources.AccountBalance, GetPercent(3, dPayments), GetAmount(3, dPayments).ToString(ReportContext.CurrencyFormat)); report.AddRow(departmentInfo.DepartmentName + Resources.Incomes, Resources.TotalIncome, "", dPayments.Sum(x => x.Amount).ToString(ReportContext.CurrencyFormat)); var dvoids = ReportContext.Tickets .SelectMany(x => x.TicketItems) .Where(x => x.Voided && x.DepartmentId == departmentInfo.DepartmentId) .Sum(x => x.GetItemValue()); var ddiscounts = ReportContext.Tickets .Where(x => x.DepartmentId == departmentInfo.DepartmentId) .SelectMany(x => x.Discounts) .Sum(x => x.DiscountAmount); var dgifts = ReportContext.Tickets .SelectMany(x => x.TicketItems) .Where(x => x.Gifted && x.DepartmentId == departmentInfo.DepartmentId) .Sum(x => x.GetItemValue()); report.AddRow(departmentInfo.DepartmentName + Resources.Incomes, Resources.VoidsTotal, "", dvoids.ToString(ReportContext.CurrencyFormat)); report.AddRow(departmentInfo.DepartmentName + Resources.Incomes, Resources.DiscountsTotal, "", ddiscounts.ToString(ReportContext.CurrencyFormat)); report.AddRow(departmentInfo.DepartmentName + Resources.Incomes, Resources.GiftsTotal, "", dgifts.ToString(ReportContext.CurrencyFormat)); } } //-- if (ReportContext.Tickets.Select(x => x.GetTagData()).Where(x => !string.IsNullOrEmpty(x)).Distinct().Count() > 0) { var dict = new Dictionary<string, List<Ticket>>(); foreach (var ticket in ReportContext.Tickets.Where(x => !string.IsNullOrEmpty(x.Tag))) { var tags = ticket.Tag.Split(new[] { '\r' }, StringSplitOptions.RemoveEmptyEntries); foreach (var tag in tags) { if (!dict.ContainsKey(tag)) dict.Add(tag, new List<Ticket>()); dict[tag].Add(ticket); } } var tagGroups = dict.Select(x => new TicketTagInfo { Amount = x.Value.Sum(y => y.GetSumWithoutTax()), TicketCount = x.Value.Count, TagName = x.Key }).OrderBy(x => x.TagName); var tagGrp = tagGroups.GroupBy(x => x.TagName.Split(':')[0]) .Where(x => ReportContext.TicketTagGroups.SingleOrDefault(y => y.Name == x.Key) != null); if (tagGrp.Count() > 0) { report.AddColumTextAlignment("Etiket", TextAlignment.Left, TextAlignment.Right, TextAlignment.Right); report.AddColumnLength("Etiket", "45*", "Auto", "35*"); report.AddTable("Etiket", Resources.TicketTags, "", ""); } foreach (var grp in tagGrp) { var tag = ReportContext.TicketTagGroups.SingleOrDefault(x => x.Name == grp.Key); if (tag == null || tag.ExcludeInReports) continue; report.AddBoldRow("Etiket", grp.Key, "", ""); if (tag.PriceTags) { var tCount = grp.Sum(x => x.TicketCount); var tSum = grp.Sum(x => Convert.ToDecimal(x.TagName.Split(':')[1]) * x.TicketCount); var amnt = grp.Sum(x => x.Amount); var rate = tSum / amnt; report.AddRow("Etiket", string.Format(Resources.TotalAmount_f, tag.Name), "", tSum.ToString(ReportContext.CurrencyFormat)); report.AddRow("Etiket", Resources.TicketCount, "", tCount); report.AddRow("Etiket", Resources.TicketTotal, "", amnt.ToString(ReportContext.CurrencyFormat)); report.AddRow("Etiket", Resources.Rate, "", rate.ToString("%#0.##")); continue; } foreach (var ticketTagInfo in grp) { report.AddRow("Etiket", ticketTagInfo.TagName.Split(':')[1], ticketTagInfo.TicketCount, ticketTagInfo.Amount.ToString(ReportContext.CurrencyFormat)); } var totalAmount = grp.Sum(x => x.Amount); report.AddRow("Etiket", string.Format(Resources.TotalAmount_f, tag.Name), "", totalAmount.ToString(ReportContext.CurrencyFormat)); var sum = 0m; if (tag.NumericTags) { try { sum = grp.Sum(x => Convert.ToDecimal(x.TagName.Split(':')[1]) * x.TicketCount); report.AddRow("Etiket", string.Format(Resources.TicketTotal_f, tag.Name), "", sum.ToString("#,##.##")); } catch (FormatException) { report.AddRow("Etiket", string.Format(Resources.TicketTotal_f, tag.Name), "", "#Hata!"); } } else { sum = grp.Sum(x => x.TicketCount); } if (sum > 0) { var average = totalAmount / sum; report.AddRow("Etiket", string.Format(Resources.TotalAmountDivTag_f, tag.Name), "", average.ToString(ReportContext.CurrencyFormat)); } } } //---- var owners = ReportContext.Tickets.SelectMany(ticket => ticket.TicketItems.Select(ticketItem => new { Ticket = ticket, TicketItem = ticketItem })) .GroupBy(x => new { x.TicketItem.CreatingUserId }) .Select(x => new UserInfo { UserId = x.Key.CreatingUserId, Amount = x.Sum(y => MenuGroupBuilder.CalculateTicketItemTotal(y.Ticket, y.TicketItem)) }); report.AddColumTextAlignment("Garson", TextAlignment.Left, TextAlignment.Right); report.AddColumnLength("Garson", "65*", "35*"); report.AddTable("Garson", Resources.UserSales, ""); foreach (var ownerInfo in owners) { report.AddRow("Garson", ownerInfo.UserName, ownerInfo.Amount.ToString(ReportContext.CurrencyFormat)); } //--- var uInfo = ReportContext.Tickets.SelectMany(x => x.Payments).Select(x => x.UserId).Distinct().Select( x => new UserInfo { UserId = x }); if (uInfo.Count() > 1) { foreach (var userInfo in uInfo) { var info = userInfo; var uPayments = ReportContext.Tickets .SelectMany(x => x.Payments) .Where(x => x.UserId == info.UserId) .GroupBy(x => new { x.PaymentType }) .Select(x => new TenderedAmount { PaymentType = x.Key.PaymentType, Amount = x.Sum(y => y.Amount) }); report.AddColumnLength(userInfo.UserName + Resources.Incomes, "40*", "Auto", "35*"); report.AddColumTextAlignment(userInfo.UserName + Resources.Incomes, TextAlignment.Left, TextAlignment.Right, TextAlignment.Right); report.AddTable(userInfo.UserName + Resources.Incomes, string.Format(Resources.ReceivedBy_f, userInfo.UserName), "", ""); report.AddRow(userInfo.UserName + Resources.Incomes, Resources.Cash, GetPercent(0, uPayments), GetAmount(0, uPayments).ToString(ReportContext.CurrencyFormat)); report.AddRow(userInfo.UserName + Resources.Incomes, Resources.CreditCard, GetPercent(1, uPayments), GetAmount(1, uPayments).ToString(ReportContext.CurrencyFormat)); report.AddRow(userInfo.UserName + Resources.Incomes, Resources.Voucher, GetPercent(2, uPayments), GetAmount(2, uPayments).ToString(ReportContext.CurrencyFormat)); report.AddRow(userInfo.UserName + Resources.Incomes, Resources.AccountBalance, GetPercent(3, uPayments), GetAmount(3, uPayments).ToString(ReportContext.CurrencyFormat)); report.AddRow(userInfo.UserName + Resources.Incomes, Resources.Total, "", uPayments.Sum(x => x.Amount).ToString(ReportContext.CurrencyFormat)); } } //--- var menuGroups = MenuGroupBuilder.CalculateMenuGroups(ReportContext.Tickets, ReportContext.MenuItems); report.AddColumTextAlignment("Gıda", TextAlignment.Left, TextAlignment.Right, TextAlignment.Right); report.AddColumnLength("Gıda", "45*", "Auto", "35*"); report.AddTable("Gıda", Resources.ItemSales, "", ""); foreach (var menuItemInfo in menuGroups) { report.AddRow("Gıda", menuItemInfo.GroupName, string.Format("%{0:0.00}", menuItemInfo.Rate), menuItemInfo.Amount.ToString(ReportContext.CurrencyFormat)); } report.AddRow("Gıda", Resources.Total.ToUpper(), "", menuGroups.Sum(x => x.Amount).ToString(ReportContext.CurrencyFormat)); return report.Document; } private static string GetPercent(int paymentType, IEnumerable<TenderedAmount> data) { var total = data.Sum(x => x.Amount); return total > 0 ? string.Format("%{0:0.00}", (GetAmount(paymentType, data) * 100) / total) : "%0"; } private static decimal GetAmount(int paymentType, IEnumerable<TenderedAmount> data) { var r = data.SingleOrDefault(x => x.PaymentType == paymentType); return r != null ? r.Amount : 0; } protected override string GetHeader() { return Resources.WorkPeriodReport; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/EndOfDayReport/EndDayReportViewModel.cs
C#
gpl3
23,693
namespace Samba.Modules.BasicReports.Reports { internal class MenuItemGroupInfo { public string GroupName { get; set; } public decimal Amount { get; set; } public decimal Quantity { get; set; } public decimal Rate { get; set; } public decimal QuantityRate { get; set; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Reports/MenuItemGroupInfo.cs
C#
gpl3
338
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Modules.BasicReports { /// <summary> /// Interaction logic for BasicReportView.xaml /// </summary> /// [Export] public partial class BasicReportView : UserControl { [ImportingConstructor] public BasicReportView(BasicReportViewModel viewModel) { InitializeComponent(); DataContext = viewModel; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/BasicReportView.xaml.cs
C#
gpl3
833
using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.Practices.Prism.Commands; using Microsoft.Practices.Prism.Events; using Samba.Domain.Models.Users; using Samba.Presentation.Common; namespace Samba.Modules.BasicReports { [Export] public class BasicReportViewModel : ObservableObject { public IEnumerable<ReportViewModelBase> Reports { get { return ReportContext.Reports; } } public DelegateCommand<ReportViewModelBase> ReportExecuteCommand { get; set; } private ReportViewModelBase _activeReport; public ReportViewModelBase ActiveReport { get { return _activeReport; } set { _activeReport = value; RaisePropertyChanged("ActiveReport"); RaisePropertyChanged("IsReportVisible"); } } public bool IsReportVisible { get { return ActiveReport != null; } } public BasicReportViewModel() { ReportExecuteCommand = new DelegateCommand<ReportViewModelBase>(OnExecuteReport); EventServiceFactory.EventService.GetEvent<GenericEvent<User>>().Subscribe(x => { if (x.Topic == EventTopicNames.UserLoggedOut && ActiveReport != null) { ActiveReport.Document = null; ActiveReport = null; } }); EventServiceFactory.EventService.GetEvent<GenericEvent<EventAggregator>>().Subscribe( x => { if (x.Topic == EventTopicNames.ActivateNavigation && ActiveReport != null) { ActiveReport.Document = null; ActiveReport = null; } }); } private void OnExecuteReport(ReportViewModelBase obj) { foreach (var report in Reports) report.Selected = false; obj.Selected = true; ActiveReport = obj; ActiveReport.RefreshReport(); } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/BasicReportViewModel.cs
C#
gpl3
2,149
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Samba.Modules.BasicReports")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.Modules.BasicReports")] [assembly: AssemblyCopyright("Copyright © 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6647cd5d-8268-47fd-9ece-42f29c61b2a3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("")]
zzgaminginc-pointofssale
Samba.Modules.BasicReports/Properties/AssemblyInfo.cs
C#
gpl3
1,540
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Globalization; using System.Linq; using Samba.Domain; using Samba.Domain.Models.Inventory; using Samba.Domain.Models.Menus; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Tickets; using Samba.Domain.Models.Users; using Samba.Infrastructure.Data; using Samba.Localization.Properties; using Samba.Modules.BasicReports.Reports; using Samba.Modules.BasicReports.Reports.AccountReport; using Samba.Modules.BasicReports.Reports.CashReport; using Samba.Modules.BasicReports.Reports.CSVBuilder; using Samba.Modules.BasicReports.Reports.EndOfDayReport; using Samba.Modules.BasicReports.Reports.InventoryReports; using Samba.Modules.BasicReports.Reports.ProductReport; using Samba.Persistance.Data; using Samba.Services; namespace Samba.Modules.BasicReports { public static class ReportContext { public static IList<ReportViewModelBase> Reports { get; private set; } private static IWorkspace _workspace; public static IWorkspace Workspace { get { return _workspace ?? (_workspace = WorkspaceFactory.Create()); } } private static IEnumerable<Ticket> _tickets; public static IEnumerable<Ticket> Tickets { get { return _tickets ?? (_tickets = GetTickets(Workspace)); } } private static IEnumerable<Department> _departments; public static IEnumerable<Department> Departments { get { return _departments ?? (_departments = GetDepartments()); } } private static IEnumerable<MenuItem> _menutItems; public static IEnumerable<MenuItem> MenuItems { get { return _menutItems ?? (_menutItems = GetMenuItems()); } } private static IEnumerable<Transaction> _transactions; public static IEnumerable<Transaction> Transactions { get { return _transactions ?? (_transactions = GetTransactions()); } } private static IEnumerable<PeriodicConsumption> _periodicConsumptions; public static IEnumerable<PeriodicConsumption> PeriodicConsumptions { get { return _periodicConsumptions ?? (_periodicConsumptions = GetPeriodicConsumtions()); } } private static IEnumerable<InventoryItem> _inventoryItems; public static IEnumerable<InventoryItem> InventoryItems { get { return _inventoryItems ?? (_inventoryItems = GetInventoryItems()); } } private static IEnumerable<CashTransactionData> _cashTransactions; public static IEnumerable<CashTransactionData> CashTransactions { get { return _cashTransactions ?? (_cashTransactions = GetCashTransactions()); } } private static IEnumerable<TicketTagGroup> _ticketTagGroups; public static IEnumerable<TicketTagGroup> TicketTagGroups { get { return _ticketTagGroups ?? (_ticketTagGroups = Dao.Query<TicketTagGroup>()); } } public static IEnumerable<User> Users { get { return AppServices.MainDataContext.Users; } } private static IEnumerable<WorkPeriod> _workPeriods; public static IEnumerable<WorkPeriod> WorkPeriods { get { return _workPeriods ?? (_workPeriods = Dao.Query<WorkPeriod>()); } } private static IEnumerable<TaxServiceTemplate> _taxServiceTemplates; public static IEnumerable<TaxServiceTemplate> TaxServiceTemplates { get { return _taxServiceTemplates ?? (_taxServiceTemplates = Dao.Query<TaxServiceTemplate>()); } } private static WorkPeriod _currentWorkPeriod; public static WorkPeriod CurrentWorkPeriod { get { return _currentWorkPeriod ?? (_currentWorkPeriod = AppServices.MainDataContext.CurrentWorkPeriod); } set { _currentWorkPeriod = value; _tickets = null; _cashTransactions = null; _periodicConsumptions = null; _transactions = null; StartDate = CurrentWorkPeriod.StartDate; EndDate = CurrentWorkPeriod.EndDate; if (StartDate == EndDate) EndDate = DateTime.Now; } } public static DateTime StartDate { get; set; } public static DateTime EndDate { get; set; } public static string StartDateString { get { return StartDate.ToString("dd MM yyyy"); } set { StartDate = StrToDate(value); } } public static string EndDateString { get { return EndDate.ToString("dd MM yyyy"); } set { EndDate = StrToDate(value); } } private static DateTime StrToDate(string value) { var vals = value.Split(' ').Select(x => Convert.ToInt32(x)).ToList(); if (vals.Count == 1) vals.Add(DateTime.Now.Month); if (vals.Count == 2) vals.Add(DateTime.Now.Year); if (vals[2] < 1) { vals[2] = DateTime.Now.Year; } if (vals[2] < 1000) { vals[2] += 2000; } if (vals[1] < 1) { vals[1] = 1; } if (vals[1] > 12) { vals[1] = 12; } var dim = DateTime.DaysInMonth(vals[0], vals[1]); if (vals[0] < 1) { vals[0] = 1; } if (vals[0] > dim) { vals[0] = dim; } return new DateTime(vals[2], vals[1], vals[0]); } private static IEnumerable<InventoryItem> GetInventoryItems() { return Dao.Query<InventoryItem>(); } private static IEnumerable<Transaction> GetTransactions() { if (CurrentWorkPeriod.StartDate != CurrentWorkPeriod.EndDate) return Dao.Query<Transaction>(x => x.Date >= CurrentWorkPeriod.StartDate && x.Date < CurrentWorkPeriod.EndDate, x => x.TransactionItems, x => x.TransactionItems.Select(y => y.InventoryItem)); return Dao.Query<Transaction>(x => x.Date >= CurrentWorkPeriod.StartDate, x => x.TransactionItems, x => x.TransactionItems.Select(y => y.InventoryItem)); } private static IEnumerable<PeriodicConsumption> GetPeriodicConsumtions() { if (CurrentWorkPeriod.StartDate != CurrentWorkPeriod.EndDate) return Dao.Query<PeriodicConsumption>(x => x.StartDate >= CurrentWorkPeriod.StartDate && x.EndDate <= CurrentWorkPeriod.EndDate, x => x.CostItems, x => x.CostItems.Select(y => y.Portion), x => x.PeriodicConsumptionItems, x => x.PeriodicConsumptionItems.Select(y => y.InventoryItem)); return Dao.Query<PeriodicConsumption>(x => x.StartDate >= CurrentWorkPeriod.StartDate, x => x.CostItems, x => x.CostItems.Select(y => y.Portion), x => x.PeriodicConsumptionItems, x => x.PeriodicConsumptionItems.Select(y => y.InventoryItem)); } private static IEnumerable<MenuItem> GetMenuItems() { return Dao.Query<MenuItem>(); } private static IEnumerable<Department> GetDepartments() { return Dao.Query<Department>(); } private static IEnumerable<Ticket> GetTickets(IWorkspace workspace) { try { if (CurrentWorkPeriod.StartDate == CurrentWorkPeriod.EndDate) return Dao.Query<Ticket>(x => x.LastPaymentDate >= CurrentWorkPeriod.StartDate, x => x.Payments, x => x.TaxServices, x => x.Discounts, x => x.TicketItems, x => x.TicketItems.Select(y => y.Properties)); return Dao.Query<Ticket>(x => x.LastPaymentDate >= CurrentWorkPeriod.StartDate && x.LastPaymentDate < CurrentWorkPeriod.EndDate, x => x.Payments, x => x.TaxServices, x => x.Discounts, x => x.TicketItems.Select(y => y.Properties)); } catch (SqlException) { if (CurrentWorkPeriod.StartDate == CurrentWorkPeriod.EndDate) return workspace.All<Ticket>(x => x.LastPaymentDate >= CurrentWorkPeriod.StartDate); return workspace.All<Ticket>(x => x.LastPaymentDate >= CurrentWorkPeriod.StartDate && x.LastPaymentDate < CurrentWorkPeriod.EndDate); } } private static IEnumerable<CashTransactionData> GetCashTransactions() { return AppServices.CashService.GetTransactionsWithCustomerData(CurrentWorkPeriod); } public static string CurrencyFormat { get { return "#,#0.00;-#,#0.00;-"; } } static ReportContext() { Reports = new List<ReportViewModelBase> { new EndDayReportViewModel(), new ProductReportViewModel(), new CashReportViewModel(), new LiabilityReportViewModel(), new ReceivableReportViewModel(), new InternalAccountsViewModel(), new PurchaseReportViewModel(), new InventoryReportViewModel(), new CostReportViewModel(), new CsvBuilderViewModel() }; } public static void ResetCache() { _tickets = null; _transactions = null; _periodicConsumptions = null; _currentWorkPeriod = null; _cashTransactions = null; _thisMonthWorkPeriod = null; _lastMonthWorkPeriod = null; _thisWeekWorkPeriod = null; _lastWeekWorkPeriod = null; _yesterdayWorkPeriod = null; _todayWorkPeriod = null; _workPeriods = null; _taxServiceTemplates = null; _workspace = null; } private static WorkPeriod _thisMonthWorkPeriod; public static WorkPeriod ThisMonthWorkPeriod { get { return _thisMonthWorkPeriod ?? (_thisMonthWorkPeriod = CreateThisMonthWorkPeriod()); } } private static WorkPeriod _lastMonthWorkPeriod; public static WorkPeriod LastMonthWorkPeriod { get { return _lastMonthWorkPeriod ?? (_lastMonthWorkPeriod = CreateLastMonthWorkPeriod()); } } private static WorkPeriod _thisWeekWorkPeriod; public static WorkPeriod ThisWeekWorkPeriod { get { return _thisWeekWorkPeriod ?? (_thisWeekWorkPeriod = CreateThisWeekWorkPeriod()); } } private static WorkPeriod _lastWeekWorkPeriod; public static WorkPeriod LastWeekWorkPeriod { get { return _lastWeekWorkPeriod ?? (_lastWeekWorkPeriod = CreateLastWeekWorkPeriod()); } } private static WorkPeriod _yesterdayWorkPeriod; public static WorkPeriod YesterdayWorkPeriod { get { return _yesterdayWorkPeriod ?? (_yesterdayWorkPeriod = CreateYesterdayWorkPeriod()); } } private static WorkPeriod _todayWorkPeriod; public static WorkPeriod TodayWorkPeriod { get { return _todayWorkPeriod ?? (_todayWorkPeriod = CreteTodayWorkPeriod()); } } private static WorkPeriod CreteTodayWorkPeriod() { var start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); return CreateCustomWorkPeriod(Resources.Today, start, start.AddDays(1).AddSeconds(-1)); } private static WorkPeriod CreateYesterdayWorkPeriod() { var start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(-1); var end = start.AddDays(1).AddSeconds(-1); return CreateCustomWorkPeriod(Resources.Yesterday, start, end); } private static WorkPeriod CreateLastMonthWorkPeriod() { var lastmonth = DateTime.Now.AddMonths(-1); var start = new DateTime(lastmonth.Year, lastmonth.Month, 1); var end = new DateTime(lastmonth.Year, lastmonth.Month, DateTime.DaysInMonth(lastmonth.Year, lastmonth.Month)); end = end.AddDays(1).AddSeconds(-1); return CreateCustomWorkPeriod(Resources.PastMonth + ": " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(start.Month), start, end); } private static WorkPeriod CreateThisMonthWorkPeriod() { var start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); var end = DateTime.Now.Date.AddDays(1).AddSeconds(-1); return CreateCustomWorkPeriod(Resources.ThisMonth + ": " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(start.Month), start, end); } private static WorkPeriod CreateThisWeekWorkPeriod() { var w = (int)DateTime.Now.DayOfWeek; var start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(-w + 1); var end = DateTime.Now.Date.AddDays(1).AddSeconds(-1); return CreateCustomWorkPeriod(Resources.ThisWeek, start, end); } private static WorkPeriod CreateLastWeekWorkPeriod() { var w = (int)DateTime.Now.DayOfWeek; var start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(-6 - w); var end = start.AddDays(7).AddSeconds(-1); return CreateCustomWorkPeriod(Resources.PastWeek, start, end); } public static IEnumerable<WorkPeriod> GetWorkPeriods(DateTime startDate, DateTime endDate) { var wp = WorkPeriods.Where(x => x.EndDate >= endDate && x.StartDate < startDate); if (wp.Count() == 0) wp = WorkPeriods.Where(x => x.StartDate >= startDate && x.StartDate < endDate); if (wp.Count() == 0) wp = WorkPeriods.Where(x => x.EndDate >= startDate && x.EndDate < endDate); if (wp.Count() == 0 && AppServices.MainDataContext.CurrentWorkPeriod.StartDate < startDate) wp = new List<WorkPeriod> { AppServices.MainDataContext.CurrentWorkPeriod }; return wp.OrderBy(x => x.StartDate); } public static WorkPeriod CreateCustomWorkPeriod(string name, DateTime startDate, DateTime endDate) { var periods = GetWorkPeriods(startDate, endDate); var startPeriod = periods.FirstOrDefault(); var endPeriod = periods.LastOrDefault(); var start = startPeriod != null ? startPeriod.StartDate : startDate; var end = endPeriod != null ? endPeriod.EndDate : endDate; if (endPeriod != null && end == endPeriod.StartDate) end = DateTime.Now; var result = new WorkPeriod { Name = name, StartDate = start, EndDate = end }; return result; } public static string GetUserName(int userId) { var user = Users.SingleOrDefault(x => x.Id == userId); return user != null ? user.Name : Resources.UndefinedWithBrackets; } public static string GetReasonName(int reasonId) { if (AppServices.MainDataContext.Reasons.ContainsKey(reasonId)) return AppServices.MainDataContext.Reasons[reasonId].Name; return Resources.UndefinedWithBrackets; } internal static string GetDepartmentName(int departmentId) { var d = AppServices.MainDataContext.Departments.SingleOrDefault(x => x.Id == departmentId); return d != null ? d.Name : Resources.UndefinedWithBrackets; } internal static AmountCalculator GetOperationalAmountCalculator() { var groups = Tickets .SelectMany(x => x.Payments) .GroupBy(x => new { x.PaymentType }) .Select(x => new TenderedAmount { PaymentType = x.Key.PaymentType, Amount = x.Sum(y => y.Amount) }); return new AmountCalculator(groups); } internal static decimal GetCashTotalAmount() { return CashTransactions.Where(x => x.PaymentType == (int)PaymentType.Cash && x.TransactionType == (int)TransactionType.Income).Sum(x => x.Amount) - CashTransactions.Where(x => x.PaymentType == (int)PaymentType.Cash && x.TransactionType == (int)TransactionType.Expense).Sum(x => x.Amount); } internal static decimal GetCreditCardTotalAmount() { return CashTransactions.Where(x => x.PaymentType == (int)PaymentType.CreditCard && x.TransactionType == (int)TransactionType.Income).Sum(x => x.Amount) - CashTransactions.Where(x => x.PaymentType == (int)PaymentType.CreditCard && x.TransactionType == (int)TransactionType.Expense).Sum(x => x.Amount); } internal static decimal GetTicketTotalAmount() { return CashTransactions.Where(x => x.PaymentType == (int)PaymentType.Ticket && x.TransactionType == (int)TransactionType.Income).Sum(x => x.Amount) - CashTransactions.Where(x => x.PaymentType == (int)PaymentType.Ticket && x.TransactionType == (int)TransactionType.Expense).Sum(x => x.Amount); } public static PeriodicConsumption GetCurrentPeriodicConsumption() { var workspace = WorkspaceFactory.Create(); return InventoryService.GetCurrentPeriodicConsumption(workspace); } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/ReportContext.cs
C#
gpl3
17,853
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Modules.BasicReports { /// <summary> /// Interaction logic for ReportDisplay.xaml /// </summary> public partial class ReportView : UserControl { public ReportView() { InitializeComponent(); } private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { var browsable = ((PropertyDescriptor)e.PropertyDescriptor).Attributes[typeof(BrowsableAttribute)] as BrowsableAttribute; if (browsable != null && !browsable.Browsable) { e.Cancel = true; return; } var displayName = ((PropertyDescriptor)e.PropertyDescriptor).Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute; if (displayName != null && !string.IsNullOrEmpty(displayName.DisplayName)) { e.Column.Header = displayName.DisplayName; } else e.Column.Header = e.PropertyName; } } }
zzgaminginc-pointofssale
Samba.Modules.BasicReports/ReportView.xaml.cs
C#
gpl3
1,472
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using Samba.Localization.Properties; namespace Samba.Localization { public class LocalizedCategoryAttribute : CategoryAttribute { private readonly string _resourceName; public LocalizedCategoryAttribute(string resourceName) : base() { _resourceName = resourceName; } protected override string GetLocalizedString(string value) { return Resources.ResourceManager.GetString(_resourceName); } } }
zzgaminginc-pointofssale
Samba.Localization/LocalizedCategoryAttribute.cs
C#
gpl3
641
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using Samba.Localization.Properties; namespace Samba.Localization { [AttributeUsage(AttributeTargets.Property)] public class LocalizedDisplayNameAttribute : DisplayNameAttribute { private readonly string _resourceName; public LocalizedDisplayNameAttribute(string resourceName) { _resourceName = resourceName; } public LocalizedDisplayNameAttribute() { var type = GetType(); _resourceName = type.Name; } public override string DisplayName { get { return Resources.ResourceManager.GetString(_resourceName); } } } public class LocalizedDescriptionAttribute : DescriptionAttribute { private readonly string _resourceName; public LocalizedDescriptionAttribute(string resourceName) { _resourceName = resourceName; } public LocalizedDescriptionAttribute() { var type = GetType(); _resourceName = type.Name; } public override string Description { get { return Resources.ResourceManager.GetString(_resourceName); } } } }
zzgaminginc-pointofssale
Samba.Localization/LocalizedDisplayNameAttribute.cs
C#
gpl3
1,458
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Markup; using Samba.Localization.Engine; namespace Samba.Localization.BaseExtensions { /// <summary> /// Implements the BaseLocalizeExtension. /// Represents a LocalizationExtension which provides a localized object of a .resx dictionary. /// </summary> /// <typeparam name="TValue">The type of the provided value.</typeparam> /// <remarks> /// If a content between two tags in xaml is set, this has the higher priority and will overwrite the settled properties /// </remarks> [MarkupExtensionReturnType(typeof(object))] [ContentProperty("ResourceIdentifierKey")] public abstract class BaseLocalizeExtension<TValue> : MarkupExtension, IWeakEventListener, INotifyPropertyChanged { /// <summary> /// Holds the collection of assigned dependency objects as WeakReferences /// </summary> private readonly Dictionary<WeakReference, object> targetObjects; /// <summary> /// Holds the name of the Assembly where the .resx is located /// </summary> private string assembly; /// <summary> /// The current value /// </summary> private TValue currentValue; /// <summary> /// Holds the Name of the .resx dictionary. /// If it's null, "Resources" will get returned /// </summary> private string dict; /// <summary> /// Holds the Key to a .resx object /// </summary> private string key; /// <summary> /// Holds the name of the assembly containing the WPF window or usercontrol which /// is using this instance. /// </summary> private string dialogAssembly; /// <summary> /// Initializes a new instance of the BaseLocalizeExtension class. /// </summary> protected BaseLocalizeExtension() { // initialize the collection of the assigned dependency objects this.targetObjects = new Dictionary<WeakReference, object>(); } /// <summary> /// Initializes a new instance of the BaseLocalizeExtension class. /// </summary> /// <param name="key">Three types are supported: /// Direct: passed key = key; /// Dict/Key pair: this have to be separated like ResXDictionaryName:ResourceKey /// Assembly/Dict/Key pair: this have to be separated like ResXDictionaryName:ResourceKey</param> /// <remarks> /// This constructor register the <see cref="EventHandler"/><c>OnCultureChanged</c> on <c>LocalizeDictionary</c> /// to get an acknowledge of changing the culture /// </remarks> protected BaseLocalizeExtension(string key) : this() { // parse the key value and split it up if necessary LocalizeDictionary.ParseKey(key, out this.assembly, out this.dict, out this.key); } /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the name of the Assembly where the .resx is located. /// If it's null, the executing assembly (where this LocalizeEngine is located at) will get returned /// </summary> public string Assembly { get { return this.assembly ?? this.dialogAssembly; } set { this.assembly = !string.IsNullOrEmpty(value) ? value : null; } } /// <summary> /// Gets the current value. /// This property has only a value, if the <c>BaseLocalizeExtension</c> is binded to a target. /// </summary> /// <value>The current value.</value> public TValue CurrentValue { get { return this.currentValue; } private set { this.currentValue = value; this.RaiseNotifyPropertyChanged("CurrentValue"); } } /// <summary> /// Gets or sets the design value. /// </summary> /// <value>The design value.</value> [DesignOnly(true)] public object DesignValue { get; set; } /// <summary> /// Gets or sets the Name of the .resx dictionary. /// If it's null, "Resources" will get returned /// </summary> public string Dict { get { return this.dict ?? LocalizeDictionary.ResourcesName; } set { this.dict = !string.IsNullOrEmpty(value) ? value : null; } } /// <summary> /// Gets or sets the culture to force a fixed localized object /// </summary> public string ForceCulture { get; set; } /// <summary> /// Gets or sets the Key to a .resx object /// </summary> public string Key { get { return this.key; } set { this.key = value; } } /// <summary> /// Gets or sets the initialize value. /// This is ONLY used to support the localize extension in blend! /// </summary> /// <value>The initialize value.</value> [EditorBrowsable(EditorBrowsableState.Never)] [ConstructorArgument("key")] public string InitializeValue { get; set; } /// <summary> /// Gets or sets the Key that identifies a resource (Assembly:Dictionary:Key) /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public string ResourceIdentifierKey { get { return string.Format("{0}:{1}:{2}", this.Assembly, this.Dict, this.Key ?? "(null)"); } set { LocalizeDictionary.ParseKey(value, out this.assembly, out this.dict, out this.key); } } /// <summary> /// Gets the collection of <see cref="DependencyObject"/> as WeakReferences and the target property. /// </summary> public Dictionary<WeakReference, object> TargetObjects { get { return this.targetObjects; } } private static Assembly GetDialogAssembly(DependencyObject targetObject) { var w = Window.GetWindow(targetObject); if (w != null) return w.GetType().Assembly; while (targetObject != null) { Debug.WriteLine(targetObject.GetType().ToString()); if (targetObject is UserControl || targetObject is Window || targetObject is Page) { var type = targetObject.GetType(); return type.Assembly; } targetObject = LogicalTreeHelper.GetParent(targetObject); } //Design time //Try to find the main assembly var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var item in assemblies) { // Check if the assembly is executable if (item.EntryPoint != null) { // Check if the assembly contains WPF application (e.g. MyApplication.App class // that derives from System.Windows.Application) var applicationType = item.GetType(item.GetName().Name + ".App", false); if (applicationType != null && typeof(System.Windows.Application).IsAssignableFrom(applicationType)) { return item; } } } return System.Reflection.Assembly.GetEntryAssembly(); } /// <summary> /// Provides the Value for the first Binding /// </summary> /// <param name="serviceProvider">The <see cref="System.Windows.Markup.IProvideValueTarget"/> provided from the <see cref="MarkupExtension"/></param> /// <returns> /// The founded item from the .resx directory or null if not founded /// </returns> /// <remarks> /// This method register the <see cref="EventHandler"/><c>OnCultureChanged</c> on <c>LocalizeDictionary</c> /// to get an acknowledge of changing the culture, if the passed <see cref="TargetObjects"/> type of <see cref="DependencyObject"/>. /// !PROOF: On every single <see cref="UserControl"/>, Window, and Page, /// there is a new SharedDP reference, and so there is every time a new <c>BaseLocalizeExtension</c>! /// Because of this, we don't need to notify every single DependencyObjects to update their value (for GC). /// </remarks> /// <exception cref="System.InvalidOperationException"> /// thrown if <paramref name="serviceProvider"/> is not type of <see cref="System.Windows.Markup.IProvideValueTarget"/> /// </exception> public override object ProvideValue(IServiceProvider serviceProvider) { // if the service provider is null, return this if (serviceProvider == null) { return this; } // try to cast the passed serviceProvider to a IProvideValueTarget IProvideValueTarget service = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget; // if the cast fails, return this if (service == null) { return this; } // if the service.TargetObject is a Binding, throw an exception if (service.TargetObject is Binding) { throw new InvalidOperationException("Use as binding is not supported!"); } // declare a target property object targetProperty = null; // check if the service.TargetProperty is a DependencyProperty or a PropertyInfo if (service.TargetProperty is DependencyProperty || service.TargetProperty is PropertyInfo) { // set the target property to the service.TargetProperty targetProperty = service.TargetProperty; } // check if the target property is null if (targetProperty == null) { // return this. return this; } // Setter of a style? if (service.TargetObject is Setter) { // Evaluate later return this; } // if the service.TargetObject is System.Windows.SharedDp (= not a DependencyObject), we return "this". // the SharedDp will call this instance later again. if (!(service.TargetObject is DependencyObject) && !(service.TargetProperty is PropertyInfo)) { // by returning "this", the provide value will be called later again. return this; } // indicates, if the target object was found bool foundInWeakReferences = false; // search for the target in the target object list foreach (KeyValuePair<WeakReference, object> wr in this.targetObjects) { // if the target is the target of the weakreference if (wr.Key.Target == service.TargetObject && wr.Value == service.TargetProperty) { // set the flag to true and stop searching foundInWeakReferences = true; break; } } // if the target is a dependency object and it's not collected already, collect it if (service.TargetObject is DependencyObject && !foundInWeakReferences) { // if it's the first object, add an event handler too if (this.targetObjects.Count == 0) { // add this localize extension to the WeakEventManager on LocalizeDictionary LocalizeDictionary.Instance.AddEventListener(this); } // add the target as an dependency object as weakreference to the dependency object list this.targetObjects.Add(new WeakReference(service.TargetObject), service.TargetProperty); // adds this localize extension to the ObjectDependencyManager to ensure the lifetime along with the targetobject ObjectDependencyManager.AddObjectDependency(new WeakReference(service.TargetObject), this); } // Use the assembly defining the dialog if no assembly was provided if (String.IsNullOrEmpty(this.assembly)) { var targetObject = service.TargetObject as DependencyObject; if (targetObject != null) { var a = System.Reflection.Assembly.GetExecutingAssembly(); // GetDialogAssembly(targetObject); if (a != null) { this.dialogAssembly = LocalizeDictionary.Instance.GetAssemblyName(a); } } } // return the new value for the DependencyProperty return LocalizeDictionary.Instance.GetLocalizedObject<object>( this.Assembly, this.Dict, this.Key, this.GetForcedCultureOrDefault()); } /// <summary> /// Resolves the localized value of the current Assembly, Dict, Key pair. /// </summary> /// <param name="resolvedValue">The resolved value.</param> /// <returns> /// True if the resolve was success, otherwise false. /// </returns> /// <exception> /// If the Assembly, Dict, Key pair was not found. /// </exception> public bool ResolveLocalizedValue(out TValue resolvedValue) { // return the resolved localized value with the current or forced culture. return this.ResolveLocalizedValue(out resolvedValue, this.GetForcedCultureOrDefault()); } /// <summary> /// Resolves the localized value of the current Assembly, Dict, Key pair. /// </summary> /// <param name="resolvedValue">The resolved value.</param> /// <param name="targetCulture">The target culture.</param> /// <returns> /// True if the resolve was success, otherwise false. /// </returns> /// <exception> /// If the Assembly, Dict, Key pair was not found. /// </exception> public bool ResolveLocalizedValue(out TValue resolvedValue, CultureInfo targetCulture) { // define the default value of the resolved value resolvedValue = default(TValue); // get the localized object from the dictionary object localizedObject = LocalizeDictionary.Instance.GetLocalizedObject<object>( this.Assembly, this.Dict, this.Key, targetCulture); // check if the found localized object is type of TValue if (localizedObject is TValue) { // format the localized object object formattedOutput = this.FormatOutput(localizedObject); // check if the formatted output is not null if (formattedOutput != null) { // set the content of the resolved value resolvedValue = (TValue)formattedOutput; } // return true: resolve was successfully return true; } // return false: resulve was not successfully. return false; } /// <summary> /// Sets a binding between a <see cref="DependencyObject"/> with its <see cref="DependencyProperty"/> /// or <see cref="PropertyInfo"/> and the <c>BaseLocalizeExtension</c>. /// </summary> /// <param name="targetObject">The target dependency object</param> /// <param name="targetProperty">The target dependency property</param> /// <returns> /// TRUE if the binding was setup successfully, otherwise FALSE (Binding already exists). /// </returns> /// <exception cref="ArgumentException"> /// If the <paramref name="targetProperty"/> is /// not a <see cref="DependencyProperty"/> or <see cref="PropertyInfo"/>. /// </exception> public bool SetBinding(DependencyObject targetObject, object targetProperty) { if (!(targetProperty is DependencyProperty || targetProperty is PropertyInfo)) { throw new ArgumentException( "The targetProperty should be a DependencyProperty or PropertyInfo!", "targetProperty"); } // indicates, if the target object was found bool foundInWeakReferences = false; // search for the target in the target object list foreach (KeyValuePair<WeakReference, object> wr in this.targetObjects) { // if the target is the target of the weakreference if (wr.Key.Target == targetObject && wr.Value == targetProperty) { // set the flag to true and stop searching foundInWeakReferences = true; break; } } // if the target it's not collected already, collect it if (!foundInWeakReferences) { // if it's the first object, add an event handler too if (this.targetObjects.Count == 0) { // add this localize extension to the WeakEventManager on LocalizeDictionary LocalizeDictionary.Instance.AddEventListener(this); } // add the target as an dependency object as weakreference to the dependency object list this.targetObjects.Add(new WeakReference(targetObject), targetProperty); // adds this localize extension to the ObjectDependencyManager to ensure the lifetime along with the targetobject ObjectDependencyManager.AddObjectDependency(new WeakReference(targetObject), this); // get the initial value of the dependency property object output = this.FormatOutput( LocalizeDictionary.Instance.GetLocalizedObject<object>( this.Assembly, this.Dict, this.Key, this.GetForcedCultureOrDefault())); // set the value to the dependency object this.SetTargetValue( targetObject, targetProperty, output); // return true, the binding was successfully return true; } // return false, the binding already exists return false; } /// <summary> /// Returns the Key that identifies a resource (Assembly:Dictionary:Key) /// </summary> /// <returns>Format: Assembly:Dictionary:Key</returns> public override sealed string ToString() { return base.ToString() + " -> " + this.ResourceIdentifierKey; } /// <summary> /// This method will be called through the interface, passed to the /// <see cref="LocalizeDictionary"/>.<see cref="LocalizeDictionary.WeakCultureChangedEventManager"/> to get notified on culture changed /// </summary> /// <param name="managerType">The manager Type.</param> /// <param name="sender">The sender.</param> /// <param name="e">The event argument.</param> /// <returns> /// true if the listener handled the event. It is considered an error by the <see cref="T:System.Windows.WeakEventManager"/> handling in WPF to register a listener for an event that the listener does not handle. Regardless, the method should return false if it receives an event that it does not recognize or handle. /// </returns> bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { // if the passed handler is type of LocalizeDictionary.WeakCultureChangedEventManager, handle it if (managerType == typeof(LocalizeDictionary.WeakCultureChangedEventManager)) { // call to handle the new value this.HandleNewValue(); // return true, to notify the event was processed return true; } // return false, to notify the event was not processed return false; } /// <summary> /// Determines whether if the <paramref name="checkType"/> is the <paramref name="targetType"/>. /// </summary> /// <param name="checkType">Type of the check.</param> /// <param name="targetType">Type of the target.</param> /// <returns> /// <c>true</c> if the <paramref name="checkType"/> is type of the <paramref name="targetType"/>; otherwise, <c>false</c>. /// </returns> internal bool IsTypeOf(Type checkType, Type targetType) { // if the checkType is null (possible base type), return false if (checkType == null) { return false; } // if the targetType (wrong call) is null, return false if (targetType == null) { return false; } // if we search a generic type if (targetType.IsGenericType) { // and the checkType is a generic (BaseType) if (checkType.IsGenericType) { // and the signature is the same if (checkType.GetGenericTypeDefinition() == targetType) { // return true return true; } } // otherwise call the same method again with the base type return this.IsTypeOf(checkType.BaseType, targetType); } // if we search a non generic type and its equal if (checkType.Equals(targetType)) { // return true return true; } // otherwise call the same method again with the base type return this.IsTypeOf(checkType.BaseType, targetType); } /// <summary> /// This method is used to modify the passed object into the target format /// </summary> /// <param name="input">The object that will be modified</param> /// <returns>Returns the modified object</returns> protected abstract object FormatOutput(object input); /// <summary> /// If Culture property defines a valid <see cref="CultureInfo"/>, a <see cref="CultureInfo"/> instance will get /// created and returned, otherwise <see cref="LocalizeDictionary"/>.Culture will get returned. /// </summary> /// <returns>The <see cref="CultureInfo"/></returns> /// <exception cref="System.ArgumentException"> /// thrown if the parameter Culture don't defines a valid <see cref="CultureInfo"/> /// </exception> protected CultureInfo GetForcedCultureOrDefault() { // define a culture info CultureInfo cultureInfo; // check if the forced culture is not null or empty if (!string.IsNullOrEmpty(this.ForceCulture)) { // try to create a valid cultureinfo, if defined try { // try to create a specific culture from the forced one cultureInfo = CultureInfo.CreateSpecificCulture(this.ForceCulture); } catch (ArgumentException ex) { // on error, check if designmode is on if (LocalizeDictionary.Instance.GetIsInDesignMode()) { // cultureInfo will be set to the current specific culture cultureInfo = LocalizeDictionary.Instance.SpecificCulture; } else { // tell the customer, that the forced culture cannot be converted propperly throw new ArgumentException("Cannot create a CultureInfo with '" + this.ForceCulture + "'", ex); } } } else { // take the current specific culture cultureInfo = LocalizeDictionary.Instance.SpecificCulture; } // return the evaluated culture info return cultureInfo; } /// <summary> /// This method gets the new value for the target property and call <see cref="SetNewValue"/>. /// </summary> protected virtual void HandleNewValue() { // gets the new value and set it to the dependency property on the dependency object this.SetNewValue( LocalizeDictionary.Instance.GetLocalizedObject<object>( this.Assembly, this.Dict, this.Key, this.GetForcedCultureOrDefault())); } /// <summary> /// Set the Value of the <see cref="DependencyProperty"/> to the passed Value /// </summary> /// <param name="newValue">The new Value</param> protected void SetNewValue(object newValue) { // set the new value to the current value, if its the type of TValue if (newValue is TValue) { this.CurrentValue = (TValue)newValue; } // if the list of dependency objects is empty or the target property is null, return if (this.targetObjects.Count == 0) { return; } // step through all dependency objects as WeakReference and refresh the value of the dependency property foreach (KeyValuePair<WeakReference, object> dpo in this.targetObjects) { // set the new value of the target, if the target DependencyTarget is still alive if (dpo.Key.IsAlive) { this.SetTargetValue((DependencyObject)dpo.Key.Target, dpo.Value, newValue); } } } /// <summary> /// Raises the notify property changed. /// </summary> /// <param name="propertyName">Name of the property.</param> private void RaiseNotifyPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } /// <summary> /// Sets the target value. /// </summary> /// <param name="targetObject">The target object.</param> /// <param name="targetProperty">The target property.</param> /// <param name="value">The value.</param> private void SetTargetValue(DependencyObject targetObject, object targetProperty, object value) { // check if the target property is a DependencyProperty if (targetProperty is DependencyProperty) { this.SetTargetValue(targetObject, (DependencyProperty)targetProperty, value); } // check if the target property is a PropertyInfo if (targetProperty is PropertyInfo) { this.SetTargetValue(targetObject, (PropertyInfo)targetProperty, value); } } /// <summary> /// Sets the target value. /// </summary> /// <param name="targetObject">The target object.</param> /// <param name="targetProperty">The target property.</param> /// <param name="value">The value.</param> private void SetTargetValue(DependencyObject targetObject, DependencyProperty targetProperty, object value) { targetObject.SetValue(targetProperty, value); } /// <summary> /// Sets the target value. /// </summary> /// <param name="targetObject">The target object.</param> /// <param name="targetProperty">The target property.</param> /// <param name="value">The value.</param> private void SetTargetValue(DependencyObject targetObject, PropertyInfo targetProperty, object value) { targetProperty.SetValue(targetObject, value, null); } } }
zzgaminginc-pointofssale
Samba.Localization/BaseExtensions/BaseLocalizeExtension.cs
C#
gpl3
29,862
using System; using System.Globalization; using System.Reflection; using System.Windows; using System.Windows.Markup; using Samba.Localization.BaseExtensions; using Samba.Localization.Engine; namespace Samba.Localization.Extensions { /// <summary> /// <c>BaseLocalizeExtension</c> for Thickness values /// </summary> [MarkupExtensionReturnType(typeof(Thickness))] public class LocThicknessExtension : BaseLocalizeExtension<Thickness> { /// <summary> /// Initializes a new instance of the <see cref="LocThicknessExtension"/> class. /// </summary> public LocThicknessExtension() { } /// <summary> /// Initializes a new instance of the <see cref="LocThicknessExtension"/> class. /// </summary> /// <param name="key">The resource identifier.</param> public LocThicknessExtension(string key) : base(key) { } /// <summary> /// Provides the Value for the first Binding as Thickness /// </summary> /// <param name="serviceProvider"> /// The <see cref="System.Windows.Markup.IProvideValueTarget"/> provided from the <see cref="MarkupExtension"/> /// </param> /// <returns>The founded item from the .resx directory or null if not founded</returns> /// <exception cref="System.InvalidOperationException"> /// thrown if <paramref name="serviceProvider"/> is not type of <see cref="System.Windows.Markup.IProvideValueTarget"/> /// </exception> /// <exception cref="System.NotSupportedException"> /// thrown if the founded object is not type of Thickness /// </exception> public override object ProvideValue(IServiceProvider serviceProvider) { object obj = base.ProvideValue(serviceProvider); if (obj == null) { return null; } if (this.IsTypeOf(obj.GetType(), typeof(BaseLocalizeExtension<>))) { return obj; } if (obj.GetType().Equals(typeof(string))) { return this.FormatOutput(obj); } throw new NotSupportedException( string.Format( "ResourceKey '{0}' returns '{1}' which is not type of double", this.Key, obj.GetType().FullName)); } /// <summary> /// see <c>BaseLocalizeExtension</c> /// </summary> protected override void HandleNewValue() { object obj = LocalizeDictionary.Instance.GetLocalizedObject<object>(this.Assembly, this.Dict, this.Key, this.GetForcedCultureOrDefault()); this.SetNewValue(this.FormatOutput(obj)); } /// <summary> /// This method is used to modify the passed object into the target format /// </summary> /// <param name="input">The object that will be modified</param> /// <returns>Returns the modified object</returns> protected override object FormatOutput(object input) { MethodInfo method = typeof(ThicknessConverter).GetMethod("FromString", BindingFlags.Static | BindingFlags.NonPublic); if (LocalizeDictionary.Instance.GetIsInDesignMode() && this.DesignValue != null) { try { return (Thickness) method.Invoke(null, new[] { this.DesignValue, new CultureInfo("en-US") }); } catch { return null; } } return (Thickness)method.Invoke(null, new[] { input, new CultureInfo("en-US") }); } } }
zzgaminginc-pointofssale
Samba.Localization/Extensions/LocThicknessExtension.cs
C#
gpl3
3,867
using System; using System.ComponentModel; using System.Windows.Markup; using Samba.Localization.BaseExtensions; using Samba.Localization.Engine; namespace Samba.Localization.Extensions { /// <summary> /// <c>BaseLocalizeExtension</c> for brush objects as string (uses <see cref="TypeConverter"/>) /// </summary> [MarkupExtensionReturnType(typeof(System.Windows.Media.Brush))] public class LocBrushExtension : BaseLocalizeExtension<System.Windows.Media.Brush> { /// <summary> /// Initializes a new instance of the <see cref="LocBrushExtension"/> class. /// </summary> public LocBrushExtension() { } /// <summary> /// Initializes a new instance of the <see cref="LocBrushExtension"/> class. /// </summary> /// <param name="key">The resource identifier.</param> public LocBrushExtension(string key) : base(key) { } /// <summary> /// Provides the Value for the first Binding as <see cref="System.Windows.Media.Brush"/> /// </summary> /// <param name="serviceProvider"> /// The <see cref="System.Windows.Markup.IProvideValueTarget"/> provided from the <see cref="MarkupExtension"/> /// </param> /// <returns>The founded item from the .resx directory or null if not founded</returns> /// <exception cref="System.InvalidOperationException"> /// thrown if <paramref name="serviceProvider"/> is not type of <see cref="System.Windows.Markup.IProvideValueTarget"/> /// </exception> /// <exception cref="System.NotSupportedException"> /// thrown if the founded object is not type of <see cref="System.String"/> /// </exception> /// <exception cref="System.NotSupportedException"> /// The founded resource-string cannot be converted into the appropriate object. /// </exception> public override object ProvideValue(IServiceProvider serviceProvider) { object obj = base.ProvideValue(serviceProvider); if (obj == null) { return null; } if (this.IsTypeOf(obj.GetType(), typeof(BaseLocalizeExtension<>))) { return obj; } if (obj.GetType().Equals(typeof(string))) { return this.FormatOutput(obj); } throw new NotSupportedException( string.Format( "ResourceKey '{0}' returns '{1}' which is not type of System.Drawing.Bitmap", this.Key, obj.GetType().FullName)); } /// <summary> /// see <c>BaseLocalizeExtension</c> /// </summary> protected override void HandleNewValue() { object obj = LocalizeDictionary.Instance.GetLocalizedObject<object>(this.Assembly, this.Dict, this.Key, this.GetForcedCultureOrDefault()); this.SetNewValue(new System.Windows.Media.BrushConverter().ConvertFromString((string)obj)); } /// <summary> /// This method is used to modify the passed object into the target format /// </summary> /// <param name="input">The object that will be modified</param> /// <returns>Returns the modified object</returns> protected override object FormatOutput(object input) { if (LocalizeDictionary.Instance.GetIsInDesignMode() && this.DesignValue != null) { try { return new System.Windows.Media.BrushConverter().ConvertFromString((string) this.DesignValue); } catch { return null; } } return new System.Windows.Media.BrushConverter().ConvertFromString((string)input); } } }
zzgaminginc-pointofssale
Samba.Localization/Extensions/LocBrushExtension.cs
C#
gpl3
3,998
using System; using System.Windows.Markup; using Samba.Localization.BaseExtensions; using Samba.Localization.Engine; namespace Samba.Localization.Extensions { /// <summary> /// <c>BaseLocalizeExtension</c> for string objects. /// </summary> [MarkupExtensionReturnType(typeof(string))] public class LocTextExtension : BaseLocalizeExtension<string> { /// <summary> /// Holds the local prefix value /// </summary> private string prefix; /// <summary> /// Holds the local suffix value /// </summary> private string suffix; /// <summary> /// Holds the local format segment array /// </summary> private string[] formatSegments; /// <summary> /// Initializes a new instance of the <see cref="LocTextExtension"/> class. /// </summary> public LocTextExtension() { this.InitializeLocText(); } /// <summary> /// Initializes a new instance of the <see cref="LocTextExtension"/> class. /// </summary> /// <param name="key">The resource identifier.</param> public LocTextExtension(string key) : base(key) { this.InitializeLocText(); } /// <summary> /// This enumeration is used to determine the type /// of the return value of <see cref="GetAppendText"/> /// </summary> protected enum TextAppendType { /// <summary> /// The return value is used as prefix /// </summary> Prefix, /// <summary> /// The return value is used as suffix /// </summary> Suffix } /// <summary> /// Gets or sets a prefix for the localized text /// </summary> public string Prefix { get { return this.prefix; } set { this.prefix = value; // reset the value of the target property this.HandleNewValue(); } } /// <summary> /// Gets or sets a suffix for the localized text /// </summary> public string Suffix { get { return this.suffix; } set { this.suffix = value; // reset the value of the target property this.HandleNewValue(); } } /// <summary> /// Gets or sets the format segment 1. /// This will be used to replace format place holders from the localized text. /// <see cref="LocTextLowerExtension"/> and <see cref="LocTextUpperExtension"/> will format this segment. /// </summary> /// <value>The format segment 1.</value> public string FormatSegment1 { get { return this.formatSegments[0]; } set { this.formatSegments[0] = value; this.HandleNewValue(); } } /// <summary> /// Gets or sets the format segment 2. /// This will be used to replace format place holders from the localized text. /// <see cref="LocTextUpperExtension"/> and <see cref="LocTextLowerExtension"/> will format this segment. /// </summary> /// <value>The format segment 2.</value> public string FormatSegment2 { get { return this.formatSegments[1]; } set { this.formatSegments[1] = value; this.HandleNewValue(); } } /// <summary> /// Gets or sets the format segment 3. /// This will be used to replace format place holders from the localized text. /// <see cref="LocTextUpperExtension"/> and <see cref="LocTextLowerExtension"/> will format this segment. /// </summary> /// <value>The format segment 3.</value> public string FormatSegment3 { get { return this.formatSegments[2]; } set { this.formatSegments[2] = value; this.HandleNewValue(); } } /// <summary> /// Gets or sets the format segment 4. /// This will be used to replace format place holders from the localized text. /// <see cref="LocTextUpperExtension"/> and <see cref="LocTextLowerExtension"/> will format this segment. /// </summary> /// <value>The format segment 4.</value> public string FormatSegment4 { get { return this.formatSegments[3]; } set { this.formatSegments[3] = value; this.HandleNewValue(); } } /// <summary> /// Gets or sets the format segment 5. /// This will be used to replace format place holders from the localized text. /// <see cref="LocTextUpperExtension"/> and <see cref="LocTextLowerExtension"/> will format this segment. /// </summary> /// <value>The format segment 5.</value> public string FormatSegment5 { get { return this.formatSegments[4]; } set { this.formatSegments[4] = value; this.HandleNewValue(); } } /// <summary> /// Provides the Value for the first Binding as <see cref="System.String"/> /// </summary> /// <param name="serviceProvider"> /// The <see cref="System.Windows.Markup.IProvideValueTarget"/> provided from the <see cref="MarkupExtension"/> /// </param> /// <returns>The founded item from the .resx directory or null if not founded</returns> /// <exception cref="System.InvalidOperationException"> /// thrown if <paramref name="serviceProvider"/> is not type of <see cref="System.Windows.Markup.IProvideValueTarget"/> /// </exception> /// <exception cref="System.NotSupportedException"> /// thrown if the founded object is not type of <see cref="System.String"/> /// </exception> public override object ProvideValue(IServiceProvider serviceProvider) { object obj = base.ProvideValue(serviceProvider); if (obj == null) { return null; } if (this.IsTypeOf(obj.GetType(), typeof(BaseLocalizeExtension<>))) { return obj; } if (obj.GetType().Equals(typeof(string))) { return this.FormatOutput(obj); } throw new NotSupportedException( string.Format( "ResourceKey '{0}' returns '{1}' which is not type of System.String", this.Key, obj.GetType().FullName)); } /// <summary> /// This method formats the localized text. /// If the passed target text is null, string.empty will be returned. /// </summary> /// <param name="target">The text to format.</param> /// <returns>Returns the formated text or string.empty, if the target text was null.</returns> protected virtual string FormatText(string target) { return target ?? string.Empty; } /// <summary> /// see <c>BaseLocalizeExtension</c> /// </summary> protected override void HandleNewValue() { this.SetNewValue(this.FormatOutput(null)); } /// <summary> /// This method returns the finished formatted text /// </summary> /// <param name="input">If the passed string not null, it will be used, otherwise a fresh localized text will be loaded.</param> /// <returns>Returns the finished formatted text in format [PREFIX]LocalizedText[SUFFIX]</returns> protected override object FormatOutput(object input) { if (LocalizeDictionary.Instance.GetIsInDesignMode() && this.DesignValue != null) { input = this.DesignValue; } else { // load a fresh localized text, if the passed string is null input = input ?? LocalizeDictionary.Instance.GetLocalizedObject<object>( this.Assembly, this.Dict, this.Key, this.GetForcedCultureOrDefault()); } // get the main text as string xor string.empty string textMain = input as string ?? string.Empty; //try //{ // // add some format segments, in case that the main text contains format place holders like {0} // textMain = string.Format( // LocalizeDictionary.Instance.SpecificCulture, // textMain, // this.formatSegments[0] ?? string.Empty, // this.formatSegments[1] ?? string.Empty, // this.formatSegments[2] ?? string.Empty, // this.formatSegments[3] ?? string.Empty, // this.formatSegments[4] ?? string.Empty); //} //catch (FormatException) //{ // // if a format exception was thrown, change the text to an error string // textMain = "TextFormatError: Max 5 Format PlaceHolders! {0} to {4}"; //} // get the prefix string textPrefix = this.GetAppendText(TextAppendType.Prefix); // get the suffix string textSuffix = this.GetAppendText(TextAppendType.Suffix); // format the text with prefix and suffix to [PREFIX]LocalizedText[SUFFIX] input = this.FormatText(textPrefix + textMain + textSuffix); // return the finished formatted text return input; } /// <summary> /// Initializes the <see cref="LocTextExtension"/> extension. /// </summary> private void InitializeLocText() { this.formatSegments = new string[5]; this.formatSegments.Initialize(); // removed this call, because of the fact, // if the LocTextExtension is defined with "LocTextExtension Key=abc" and not with "LocTextExtension abc". // the value will be set at call ProvideValue, AFTER the Key Property is set. ////SetNewValue(FormatOutput(null)); } /// <summary> /// Returns the prefix or suffix text, depending on the supplied <see cref="TextAppendType"/>. /// If the prefix or suffix is null, it will be returned a string.empty. /// </summary> /// <param name="at">The <see cref="TextAppendType"/> defines the format of the return value</param> /// <returns>Returns the formated prefix or suffix</returns> private string GetAppendText(TextAppendType at) { // define a return value string retVal = string.Empty; // check if it should be a prefix, the format will be [PREFIX], // or check if it should be a suffix, the format will be [SUFFIX] if (at == TextAppendType.Prefix && !string.IsNullOrEmpty(this.prefix)) { retVal = this.prefix ?? string.Empty; } else if (at == TextAppendType.Suffix && !string.IsNullOrEmpty(this.suffix)) { retVal = this.suffix ?? string.Empty; } // return the formated prefix or suffix return retVal; } } }
zzgaminginc-pointofssale
Samba.Localization/Extensions/LocTextExtension.cs
C#
gpl3
12,073
using System; using System.Drawing; using System.Windows; using System.Windows.Markup; using System.Windows.Media; using Samba.Localization.BaseExtensions; using Samba.Localization.Engine; namespace Samba.Localization.Extensions { /// <summary> /// <c>BaseLocalizeExtension</c> for image objects /// </summary> [MarkupExtensionReturnType(typeof(System.Windows.Media.Imaging.BitmapSource))] public class LocImageExtension : BaseLocalizeExtension<System.Windows.Media.Imaging.BitmapSource> { /// <summary> /// Initializes a new instance of the <see cref="LocImageExtension"/> class. /// </summary> public LocImageExtension() { } /// <summary> /// Initializes a new instance of the <see cref="LocImageExtension"/> class. /// </summary> /// <param name="key">The resource identifier.</param> public LocImageExtension(string key) : base(key) { } /// <summary> /// Provides the Value for the first Binding as <see cref="System.Windows.Media.Imaging.BitmapSource"/> /// </summary> /// <param name="serviceProvider"> /// The <see cref="System.Windows.Markup.IProvideValueTarget"/> provided from the <see cref="MarkupExtension"/> /// </param> /// <returns>The founded item from the .resx directory or null if not founded</returns> /// <exception cref="System.InvalidOperationException"> /// thrown if <paramref name="serviceProvider"/> is not type of <see cref="System.Windows.Markup.IProvideValueTarget"/> /// </exception> /// <exception cref="System.NotSupportedException"> /// thrown if the founded object is not type of <see cref="Drawing.Bitmap"/> /// </exception> public override object ProvideValue(IServiceProvider serviceProvider) { object obj = base.ProvideValue(serviceProvider); if (obj == null) { return null; } if (this.IsTypeOf(obj.GetType(), typeof(BaseLocalizeExtension<>))) { return obj; } if (obj.GetType().Equals(typeof(System.Drawing.Bitmap))) { return this.FormatOutput(obj); } throw new NotSupportedException( string.Format( "ResourceKey '{0}' returns '{1}' which is not type of System.Drawing.Bitmap", this.Key, obj.GetType().FullName)); } /// <summary> /// see <c>BaseLocalizeExtension</c> /// </summary> protected override void HandleNewValue() { object obj = LocalizeDictionary.Instance.GetLocalizedObject<object>(this.Assembly, this.Dict, this.Key, this.GetForcedCultureOrDefault()); this.SetNewValue(this.FormatOutput(obj)); } /// <summary> /// Creates a <see cref="System.Windows.Media.Imaging.BitmapSource"/> from a <see cref="Bitmap"/>. /// This extension does NOT support a DesignValue. /// </summary> /// <param name="input">The <see cref="Bitmap"/> to convert</param> /// <returns>The converted <see cref="System.Windows.Media.Imaging.BitmapSource"/></returns> protected override object FormatOutput(object input) { // allocate the memory for the bitmap IntPtr bmpPt = ((Bitmap)input).GetHbitmap(); // create the bitmapSource System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmpPt, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); // freeze the bitmap to avoid hooking events to the bitmap bitmapSource.Freeze(); // free memory DeleteObject(bmpPt); // return bitmapSource return bitmapSource; } /// <summary> /// Frees memory of a pointer. /// </summary> /// <param name="o">Object to remove from memory.</param> /// <returns>0 if the removing was success, otherwise another number.</returns> [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern int DeleteObject(IntPtr o); } }
zzgaminginc-pointofssale
Samba.Localization/Extensions/LocImageExtension.cs
C#
gpl3
4,564
using System; using System.Windows.Markup; using Samba.Localization.BaseExtensions; using Samba.Localization.Engine; namespace Samba.Localization.Extensions { /// <summary> /// <c>BaseLocalizeExtension</c> for string objects. /// This strings will be converted to lower case. /// </summary> [MarkupExtensionReturnType(typeof(string))] public class LocTextLowerExtension : LocTextExtension { /// <summary> /// Initializes a new instance of the <see cref="LocTextLowerExtension"/> class. /// </summary> public LocTextLowerExtension() { } /// <summary> /// Initializes a new instance of the <see cref="LocTextLowerExtension"/> class. /// </summary> /// <param name="key">The resource identifier.</param> public LocTextLowerExtension(string key) : base(key) { } /// <summary> /// Provides the Value for the first Binding as <see cref="System.String"/> /// </summary> /// <param name="serviceProvider"> /// The <see cref="System.Windows.Markup.IProvideValueTarget"/> provided from the <see cref="MarkupExtension"/> /// </param> /// <returns>The founded item from the .resx directory or null if not founded</returns> /// <exception cref="System.InvalidOperationException"> /// thrown if <paramref name="serviceProvider"/> is not type of <see cref="System.Windows.Markup.IProvideValueTarget"/> /// </exception> /// <exception cref="System.NotSupportedException"> /// thrown if the founded object is not type of <see cref="System.String"/> /// </exception> public override object ProvideValue(IServiceProvider serviceProvider) { object obj = base.ProvideValue(serviceProvider); if (obj == null) { return null; } if (this.IsTypeOf(obj.GetType(), typeof(BaseLocalizeExtension<>))) { return obj; } if (obj.GetType().Equals(typeof(string))) { // dont call GetLocalizedText at this point, otherwise you will get prefix and suffix twice appended return obj; } throw new NotSupportedException( string.Format( "ResourceKey '{0}' returns '{1}' which is not type of System.String", this.Key, obj.GetType().FullName)); } /// <summary> /// This method formats the localized text. /// If the passed target text is null, string.empty will be returned. /// </summary> /// <param name="target">The text to format.</param> /// <returns> /// Returns the formated text or string.empty, if the target text was null. /// </returns> protected override string FormatText(string target) { return target == null ? string.Empty : target.ToLower(this.GetForcedCultureOrDefault()); } /// <summary> /// see <c>BaseLocalizeExtension</c> /// </summary> protected override void HandleNewValue() { object obj = LocalizeDictionary.Instance.GetLocalizedObject<object>(this.Assembly, this.Dict, this.Key, this.GetForcedCultureOrDefault()); this.SetNewValue(this.FormatOutput(obj)); } } }
zzgaminginc-pointofssale
Samba.Localization/Extensions/LocTextLowerExtension.cs
C#
gpl3
3,539
using System; using System.Globalization; using System.Windows.Markup; using Samba.Localization.BaseExtensions; using Samba.Localization.Engine; namespace Samba.Localization.Extensions { /// <summary> /// <c>BaseLocalizeExtension</c> for double values /// </summary> [MarkupExtensionReturnType(typeof(double))] public class LocDoubleExtension : BaseLocalizeExtension<double> { /// <summary> /// Initializes a new instance of the <see cref="LocDoubleExtension"/> class. /// </summary> public LocDoubleExtension() { } /// <summary> /// Initializes a new instance of the <see cref="LocDoubleExtension"/> class. /// </summary> /// <param name="key">The resource identifier.</param> public LocDoubleExtension(string key) : base(key) { } /// <summary> /// Provides the Value for the first Binding as double /// </summary> /// <param name="serviceProvider"> /// The <see cref="System.Windows.Markup.IProvideValueTarget"/> provided from the <see cref="MarkupExtension"/> /// </param> /// <returns>The founded item from the .resx directory or null if not founded</returns> /// <exception cref="System.InvalidOperationException"> /// thrown if <paramref name="serviceProvider"/> is not type of <see cref="System.Windows.Markup.IProvideValueTarget"/> /// </exception> /// <exception cref="System.NotSupportedException"> /// thrown if the founded object is not type of double /// </exception> public override object ProvideValue(IServiceProvider serviceProvider) { object obj = base.ProvideValue(serviceProvider); if (obj == null) { return null; } if (this.IsTypeOf(obj.GetType(), typeof(BaseLocalizeExtension<>))) { return obj; } if (obj.GetType().Equals(typeof(string))) { return this.FormatOutput(obj); } throw new NotSupportedException( string.Format( "ResourceKey '{0}' returns '{1}' which is not type of double", this.Key, obj.GetType().FullName)); } /// <summary> /// see <c>BaseLocalizeExtension</c> /// </summary> protected override void HandleNewValue() { object obj = LocalizeDictionary.Instance.GetLocalizedObject<object>(this.Assembly, this.Dict, this.Key, this.GetForcedCultureOrDefault()); this.SetNewValue(this.FormatOutput(obj)); } /// <summary> /// This method is used to modify the passed object into the target format /// </summary> /// <param name="input">The object that will be modified</param> /// <returns>Returns the modified object</returns> protected override object FormatOutput(object input) { if (LocalizeDictionary.Instance.GetIsInDesignMode() && this.DesignValue != null) { try { return double.Parse((string) this.DesignValue, new CultureInfo("en-US")); } catch { return null; } } return double.Parse((string)input, new CultureInfo("en-US")); ////System.Reflection.MethodInfo method = typeof(System.ComponentModel.DoubleConverter).GetMethod("FromString", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); ////object result = method.Invoke(null, new object[] { source, new System.Globalization.CultureInfo("en-US") }); ////return (double)result; } } }
zzgaminginc-pointofssale
Samba.Localization/Extensions/LocDoubleExtension.cs
C#
gpl3
3,968
using System; using System.Windows; using System.Windows.Markup; using Samba.Localization.BaseExtensions; using Samba.Localization.Engine; namespace Samba.Localization.Extensions { /// <summary> /// <c>BaseLocalizeExtension</c> for <see cref="FlowDirection"/> values /// </summary> [MarkupExtensionReturnType(typeof(FlowDirection))] public class LocFlowDirectionExtension : BaseLocalizeExtension<FlowDirection> { /// <summary> /// Initializes a new instance of the <see cref="LocFlowDirectionExtension"/> class. /// </summary> public LocFlowDirectionExtension() { } /// <summary> /// Initializes a new instance of the <see cref="LocFlowDirectionExtension"/> class. /// </summary> /// <param name="key">The resource identifier.</param> public LocFlowDirectionExtension(string key) : base(key) { } /// <summary> /// Provides the Value for the first Binding as <see cref="LocFlowDirectionExtension"/> /// </summary> /// <param name="serviceProvider"> /// The <see cref="System.Windows.Markup.IProvideValueTarget"/> provided from the <see cref="MarkupExtension"/> /// </param> /// <returns>The founded item from the .resx directory or LeftToRight if not founded</returns> /// <exception cref="System.InvalidOperationException"> /// thrown if <paramref name="serviceProvider"/> is not type of <see cref="System.Windows.Markup.IProvideValueTarget"/> /// </exception> /// <exception cref="System.NotSupportedException"> /// thrown if the founded object is not type of <see cref="FlowDirection"/> /// </exception> public override object ProvideValue(IServiceProvider serviceProvider) { object obj = base.ProvideValue(serviceProvider) ?? "LeftToRight"; if (this.IsTypeOf(obj.GetType(), typeof(BaseLocalizeExtension<>))) { return obj; } if (obj.GetType().Equals(typeof(string))) { return this.FormatOutput(obj); } throw new NotSupportedException( string.Format( "ResourceKey '{0}' returns '{1}' which is not type of FlowDirection", this.Key, obj.GetType().FullName)); } /// <summary> /// see <c>BaseLocalizeExtension</c> /// </summary> protected override void HandleNewValue() { var obj = LocalizeDictionary.Instance.GetLocalizedObject<object>(this.Assembly, this.Dict, this.Key, this.GetForcedCultureOrDefault()); this.SetNewValue(this.FormatOutput(obj)); } /// <summary> /// This method is used to modify the passed object into the target format /// </summary> /// <param name="input">The object that will be modified</param> /// <returns>Returns the modified object</returns> protected override object FormatOutput(object input) { if (LocalizeDictionary.Instance.GetIsInDesignMode() && this.DesignValue != null) { try { return Enum.Parse(typeof(FlowDirection), (string) this.DesignValue, true); } catch { return null; } } return Enum.Parse(typeof(FlowDirection), (string)input, true); } } }
zzgaminginc-pointofssale
Samba.Localization/Extensions/LocFlowDirectionExtension.cs
C#
gpl3
3,634
using System; using System.Globalization; using System.Reflection; namespace Samba.Localization.Engine { /// <summary> /// Implements the LocalizedObjectOperation. /// </summary> public static class LocalizedObjectOperation { /// <summary> /// Gets the error message. /// </summary> /// <param name="errorNo">The error no.</param> /// <returns>The resolved string or a default error string.</returns> public static string GetErrorMessage(int errorNo) { try { return (string) LocalizeDictionary.Instance.GetLocalizedObject<object>( LocalizeDictionary.Instance.GetAssemblyName(Assembly.GetExecutingAssembly()), "ResError", "ERR_" + errorNo, LocalizeDictionary.Instance.Culture); } catch { return "No localized ErrorMessage founded for ErrorNr: " + errorNo; } } /// <summary> /// Gets the GUI string. /// </summary> /// <param name="key">The resource identifier.</param> /// <returns>The resolved string or a default error string.</returns> public static string GetGuiString(string key) { return GetGuiString(key, LocalizeDictionary.Instance.Culture); } /// <summary> /// Gets the GUI string. /// </summary> /// <param name="key">The resource identifier.</param> /// <param name="language">The language.</param> /// <returns>The resolved string or a default error string.</returns> public static string GetGuiString(string key, CultureInfo language) { if (key == null) { throw new ArgumentNullException("key"); } if (key == string.Empty) { throw new ArgumentException("key is empty", "key"); } try { return (string) LocalizeDictionary.Instance.GetLocalizedObject<object>( LocalizeDictionary.Instance.GetAssemblyName(Assembly.GetExecutingAssembly()), "ResGui", key, language); } catch { return "No localized GuiMessage founded for key '" + key + "'"; } } /// <summary> /// Gets the help string. /// </summary> /// <param name="key">The resource identifier.</param> /// <returns>The resolved string or a default error string.</returns> public static string GetHelpString(string key) { if (key == null) { throw new ArgumentNullException("key"); } if (key == string.Empty) { throw new ArgumentException("key is empty", "key"); } try { return (string) LocalizeDictionary.Instance.GetLocalizedObject<object>( LocalizeDictionary.Instance.GetAssemblyName(Assembly.GetExecutingAssembly()), "ResHelp", key, LocalizeDictionary.Instance.Culture); } catch { return "No localized HelpMessage founded for key '" + key + "'"; } } /// <summary> /// Gets the maintenance string. /// </summary> /// <param name="key">The resource identifier.</param> /// <returns>The resolved string or a default error string.</returns> public static string GetMaintenanceString(string key) { if (key == null) { throw new ArgumentNullException("key"); } if (key == string.Empty) { throw new ArgumentException("key is empty", "key"); } try { return (string) LocalizeDictionary.Instance.GetLocalizedObject<object>( LocalizeDictionary.Instance.GetAssemblyName(Assembly.GetExecutingAssembly()), "ResMaintenance", key, LocalizeDictionary.Instance.Culture); } catch { return "No localized MaintenanceMessage founded for key '" + key + "'"; } } /// <summary> /// Gets the update agent string. /// </summary> /// <param name="key">The resource identifier.</param> /// <returns>The resolved string or a default error string.</returns> public static string GetUpdateAgentString(string key) { if (key == null) { throw new ArgumentNullException("key"); } if (key == string.Empty) { throw new ArgumentException("key is empty", "key"); } try { return (string) LocalizeDictionary.Instance.GetLocalizedObject<object>( LocalizeDictionary.Instance.GetAssemblyName(Assembly.GetExecutingAssembly()), "ResUpdateAgent", key, LocalizeDictionary.Instance.Culture); } catch { return "No localized UpdateAgentMessage founded for key '" + key + "'"; } } } }
zzgaminginc-pointofssale
Samba.Localization/Engine/LocalizedObjectOperation.cs
C#
gpl3
6,059
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Threading; using System.Windows; using System.Windows.Markup; using Samba.Infrastructure.Settings; ////// Register this namespace under admirals one with prefix //[assembly: XmlnsDefinition("http://schemas.root-project.org/xaml/presentation", "Samba.Localization.Engine")] //[assembly: XmlnsDefinition("http://schemas.root-project.org/xaml/presentation", "Samba.Localization.Extensions")] ////// Assign a default namespace prefix for the schema //[assembly: XmlnsPrefix("http://schemas.root-project.org/xaml/presentation", "ln")] [assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "Samba.Localization.Engine")] [assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2007/xaml/presentation", "Samba.Localization.Engine")] [assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2008/xaml/presentation", "Samba.Localization.Engine")] [assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "Samba.Localization.Extensions")] [assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2007/xaml/presentation", "Samba.Localization.Extensions")] [assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.microsoft.com/winfx/2008/xaml/presentation", "Samba.Localization.Extensions")] namespace Samba.Localization.Engine { /// <summary> /// Represents the culture interface for localization /// </summary> public sealed class LocalizeDictionary : DependencyObject { /// <summary> /// <see cref="DependencyProperty"/> DesignCulture to set the Culture. /// Only supported at DesignTime. /// </summary> [DesignOnly(true)] public static readonly DependencyProperty DesignCultureProperty = DependencyProperty.RegisterAttached( "DesignCulture", typeof(string), typeof(LocalizeDictionary), new PropertyMetadata(SetCultureFromDependencyProperty)); /// <summary> /// Holds the default <see cref="ResourceDictionary"/> name /// </summary> public const string ResourcesName = "Resources"; /// <summary> /// Holds the name of the Resource Manager. /// </summary> private const string ResourceManagerName = "ResourceManager"; /// <summary> /// Holds the extension of the resource files. /// </summary> private const string ResourceFileExtension = ".resources"; /// <summary> /// Holds the binding flags for the reflection to find the resource files. /// </summary> private const BindingFlags ResourceBindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; /// <summary> /// Holds a SyncRoot to be thread safe /// </summary> private static readonly object SyncRoot = new object(); /// <summary> /// Holds the instance of singleton /// </summary> private static LocalizeDictionary instance; /// <summary> /// Holds the current chosen <see cref="CultureInfo"/> /// </summary> private CultureInfo culture; /// <summary> /// Prevents a default instance of the <see cref="LocalizeDictionary"/> class from being created. /// Static Constructor /// </summary> private LocalizeDictionary() { this.ResourceManagerList = new Dictionary<string, ResourceManager>(); } /// <summary> /// Get raised if the <see cref="LocalizeDictionary"/>.Culture is changed. /// </summary> internal event Action OnCultureChanged; /// <summary> /// Gets the default <see cref="CultureInfo"/> to initialize the <see cref="LocalizeDictionary"/>.<see cref="CultureInfo"/> /// </summary> public static CultureInfo DefaultCultureInfo { get { return CultureInfo.InvariantCulture; } } /// <summary> /// Gets the <see cref="LocalizeDictionary"/> singleton. /// If the underlying instance is null, a instance will be created. /// </summary> public static LocalizeDictionary Instance { get { // check if the underlying instance is null if (instance == null) { // if it is null, lock the syncroot. // if another thread is accessing this too, // it have to wait until the syncroot is released lock (SyncRoot) { // check again, if the underlying instance is null if (instance == null) { // create a new instance instance = new LocalizeDictionary(); } } } // return the existing/new instance return instance; } } /// <summary> /// Gets or sets the <see cref="CultureInfo"/> for localization. /// On set, <see cref="OnCultureChanged"/> is raised. /// </summary> /// <exception cref="System.InvalidOperationException"> /// You have to set <see cref="LocalizeDictionary"/>.Culture first or /// wait until System.Windows.Application.Current.MainWindow is created. /// Otherwise you will get an Exception.</exception> /// <exception cref="System.ArgumentNullException">thrown if Culture will be set to null</exception> public CultureInfo Culture { get { if (this.culture == null) { this.culture = Thread.CurrentThread.CurrentUICulture; // DefaultCultureInfo; } return this.culture; } set { // the cultureinfo cannot contains a null reference if (value == null) { throw new ArgumentNullException("value"); } // Set the CultureInfo this.culture = value; // Raise the OnCultureChanged event if (this.OnCultureChanged != null) { this.OnCultureChanged(); } } } /// <summary> /// Gets the used ResourceManagers with their corresponding <c>namespaces</c>. /// </summary> public Dictionary<string, ResourceManager> ResourceManagerList { get; private set; } /// <summary> /// Gets the specific <see cref="CultureInfo"/> of the current culture. /// This can be used for format manners. /// If the Culture is an invariant <see cref="CultureInfo"/>, /// SpecificCulture will also return an invariant <see cref="CultureInfo"/>. /// </summary> public CultureInfo SpecificCulture { get { return CultureInfo.CreateSpecificCulture(this.Culture.ToString()); } } /// <summary> /// Getter of <see cref="DependencyProperty"/> Culture. /// Only supported at DesignTime. /// If its in Runtime, <see cref="LocalizeDictionary"/>.Culture will be returned. /// </summary> /// <param name="obj">The dependency object to get the design culture from.</param> /// <returns>The design culture at design time or the current culture at runtime.</returns> [DesignOnly(true)] public static string GetDesignCulture(DependencyObject obj) { if (Instance.GetIsInDesignMode()) { return (string)obj.GetValue(DesignCultureProperty); } else { return Instance.Culture.ToString(); } } /// <summary> /// Parses a key ([[Assembly:]Dict:]Key and return the parts of it. /// </summary> /// <param name="inKey">The key to parse.</param> /// <param name="outAssembly">The found or default assembly.</param> /// <param name="outDict">The found or default dictionary.</param> /// <param name="outKey">The found or default key.</param> public static void ParseKey(string inKey, out string outAssembly, out string outDict, out string outKey) { // reset the vars to null outAssembly = null; outDict = null; outKey = null; // its a assembly/dict/key pair if (!string.IsNullOrEmpty(inKey)) { string[] split = inKey.Trim().Split(":".ToCharArray(), 3); // assembly:dict:key if (split.Length == 3) { outAssembly = !string.IsNullOrEmpty(split[0]) ? split[0] : null; outDict = !string.IsNullOrEmpty(split[1]) ? split[1] : null; outKey = split[2]; } // dict:key // assembly = ExecutingAssembly if (split.Length == 2) { outDict = !string.IsNullOrEmpty(split[0]) ? split[0] : null; outKey = split[1]; } // key // assembly = ExecutingAssembly // dict = standard resourcedictionary if (split.Length == 1) { outKey = split[0]; } } else { // if the passed value is null pr empty, throw an exception if in runtime if (!Instance.GetIsInDesignMode()) { throw new ArgumentNullException("inKey"); } } } /// <summary> /// Setter of <see cref="DependencyProperty"/> Culture. /// Only supported at DesignTime. /// </summary> /// <param name="obj">The dependency object to set the culture to.</param> /// <param name="value">The odds format.</param> [DesignOnly(true)] public static void SetDesignCulture(DependencyObject obj, string value) { if (Instance.GetIsInDesignMode()) { obj.SetValue(DesignCultureProperty, value); } } /// <summary> /// Attach an WeakEventListener to the <see cref="LocalizeDictionary"/> /// </summary> /// <param name="listener">The listener to attach</param> public void AddEventListener(IWeakEventListener listener) { // calls AddListener from the inline WeakCultureChangedEventManager WeakCultureChangedEventManager.AddListener(listener); } /// <summary> /// Returns the <see cref="AssemblyName"/> of the passed assembly instance /// </summary> /// <param name="assembly">The Assembly where to get the name from</param> /// <returns>The Assembly name</returns> public string GetAssemblyName(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (assembly.FullName == null) { throw new NullReferenceException("assembly.FullName is null"); } return assembly.FullName.Split(',')[0]; } /// <summary> /// Gets the status of the design mode /// </summary> /// <returns>TRUE if in design mode, else FALSE</returns> public bool GetIsInDesignMode() { if (Application.Current == null) { return false; } return Application.Current.MainWindow == null || DesignerProperties.GetIsInDesignMode(Application.Current.MainWindow); } /// <summary> /// Returns an object from the passed dictionary with the given name. /// If a wrong <typeparamref name="TType"/> is passed, no exception will get thrown (return obj as <typeparamref name="TType"/>). /// </summary> /// <typeparam name="TType">Type of result type. Have to be a class.</typeparam> /// <param name="resourceAssembly">The Assembly where the Resource is located at</param> /// <param name="resourceDictionary">Name of the resource directory</param> /// <param name="resourceKey">The key for the resource</param> /// <param name="cultureToUse">The culture to use.</param> /// <returns> /// The founded object or NULL if not found or wrong <typeparamref name="TType"/> is given /// </returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="resourceDictionary"/> is null /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="resourceDictionary"/> is empty /// </exception> /// <exception cref="System.ArgumentNullException"> /// <paramref name="resourceKey"/> is null /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="resourceKey"/> is empty /// </exception> /// <exception cref="System.ArgumentException"> /// Ambiguous resource name {<paramref name="resourceDictionary"/>} /// </exception> /// <exception cref="System.ArgumentException"> /// No resource with name '{<paramref name="resourceDictionary"/>}' founded /// </exception> public TType GetLocalizedObject<TType>( string resourceAssembly, string resourceDictionary, string resourceKey, CultureInfo cultureToUse) where TType : class { if (resourceDictionary == null) { throw new ArgumentNullException("resourceDictionary"); } if (resourceDictionary == string.Empty) { throw new ArgumentException("resourceDictionary is empty", "resourceDictionary"); } if (string.IsNullOrEmpty(resourceKey)) { if (this.GetIsInDesignMode()) { return null; } else { if (resourceKey == null) { throw new ArgumentNullException("resourceKey"); } else if (resourceKey == string.Empty) { throw new ArgumentException("resourceKey is empty", "resourceKey"); } } } // declaring local ResourceManager ResourceManager resManager; // try to get the resouce manager try { resManager = this.GetResourceManager(resourceAssembly, resourceDictionary, resourceKey); } catch { // if an error occour, throw exception, if in runtime if (this.GetIsInDesignMode()) { return null; } else { throw; } } // gets the resourceobject with the choosen localization object retVal = resManager.GetObject(resourceKey, cultureToUse) as TType; // if the retVal is null, throw exception, if in runtime if (retVal == null && !this.GetIsInDesignMode()) { throw new ArgumentException( string.Format( "No resource key with name '{0}' in dictionary '{1}' in assembly '{2}' founded! ({2}.{1}.{0})", resourceKey, resourceDictionary, resourceAssembly)); } // finally, return the searched object as type of the generic type return retVal as TType; } /// <summary> /// Detach an WeakEventListener to the <see cref="LocalizeDictionary"/> /// </summary> /// <param name="listener">The listener to detach</param> public void RemoveEventListener(IWeakEventListener listener) { // calls RemoveListener from the inline WeakCultureChangedEventManager WeakCultureChangedEventManager.RemoveListener(listener); } /// <summary> /// Looks up the ResourceManagers for the searched <paramref name="resourceKey"/> /// in the <paramref name="resourceDictionary"/> in the <paramref name="resourceAssembly"/> /// with an Invariant Culture. /// </summary> /// <param name="resourceAssembly">The resource assembly (e.g.: <c>BaseLocalizeExtension</c>). NULL = Name of the executing assembly</param> /// <param name="resourceDictionary">The dictionary to look up (e.g.: ResHelp, Resources, ...). NULL = Name of the default resource file (Resources)</param> /// <param name="resourceKey">The key of the searched entry (e.g.: <c>btnHelp</c>, Cancel, ...). NULL = Exception</param> /// <returns> /// TRUE if the searched one is found, otherwise FALSE /// </returns> /// <exception cref="System.InvalidOperationException"> /// If the ResourceManagers cannot be looked up /// </exception> /// <exception cref="System.ArgumentException"> /// If the searched <see cref="ResourceManager"/> wasn't found (only in runtime) /// </exception> /// <exception cref="System.ArgumentException"> /// If the <paramref name="resourceKey"/> is null or empty /// </exception> public bool ResourceKeyExists(string resourceAssembly, string resourceDictionary, string resourceKey) { return this.ResourceKeyExists(resourceAssembly, resourceDictionary, resourceKey, CultureInfo.InvariantCulture); } /// <summary> /// Looks up the ResourceManagers for the searched <paramref name="resourceKey"/> /// in the <paramref name="resourceDictionary"/> in the <paramref name="resourceAssembly"/> /// with the passed culture. If the searched one does not exists with the passed culture, is will searched /// until the invariant culture is used. /// </summary> /// <param name="resourceAssembly">The resource assembly (e.g.: <c>BaseLocalizeExtension</c>). NULL = Name of the executing assembly</param> /// <param name="resourceDictionary">The dictionary to look up (e.g.: ResHelp, Resources, ...). NULL = Name of the default resource file (Resources)</param> /// <param name="resourceKey">The key of the searched entry (e.g.: <c>btnHelp</c>, Cancel, ...). NULL = Exception</param> /// <param name="cultureToUse">The culture to use.</param> /// <returns> /// TRUE if the searched one is found, otherwise FALSE /// </returns> /// <exception cref="System.InvalidOperationException"> /// If the ResourceManagers cannot be looked up /// </exception> /// <exception cref="System.ArgumentException"> /// If the searched <see cref="ResourceManager"/> wasn't found (only in runtime) /// </exception> /// <exception cref="System.ArgumentException"> /// If the <paramref name="resourceKey"/> is null or empty /// </exception> public bool ResourceKeyExists( string resourceAssembly, string resourceDictionary, string resourceKey, CultureInfo cultureToUse) { try { return this.GetResourceManager(resourceAssembly, resourceDictionary, resourceKey).GetObject( resourceKey, cultureToUse) != null; } catch { if (this.GetIsInDesignMode()) { return false; } else { throw; } } } /// <summary> /// Callback function. Used to set the <see cref="LocalizeDictionary"/>.Culture if set in Xaml. /// Only supported at DesignTime. /// </summary> /// <param name="obj">The dependency object.</param> /// <param name="args">The event argument.</param> [DesignOnly(true)] private static void SetCultureFromDependencyProperty(DependencyObject obj, DependencyPropertyChangedEventArgs args) { if (!Instance.GetIsInDesignMode()) { return; } CultureInfo culture; try { culture = CultureInfo.GetCultureInfo((string)args.NewValue); } catch { if (Instance.GetIsInDesignMode()) { culture = DefaultCultureInfo; } else { throw; } } if (culture != null) { Instance.Culture = culture; } } /// <summary> /// Looks up in the cached <see cref="ResourceManager"/> list for the searched <see cref="ResourceManager"/>. /// </summary> /// <param name="resourceAssembly">The resource assembly (e.g.: <c>BaseLocalizeExtension</c>). NULL = Name of the executing assembly</param> /// <param name="resourceDictionary">The dictionary to look up (e.g.: ResHelp, Resources, ...). NULL = Name of the default resource file (Resources)</param> /// <param name="resourceKey">The key of the searched entry (e.g.: <c>btnHelp</c>, Cancel, ...). NULL = Exception</param> /// <returns> /// The founded <see cref="ResourceManager"/> /// </returns> /// <exception cref="System.InvalidOperationException"> /// If the ResourceManagers cannot be looked up /// </exception> /// <exception cref="System.ArgumentException"> /// If the searched <see cref="ResourceManager"/> wasn't found /// </exception> /// <exception cref="System.ArgumentException"> /// If the <paramref name="resourceKey"/> is null or empty /// </exception> private ResourceManager GetResourceManager(string resourceAssembly, string resourceDictionary, string resourceKey) { if (resourceAssembly == null) { resourceAssembly = GetAssemblyName(Assembly.GetExecutingAssembly()); } if (resourceDictionary == null) { resourceDictionary = ResourcesName; } if (string.IsNullOrEmpty(resourceKey)) { throw new ArgumentNullException("resourceKey"); } PropertyInfo propInfo; MethodInfo methodInfo; Assembly assembly = null; ResourceManager resManager; string foundedResource = null; string resManagerNameToSearch = "." + resourceDictionary + ResourceFileExtension; string[] availableResources; if (this.ResourceManagerList.ContainsKey(resourceAssembly + resManagerNameToSearch)) { resManager = this.ResourceManagerList[resourceAssembly + resManagerNameToSearch]; } else { // if the assembly cannot be loaded, throw an exception try { // go through every assembly loaded in the app domain foreach (Assembly assemblyInAppDomain in AppDomain.CurrentDomain.GetAssemblies()) { // check if the name pf the assembly is not null if (assemblyInAppDomain.FullName != null) { // get the assembly name object var assemblyName = new AssemblyName(assemblyInAppDomain.FullName); // check if the name of the assembly is the seached one if (assemblyName.Name == resourceAssembly) { // assigne the assembly assembly = assemblyInAppDomain; // stop the search here break; } } } // check if the assembly is still null if (assembly == null) { // assign the loaded assembly assembly = Assembly.Load(new AssemblyName(resourceAssembly)); } } catch (Exception ex) { throw new Exception(string.Format("The Assembly '{0}' cannot be loaded.", resourceAssembly), ex); } // get all available resourcenames // availableResources = Assembly.GetExecutingAssembly().GetManifestResourceNames(); availableResources = assembly.GetManifestResourceNames(); // search for the best fitting resourcefile. pattern: ".{NAME}.resources" // search for the best fitting resourcefile. pattern: ".{NAME}.resources" for (int i = 0; i < availableResources.Length; i++) { if (/* availableResources[i].StartsWith(resourceAssembly + ".") && */ availableResources[i].EndsWith(resManagerNameToSearch)) { // take the first occurrence and break foundedResource = availableResources[i]; break; } } // if no one was found, exception if (foundedResource == null) { throw new ArgumentException( string.Format( "No resource key with name '{0}' in dictionary '{1}' in assembly '{2}' founded! ({2}.{1}.{0})", resourceKey, resourceDictionary, resourceAssembly)); } // remove ".resources" from the end foundedResource = foundedResource.Substring(0, foundedResource.Length - ResourceFileExtension.Length); //// Resources.{foundedResource}.ResourceManager.GetObject() //// ^^ prop-info ^^ method get try { // get the propertyinfo from resManager over the type from foundedResource propInfo = assembly.GetType(foundedResource).GetProperty(ResourceManagerName, ResourceBindingFlags); // get the GET-method from the methodinfo methodInfo = propInfo.GetGetMethod(true); // get the static ResourceManager property object resManObject = methodInfo.Invoke(null, null); // cast it to a ResourceManager for better working with resManager = (ResourceManager)resManObject; } catch (Exception ex) { // this error has to get thrown because this has to work throw new InvalidOperationException("Cannot resolve the ResourceManager!", ex); } // Add the ResourceManager to the cachelist this.ResourceManagerList.Add(resourceAssembly + resManagerNameToSearch, resManager); } // return the founded ResourceManager return resManager; } /// <summary> /// This in line class is used to handle weak events to avoid memory leaks /// </summary> internal sealed class WeakCultureChangedEventManager : WeakEventManager { /// <summary> /// Indicates, if the current instance is listening on the source event /// </summary> private bool isListening; /// <summary> /// Holds the inner list of listeners /// </summary> private ListenerList listeners; /// <summary> /// Prevents a default instance of the <see cref="WeakCultureChangedEventManager"/> class from being created. /// Creates a new instance of WeakCultureChangedEventManager /// </summary> private WeakCultureChangedEventManager() { // creates a new list and assign it to listeners this.listeners = new ListenerList(); } /// <summary> /// Gets the singleton instance of <see cref="WeakCultureChangedEventManager"/> /// </summary> private static WeakCultureChangedEventManager CurrentManager { get { // store the type of this WeakEventManager Type managerType = typeof(WeakCultureChangedEventManager); // try to retrieve an existing instance of the stored type WeakCultureChangedEventManager manager = (WeakCultureChangedEventManager)GetCurrentManager(managerType); // if the manager does not exists if (manager == null) { // create a new instance of WeakCultureChangedEventManager manager = new WeakCultureChangedEventManager(); // add the new instance to the WeakEventManager manager-store SetCurrentManager(managerType, manager); } // return the new / existing WeakCultureChangedEventManager instance return manager; } } /// <summary> /// Adds an listener to the inner list of listeners /// </summary> /// <param name="listener">The listener to add</param> internal static void AddListener(IWeakEventListener listener) { // add the listener to the inner list of listeners CurrentManager.listeners.Add(listener); // start / stop the listening process CurrentManager.StartStopListening(); } /// <summary> /// Removes an listener from the inner list of listeners /// </summary> /// <param name="listener">The listener to remove</param> internal static void RemoveListener(IWeakEventListener listener) { // removes the listener from the inner list of listeners CurrentManager.listeners.Remove(listener); // start / stop the listening process CurrentManager.StartStopListening(); } /// <summary> /// This method starts the listening process by attaching on the source event /// </summary> /// <param name="source">The source.</param> [MethodImpl(MethodImplOptions.Synchronized)] protected override void StartListening(object source) { if (!this.isListening) { Instance.OnCultureChanged += this.Instance_OnCultureChanged; this.isListening = true; } } /// <summary> /// This method stops the listening process by detaching on the source event /// </summary> /// <param name="source">The source to stop listening on.</param> [MethodImpl(MethodImplOptions.Synchronized)] protected override void StopListening(object source) { if (this.isListening) { Instance.OnCultureChanged -= this.Instance_OnCultureChanged; this.isListening = false; } } /// <summary> /// This method is called if the <see cref="LocalizeDictionary"/>.OnCultureChanged /// is called and the listening process is enabled /// </summary> private void Instance_OnCultureChanged() { // tells every listener in the list that the event is occurred this.DeliverEventToList(Instance, EventArgs.Empty, this.listeners); } /// <summary> /// This method starts and stops the listening process by attaching/detaching on the source event /// </summary> [MethodImpl(MethodImplOptions.Synchronized)] private void StartStopListening() { // check if listeners are available and the listening process is stopped, start it. // otherwise if no listeners are available and the listening process is started, stop it if (this.listeners.Count != 0) { if (!this.isListening) { this.StartListening(null); } } else { if (this.isListening) { this.StopListening(null); } } } } public static void ChangeLanguage(string languageName) { var requestedLang = languageName; if (string.IsNullOrEmpty(requestedLang)) { var currentUiLanguageLarge = Thread.CurrentThread.CurrentCulture.Name; if (LocalSettings.SupportedLanguages.Contains(currentUiLanguageLarge)) { requestedLang = currentUiLanguageLarge; } else { var currentUiLanguage = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName; requestedLang = LocalSettings.SupportedLanguages.Contains(currentUiLanguage) ? currentUiLanguage : LocalSettings.SupportedLanguages[0]; } } Instance.Culture = CultureInfo.GetCultureInfo(requestedLang); if (LocalSettings.CurrentLanguage != requestedLang) { LocalSettings.MajorCurrencyName = ""; } LocalSettings.CurrentLanguage = requestedLang; } } }
zzgaminginc-pointofssale
Samba.Localization/Engine/LocalizeDictionary.cs
C#
gpl3
36,320
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Samba.Localization.Engine { /// <summary> /// This class ensures, that a specific object lives as long a associated object is alive. /// </summary> public static class ObjectDependencyManager { /// <summary> /// This member holds the list of all <see cref="WeakReference"/>s and their appropriate objects. /// </summary> private static Dictionary<object, List<WeakReference>> internalList; /// <summary> /// Initializes static members of the <see cref="ObjectDependencyManager"/> class. /// Static Constructor. Creates a new instance of /// Dictionary(object, <see cref="WeakReference"/>) and set it to the <see cref="internalList"/>. /// </summary> static ObjectDependencyManager() { internalList = new Dictionary<object, List<WeakReference>>(); } /// <summary> /// This method adds a new object dependency /// </summary> /// <param name="weakRefDp">The <see cref="WeakReference"/>, which ensures the live cycle of <paramref name="objToHold"/></param> /// <param name="objToHold">The object, which should stay alive as long <paramref name="weakRefDp"/> is alive</param> /// <returns> /// true, if the binding was successfully, otherwise false /// </returns> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="objToHold"/> cannot be null /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="objToHold"/> cannot be type of <see cref="WeakReference"/> /// </exception> /// <exception cref="System.InvalidOperationException"> /// The <see cref="WeakReference"/>.Target cannot be the same as <paramref name="objToHold"/> /// </exception> [MethodImpl(MethodImplOptions.Synchronized)] public static bool AddObjectDependency(WeakReference weakRefDp, object objToHold) { // run the clean up to ensure that only objects are watched they are realy still alive CleanUp(); // if the objToHold is null, we cannot handle this afterwards. if (objToHold == null) { throw new ArgumentNullException("objToHold", "The objToHold cannot be null"); } // if the objToHold is a weakreference, we cannot handle this type afterwards. if (objToHold.GetType() == typeof(WeakReference)) { throw new ArgumentException("objToHold cannot be type of WeakReference", "objToHold"); } // if the target of the weakreference is the objToHold, this would be a cycling play. if (weakRefDp.Target == objToHold) { throw new InvalidOperationException("The WeakReference.Target cannot be the same as objToHold"); } // holds the status of registration of the object dependency bool itemRegistered = false; // check if the objToHold is contained in the internalList. if (!internalList.ContainsKey(objToHold)) { // add the objToHold to the internal list. List<WeakReference> lst = new List<WeakReference> { weakRefDp }; internalList.Add(objToHold, lst); itemRegistered = true; } else { // otherweise, check if the weakRefDp exists and add it if necessary List<WeakReference> lst = internalList[objToHold]; if (!lst.Contains(weakRefDp)) { lst.Add(weakRefDp); itemRegistered = true; } } // return the status of the registration return itemRegistered; } /// <summary> /// This method cleans up all independent (!<see cref="WeakReference"/>.IsAlive) objects. /// </summary> public static void CleanUp() { // call the overloaded method CleanUp(null); } /// <summary> /// This method cleans up all independent (!<see cref="WeakReference"/>.IsAlive) objects or a single object. /// </summary> /// <param name="objToRemove"> /// If defined, the associated object dependency will be removed instead of a full CleanUp /// </param> [MethodImpl(MethodImplOptions.Synchronized)] public static void CleanUp(object objToRemove) { // if a particular object is passed, remove it. if (objToRemove != null) { // if the key wasnt found, throw an exception. if (!internalList.Remove(objToRemove)) { throw new Exception("Key was not found!"); } // stop here return; } // perform an full clean up // this list will hold all keys they has to be removed List<object> keysToRemove = new List<object>(); // step through all object dependenies foreach (KeyValuePair<object, List<WeakReference>> kvp in internalList) { // step recursive through all weak references for (int i = kvp.Value.Count - 1; i >= 0; i--) { // if this weak reference is no more alive, remove it if (!kvp.Value[i].IsAlive) { kvp.Value.RemoveAt(i); } } // if the list of weak references is empty, temove the whole entry if (kvp.Value.Count == 0) { keysToRemove.Add(kvp.Key); } } // step recursive through all keys that have to be remove for (int i = keysToRemove.Count - 1; i >= 0; i--) { // remove the key from the internalList internalList.Remove(keysToRemove[i]); } // clear up the keysToRemove keysToRemove.Clear(); } } }
zzgaminginc-pointofssale
Samba.Localization/Engine/ObjectDependencyManager.cs
C#
gpl3
6,551
using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows; //////// Register this namespace under admirals one with prefix ////[assembly: XmlnsDefinition("http://schemas.root-project.org/xaml/presentation", "WPFLocalizeExtension.Engine")] ////[assembly: XmlnsDefinition("http://schemas.root-project.org/xaml/presentation", "WPFLocalizeExtension.Extensions")] //////// Assign a default namespace prefix for the schema ////[assembly: XmlnsPrefix("http://schemas.root-project.org/xaml/presentation", "lex")] namespace Samba.Localization.Engine { /// <summary> /// Represents the odds format manager /// </summary> public sealed class OddsFormatManager : DependencyObject { /// <summary> /// <see cref="DependencyProperty"/> DesignOddsFormat to set the <see cref="OddsFormatType"/>. /// Only supported at DesignTime. /// </summary> [DesignOnly(true)] public static readonly DependencyProperty DesignOddsFormatProperty = DependencyProperty.RegisterAttached( "DesignOddsFormat", typeof(OddsFormatType), typeof(OddsFormatManager), new PropertyMetadata(DefaultOddsFormatType, SetOddsFormatFromDependencyProperty)); /// <summary> /// Holds a SyncRoot to be thread safe /// </summary> private static readonly object SyncRoot = new object(); /// <summary> /// Holds the instance of singleton /// </summary> private static OddsFormatManager instance; /// <summary> /// Holds the current chosen <see cref="OddsFormatType"/>. /// </summary> private OddsFormatType oddsFormatType = DefaultOddsFormatType; /// <summary> /// Prevents a default instance of the <see cref="OddsFormatManager"/> class from being created. /// Static Constructor /// </summary> private OddsFormatManager() {} /// <summary> /// Get raised if the <see cref="OddsFormatManager"/>.<see cref="OddsFormatType"/> is changed. /// </summary> internal event Action OnOddsFormatChanged; /// <summary> /// Gets the default <see cref="OddsFormatType"/> to initialize the /// <see cref="OddsFormatManager"/>.<see cref="OddsFormatType"/>. /// </summary> public static OddsFormatType DefaultOddsFormatType { get { return OddsFormatType.EU; } } /// <summary> /// Gets the <see cref="OddsFormatManager"/> singleton. /// If the underlying instance is null, a instance will be created. /// </summary> public static OddsFormatManager Instance { get { // check if the underlying instance is null if (instance == null) { // if it is null, lock the syncroot. // if another thread is accessing this too, // it have to wait until the syncroot is released lock (SyncRoot) { // check again, if the underlying instance is null if (instance == null) { // create a new instance instance = new OddsFormatManager(); } } } // return the existing/new instance return instance; } } /// <summary> /// Gets or sets the OddsFormatType for localization. /// On set, <see cref="OnOddsFormatChanged"/> is raised. /// </summary> /// <exception cref="System.InvalidOperationException"> /// You have to set <see cref="OddsFormatManager"/>.<see cref="OddsFormatType"/> first or /// wait until System.Windows.Application.Current.MainWindow is created. /// Otherwise you will get an Exception.</exception> /// <exception cref="System.ArgumentNullException">thrown if OddsFormatType is not defined</exception> public OddsFormatType OddsFormatType { get { return this.oddsFormatType; } set { // the suplied value has to be defined, otherwise an exception will be raised if (!Enum.IsDefined(typeof(OddsFormatType), value)) { throw new ArgumentNullException("value"); } // Set the OddsFormatType this.oddsFormatType = value; // Raise the OnOddsFormatChanged event if (this.OnOddsFormatChanged != null) { this.OnOddsFormatChanged(); } } } /// <summary> /// Getter of <see cref="DependencyProperty"/> DesignOddsFormat. /// Only supported at DesignTime. /// If its in Runtime, the current <see cref="OddsFormatType"/> will be returned. /// </summary> /// <param name="obj">The dependency object to get the odds format type from.</param> /// <returns>The design odds format at design time or the current odds format at runtime.</returns> [DesignOnly(true)] public static OddsFormatType GetDesignOddsFormat(DependencyObject obj) { if (Instance.GetIsInDesignMode()) { return (OddsFormatType) obj.GetValue(DesignOddsFormatProperty); } else { return Instance.OddsFormatType; } } /// <summary> /// Setter of <see cref="DependencyProperty"/> DesignOddsFormat. /// Only supported at DesignTime. /// </summary> /// <param name="obj">The dependency object to set the odds format to.</param> /// <param name="value">The odds format.</param> [DesignOnly(true)] public static void SetDesignOddsFormat(DependencyObject obj, OddsFormatType value) { if (Instance.GetIsInDesignMode()) { obj.SetValue(DesignOddsFormatProperty, value); } } /// <summary> /// Attach an WeakEventListener to the <see cref="OddsFormatManager"/> /// </summary> /// <param name="listener">The listener to attach</param> public void AddEventListener(IWeakEventListener listener) { // calls AddListener from the inline WeakOddsFormatChangedEventManager WeakOddsFormatChangedEventManager.AddListener(listener); } /// <summary> /// Gets the status of the design mode /// </summary> /// <returns>TRUE if in design mode, else FALSE</returns> public bool GetIsInDesignMode() { return DesignerProperties.GetIsInDesignMode(this); } /// <summary> /// Detach an WeakEventListener to the <see cref="OddsFormatManager"/> /// </summary> /// <param name="listener">The listener to detach</param> public void RemoveEventListener(IWeakEventListener listener) { // calls RemoveListener from the inline WeakOddsFormatChangedEventManager WeakOddsFormatChangedEventManager.RemoveListener(listener); } /// <summary> /// Callback function. Used to set the <see cref="OddsFormatManager"/>.<see cref="OddsFormatType"/> if set in Xaml. /// Only supported at DesignTime. /// </summary> /// <param name="obj">The dependency object to set the odds format to.</param> /// <param name="args">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance /// containing the event data.</param> [DesignOnly(true)] private static void SetOddsFormatFromDependencyProperty(DependencyObject obj, DependencyPropertyChangedEventArgs args) { if (!Instance.GetIsInDesignMode()) { return; } if (!Enum.IsDefined(typeof(OddsFormatType), args.NewValue)) { if (Instance.GetIsInDesignMode()) { Instance.OddsFormatType = DefaultOddsFormatType; } else { throw new InvalidCastException(string.Format("\"{0}\" not defined in Enum OddsFormatType", args.NewValue)); } } else { Instance.OddsFormatType = (OddsFormatType) Enum.Parse(typeof(OddsFormatType), args.NewValue.ToString(), true); } } /// <summary> /// This in line class is used to handle weak events to avoid memory leaks /// </summary> internal sealed class WeakOddsFormatChangedEventManager : WeakEventManager { /// <summary> /// Indicates, if the current instance is listening on the source event /// </summary> private bool isListening; /// <summary> /// Holds the inner list of listeners /// </summary> private ListenerList listeners; /// <summary> /// Prevents a default instance of the <see cref="WeakOddsFormatChangedEventManager"/> class from being created. /// Creates a new instance of WeakOddsFormatChangedEventManager /// </summary> private WeakOddsFormatChangedEventManager() { // creates a new list and assign it to listeners this.listeners = new ListenerList(); } /// <summary> /// Gets the singleton instance of <see cref="WeakOddsFormatChangedEventManager"/> /// </summary> private static WeakOddsFormatChangedEventManager CurrentManager { get { // store the type of this WeakEventManager Type managerType = typeof(WeakOddsFormatChangedEventManager); // try to retrieve an existing instance of the stored type WeakOddsFormatChangedEventManager manager = (WeakOddsFormatChangedEventManager) GetCurrentManager(managerType); // if the manager does not exists if (manager == null) { // create a new instance of WeakOddsFormatChangedEventManager manager = new WeakOddsFormatChangedEventManager(); // add the new instance to the WeakEventManager manager-store SetCurrentManager(managerType, manager); } // return the new / existing WeakOddsFormatChangedEventManager instance return manager; } } /// <summary> /// Adds an listener to the inner list of listeners /// </summary> /// <param name="listener">The listener to add</param> internal static void AddListener(IWeakEventListener listener) { // add the listener to the inner list of listeners CurrentManager.listeners.Add(listener); // start / stop the listening process CurrentManager.StartStopListening(); } /// <summary> /// Removes an listener from the inner list of listeners /// </summary> /// <param name="listener">The listener to remove</param> internal static void RemoveListener(IWeakEventListener listener) { // removes the listener from the inner list of listeners CurrentManager.listeners.Remove(listener); // start / stop the listening process CurrentManager.StartStopListening(); } /// <summary> /// This method starts the listening process by attaching on the source event /// </summary> /// <param name="source">The source.</param> [MethodImpl(MethodImplOptions.Synchronized)] protected override void StartListening(object source) { if (!this.isListening) { Instance.OnOddsFormatChanged += this.Instance_OnOddsFormatChanged; LocalizeDictionary.Instance.OnCultureChanged += this.Instance_OnCultureChanged; this.isListening = true; } } /// <summary> /// This method stops the listening process by detaching on the source event /// </summary> /// <param name="source">The source to stop listening on.</param> [MethodImpl(MethodImplOptions.Synchronized)] protected override void StopListening(object source) { if (this.isListening) { Instance.OnOddsFormatChanged -= this.Instance_OnOddsFormatChanged; LocalizeDictionary.Instance.OnCultureChanged -= this.Instance_OnCultureChanged; this.isListening = false; } } /// <summary> /// This method is called if the <see cref="LocalizeDictionary"/>.OnCultureChanged /// is called and the listening process is enabled /// </summary> private void Instance_OnCultureChanged() { // tells every listener in the list that the event is occurred this.DeliverEventToList(Instance, EventArgs.Empty, this.listeners); } /// <summary> /// This method is called if the <see cref="OddsFormatManager"/>.OnOddsFormatChanged /// is called and the listening process is enabled /// </summary> private void Instance_OnOddsFormatChanged() { // tells every listener in the list that the event is occurred this.DeliverEventToList(Instance, EventArgs.Empty, this.listeners); } /// <summary> /// This method starts and stops the listening process by attaching/detaching on the source event /// </summary> [MethodImpl(MethodImplOptions.Synchronized)] private void StartStopListening() { // check if listeners are available and the listening process is stopped, start it. // otherwise if no listeners are available and the listening process is started, stop it if (this.listeners.Count != 0) { if (!this.isListening) { this.StartListening(null); } } else { if (this.isListening) { this.StopListening(null); } } } } } }
zzgaminginc-pointofssale
Samba.Localization/Engine/OddsFormatManager.cs
C#
gpl3
15,678
namespace Samba.Localization.Engine { /// <summary> /// Defines the Format of the odds output. /// </summary> public enum OddsFormatType { /// <summary> /// Format "1.23" /// </summary> EU = 0, /// <summary> /// Format "1/2" /// </summary> UK = 1, /// <summary> /// Format "-200" /// </summary> US = 2 } }
zzgaminginc-pointofssale
Samba.Localization/Engine/OddsFormatType.cs
C#
gpl3
449
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Samba.Localization")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.Localization")] [assembly: AssemblyCopyright("Copyright © 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7c71e4c8-3f9e-4ed2-8772-f896644998c5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzgaminginc-pointofssale
Samba.Localization/Properties/AssemblyInfo.cs
C#
gpl3
1,448
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Samba.Localization { public static class ResourceStrings { public const string Table = "Table"; public const string ImageOnly = "ImageOnly"; public const string Big = "Big"; public const string Small = "Small"; public const string None = "None"; public const string MaxItems = "MaxItems"; public const string SortType = "SortType"; public const string Portion = "Portion"; public const string SubButtonHeight = "SubButtonHeight"; public const string Tag = "Tag"; public const string CornerRadius = "CornerRadius"; public const string Angle = "Angle"; public const string Width = "Width"; public const string Height = "Height"; public const string DefaultProperties = "DefaultProperties"; public const string Gift = "Gift"; public const string Quantity = "Quantity"; public const string Header = "Header"; public const string Color = "Color"; public const string AutoSelect = "AutoSelect"; public const string SortOrder = "SortOrder"; public const string Product = "Product"; public const string NumeratorProperties = "NumeratorProperties"; public const string MenuProperties = "MenuProperties"; public const string CategoryProperties = "CategoryProperties"; public const string AlphanumericButtonValues = "AlphanumericButtonValues"; public const string NumeratorValue = "NumeratorValue"; public const string NumeratorType = "NumeratorType"; public const string WrapText = "WrapText"; public const string PageCount = "PageCount"; public const string ColumnCount = "ColumnCount"; public const string ImagePath = "ImagePath"; public const string ButtonColor = "ButtonColor"; public const string ButtonHeight = "ButtonHeight"; public const string CategoryName = "CategoryName"; public const string FastMenu = "FastMenu"; } }
zzgaminginc-pointofssale
Samba.Localization/ResourceStrings.cs
C#
gpl3
2,168
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.Linq; using System.Text; using Samba.Presentation.Common; using Samba.Presentation.Common.Services; namespace Samba.Modules.NavigationModule { [Export] public class NavigationViewModel : ObservableObject { public ObservableCollection<ICategoryCommand> CategoryView { get { return new ObservableCollection<ICategoryCommand>( PresentationServices.NavigationCommandCategories.OrderBy(x => x.Order)); } } public void Refresh() { RaisePropertyChanged("CategoryView"); } } }
zzgaminginc-pointofssale
Samba.Modules.NavigationModule/NavigationViewModel.cs
C#
gpl3
791
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Samba.Modules.NavigationModule { /// <summary> /// Interaction logic for NavigationView.xaml /// </summary> [Export] public partial class NavigationView : UserControl { [ImportingConstructor] public NavigationView(NavigationViewModel viewModel) { InitializeComponent(); DataContext = viewModel; } } }
zzgaminginc-pointofssale
Samba.Modules.NavigationModule/NavigationView.xaml.cs
C#
gpl3
825
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Samba.Modules.NavigationModule")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.Modules.NavigationModule")] [assembly: AssemblyCopyright("Copyright © 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("514e84cb-9211-494e-b1ce-614046651fa7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzgaminginc-pointofssale
Samba.Modules.NavigationModule/Properties/AssemblyInfo.cs
C#
gpl3
1,472
using System; using System.ComponentModel.Composition; using System.Windows.Threading; using Microsoft.Practices.Prism.Events; using Microsoft.Practices.Prism.MefExtensions.Modularity; using Microsoft.Practices.Prism.Regions; using Samba.Domain.Models.Users; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Presentation.Common.Services; using Samba.Services; namespace Samba.Modules.NavigationModule { [ModuleExport(typeof(NavigationModule))] public class NavigationModule : ModuleBase { private readonly IRegionManager _regionManager; private readonly NavigationView _navigationView; [ImportingConstructor] public NavigationModule(IRegionManager regionManager, NavigationView navigationView) { _regionManager = regionManager; _navigationView = navigationView; PermissionRegistry.RegisterPermission(PermissionNames.OpenNavigation, PermissionCategories.Navigation, Resources.CanOpenNavigation); EventServiceFactory.EventService.GetEvent<GenericEvent<User>>().Subscribe( x => { if (x.Topic == EventTopicNames.UserLoggedIn) ActivateNavigation(); }); EventServiceFactory.EventService.GetEvent<GenericEvent<EventAggregator>>().Subscribe( x => { if (x.Topic == EventTopicNames.ActivateNavigation) ActivateNavigation(); }); } protected override void OnInitialization() { _regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(NavigationView)); } private void ActivateNavigation() { InteractionService.ClearMouseClickQueue(); if (AppServices.IsUserPermittedFor(PermissionNames.OpenNavigation)) { AppServices.ActiveAppScreen = AppScreens.Navigation; _regionManager.Regions[RegionNames.MainRegion].Activate(_navigationView); (_navigationView.DataContext as NavigationViewModel).Refresh(); } else if (AppServices.MainDataContext.IsCurrentWorkPeriodOpen) { EventServiceFactory.EventService.PublishEvent(EventTopicNames.ActivateTicketView); } else { AppServices.CurrentLoggedInUser.PublishEvent(EventTopicNames.UserLoggedOut); AppServices.LogoutUser(); } } } }
zzgaminginc-pointofssale
Samba.Modules.NavigationModule/NavigationModule.cs
C#
gpl3
2,675
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using Samba.Domain; using Samba.Domain.Models.Customers; using Samba.Domain.Models.Transactions; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Presentation.ViewModels; using Samba.Services; namespace Samba.Modules.CashModule { [Export] public class CashViewModel : ObservableObject { private IEnumerable<CashTransaction> _transactions; public IEnumerable<CashTransaction> Transactions { get { return _transactions ?? (_transactions = GetTransactions()); } } private IEnumerable<ICashTransactionViewModel> _incomeTransactions; public IEnumerable<ICashTransactionViewModel> IncomeTransactions { get { if (_incomeTransactions == null) { _incomeTransactions = Transactions.Where(x => x.TransactionType == (int)TransactionType.Income).Select( x => new CashTransactionViewModel(x)).OrderByDescending(x => x.Date).Cast<ICashTransactionViewModel>().ToList(); var operations = AppServices.CashService.GetCurrentCashOperationData(); var operationViewModel = new CashOperationViewModel() { CashPaymentValue = operations[0], CreditCardPaymentValue = operations[1], TicketPaymentValue = operations[2], Description = Resources.OperationIncome, Date = DateTime.Now }; (_incomeTransactions as IList).Insert(0, operationViewModel); if (AppServices.MainDataContext.CurrentWorkPeriod != null) { var dayStartCashViewModel = new CashOperationViewModel() { CashPaymentValue = AppServices.MainDataContext.CurrentWorkPeriod.CashAmount, CreditCardPaymentValue = AppServices.MainDataContext.CurrentWorkPeriod.CreditCardAmount, TicketPaymentValue = AppServices.MainDataContext.CurrentWorkPeriod.TicketAmount, Description = Resources.StartOfDay, Date = AppServices.MainDataContext.CurrentWorkPeriod.StartDate }; (_incomeTransactions as IList).Insert(0, dayStartCashViewModel); } } return _incomeTransactions; } } private IEnumerable<ICashTransactionViewModel> _expenseTransactions; public IEnumerable<ICashTransactionViewModel> ExpenseTransactions { get { return _expenseTransactions ?? (_expenseTransactions = Transactions.Where(x => x.TransactionType == (int)TransactionType.Expense).Select( x => new CashTransactionViewModel(x)).ToList().OrderByDescending(x => x.Date)); } } private ICashTransactionViewModel _selectedIncomeTransaction; public ICashTransactionViewModel SelectedIncomeTransaction { get { return _selectedIncomeTransaction; } set { _selectedIncomeTransaction = value; foreach (var cashTransactionViewModel in _incomeTransactions) cashTransactionViewModel.IsSelected = cashTransactionViewModel == value; } } private ICashTransactionViewModel _selectedExpenseTransaction; public ICashTransactionViewModel SelectedExpenseTransaction { get { return _selectedExpenseTransaction; } set { _selectedExpenseTransaction = value; foreach (var cashTransactionViewModel in _expenseTransactions) cashTransactionViewModel.IsSelected = cashTransactionViewModel == value; } } private CustomerViewModel _selectedCustomer; public CustomerViewModel SelectedCustomer { get { return _selectedCustomer; } set { _selectedCustomer = value; RaisePropertyChanged("IsCustomerDetailsVisible"); RaisePropertyChanged("SelectedCustomer"); } } public ICaptionCommand ActivateIncomeTransactionRecordCommand { get; set; } public ICaptionCommand ActivateExpenseTransactionRecordCommand { get; set; } public ICaptionCommand ApplyCashTransactionCommand { get; set; } public ICaptionCommand ApplyCreditCardTransactionCommand { get; set; } public ICaptionCommand ApplyTicketTransactionCommand { get; set; } public ICaptionCommand ApplyTransactionCommand { get; set; } public ICaptionCommand CancelTransactionCommand { get; set; } public ICaptionCommand DisplayCustomerAccountsCommand { get; set; } private string _description; public string Description { get { return _description; } set { _description = value; RaisePropertyChanged("Description"); } } private decimal _amount; public decimal Amount { get { return _amount; } set { _amount = value; RaisePropertyChanged("Amount"); } } private TransactionType _transactionType; public TransactionType TransactionType { get { return _transactionType; } set { _transactionType = value; RaisePropertyChanged("TransactionDescription"); } } public string TransactionDescription { get { switch (TransactionType) { case TransactionType.Income: return Resources.NewIncomeTransaction; case TransactionType.Expense: return Resources.NewExpenseTransaction; case TransactionType.Liability: return Resources.NewLiabilityTransaction; case TransactionType.Receivable: return Resources.NewReceivableTransaction; } throw new Exception("Invalid Transaction Type"); } } private int _activeView; public int ActiveView { get { return _activeView; } set { _activeView = value; RaisePropertyChanged("ActiveView"); RaisePropertyChanged("IsPaymentButtonsVisible"); RaisePropertyChanged("IsTransactionButtonVisible"); } } public bool IsCustomerDetailsVisible { get { return SelectedCustomer != null; } } public bool IsPaymentButtonsVisible { get { return TransactionType == TransactionType.Income || TransactionType == TransactionType.Expense; } } public bool IsTransactionButtonVisible { get { return !IsPaymentButtonsVisible; } } public decimal CashIncomeTotal { get { return IncomeTransactions.Sum(x => x.CashPaymentValue); } } public decimal CreditCardIncomeTotal { get { return IncomeTransactions.Sum(x => x.CreditCardPaymentValue); } } public decimal TicketIncomeTotal { get { return IncomeTransactions.Sum(x => x.TicketPaymentValue); } } public decimal CashExpenseTotal { get { return ExpenseTransactions.Sum(x => x.CashPaymentValue); } } public decimal CreditCardExpenseTotal { get { return ExpenseTransactions.Sum(x => x.CreditCardPaymentValue); } } public decimal TicketExpenseTotal { get { return ExpenseTransactions.Sum(x => x.TicketPaymentValue); } } public decimal CashTotal { get { return CashIncomeTotal - CashExpenseTotal; } } public decimal CreditCardTotal { get { return CreditCardIncomeTotal - CreditCardExpenseTotal; } } public decimal TicketTotal { get { return TicketIncomeTotal - TicketExpenseTotal; } } public CashViewModel() { ActivateIncomeTransactionRecordCommand = new CaptionCommand<string>(Resources.IncomeTransaction_r, OnActivateIncomeTransactionRecord, CanActivateIncomeTransactionRecord); ActivateExpenseTransactionRecordCommand = new CaptionCommand<string>(Resources.ExpenseTransaction_r, OnActivateExpenseTransactionRecord, CanActivateIncomeTransactionRecord); CancelTransactionCommand = new CaptionCommand<string>(Resources.Cancel, OnCancelTransaction); ApplyTransactionCommand = new CaptionCommand<string>(Resources.Save, OnApplyTransaction, CanApplyTransaction); ApplyCashTransactionCommand = new CaptionCommand<string>(Resources.Cash, OnApplyCashTransaction, CanApplyTransaction); ApplyCreditCardTransactionCommand = new CaptionCommand<string>(Resources.CreditCard, OnApplyCreditCardTransaction, CanApplyTransaction); ApplyTicketTransactionCommand = new CaptionCommand<string>(Resources.Voucher, OnApplyTicketTransaction, CanApplyTransaction); DisplayCustomerAccountsCommand = new CaptionCommand<string>(Resources.CustomerAccounts, OnDisplayCustomerAccounts); } private static void OnDisplayCustomerAccounts(string obj) { EventServiceFactory.EventService.PublishEvent(EventTopicNames.ActivateCustomerView); } private static bool CanActivateIncomeTransactionRecord(string arg) { return AppServices.MainDataContext.IsCurrentWorkPeriodOpen && AppServices.IsUserPermittedFor(PermissionNames.MakeCashTransaction); } private int GetSelectedCustomerId() { return SelectedCustomer != null ? SelectedCustomer.Id : 0; } private void OnApplyTransaction(string obj) { if (TransactionType == TransactionType.Liability) AppServices.CashService.AddLiability(GetSelectedCustomerId(), Amount, Description); else if (TransactionType == TransactionType.Receivable) AppServices.CashService.AddReceivable(GetSelectedCustomerId(), Amount, Description); ActivateTransactionList(); } private void OnApplyTicketTransaction(string obj) { if (TransactionType == TransactionType.Expense) AppServices.CashService.AddExpense(GetSelectedCustomerId(), Amount, Description, PaymentType.Ticket); else AppServices.CashService.AddIncome(GetSelectedCustomerId(), Amount, Description, PaymentType.Ticket); ActivateTransactionList(); } private void OnApplyCreditCardTransaction(string obj) { if (TransactionType == TransactionType.Expense) AppServices.CashService.AddExpense(GetSelectedCustomerId(), Amount, Description, PaymentType.CreditCard); else AppServices.CashService.AddIncome(GetSelectedCustomerId(), Amount, Description, PaymentType.CreditCard); ActivateTransactionList(); } private void OnApplyCashTransaction(string obj) { if (TransactionType == TransactionType.Expense) AppServices.CashService.AddExpense(GetSelectedCustomerId(), Amount, Description, PaymentType.Cash); else AppServices.CashService.AddIncome(GetSelectedCustomerId(), Amount, Description, PaymentType.Cash); ActivateTransactionList(); } private bool CanApplyTransaction(string arg) { return AppServices.MainDataContext.IsCurrentWorkPeriodOpen && !string.IsNullOrEmpty(Description) && Amount != 0; } private void OnCancelTransaction(string obj) { ActivateTransactionList(); } private void OnActivateIncomeTransactionRecord(object obj) { ResetTransactionData(TransactionType.Income); } private void OnActivateExpenseTransactionRecord(object obj) { ResetTransactionData(TransactionType.Expense); } internal void ResetTransactionData(TransactionType transactionType) { TransactionType = transactionType; Description = ""; Amount = 0; ActiveView = 1; } public void ActivateTransactionList() { ResetTransactionData(TransactionType); ActiveView = 0; _transactions = null; _incomeTransactions = null; _expenseTransactions = null; if (SelectedCustomer != null) { SelectedCustomer.Model.PublishEvent(EventTopicNames.ActivateCustomerAccount); SelectedCustomer = null; return; } RaisePropertyChanged("IncomeTransactions"); RaisePropertyChanged("ExpenseTransactions"); RaisePropertyChanged("CashIncomeTotal"); RaisePropertyChanged("CreditCardIncomeTotal"); RaisePropertyChanged("TicketIncomeTotal"); RaisePropertyChanged("CashExpenseTotal"); RaisePropertyChanged("CreditCardExpenseTotal"); RaisePropertyChanged("TicketExpenseTotal"); RaisePropertyChanged("CashTotal"); RaisePropertyChanged("CreditCardTotal"); RaisePropertyChanged("TicketTotal"); } private static IEnumerable<CashTransaction> GetTransactions() { return AppServices.MainDataContext.CurrentWorkPeriod != null ? AppServices.CashService.GetTransactions(AppServices.MainDataContext.CurrentWorkPeriod).ToList() : new List<CashTransaction>(); } public void MakePaymentToCustomer(Customer customer) { ResetTransactionData(TransactionType.Expense); SelectedCustomer = new CustomerViewModel(customer); } internal void GetPaymentFromCustomer(Customer customer) { ResetTransactionData(TransactionType.Income); SelectedCustomer = new CustomerViewModel(customer); } internal void AddLiabilityAmount(Customer customer) { ResetTransactionData(TransactionType.Liability); SelectedCustomer = new CustomerViewModel(customer); } internal void AddReceivableAmount(Customer customer) { ResetTransactionData(TransactionType.Receivable); SelectedCustomer = new CustomerViewModel(customer); } } }
zzgaminginc-pointofssale
Samba.Modules.CashModule/CashViewModel.cs
C#
gpl3
15,642