Ejemplo n.º 1
0
        public string countCustomers(string serverName, string databaseName)
        {
            CompanyIdentifier companyIdentifier = session.LookupCompanyIdentifier(serverName, databaseName);

            connectionStatus = session.RequestAccess(companyIdentifier);
            Console.WriteLine("Result {0}", connectionStatus.ToString());

            if (connectionStatus == AuthorizationResult.Granted)
            {
                Company company = session.Open(companyIdentifier);
                Console.WriteLine("Company {0}", company.CompanyIdentifier.CompanyName);
                var customers           = company.Factories.CustomerFactory.List();
                FilterExpression filter = FilterExpression.Equal(
                    FilterExpression.Property("Customer.IsInactive"),
                    FilterExpression.Constant(false));
                LoadModifiers modifiers = LoadModifiers.Create();
                modifiers.Filters = filter;
                customers.Load(modifiers);

                int count = customers.Count;
                session.Close(company);

                return("{\"count\":\"" + count + "\"}");
            }

            return("{\"error\":\"Access: " + connectionStatus.ToString() + "\"}");
        }
Ejemplo n.º 2
0
        public string getCompany(string serverName, string databaseName)
        {
            CompanyIdentifier companyIdentifier = session.LookupCompanyIdentifier(serverName, databaseName);
            var json = new JavaScriptSerializer().Serialize(companyIdentifier);

            return(json.ToString());
        }
Ejemplo n.º 3
0
        public Task <IList <Treasury> > GetTreasuriesByCompany(CompanyIdentifier companyIdentifier)
        {
            var treasuries = new List <Treasury>();

            treasuries.Add(new Treasury(new PersonIdentifier(Guid.NewGuid()), new Money(100, Currency.PLN), new Money(100, Currency.PLN)));
            treasuries.Add(new Treasury(new PersonIdentifier(Guid.NewGuid()), new Money(100, Currency.PLN), new Money(100, Currency.PLN)));
            return(Task.FromResult((IList <Treasury>)treasuries));
        }
Ejemplo n.º 4
0
        public Task <IList <PersonIdentifier> > GetPeopleByCompany(CompanyIdentifier companyIdentifier)
        {
            var people = new List <PersonIdentifier>();

            people.Add(new PersonIdentifier(Guid.NewGuid()));
            people.Add(new PersonIdentifier(Guid.NewGuid()));
            return(Task.FromResult((IList <PersonIdentifier>)people));
        }
        public BillingPreference GetBillingPreference(CompanyIdentifier companyIdentifier)
        {
            var rnd = new Random();

            if (rnd.NextDouble() > 0.5)
            {
                return(BillingPreference.BillingPerTrigger);
            }
            return(BillingPreference.BillingPerTriggerOrder);
        }
