티스토리 뷰

WPF .NET

Kiosk 만들기 - Part9

kaki104 2023. 11. 7. 10:00
반응형

마감 화면 작업 진행합니다.

1. 마감 화면 작업

Deadline.xaml

<UserControl
    x:Class="PrismKiosk.Views.Deadline"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:PrismKiosk.Views"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:prism="http://prismlibrary.com/"
    xmlns:vm="clr-namespace:PrismKiosk.ViewModels"
    d:DataContext="{d:DesignInstance vm:DeadlineViewModel,
                                     IsDesignTimeCreatable=True}"
    d:DesignHeight="1080"
    d:DesignWidth="640"
    prism:ViewModelLocator.AutoWireViewModel="True"
    FontSize="20"
    mc:Ignorable="d">
    <UserControl.Resources>
        <Style x:Key="DataGridTextColumnRight" TargetType="TextBlock">
            <Setter Property="HorizontalAlignment" Value="Right" />
        </Style>
        <Style x:Key="HeaderTextCenter" TargetType="DataGridColumnHeader">
            <Setter Property="HorizontalAlignment" Value="Center" />
        </Style>
    </UserControl.Resources>

    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <TextBlock
                Margin="0,10"
                FontWeight="Bold"
                Text="마감" />
            <Button
                Grid.Column="1"
                Width="100"
                HorizontalAlignment="Right"
                VerticalAlignment="Center"
                Command="{Binding LogoutCommand}"
                Content="로그아웃" />
        </Grid>
        <StackPanel
            Grid.Row="1"
            Margin="0,10,0,0"
            Orientation="Horizontal">
            <TextBlock VerticalAlignment="Center" Text="마감일" />
            <DatePicker Margin="10,0,0,0" SelectedDate="{Binding DeadlineDatetime, Mode=TwoWay}" />
            <Button
                Width="100"
                Margin="10,0,0,0"
                Command="{Binding SearchCommand}"
                Content="검색" />
        </StackPanel>
        <TabControl Grid.Row="2" Margin="0,10,0,0">
            <TabItem Header="매출 목록">
                <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding CurrentOrders}">
                    <DataGrid.Columns>
                        <DataGridTextColumn Binding="{Binding OrderId}" Header="주문Id" />
                        <DataGridTextColumn
                            Binding="{Binding TotalQuantity, StringFormat={}{0:N0}}"
                            ElementStyle="{StaticResource DataGridTextColumnRight}"
                            Header="총수량" />
                        <DataGridTextColumn
                            Binding="{Binding TotalAmount, StringFormat={}{0:N0}}"
                            ElementStyle="{StaticResource DataGridTextColumnRight}"
                            Header="총금액" />
                        <DataGridTextColumn
                            Binding="{Binding ReceivedAmount, StringFormat={}{0:N0}}"
                            ElementStyle="{StaticResource DataGridTextColumnRight}"
                            Header="받은 금액" />
                        <DataGridTextColumn
                            Binding="{Binding Change, StringFormat={}{0:N0}}"
                            ElementStyle="{StaticResource DataGridTextColumnRight}"
                            Header="거스름돈" />
                        <DataGridTextColumn Binding="{Binding OrderDatetime, StringFormat={}{0:g}}" Header="결제 일시" />
                        <DataGridCheckBoxColumn Binding="{Binding IsDeadline}" Header="마감여부" />
                        <DataGridTextColumn Binding="{Binding DeadlineDatetime, StringFormat={}{0:g}}" Header="마감일시" />
                    </DataGrid.Columns>
                </DataGrid>
            </TabItem>
        </TabControl>

        <StackPanel
            Grid.Row="3"
            Margin="0,10"
            Orientation="Horizontal">
            <Button
                Width="100"
                Command="{Binding MakeDeadlineCommand}"
                Content="마감" />
        </StackPanel>
    </Grid>
</UserControl>

* DatePicker를 이용해서 마감일(DeadlineDatetime)을 변경해서 조회할 수 있도록 만들었습니다.

* CurrentOrders가 현재 마감일 데이터의 목록입니다.

 

DeadlineViewModel.cs

