/// <summary>
        /// get month identity
        /// </summary>
        /// <param name="startId">start month identity</param>
        /// <param name="endId">end month identity</param>
        /// <returns></returns>
        public List<HeadEntity> getEntities(MonthIdentity startId,
                MonthIdentity endId)
        {
            if (startId == null)
            {
                startId = _coreDriver.StartMonthId;
            }
            if (endId == null)
            {
                endId = _coreDriver.CurCalendarMonthId;
            }
            List<HeadEntity> ret = new List<HeadEntity>();
            foreach (HeadEntity head in _list)
            {
                if (head.MonthID.CompareTo(endId) > 0)
                {
                    break;
                }

                if (head.MonthID.CompareTo(startId) >= 0)
                {
                    ret.Add(head);
                }
            }
            return ret;
        }
        /// <summary>
        /// get month identity
        /// </summary>
        /// <param name="startId">start month identity</param>
        /// <param name="endId">end month identity</param>
        /// <returns></returns>
        public List <HeadEntity> getEntities(MonthIdentity startId,
                                             MonthIdentity endId)
        {
            if (startId == null)
            {
                startId = _coreDriver.StartMonthId;
            }
            if (endId == null)
            {
                endId = _coreDriver.CurCalendarMonthId;
            }
            List <HeadEntity> ret = new List <HeadEntity>();

            foreach (HeadEntity head in _list)
            {
                if (head.MonthID.CompareTo(endId) > 0)
                {
                    break;
                }

                if (head.MonthID.CompareTo(startId) >= 0)
                {
                    ret.Add(head);
                }
            }
            return(ret);
        }
 /// <summary>
 /// Get amount
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public CurrencyAmount GetAmount(MonthIdentity id)
 {
     if (_list.ContainsKey(id))
     {
         CurrencyAmount amount;
         _list.TryGetValue(id, out amount);
         return new CurrencyAmount(amount);
     }
     return new CurrencyAmount();
 }
        /// <summary>
        /// create root folder for creation test in 2012_07
        /// </summary>
        /// <param name="name"></param>
        /// <param name="coreDriver"></param>
        /// <returns></returns>
        public static async Task EstablishFolder_2012_07(String name
                                                         , CoreDriver coreDriver)
        {
            coreDriver.RootFolder = await CreateRootFolder(name);

            await coreDriver.RestartAsync();

            MonthIdentity monthId;

            monthId = new MonthIdentity(2012, 7);
            coreDriver.SetStartMonthId(monthId);
        }
        /// <summary>
        /// get amount
        /// </summary>
        /// <param name="monthID"></param>
        /// <returns></returns>
        public CurrencyAmount getAmount(MonthIdentity monthID)
        {
            CurrencyAmount sum = new CurrencyAmount();
            CurrencyAmount amount;

            if (_amountList.TryGetValue(monthID, out amount))
            {
                sum.AddTo(amount);
            }

            return(sum);
        }
        /// <summary>
        /// add currency amount
        /// </summary>
        /// <param name="monthId"></param>
        /// <param name="amount"></param>
        internal void addAmount(MonthIdentity monthId, CurrencyAmount amount)
        {
            CurrencyAmount v1;

            if (_amountList.TryGetValue(monthId, out v1))
            {
                v1.AddTo(amount);
                return;
            }
            // put
            _amountList.Add(monthId, amount);
        }
        /// <summary>
        /// Get sum of amount from start month to end month
        /// </summary>
        /// <param name="startId">id of start month</param>
        /// <param name="endId">id of end month</param>
        /// <returns></returns>
        public CurrencyAmount GetSumAmount(MonthIdentity startId,
                MonthIdentity endId)
        {
            CurrencyAmount sum = new CurrencyAmount();
            foreach (var item in _list)
            {
                if (item.Key.CompareTo(startId) >= 0 && item.Key.CompareTo(endId) <= 0)
                {
                    sum.AddTo(item.Value);
                }
            }

            return sum;
        }
        /// <summary>
        /// Add amount 
        /// </summary>
        /// <param name="monthId"></param>
        /// <param name="amount"></param>
        internal void AddAmount(MonthIdentity monthId, CurrencyAmount amount)
        {
            _sum.AddTo(amount);

            if (_list.ContainsKey(monthId))
            {
                CurrencyAmount sum;
                _list.TryGetValue(monthId, out sum);
                sum.AddTo(amount);
            }
            else
            {
                _list.Add(monthId, new CurrencyAmount(amount));
            }
        }