Ejemplo n.º 6
0
        private static void setCompanyList()
        {
            // Get CompanyIdentifer for Bellwether Garden Supply sample company
            CompanyIdentifierList m_companyIdList = apiSession.CompanyList();



            CompanyIdentifier c = m_companyIdList.ElementAt <CompanyIdentifier>(0);


            Console.WriteLine(c.CompanyName + ":" + c.DatabaseName + ":" + c.ServerName + ":" + c.Guid.ToString() + ":" + c.Path);
            Console.ReadLine();
        }
        private void OpenCompany(CompanyIdentifier companyId)
        {
            // Request authorization from Sage 50 for our third-party application.
            try
            {
                OnPeachtreeInformation(EventData("Requesting access to your company in Sage 50..."));
                var presentAccessStatus = Session.VerifyAccess(companyId);
                var authorizationResult = presentAccessStatus == AuthorizationResult.Granted ? presentAccessStatus : Session.RequestAccess(companyId);

                // Check to see we were granted access to Sage 50 company, if so, go ahead and open the company.
                if (authorizationResult == AuthorizationResult.Granted)
                {
                    Company = Session.Open(companyId);
                    Logger.Information("Authorization granted");
                    OnPeachtreeInformation(EventData("Access to your company was granted"));
                    OnLoggedInStateChanged(EventData("Logged In"));
                }
                else // otherwise, display a message to user that there was insufficient access.
                {
                    Logger.Error("Authorization request was not successful - {0}. Will retry.", authorizationResult);
                    OnPeachtreeInformation(EventData($"Authorization status is {authorizationResult}. Still waiting for authorization to access your company..."));
                    OnLoggedInStateChanged(EventData("Logged Out. Waiting for Sage 50 authorization"));
                }
            }
            catch (Sage.Peachtree.API.Exceptions.LicenseNotAvailableException e)
            {
                Logger.Debug(e, e.Message);
                OnPeachtreeInformation(EventData("Could not open your company because it seems like you do not have a license."));
            }
            catch (Sage.Peachtree.API.Exceptions.RecordInUseException e)
            {
                Logger.Debug(e, e.Message);
                OnPeachtreeInformation(EventData("Could not open your company as one or more records are in use."));
            }
            catch (Sage.Peachtree.API.Exceptions.AuthorizationException e)
            {
                Logger.Debug(e, e.Message);
                OnPeachtreeInformation(EventData($"Could not open your company as authorization failed. {e.Message}"));
            }
            catch (Sage.Peachtree.API.Exceptions.PeachtreeException e)
            {
                Logger.Debug(e, e.Message);
                OnPeachtreeInformation(EventData($"Could not open your company due to a Sage 50 internal error. {e.Message}"));
            }
            catch (Exception e)
            {
                Logger.Debug(e, e.Message);
                OnPeachtreeInformation(EventData($"Something went wrong. {e.Message}"));
            }
        }
        private CompanyIdentifier DiscoverCompany()
        {
            bool Predicate(CompanyIdentifier c)
            {
                return(c.CompanyName == CompanyName);
            }

            try
            {
                var companies = Session.CompanyList();
                var company   = companies.Find(Predicate);
                return(company);
            }
            catch (Exception e)
            {
                CompanyIdentifier company = null;
                OnPeachtreeInformation(EventData($"Something went wrong. {e.Message}."));
                return(company);
            }
        }
Ejemplo n.º 9
0
        public void OpenCompany(CompanyIdentifier CompanyID)
        {
            CloseCurrentCompany();

            if (CompanyID == null)
            {
                return;
            }

            // Ask the Sage 50 application if this application has
            // been granted access to the company.
            var AuthResult = CurrentSession.VerifyAccess(CompanyID);

            // if the app has never asked for authorization before, We need to ask now
            if (AuthResult == AuthorizationResult.NoCredentials)
            {
                AuthResult = CurrentSession.RequestAccess(CompanyID);
            }

            // handle the authorization result
            switch (AuthResult)
            {
            case AuthorizationResult.CompanyLocked:
            case AuthorizationResult.LoginRestricted:
            case AuthorizationResult.Denied:
            case AuthorizationResult.CorruptedOrTampered:
            case AuthorizationResult.Pending:
                // show the error messages for these situations
                System.Console.WriteLine($"Error OpenCompany_{AuthResult.ToString()}");
                break;

            case AuthorizationResult.Granted:
                // open the company
                m_Company = CurrentSession.Open(CompanyID);
                break;

            default:
                Debug.Fail(AuthResult.ToString());
                break;
            }
        }