using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using PrismKiosk.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace PrismKiosk.ViewModels
{
    /// <summary>
    /// 마감 뷰모델
    /// </summary>
    public class DeadlineViewModel : ViewModelBase
    {
        private IList<Order> _currentOrders;
        /// <summary>
        /// 현재 주문 목록
        /// </summary>
        public IList<Order> CurrentOrders
        {
            get => _currentOrders;
            set => SetProperty(ref _currentOrders, value);
        }
        /// <summary>
        /// 마감 커맨드
        /// </summary>
        public ICommand MakeDeadlineCommand { get; set; }
        /// <summary>
        /// 로그아웃 커맨드
        /// </summary>
        public ICommand LogoutCommand { get; set; }
        /// <summary>
        /// 검색 커맨드
        /// </summary>
        public ICommand SearchCommand { get; set; }

        private DateTime _deadlineDatetime;
        /// <summary>
        /// 마감일
        /// </summary>
        public DateTime DeadlineDatetime
        {
            get => _deadlineDatetime;
            set => SetProperty(ref _deadlineDatetime, value);
        }
        /// <summary>
        /// 기본 생성자
        /// </summary>
        public DeadlineViewModel()
        {
        }
        /// <summary>
        /// 런타임 생성자
        /// </summary>
        /// <param name="containerProvider"></param>
        public DeadlineViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            Init();
        }
        /// <summary>
        /// 초기화
        /// </summary>
        private void Init()
        {
            MakeDeadlineCommand = new DelegateCommand(OnMakeDeadline);
            LogoutCommand = new DelegateCommand(OnLogout);
            //비동기 메서드 호출
            SearchCommand = new DelegateCommand(async () => await OnSearchAsync());
        }
        /// <summary>
        /// 검색
        /// </summary>
        private async Task OnSearchAsync()
        {
            //검색 조건의 일자가 오늘이면
            if (DeadlineDatetime.Date == DateTime.Today)
            {
                CurrentOrders = AppContext.Orders;
            }
            else
            {
                //데이터를 db에서 조회하거나 서비스에서 조회를 하면 비동기로 처리되기 때문에 비동기 메서드로 만들었습니다.
                await Task.Delay(10);

                //이전에 마감된 데이터를 조회해서 출력해야함 - 여기는 셈플 데이터로 대체
                List<Order> list = new();
                for (int i = 0; i < 100; i++)
                {
                    list.Add(new Order
                    {
                        OrderId = Guid.NewGuid(),
                        TotalQuantity = i,
                        TotalAmount = 10000 + i,
                        ReceivedAmount = 10000 + i,
                        OrderDatetime = DeadlineDatetime.Date,
                        IsDeadline = true,
                        DeadlineDatetime = DeadlineDatetime.Date
                    });
                }
                CurrentOrders = list;
            }
        }

        /// <summary>
        /// 로그아웃
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void OnLogout()
        {
            MessageBoxResult result = MessageBox.Show("로그아웃 하시겠습니까?", "확인", MessageBoxButton.YesNo);
            if (result != MessageBoxResult.Yes)
            {
                return;
            }
            LogoutManager();
        }
        /// <summary>
        /// 마감
        /// </summary>
        private void OnMakeDeadline()
        {
            //모든 데이터가 마감되어 있으면 더이상 마감하지 않음
            if (CurrentOrders.All(o => o.IsDeadline))
            {
                _ = MessageBox.Show("모든 주문이 마감처리되어 있습니다.");
                return;
            }

            MessageBoxResult result = MessageBox.Show("마감처리 하시겠습니까?", "확인", MessageBoxButton.YesNo);
            if (result != MessageBoxResult.Yes)
            {
                return;
            }
            foreach (Order order in CurrentOrders)
            {
                order.IsDeadline = true;
                order.DeadlineDatetime = DateTime.Now;
            }
        }

        public override async void OnNavigatedTo(NavigationContext navigationContext)
        {
            DeadlineDatetime = DateTime.Now;
            await OnSearchAsync();
        }
    }
}

* OnNavigatedTo로 진입하면, 마감일을 오늘날짜로 설정하고 OnSearchAsync()를 호출해서 데이터를 조회합니다.

* 마감 버튼을 누르면 OnMakeDeadline() 메서드를 호출하고 CurrentOrder에있는 데이터를 확인해서 마감전인지 아닌지 확인합니다. 미 마감 데이터가 있으면 모든 데이터를 마감합니다.

이 셈플에서는 모든 데이터를 다시 마감하는데, 일반적으로는 미 마감 데이터에 대해서만 처리를 할 것 같습니다.

2. 소스

kaki104/PrismKiosk at Part9/edit-deadline (github.com)

 

GitHub - kaki104/PrismKiosk

Contribute to kaki104/PrismKiosk development by creating an account on GitHub.

github.com

 

반응형
댓글