Example #9
0
        /// <summary>
        /// set starting month id
        /// </summary>
        /// <param name="monthId"></param>
        /// <returns></returns>
        public bool SetStartMonthId(MonthIdentity monthId)
        {
            // check
            if (this._startMonthId.CompareTo(monthId) <= 0)
            {
                return(false);
            }

            this._startMonthId = monthId;

            // save meta data
            saveMetaData();

            return(true);
        }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="monthId"></param>
        /// <returns></returns>
        public ObservableCollection <AbstractAdapterItem> GetItems(MonthIdentity monthId)
        {
            CoreDriver coreDriver = _dataCore.BackendCoreDriver;

            if (coreDriver.IsInitialize == false)
            {
                return(_items);
            }

            if (_curMonthId == null ||
                _curMonthId.Equals(monthId) == false)
            {
                // clear
                _items.Clear();

                // change month
                _curMonthId = monthId;
                GLAccountBalanceCollection balCol = coreDriver.TransMgmt.AccountBalanceCol;
                MasterDataManagement       mdMgmt = coreDriver.MdMgmt;

                // for each cost group
                List <CostReportItem> costList = new List <CostReportItem>();
                foreach (GLAccountGroupENUM group in GLAccountGroup.COST_GROUP)
                {
                    List <MasterDataIdentity_GLAccount> ids = mdMgmt
                                                              .GetGLAccountsBasedGroup(group);
                    // for g/l account in each group
                    foreach (MasterDataIdentity_GLAccount id in ids)
                    {
                        // get master data
                        GLAccountMasterData masterData = (GLAccountMasterData)mdMgmt
                                                         .GetMasterData(id, MasterDataType.GL_ACCOUNT);
                        // get balance item
                        GLAccountBalanceItem item = balCol.GetBalanceItem(id);
                        costList.Add(new CostReportItem(id, masterData.Descp
                                                        , item.GetAmount(_curMonthId), this));
                    }
                }
                // sort
                costList.Sort();
                foreach (CostReportItem costItem in costList)
                {
                    _items.Add(costItem);
                }
            }

            return(_items);
        }