Ejemplo n.º 10
0
        public async Task Handle(SetupAllCompanyTriggerOrderCommand command)
        {
            var companyId  = new CompanyIdentifier(command.CompanyId);
            var currency   = (Currency)Enum.Parse(typeof(Currency), command.Currency);
            var treasuries = await _treasuryRepository.GetTreasuriesByCompany(companyId);

            var company = await _companyRepository.GetCompanyById(companyId);

            var triggerOrder = new TriggerOrder(
                description: command.Description,
                companyIdentifier: companyId,
                currency: currency);
            var moneyPerPerson = new Money(Decimal.Round(command.Amount / treasuries.Count, 2), currency);

            foreach (var treasury in treasuries)
            {
                var trigger = new Trigger(
                    Description: $"Part of \"{command.Description}\" order",
                    Money: moneyPerPerson,
                    Giver: company.BigBoss,
                    Receiver: treasury.PersonIdentifier,
                    TreasuryMoneyType.Giving);
                triggerOrder.AddTrigger(trigger);
                treasury.ReceiveTrigger(trigger);
            }
            if (!company.CanPay(triggerOrder.Billing))
            {
                throw new DomainException($"{company.Identifier.Id} cannot pay for trigger order");
            }
            company.Pay(triggerOrder.Billing);

            await _companyRepository.Update(company);

            await _triggerOrderRepository.Save(triggerOrder);

            foreach (var treasury in treasuries)
            {
                await _treasuryRepository.Update(treasury);
            }
        }
Ejemplo n.º 11
0
        private void OpenCompany(CompanyIdentifier companyId)
        {
            // Request authorization from Sage 50 for our third-party application.
            try
            {
                var authorizationResult = Session.RequestAccess(companyId);

                // Check to see we were granted access to Sage 50 company, if so, go ahead and open the company.
                if (authorizationResult == AuthorizationResult.Granted)
                {
                    Company = Session.Open(companyId);
                    Logger.Information("Authorization granted");
                }
                else // otherwise, display a message to user that there was insufficient access.
                {
                    Logger.Error("Authorization request was not successful - {0}. Will retry.", authorizationResult);
                }
            }
            catch (Sage.Peachtree.API.Exceptions.LicenseNotAvailableException e)
            {
                Logger.Debug(e, e.Message);
            }
            catch (Sage.Peachtree.API.Exceptions.RecordInUseException e)
            {
                Logger.Debug(e, e.Message);
            }
            catch (Sage.Peachtree.API.Exceptions.AuthorizationException e)
            {
                Logger.Debug(e, e.Message);
            }
            catch (Sage.Peachtree.API.Exceptions.PeachtreeException e)
            {
                Logger.Debug(e, e.Message);
            }
            catch (Exception e)
            {
                Logger.Debug(e, e.Message);
            }
        }
 public Task <Company> GetCompanyById(CompanyIdentifier companyIdentifier)
 {
     return(Task.FromResult(new Company(companyIdentifier, new Money(300, Currency.PLN), new PersonIdentifier(Guid.NewGuid()))));
 }
Ejemplo n.º 13
0
        public string getCustomers(string serverName, string databaseName, int page)
        {
            CompanyIdentifier companyIdentifier = session.LookupCompanyIdentifier(serverName, databaseName);

            connectionStatus = session.RequestAccess(companyIdentifier);
            Console.WriteLine("Result {0}", connectionStatus.ToString());

            if (connectionStatus == AuthorizationResult.Granted)
            {
                Company company = session.Open(companyIdentifier);
                Console.WriteLine("Company {0}", company.CompanyIdentifier.CompanyName);
                var customers           = company.Factories.CustomerFactory.List();
                FilterExpression filter = FilterExpression.Equal(
                    FilterExpression.Property("Customer.IsInactive"),
                    FilterExpression.Constant(false));

                LoadModifiers modifiers = LoadModifiers.Create();
                modifiers.Filters = filter;
                customers.Load(modifiers);
                var cs = customers.ToList();

                List <CustomerDetails> customerDetailsList = new List <CustomerDetails>();

                int start_index = page * config.recordsPerPage;

                for (int index = start_index; index < start_index + config.recordsPerPage; index++)
                {
                    if (index >= cs.Count)
                    {
                        break;
                    }

                    Customer customer = cs[index];

                    CustomerDetails customerDetails = new CustomerDetails(customer.ID)
                    {
                        AccountNumber     = customer.AccountNumber,
                        Balance           = customer.Balance,
                        Email             = customer.Email,
                        LastInvoiceAmount = customer.LastInvoiceAmount,

                        Name = customer.Name,

                        LastPaymentAmount = customer.LastPaymentAmount,

                        PaymentMethod = customer.PaymentMethod,


                        Category = customer.Category
                    };

                    if (customer.AverageDaysToPayInvoices != null)
                    {
                        customerDetails.AverageDaysToPayInvoices = (decimal)customer.AverageDaysToPayInvoices;
                    }

                    customerDetails.PhoneNumbers = customer.PhoneNumbers;

                    if (customer.CustomerSince != null)
                    {
                        customerDetails.CustomerSince = customer.CustomerSince.ToString();
                    }

                    if (customer.LastPaymentDate != null)
                    {
                        customerDetails.LastPaymentDate = customer.LastPaymentDate.ToString();
                    }

                    if (customer.LastStatementDate != null)
                    {
                        customerDetails.LastStatementDate = customer.LastStatementDate.ToString();
                    }

                    if (customer.LastInvoiceDate != null)
                    {
                        customerDetails.LastInvoiceDate = customer.LastInvoiceDate.ToString();
                    }

                    customerDetailsList.Add(customerDetails);
                }

                session.Close(company);

                var json = new JavaScriptSerializer().Serialize(customerDetailsList);
                return(json.ToString());
            }



            return("{\"error\":\"Access: " + connectionStatus.ToString() + "\"}");
        }
Ejemplo n.º 14
0
        public string getCustomerReceipts(string serverName, string databaseName, string customerID, DateTime dateFrom, DateTime dateTo)
        {
            CompanyIdentifier companyIdentifier = session.LookupCompanyIdentifier(serverName, databaseName);

            connectionStatus = session.RequestAccess(companyIdentifier);

            if (connectionStatus == AuthorizationResult.Granted)
            {
                Company company = session.Open(companyIdentifier);

                var customers = company.Factories.CustomerFactory.List();

                FilterExpression filter3 = FilterExpression.Equal(
                    FilterExpression.Property("Customer.ID"),
                    FilterExpression.Constant(customerID));


                LoadModifiers modifiers3 = LoadModifiers.Create();
                modifiers3.Filters = filter3;
                customers.Load(modifiers3);
                var cs = customers.ToList();

                if (cs.Count == 0)
                {
                    session.Close(company);
                    return("{\"error\":\"Customer not found" + "\"}");
                }

                Customer customer = cs[0];

                EntityReference customer_key = customer.Key;

                var receipts = company.Factories.ReceiptFactory.List();

                //var cpf = company.Factories.ReceiptInvoiceLineFactory.List();


                FilterExpression filter_receipt = FilterExpression.Equal(
                    FilterExpression.Property("Receipt.CustomerReference"),
                    FilterExpression.Constant(customer_key));

                LoadModifiers modifiers = LoadModifiers.Create();
                modifiers.Filters = filter_receipt;
                receipts.Load(modifiers);

                //LoadModifiers modifiers2 = LoadModifiers.Create();
                //modifiers.Filters = filter_receipt;


                //cpf.Load();

                //List<Sage.Peachtree.API.ReceiptInvoiceLine> cpfList = cpf.ToList();

                List <Sage.Peachtree.API.Receipt> receiptList        = receipts.ToList();
                List <ReceiptDetails>             receiptDetailsList = new List <ReceiptDetails>();

                for (int index = 0; index < receiptList.Count; index++)
                {
                    Receipt receipt = receiptList[index];

                    ReceiptDetails ReceiptDetails = new ReceiptDetails((decimal)receipt.Amount)
                    {
                        PaymentMethod   = receipt.PaymentMethod,
                        ReferenceNumber = receipt.ReferenceNumber,
                        Key             = receipt.Key.Guid.ToString()
                    };

                    if (receipt.Date != null)
                    {
                        ReceiptDetails.Date = receipt.Date.ToString();
                    }

                    for (int x = 0; x < receipt.ApplyToInvoiceLines.Count; x++)
                    {
                        InvoiceLine Invoice = new InvoiceLine(receipt.ApplyToInvoiceLines[x].Amount, receipt.ApplyToInvoiceLines[x].AmountPaid)
                        {
                            Description    = receipt.ApplyToInvoiceLines[x].Description,
                            DiscountAmount = receipt.ApplyToInvoiceLines[x].DiscountAmount,
                            InvoiceKey     = receipt.ApplyToInvoiceLines[x].InvoiceReference.Guid.ToString()
                        };

                        ReceiptDetails.ApplyToInvoices.Add(Invoice);
                    }

                    receiptDetailsList.Add(ReceiptDetails);
                }

                session.Close(company);

                var json = new JavaScriptSerializer().Serialize(receiptDetailsList);
                return(json.ToString());
            }

            return("{\"error\":\"Access: " + connectionStatus.ToString() + "\"}");
        }