Example #11
0
        /// <summary>
        /// get amount
        /// </summary>
        /// <param name="startId">start month identity</param>
        /// <param name="endId">end month identity</param>
        /// <returns></returns>
        public CurrencyAmount getAmount(MonthIdentity startId, MonthIdentity endId)
        {
            CurrencyAmount    amount = new CurrencyAmount();
            List <HeadEntity> docs   = this.getEntities(startId, endId);

            foreach (HeadEntity head in docs)
            {
                List <ItemEntity> items = head.Items;
                foreach (ItemEntity item in items)
                {
                    amount.AddTo(getAmountFromItem(item));
                }
            }

            return(amount);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="monthId"></param>
        /// <returns></returns>
        public ObservableCollection<AbstractAdapterItem> GetItems(MonthIdentity monthId)
        {
            CoreDriver coreDriver = _dataCore.BackendCoreDriver;
            if (coreDriver.IsInitialize == false)
            {
                return _items;
            }

            if (_curMonthId == null
                || _curMonthId.Equals(monthId) == false)
            {
                // clear
                _items.Clear();

                // change month
                _curMonthId = monthId;
                GLAccountBalanceCollection balCol = coreDriver.TransMgmt.AccountBalanceCol;
                MasterDataManagement mdMgmt = coreDriver.MdMgmt;

                // for each cost group
                List<CostReportItem> costList = new List<CostReportItem>();
                foreach (GLAccountGroupENUM group in GLAccountGroup.COST_GROUP)
                {
                    List<MasterDataIdentity_GLAccount> ids = mdMgmt
                            .GetGLAccountsBasedGroup(group);
                    // for g/l account in each group
                    foreach (MasterDataIdentity_GLAccount id in ids)
                    {
                        // get master data
                        GLAccountMasterData masterData = (GLAccountMasterData)mdMgmt
                                .GetMasterData(id, MasterDataType.GL_ACCOUNT);
                        // get balance item
                        GLAccountBalanceItem item = balCol.GetBalanceItem(id);
                        costList.Add(new CostReportItem(id, masterData.Descp
                            , item.GetAmount(_curMonthId), this));
                    }
                }
                // sort 
                costList.Sort();
                foreach(CostReportItem costItem in costList)
                {
                    _items.Add(costItem);
                }                
            }

            return _items;
        }
Example #13
0
        /// <summary>
        /// check customer document
        /// </summary>
        /// <param name="customerDoc"></param>
        private static void checkCustomerDoc(HeadEntity customerDoc)
        {
            // check document number
            Assert.AreEqual(TestData.DOC_NUM2, customerDoc.DocNumber
                            .ToString());
            // check posting date
            Assert.AreEqual(TestData.DATE_2012_07, customerDoc.PstDate.ToString(
                                MasterDataUtils.DATE_FORMAT));
            MonthIdentity monthId = customerDoc.MonthID;

            Assert.AreEqual(TestData.YEAR, monthId.FiscalYear);
            Assert.AreEqual(TestData.MONTH_07, monthId.FiscalMonth);
            // check document type
            Assert.AreEqual(DocumentType.CUSTOMER_INVOICE,
                            customerDoc.DocType);
            // check text
            Assert.AreEqual(TestData.TEXT_CUSTOMER_DOC, customerDoc.DocText);
            // check is reversed
            Assert.AreEqual(false, customerDoc.IsReversed);

            Assert.AreEqual(2, customerDoc.ItemCount);
            List <ItemEntity> items = customerDoc.Items;

            // check revenue item
            Assert.AreEqual(0, items[0].LineNum);
            Assert.AreEqual(AccountType.GL_ACCOUNT, items[0].AccType);
            Assert.AreEqual(CreditDebitIndicator.CREDIT, items[0].CdIndicator);
            Assert.AreEqual(TestData.AMOUNT_CUSTOMER, items[0].Amount);
            Assert.AreEqual(null, items[0].Customer);
            Assert.AreEqual(null, items[0].Vendor);
            Assert.AreEqual(TestData.GL_ACCOUNT_REV, items[0].GLAccount
                            .ToString());
            Assert.AreEqual(null, items[0].BusinessArea);

            // check customer item
            Assert.AreEqual(1, items[1].LineNum);
            Assert.AreEqual(AccountType.CUSTOMER, items[1].AccType);
            Assert.AreEqual(CreditDebitIndicator.DEBIT, items[1].CdIndicator);
            Assert.AreEqual(TestData.AMOUNT_CUSTOMER, items[1].Amount);
            Assert.AreEqual(TestData.CUSTOMER1, items[1].Customer.ToString());
            Assert.AreEqual(null, items[1].Vendor);
            Assert.AreEqual(TestData.GL_ACCOUNT_BANK, items[1].GLAccount
                            .ToString());
            Assert.AreEqual(null, items[1].BusinessArea);
        }
Example #14
0
        /// <summary>
        /// check vendor document
        /// </summary>
        /// <param name="vendorDoc"></param>
        private static void checkVendorDoc(HeadEntity vendorDoc)
        {
            // check document number
            Assert.AreEqual(TestData.DOC_NUM1, vendorDoc.DocNumber
                            .ToString());
            // check posting date
            Assert.AreEqual(TestData.DATE_2012_07, vendorDoc.PstDate.ToString(MasterDataUtils.DATE_FORMAT));
            MonthIdentity monthId = vendorDoc.MonthID;

            Assert.AreEqual(TestData.YEAR, monthId.FiscalYear);
            Assert.AreEqual(TestData.MONTH_07, monthId.FiscalMonth);
            // check document type
            Assert.AreEqual(DocumentType.VENDOR_INVOICE, vendorDoc.DocType);
            // check text
            Assert.AreEqual(TestData.TEXT_VENDOR_DOC, vendorDoc.DocText);
            // check is reversed
            Assert.AreEqual(false, vendorDoc.IsReversed);

            Assert.AreEqual(2, vendorDoc.ItemCount);
            List <ItemEntity> items = vendorDoc.Items;

            // check the vendor item
            Assert.AreEqual(0, items[0].LineNum);
            Assert.AreEqual(AccountType.VENDOR, items[0].AccType);
            Assert.AreEqual(CreditDebitIndicator.CREDIT, items[0].CdIndicator);
            Assert.AreEqual(TestData.AMOUNT_VENDOR, items[0].Amount);
            Assert.AreEqual(null, items[0].Customer);
            Assert.AreEqual(TestData.VENDOR_BUS, items[0].Vendor.ToString());
            Assert.AreEqual(TestData.GL_ACCOUNT_CASH, items[0].GLAccount
                            .ToString());
            Assert.AreEqual(null, items[0].BusinessArea);

            // check cost item
            Assert.AreEqual(1, items[1].LineNum);
            Assert.AreEqual(AccountType.GL_ACCOUNT, items[1].AccType);
            Assert.AreEqual(CreditDebitIndicator.DEBIT, items[1].CdIndicator);
            Assert.AreEqual(TestData.AMOUNT_VENDOR, items[1].Amount);
            Assert.AreEqual(null, items[1].Customer);
            Assert.AreEqual(null, items[1].Vendor);
            Assert.AreEqual(TestData.GL_ACCOUNT_COST, items[1].GLAccount
                            .ToString());
            Assert.AreEqual(TestData.BUSINESS_AREA_WORK, items[1].BusinessArea
                            .ToString());
        }
        public static void CheckAccountBalance(CoreDriver coreDriver)
        {
            TransactionDataManagement  transMgmt = coreDriver.TransMgmt;
            GLAccountBalanceCollection balCol    = transMgmt.AccountBalanceCol;

            MonthIdentity month07 = new MonthIdentity(2012, 7);
            MonthIdentity month08 = new MonthIdentity(2012, 8);

            MasterDataIdentity_GLAccount glAccount2 = new MasterDataIdentity_GLAccount(
                TestData.GL_ACCOUNT_CASH);
            GLAccountBalanceItem balItem = balCol.GetBalanceItem(glAccount2);
            CurrencyAmount       amount2 = new CurrencyAmount(123.45 - 23.45);

            Assert.AreEqual(amount2, balItem.Sum);
            Assert.AreEqual(amount2, balItem.GetAmount(month07));
            Assert.AreEqual(new CurrencyAmount(), balItem.GetAmount(month08));

            Assert.AreEqual(amount2, balCol.GetGroupBalance(GLAccountGroupENUM.CASH));
            Assert.AreEqual(amount2,
                            balCol.GetGroupBalance(GLAccountGroupENUM.CASH, month07, month07));
            Assert.AreEqual(new CurrencyAmount(),
                            balCol.GetGroupBalance(GLAccountGroupENUM.CASH, month08, month08));

            // cost
            Assert.AreEqual(new CurrencyAmount(123.45),
                            balCol.GetGroupBalance(GLAccountGroupENUM.COST_PURE));
            Assert.AreEqual(new CurrencyAmount(123.45), balCol.GetGroupBalance(
                                GLAccountGroupENUM.COST_PURE, month07, month07));
            Assert.AreEqual(new CurrencyAmount(), balCol.GetGroupBalance(
                                GLAccountGroupENUM.COST_PURE, month08, month08));

            // revenue
            Assert.AreEqual(new CurrencyAmount(-543.21),
                            balCol.GetGroupBalance(GLAccountGroupENUM.SALARY));
            Assert.AreEqual(new CurrencyAmount(-543.21),
                            balCol.GetGroupBalance(GLAccountGroupENUM.SALARY, month07, month07));
            Assert.AreEqual(new CurrencyAmount(),
                            balCol.GetGroupBalance(GLAccountGroupENUM.SALARY, month08, month08));
        }
        public static void CheckAccountBalance(CoreDriver coreDriver)
        {
            TransactionDataManagement transMgmt = coreDriver.TransMgmt;
            GLAccountBalanceCollection balCol = transMgmt.AccountBalanceCol;

            MonthIdentity month07 = new MonthIdentity(2012, 7);
            MonthIdentity month08 = new MonthIdentity(2012, 8);

            MasterDataIdentity_GLAccount glAccount2 = new MasterDataIdentity_GLAccount(
                    TestData.GL_ACCOUNT_CASH);
            GLAccountBalanceItem balItem = balCol.GetBalanceItem(glAccount2);
            CurrencyAmount amount2 = new CurrencyAmount(123.45 - 23.45);
            Assert.AreEqual(amount2, balItem.Sum);
            Assert.AreEqual(amount2, balItem.GetAmount(month07));
            Assert.AreEqual(new CurrencyAmount(), balItem.GetAmount(month08));

            Assert.AreEqual(amount2, balCol.GetGroupBalance(GLAccountGroupENUM.CASH));
            Assert.AreEqual(amount2,
                    balCol.GetGroupBalance(GLAccountGroupENUM.CASH, month07, month07));
            Assert.AreEqual(new CurrencyAmount(),
                    balCol.GetGroupBalance(GLAccountGroupENUM.CASH, month08, month08));

            // cost
            Assert.AreEqual(new CurrencyAmount(123.45),
                    balCol.GetGroupBalance(GLAccountGroupENUM.COST_PURE));
            Assert.AreEqual(new CurrencyAmount(123.45), balCol.GetGroupBalance(
                    GLAccountGroupENUM.COST_PURE, month07, month07));
            Assert.AreEqual(new CurrencyAmount(), balCol.GetGroupBalance(
                    GLAccountGroupENUM.COST_PURE, month08, month08));

            // revenue
            Assert.AreEqual(new CurrencyAmount(-543.21),
                    balCol.GetGroupBalance(GLAccountGroupENUM.SALARY));
            Assert.AreEqual(new CurrencyAmount(-543.21),
                    balCol.GetGroupBalance(GLAccountGroupENUM.SALARY, month07, month07));
            Assert.AreEqual(new CurrencyAmount(),
                    balCol.GetGroupBalance(GLAccountGroupENUM.SALARY, month08, month08));
        }
Example #17
0
        /// <summary>
        /// establish folder
        /// </summary>
        private async Task establishFolderAsync()
        {
            // set meta data
            int year  = DateTime.Today.Year;
            int month = DateTime.Today.Month;

            // set starting month identity
            try
            {
                _startMonthId = new MonthIdentity(year, month);
                // _curMonthId = new MonthIdentity(year, month);
            }
            catch (FiscalYearRangeException e)
            {
                this.logDebugInfo(this.GetType(), 300, e.ToString(),
                                  MessageType.ERRO);
                throw new SystemException(e);// bug
            }
            catch (FiscalMonthRangeException e)
            {
                this.logDebugInfo(this.GetType(), 302, e.ToString(),
                                  MessageType.ERRO);
                throw new SystemException(e);// bug
            }

            await saveMetaDataAsync();

            foreach (var item in _managements)
            {
                if (item.Value.NeedEstablishFile)
                {
                    await item.Value.EstablishFilesAsync();
                }
            }
            _isInitialized = true;
        }
Example #18
0
        public CoreDriver()
        {
            _infos = new List <DebugInformation>();

            _listenerManagement = new ListenersManagement();
            // _listenerManagement.addCloseLedgerListener(_closeLedgerListener);

            // managements
            _managements = new Dictionary <String, AbstractManagement>();

            MasterDataManagement mdMgmt = new MasterDataManagement(this);

            _managements.Add(MASTERDATA, mdMgmt);


            _managements.Add(TRANDATA, new TransactionDataManagement(this, mdMgmt));
            _managements.Add(REPORTDATA, new ReportsManagement(this, mdMgmt));
            _managements.Add(TEMPLATE, new EntryTemplatesManagement(this, mdMgmt));

            _startMonthId = null;

            _isInitialized = false;
            _language      = Language.SimpleChinese;
        }
        /// <summary>
        /// Get Ledger
        /// </summary>
        /// <param name="monthId"></param>
        /// <returns></returns>
        public MonthLedger GetLedger(MonthIdentity monthId)
        {
            // get current calendar month
            MonthIdentity curMonthId = _coreDriver.CurCalendarMonthId;

            // check whether ledger beyond the range
            if (_coreDriver.StartMonthId.CompareTo(monthId) > 0
                    || curMonthId.CompareTo(monthId) < 0)
            {
                return null;
            }

            // create new month ledger
            MonthLedger monthLedger;
            if (!_list.TryGetValue(monthId, out monthLedger))
            {
                monthLedger = new MonthLedger(monthId);
                _list.Add(monthId, monthLedger);
            }

            return monthLedger;
        }
 /// <summary>
 /// add currency amount
 /// </summary>
 /// <param name="monthId"></param>
 /// <param name="amount"></param>
 internal void addAmount(MonthIdentity monthId, CurrencyAmount amount)
 {
     CurrencyAmount v1;
     if (_amountList.TryGetValue(monthId, out v1))
     {
         v1.AddTo(amount);
         return;
     }
     // put
     _amountList.Add(monthId, amount);
 }
        /// <summary>
        /// get amount
        /// </summary>
        /// <param name="monthID"></param>
        /// <returns></returns>
        public CurrencyAmount getAmount(MonthIdentity monthID)
        {
            CurrencyAmount sum = new CurrencyAmount();
            CurrencyAmount amount;
            if (_amountList.TryGetValue(monthID, out amount))
            {
                sum.AddTo(amount);
            }

            return sum;
        }
 /// <summary>
 /// create root folder for creation test in 2012_07
 /// </summary>
 /// <param name="name"></param>
 /// <param name="coreDriver"></param>
 /// <returns></returns>
 public static async Task EstablishFolder_2012_07(String name
     , CoreDriver coreDriver)
 {
     coreDriver.RootFolder = await CreateRootFolder(name);
     await coreDriver.RestartAsync();
     MonthIdentity monthId;
     monthId = new MonthIdentity(2012, 7);
     coreDriver.SetStartMonthId(monthId);
 }
Example #23
0
 public MonthItem(MonthIdentity monthId, MonthAdapter parent)
     : base(monthId, String.Empty, parent)
 {
 }
Example #24
0
        /// <summary>
        /// load meta data
        /// </summary>
        /// <exception cref="MetaDataFormatException">Format exception of the meta-data file</exception>
        private async Task loadMetaDataAsync()
        {
            StorageFile mdFile = await _rootFolder.GetFileAsync(META_DATA);

            if (mdFile == null)
            {
                return;
            }

            try
            {
                IList <string> lines = await FileIO.ReadLinesAsync(mdFile);

                int startYear     = 0;
                int startMonth    = 0;
                int versionNumber = 0;
                foreach (string line in lines)
                {
                    String[] values = line.Split('=');
                    if (values.Length != 2)
                    {
                        throw new MetaDataFormatException("Meta data format error.");
                    }

                    if (values[0].Equals(START_MONTH_TAG))
                    {
                        startMonth = Int32.Parse(values[1]);
                    }
                    else if (values[0].Equals(START_YEAR_TAG))
                    {
                        startYear = Int32.Parse(values[1]);
                    }
                    else if (values[0].Equals(VERSION))
                    {
                        versionNumber = Int32.Parse(values[1]);
                    }
                }

                _startMonthId = new MonthIdentity(startYear, startMonth);
                // _curMonthId = new MonthIdentity(curYear, curMonth);
                // check version
                bool ret = this.versionCheck(versionNumber);
                if (ret == false)
                {
                    throw new MetaDataFormatException("Version Error");
                }
            }
            catch (ArgumentNullException e)
            {
                throw new MetaDataFormatException(e.Message);
            }
            catch (FormatException e)
            {
                throw new MetaDataFormatException(e.Message);
            }
            catch (OverflowException e)
            {
                throw new MetaDataFormatException(e.Message);
            }
            finally
            {
            }
        }
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="docNum"></param>
 /// <param name="monthIdentity"></param>
 public DocumentIdentity(DocumentNumber docNum, MonthIdentity monthIdentity)
 {
     _docNumber = docNum;
     _monthIdentity = monthIdentity;
 }
        /// <summary>
        /// load month identity
        /// </summary>
        /// <param name="monthId"></param>
        /// <returns></returns>
        /// <exception cref="TransactionDataFileFormatException"></exception>
        public async Task<MonthLedger> Load(MonthIdentity monthId)
        {
            // construct month ledger
            MonthLedger monthledger = new MonthLedger(monthId);
            _list.Add(monthId, monthledger);

            _coreDriver.logDebugInfo(
                    this.GetType(),
                    102,
                    String.Format("Loading transaction data {0} ...",
                            monthId.ToString()), MessageType.INFO);

            // get file path
            StorageFile file = await generateFilePath(monthId, false);
            if (file == null)
            {// empty
                return monthledger;
            }
            _coreDriver.logDebugInfo(this.GetType(), 109,
                    String.Format("Transaction data file: {0} .", file.Path),
                    MessageType.INFO);
            try
            {
                string text = await FileIO.ReadTextAsync(file);
                XDocument xdoc = XDocument.Parse(text);

                XElement rootElem = xdoc.Element(TransDataUtils.XML_ROOT);
                // no root element
                if (rootElem == null)
                {
                    throw new TransactionDataFileFormatException(file.Path);
                }

                // -------------------------------------------------------------------
                // parse all the documents
                foreach (XElement elem in rootElem.Elements(TransDataUtils.XML_DOCUMENT))
                {
                    HeadEntity head = HeadEntity.Parse(_coreDriver,
                            _masterDataMgmt, elem);
                    _coreDriver
                            .logDebugInfo(
                                    this.GetType(),
                                    172,
                                    String.Format(
                                            "Document {0} add to list during loading.",
                                            head.DocIdentity
                                                    .ToString()),
                                    MessageType.INFO);
                    monthledger.Add(head);

                    // raise load document
                    _coreDriver.ListenerMgmt.LoadDoc(this, head);

                    // raise reverse document
                    if (head.IsReversed)
                        _coreDriver.ListenerMgmt.ReverseDoc(head);
                }
                // -----------------------------------------------------------------

                return monthledger;
            }
            catch (TransactionDataFileFormatException e)
            {
                _coreDriver.logDebugInfo(this.GetType(), 170, e.Message,
                        MessageType.ERRO);
                throw new TransactionDataFileFormatException(file.Path);
            }

        }
        public CoreDriver()
        {
            _infos = new List<DebugInformation>();

            _listenerManagement = new ListenersManagement();
            // _listenerManagement.addCloseLedgerListener(_closeLedgerListener);

            // managements
            _managements = new Dictionary<String, AbstractManagement>();

            MasterDataManagement mdMgmt = new MasterDataManagement(this);
            _managements.Add(MASTERDATA, mdMgmt);


            _managements.Add(TRANDATA, new TransactionDataManagement(this, mdMgmt));
            _managements.Add(REPORTDATA, new ReportsManagement(this, mdMgmt));
            _managements.Add(TEMPLATE, new EntryTemplatesManagement(this, mdMgmt));

            _startMonthId = null;

            _isInitialized = false;
            _language = Language.SimpleChinese;
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="docNum"></param>
 /// <param name="fiscalYear"></param>
 /// <param name="fiscalMonth"></param>
 /// <exception cref="FiscalYearRangeException"></exception>
 /// <exception cref="FiscalMonthRangeException"></exception>
 public DocumentIdentity(DocumentNumber docNum, int fiscalYear,
         int fiscalMonth)
 {
     _docNumber = docNum;
     _monthIdentity = new MonthIdentity(fiscalYear, fiscalMonth);
 }
 /// <summary>
 /// store month identity
 /// </summary>
 /// <param name="monthId"></param>
 public async void Store(MonthIdentity monthId)
 {
     await StoreAsync(monthId);
 }
        /// <summary>
        /// get ledger
        /// </summary>
        /// <param name="fiscalYear"></param>
        /// <param name="fiscalMonth"></param>
        /// <returns></returns>
        public MonthLedger GetLedger(int fiscalYear, int fiscalMonth)
        {
            MonthIdentity monthId;
            try
            {
                monthId = new MonthIdentity(fiscalYear, fiscalMonth);
            }
            catch (FiscalYearRangeException)
            {
                return null;
            }
            catch (FiscalMonthRangeException)
            {
                return null;
            }

            return GetLedger(monthId);
        }
 /// <summary>
 /// get file 
 /// </summary>
 /// <param name="monthId"></param>
 /// <returns></returns>
 /// <exception cref="SystemException"></exception>
 private async Task<StorageFile> generateFilePath(MonthIdentity monthId, bool createIfNotExist)
 {
     StorageFolder transactionFolder = await _coreDriver.RootFolder
         .GetFolderAsync(TRANSACTION_DATA_FOLDER);
     if (transactionFolder == null)
     {
         throw new SystemException(null); // bug
     }
     String fileName = String.Format("{0}.xml", monthId.ToString());
     
     if (createIfNotExist == false)
     {
         try
         {
             StorageFile file = await transactionFolder.GetFileAsync(fileName);
             return file;
         }
         catch (FileNotFoundException)
         {
             return null;
         }
     }
     else
     {
         StorageFile file = await transactionFolder.CreateFileAsync(fileName
                 , CreationCollisionOption.OpenIfExists);
         return file;
     }
 }
        /// <summary>
        /// Get group balance from start month to end month
        /// </summary>
        /// <param name="accountGroup"></param>
        /// <param name="startMonthId"></param>
        /// <param name="endMonthId"></param>
        /// <returns></returns>
        /// <exception cref="SystemException"></exception>
        public CurrencyAmount GetGroupBalance(GLAccountGroupENUM accountGroup,
            MonthIdentity startMonthId, MonthIdentity endMonthId)
        {
            CurrencyAmount ret = new CurrencyAmount();
            MasterDataManagement mdMgmt = this._mdMgmt;
            foreach (var item in _items)
            {
                GLAccountMasterData glAccount;
                try
                {
                    glAccount = (GLAccountMasterData)mdMgmt
                           .GetMasterData(item.Key, MasterDataType.GL_ACCOUNT);
                }
                catch (Exception e)
                {
                    _coreDriver.logDebugInfo(this.GetType(), 183, e.Message, MessageType.ERRO);
                    throw new SystemException(e);
                }
                if (glAccount.Group.Identity == accountGroup)
                {
                    ret.AddTo(item.Value.GetSumAmount(startMonthId, endMonthId));
                }
            }

            return ret;
        }
        /// <summary>
        /// set starting month id
        /// </summary>
        /// <param name="monthId"></param>
        /// <returns></returns>
        public bool SetStartMonthId(MonthIdentity monthId)
        {
            // check
            if (this._startMonthId.CompareTo(monthId) <= 0)
            {
                return false;
            }

            this._startMonthId = monthId;

            // save meta data
            saveMetaData();

            return true;
        }
        /// <summary>
        /// store month ledger to file system
        /// </summary>
        /// <param name="monthId"></param>
        /// <exception cref="SystemException"></exception>
        public async Task StoreAsync(MonthIdentity monthId)
        {
            // store master data
            _coreDriver.logDebugInfo(this.GetType(), 293,
                    String.Format("Start storing %s to disk", monthId),
                    MessageType.INFO);

            _coreDriver.logDebugInfo(this.GetType(), 297,
                    "Store master data at first.", MessageType.INFO);
            await this._masterDataMgmt.StoreAsync();

            MonthLedger collection = this.GetLedger(monthId);

            StorageFile file = await this.generateFilePath(monthId, true);
            _coreDriver.logDebugInfo(this.GetType(), 297, "Generate file path: "
                    + file.Path, MessageType.INFO);
            if (file == null)
            {
                StorageFolder transactionFolder = await _coreDriver.RootFolder
                .GetFolderAsync(TRANSACTION_DATA_FOLDER);
                if (transactionFolder == null)
                {
                    throw new SystemException(null); // bug
                }
                String fileName = String.Format("{0}.xml", monthId.ToString());
                file = await transactionFolder.CreateFileAsync(fileName
                    , CreationCollisionOption.OpenIfExists);
            }


            XDocument xdoc = collection.toXML();
            _coreDriver
                    .logDebugInfo(this.GetType(), 297,
                            "Parsed document collections to XML document",
                            MessageType.INFO);
            try
            {
                await FileIO.WriteTextAsync(file, xdoc.ToString());
            }
            catch (FileNotFoundException e)
            {
                _coreDriver.logDebugInfo(this.GetType(), 316, e.Message,
                        MessageType.ERRO);
                throw new SystemException(e);
            }

            _coreDriver.logDebugInfo(this.GetType(), 335,
                    "Save document collection successfully.", MessageType.INFO);
        }
        /// <summary>
        /// get amount
        /// </summary>
        /// <param name="startId">start month identity</param>
        /// <param name="endId">end month identity</param>
        /// <returns></returns>
        public CurrencyAmount getAmount(MonthIdentity startId, MonthIdentity endId)
        {
            CurrencyAmount amount = new CurrencyAmount();
            List<HeadEntity> docs = this.getEntities(startId, endId);
            foreach (HeadEntity head in docs)
            {
                List<ItemEntity> items = head.Items;
                foreach (ItemEntity item in items)
                {
                    amount.AddTo(getAmountFromItem(item));
                }
            }

            return amount;
        }
        /// <summary>
        /// load meta data
        /// </summary>
        /// <exception cref="MetaDataFormatException">Format exception of the meta-data file</exception>
        private async Task loadMetaDataAsync()
        {
            StorageFile mdFile = await _rootFolder.GetFileAsync(META_DATA);

            if (mdFile == null)
            {
                return;
            }

            try
            {
               
                IList<string> lines = await FileIO.ReadLinesAsync(mdFile);

                int startYear = 0;
                int startMonth = 0;
                int versionNumber = 0;
                foreach (string line in lines)
                {
                    String[] values = line.Split('=');
                    if (values.Length != 2)
                    {
                        throw new MetaDataFormatException("Meta data format error.");
                    }

                    if (values[0].Equals(START_MONTH_TAG))
                    {
                        startMonth = Int32.Parse(values[1]);
                    }
                    else if (values[0].Equals(START_YEAR_TAG))
                    {
                        startYear = Int32.Parse(values[1]);
                    }
                    else if (values[0].Equals(VERSION))
                    {
                        versionNumber = Int32.Parse(values[1]);
                    }
                }

                _startMonthId = new MonthIdentity(startYear, startMonth);
                // _curMonthId = new MonthIdentity(curYear, curMonth);
                // check version
                bool ret = this.versionCheck(versionNumber);
                if (ret == false)
                {
                    throw new MetaDataFormatException("Version Error");
                }
            }
            catch (ArgumentNullException e)
            {
                throw new MetaDataFormatException(e.Message);
            }
            catch (FormatException e)
            {
                throw new MetaDataFormatException(e.Message);
            }
            catch (OverflowException e)
            {
                throw new MetaDataFormatException(e.Message);
            }
            finally
            {
            }
        }
 /// <summary>
 /// Month ledger
 /// </summary>
 /// <param name="monthId"></param>
 public MonthLedger(MonthIdentity monthId)
 {
     _monthId = monthId;
     _list = new Dictionary<DocumentIdentity, HeadEntity>();
 }
        /// <summary>
        /// establish folder
        /// </summary>
        private async Task establishFolderAsync()
        {
            // set meta data
            int year = DateTime.Today.Year;
            int month = DateTime.Today.Month;

            // set starting month identity
            try
            {
                _startMonthId = new MonthIdentity(year, month);
                // _curMonthId = new MonthIdentity(year, month);
            }
            catch (FiscalYearRangeException e)
            {
                this.logDebugInfo(this.GetType(), 300, e.ToString(),
                        MessageType.ERRO);
                throw new SystemException(e);// bug
            }
            catch (FiscalMonthRangeException e)
            {
                this.logDebugInfo(this.GetType(), 302, e.ToString(),
                        MessageType.ERRO);
                throw new SystemException(e);// bug
            }

            await saveMetaDataAsync();

            foreach (var item in _managements)
            {
                if(item.Value.NeedEstablishFile)
                    await item.Value.EstablishFilesAsync();
            }
            _isInitialized = true;
        }
 public MonthItem(MonthIdentity monthId, MonthAdapter parent)
     : base(monthId, String.Empty, parent)
 {
 }