Ejemplo n.º 15
0
        public string getCustomerInvoices(string serverName, string databaseName, string customerID, DateTime dateFrom, DateTime dateTo)
        {
            CompanyIdentifier companyIdentifier = session.LookupCompanyIdentifier(serverName, databaseName);

            connectionStatus = session.RequestAccess(companyIdentifier);

            if (connectionStatus == AuthorizationResult.Granted)
            {
                Company company = session.Open(companyIdentifier);

                var customers = company.Factories.CustomerFactory.List();

                FilterExpression filter2 = FilterExpression.Equal(
                    FilterExpression.Property("Customer.ID"),
                    FilterExpression.Constant(customerID));


                LoadModifiers modifiers2 = LoadModifiers.Create();
                modifiers2.Filters = filter2;
                customers.Load(modifiers2);
                var cs = customers.ToList();

                if (cs.Count == 0)
                {
                    session.Close(company);
                    return("{\"error\":\"Customer not found" + "\"}");
                }

                Customer customer = cs[0];

                EntityReference customer_key = customer.Key;

                var invoices            = company.Factories.SalesInvoiceFactory.List();
                FilterExpression filter = FilterExpression.Equal(
                    FilterExpression.Property("SalesInvoice.CustomerReference"),
                    FilterExpression.Constant(customer_key));

                LoadModifiers modifiers = LoadModifiers.Create();
                modifiers.Filters = filter;
                invoices.Load(modifiers);



                List <Sage.Peachtree.API.SalesInvoice> invoicesList = invoices.ToList();
                List <InvoiceDetails> invoiceDetailsList            = new List <InvoiceDetails>();

                for (int index = 0; index < invoicesList.Count; index++)
                {
                    SalesInvoice invoice = invoicesList[index];

                    InvoiceDetails invoiceDetails = new InvoiceDetails((decimal)invoice.Amount, (decimal)invoice.AmountDue)
                    {
                        DiscountAmount  = (decimal)invoice.DiscountAmount,
                        ReferenceNumber = invoice.ReferenceNumber,
                        Key             = invoice.Key.Guid.ToString()
                    };

                    if (invoice.Date != null)
                    {
                        invoiceDetails.Date = invoice.Date.ToString();
                    }

                    if (invoice.DateDue != null)
                    {
                        invoiceDetails.DateDue = invoice.DateDue.ToString();
                    }

                    if (invoice.DiscountDate != null)
                    {
                        invoiceDetails.DiscountDate = invoice.DiscountDate.ToString();
                    }


                    invoiceDetailsList.Add(invoiceDetails);
                }

                session.Close(company);

                var json = new JavaScriptSerializer().Serialize(invoiceDetailsList);
                return(json.ToString());
            }


            return("{\"error\":\"Access: " + connectionStatus.ToString() + "\"}");
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            string devToken = ConfigurationManager.AppSettings["applicationIdentifier"];
            var    resolver = Assembly.LoadWithPartialName("Sage.Peachtree.API.Resolver");
            var    api      = Assembly.LoadWithPartialName("Sage.Peachtree.API");

            Console.WriteLine("Sage 50 ShipGear write-back performance test");

            Console.WriteLine("Enter server name:");
            string serverName = Console.ReadLine();

            AssemblyInitializer.Initialize();

            var session = new PeachtreeSession();

            try
            {
                try
                {
                    session.Begin(devToken);
                }
                catch (InvalidApplicationIdentifierException e)
                {
                    Message("Put a valid application identifier into the app configuration file.");
                }

                var companyList = session.CompanyList();
                foreach (var item in companyList)
                {
                    Console.WriteLine(string.Format("{0} {1}", item.CompanyName, item.Path));
                }

                Console.WriteLine("Enter company name. The first will be selected if more than one with the same name.");
                string companyName = Console.ReadLine();

                CompanyIdentifier company = null;
                foreach (var item in companyList)
                {
                    if (item.CompanyName == companyName)
                    {
                        company = item;
                        break;
                    }
                }

                if (company == null)
                {
                    Message("No company was selected - quit.");
                }

                var authResult = session.RequestAccess(company);
                if (authResult == AuthorizationResult.Granted)
                {
                    Company comp = null;
                    try
                    {
                        comp = session.Open(company);
                    }
                    catch (Sage.Peachtree.API.Exceptions.AuthorizationException e)
                    {
                        Message("Reopen the company in Sage 50 to enable access to this application.");
                    }

                    try
                    {
                        SalesInvoiceList list = comp.Factories.SalesInvoiceFactory.List();

                        Console.WriteLine("Enter invoice number:");
                        string           documentKey = Console.ReadLine();
                        FilterExpression filter      = FilterExpression.Equal(FilterExpression.Property("SalesInvoice.ReferenceNumber"), FilterExpression.Constant(documentKey));
                        var modifiers = LoadModifiers.Create();
                        modifiers.Filters = filter;

                        list.Load(modifiers);
                        Console.WriteLine("Invoices selected: {0}", list.Count());

                        var enumerator = list.GetEnumerator();
                        if (enumerator == null)
                        {
                            Message("GetEnumerator returned NULL");
                        }

                        Console.WriteLine("Moving to the next record");
                        enumerator.MoveNext();

                        enumerator.Current.CustomerNote = "Test Customer Note";
                        enumerator.Current.InternalNote = "Test Internal Note";

                        Console.WriteLine("Editing the freight (Y[y]/N[n], Y if empty)?");
                        string strFreightEdit = Console.ReadLine();
                        if (string.IsNullOrWhiteSpace(strFreightEdit))
                        {
                            strFreightEdit = "Y";
                        }
                        bool freightEdit = string.Equals(strFreightEdit, "Y", StringComparison.CurrentCultureIgnoreCase);

                        Console.WriteLine("Editing freight: {0}", freightEdit.ToString());
                        if (freightEdit)
                        {
                            enumerator.Current.FreightAmount = 199.99M;
                        }

                        Stopwatch w = Stopwatch.StartNew();
                        Console.WriteLine("Starting performance counter");
                        enumerator.Current.Save();
                        w.Stop();
                        Message(string.Format("Elapsed msec: {0}", w.Elapsed.TotalMilliseconds), ConsoleColor.Green, false);
                        Message("Completed", ConsoleColor.Green, true);
                    }
                    finally
                    {
                        comp.Close();
                    }
                }
                else if (authResult == AuthorizationResult.Pending)
                {
                    Message("Authorization result: Pending - cannot continue. Reopen the company in Sage 50 to enable access to this application.");
                }
                else
                {
                    Message(string.Format("Authorization result: {0} - cannot continue", authResult.ToString()));
                }
            }
            finally
            {
                session.End();
            }
        }