static private FinancialDependencyType GetFinancialDependencyType(IHasIdentity foreignObject)
        {
            if (foreignObject is ExpenseClaim)
            {
                return(FinancialDependencyType.ExpenseClaim);
            }
            else if (foreignObject is InboundInvoice)
            {
                return(FinancialDependencyType.InboundInvoice);
            }
            else if (foreignObject is OutboundInvoice)
            {
                return(FinancialDependencyType.OutboundInvoice);
            }
            else if (foreignObject is Salary)
            {
                return(FinancialDependencyType.Salary);
            }
            else if (foreignObject is Payout)
            {
                return(FinancialDependencyType.Payout);
            }
            else if (foreignObject is PaymentGroup)
            {
                return(FinancialDependencyType.PaymentGroup);
            }
            else if (foreignObject is FinancialTransaction)
            {
                return(FinancialDependencyType.FinancialTransaction);
            }

            throw new NotImplementedException("Unidentified dependency encountered in GetFinancialDependencyType:" +
                                              foreignObject.GetType().ToString());
        }
Example #2
0
        public static ObjectOptionalData ForObject(IHasIdentity identifiableObject)
        {
            ObjectOptionalData thisObject = FromBasic(SwarmDb.GetDatabaseForReading().GetObjectOptionalData((IHasIdentity)identifiableObject));

            thisObject.forObject = identifiableObject;
            return(thisObject);
        }
Example #3
0
        public BasicChurnDataPoint[] GetChurnDataForOrganization(IHasIdentity organization, DateTime lowerDate,
                                                                 DateTime upperDate)
        {
            // Since I don't trust SQL Server to make correct date comparisons, especially given
            // that the dates are passed in text in SQL, we get ALL the data and do
            // the comparison in code instead. This is a run-seldom function, anyway, and getting
            // some 30k records with two unlinked fields isn't that expensive.

            DateTime minimumDateTime = lowerDate.Date;
            DateTime maximumDateTime = upperDate.Date.AddDays(1);

            List <BasicChurnDataPoint> result = new List <BasicChurnDataPoint>();

            BasicChurnDataPoint[] rawData = this.GetChurnData(organization);

            foreach (BasicChurnDataPoint churnPoint in rawData)
            {
                // It is important that the lower border is inclusive and the upper exclusive in this
                // comparison:

                if (churnPoint.ExpiryDate >= minimumDateTime && churnPoint.ExpiryDate < maximumDateTime)
                {
                    result.Add(churnPoint);
                }
            }

            return(result.ToArray());
        }
Example #4
0
        public BasicChurnDataPoint[] GetChurnDataForOrganization (IHasIdentity organization, DateTime lowerDate,
                                                                  DateTime upperDate)
        {
            // Since I don't trust SQL Server to make correct date comparisons, especially given
            // that the dates are passed in text in SQL, we get ALL the data and do
            // the comparison in code instead. This is a run-seldom function, anyway, and getting
            // some 30k records with two unlinked fields isn't that expensive.

            DateTime minimumDateTime = lowerDate.Date;
            DateTime maximumDateTime = upperDate.Date.AddDays(1);

            List<BasicChurnDataPoint> result = new List<BasicChurnDataPoint>();
            BasicChurnDataPoint[] rawData = this.GetChurnData(organization);

            foreach (BasicChurnDataPoint churnPoint in rawData)
            {
                // It is important that the lower border is inclusive and the upper exclusive in this
                // comparison:

                if (churnPoint.ExpiryDate >= minimumDateTime && churnPoint.ExpiryDate < maximumDateTime)
                {
                    result.Add(churnPoint);
                }
            }

            return result.ToArray();
        }
Example #5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        _transaction = GetTransaction();

        if (!_authority.HasPermission(Permission.CanSeeEconomyTransactions, _transaction.OrganizationId, -1, Authorization.Flag.ExactOrganization))
        {
            throw new UnauthorizedAccessException("Access Denied");
        }


        if (!Page.IsPostBack)
        {
            // Populate all data

            this.DatePicker.DateInput.Culture = new CultureInfo("sv-SE");
            this.DatePicker.SelectedDate      = _transaction.DateTime;
            this.TextDescription.Text         = _transaction.Description;
            this.TextDescription.Style.Add(HtmlTextWriterStyle.Width, "100%");

            PopulateGrid();
            PopulateEvents();

            IHasIdentity dependency = _transaction.Dependency;
        }

        Documents documents = _transaction.Documents;

        Page.Title = "Auditing Transaction #" + _transaction.Identity.ToString();
    }
        public BasicMembership[] GetExpiringMemberships(IHasIdentity organization, DateTime lowerBound, DateTime upperBound, DatabaseCondition condition)
        {
            // Since I don't trust SQL Server to make correct date comparisons, especially given
            // that the dates are passed in text in SQL, we get ALL the memberships and do
            // the comparison in code instead. This is a run-seldom function, anyway, and getting
            // some 50k records with four short unlinked fields isn't that expensive.

            BasicMembership[] memberships = this.GetMemberships(organization, condition);

            DateTime minimumDateTime = lowerBound.Date;
            DateTime maximumDateTime = upperBound.Date.AddDays(1);

            List <BasicMembership> result = new List <BasicMembership>();

            foreach (BasicMembership membership in memberships)
            {
                // It is important that the lower border is inclusive and the upper exclusive in this
                // comparison:

                if (membership.Expires >= minimumDateTime && membership.Expires < maximumDateTime)
                {
                    result.Add(membership);
                }
            }

            return(result.ToArray());
        }
 public static FinancialValidations ForObject(IHasIdentity financialDependency)
 {
     return
         (FromArray(SwarmDb.GetDatabaseForReading()
                    .GetFinancialValidations(GetDependencyType(financialDependency),
                                             financialDependency.Identity)));
 }
 public static void Create(FinancialValidationType validationType, IHasIdentity foreignObject,
                           Person actingPerson, double amount)
 {
     SwarmDb.GetDatabaseForWriting()
     .CreateFinancialValidation(validationType, GetDependencyType(foreignObject), foreignObject.Identity,
                                DateTime.Now, actingPerson.Identity, amount);
 }
Example #9
0
 public void SetForeignObjectForAll(IHasIdentity foreignObject)
 {
     foreach (Document doc in this)
     {
         doc.SetForeignObject(foreignObject);
     }
 }
        private static ObjectType GetObjectTypeForObject(IHasIdentity objectToIdentify)
        {
            //string objectTypeString = objectToIdentify.GetType().ToString();

            //// Strip namespace

            //int lastPeriodIndex = objectTypeString.LastIndexOf('.');
            //objectTypeString = objectTypeString.Substring(lastPeriodIndex + 1);

            string objectTypeString = objectToIdentify.GetType().Name;

            // At this point, we should be able to cast the string to an ObjectType enum
            try
            {
                return((ObjectType)Enum.Parse(typeof(ObjectType), objectTypeString));
            }
            catch
            {
                //That failed. This could be a subclass, try upwards.
                Type parentType = objectToIdentify.GetType().BaseType;
                while (parentType != typeof(Object))
                {
                    try
                    {
                        return((ObjectType)Enum.Parse(typeof(ObjectType), parentType.Name));
                    }
                    catch
                    {
                        parentType = parentType.BaseType;
                    }
                }
            }
            throw new InvalidCastException("GetObjectTypeForObject could not identify object of type " +
                                           objectToIdentify.GetType().Name);
        }
Example #11
0
        internal static object FromBasic(IHasIdentity basic)
        {
            MethodInfo basicConverterMethod = null;
            Type       basicType            = basic.GetType();

            if (_converterLookup.ContainsKey(basicType))
            {
                basicConverterMethod = _converterLookup[basicType];
            }
            else
            {
                Assembly logicAssembly = typeof(SingularFactory).Assembly;
                Assembly basicAssembly = typeof(BasicPerson).Assembly;

                System.Type[] logicTypes =
                    logicAssembly.GetTypes().Where(type => type.IsSubclassOf(basicType)).ToArray();

                if (logicTypes.Length > 1)
                {
                    throw new InvalidOperationException("More than one type in Swarmops.Logic derives from " +
                                                        basicType.ToString());
                }
                if (logicTypes.Length == 0)
                {
                    // There are no matching types in Swarmops.Logic; look through registered assemblies

                    foreach (Assembly foreignAssembly in _assemblyLookup.Values)
                    {
                        logicTypes = foreignAssembly.GetTypes().Where(type => type.IsSubclassOf(basicType)).ToArray();
                        if (logicTypes.Length == 1)
                        {
                            break;
                        }
                    }

                    if (logicTypes.Length == 0)
                    {
                        throw new InvalidOperationException(
                                  "Unable to find higher-order class for base type " + basicType.ToString() + "; if it's in a plugin, was the higher-order assembly registered with SingularFactory?");
                    }
                }

                Type logicType = logicTypes[0];

                basicConverterMethod = logicType.GetMethod("FromBasic", BindingFlags.Static | BindingFlags.Public);

                if (basicConverterMethod == null)
                {
                    throw new InvalidOperationException(
                              "Unable to find a public static method named \"" + logicType.ToString() + ".FromBasic (" + basicType.ToString() + ")\" in a loaded assembly");
                }

                _converterLookup[basicType] = basicConverterMethod;
            }

            object result = basicConverterMethod.Invoke(null, new object[] { basic });

            return(result);
        }
Example #12
0
        public static Document Create (string serverFileName, string clientFileName, Int64 fileSize, 
            string description, IHasIdentity identifiableObject, Person uploader)
        {
            int newDocumentId = SwarmDb.GetDatabaseForWriting().
                CreateDocument(serverFileName, clientFileName, fileSize, description, GetDocumentTypeForObject(identifiableObject), identifiableObject == null? 0: identifiableObject.Identity, uploader.Identity);

            return FromIdentityAggressive(newDocumentId);
        }
Example #13
0
        public static Document Create(string serverFileName, string clientFileName, Int64 fileSize,
                                      string description, IHasIdentity identifiableObject, Person uploader)
        {
            int newDocumentId = SwarmDb.GetDatabaseForWriting().
                                CreateDocument(serverFileName, clientFileName, fileSize, description, GetDocumentTypeForObject(identifiableObject), identifiableObject == null? 0: identifiableObject.Identity, uploader.Identity);

            return(FromIdentityAggressive(newDocumentId));
        }
Example #14
0
 public static FinancialTransactions ForDependentObject(IHasIdentity foreignObject)
 {
     return
         (FromArray(
              SwarmDb.GetDatabaseForReading()
              .GetDependentFinancialTransactions(GetDependencyType(foreignObject),
                                                 foreignObject.Identity)));
 }
Example #15
0
        public void CreateAffectedObject(IHasIdentity affectedObject)
        {
            string className = affectedObject.GetType().ToString();
            int    dotIndex  = className.LastIndexOf('.');

            className = className.Substring(dotIndex + 1); // assumes there's always at least one dot in a class name


            SwarmDb.GetDatabaseForWriting().CreateSwarmopsLogEntryAffectedObject(this.Identity, className, affectedObject.Identity);
        }
Example #16
0
        public void CreateAffectedObject (IHasIdentity affectedObject)
        {
            string className = affectedObject.GetType().ToString();
            int dotIndex = className.LastIndexOf('.');

            className = className.Substring(dotIndex + 1); // assumes there's always at least one dot in a class name
            

            SwarmDb.GetDatabaseForWriting().CreateSwarmopsLogEntryAffectedObject(this.Identity, className, affectedObject.Identity);
        }
Example #17
0
        private static string GetObjectDetails(IHasIdentity identifiableObject)
        {
            switch (identifiableObject.GetType().Name)
            {
            case "ExpenseClaim":
                ExpenseClaim claim = (ExpenseClaim)identifiableObject;

                return("<strong>" +
                       String.Format(Global.Financial_ExpenseClaimLongSpecification, claim.Identity) +
                       ":</strong> " + claim.Organization.Currency.Code + " " +
                       (claim.AmountCents / 100.0).ToString("N2") + ". " +
                       HttpUtility.HtmlEncode(GetValidationDetails(claim.Validations)) + " " +
                       GetDocumentDetails(claim.Documents, claim));

            case "CashAdvance":
                CashAdvance advance = (CashAdvance)identifiableObject;

                return("<strong>" +
                       String.Format(Global.Financial_CashAdvanceSpecification, advance.Identity) +
                       ":</strong> " + advance.Organization.Currency.Code + " " +
                       (advance.AmountCents / 100.0).ToString("N2") + ". " +
                       HttpUtility.HtmlEncode(GetValidationDetails(advance.Validations)));

            case "InboundInvoice":
                InboundInvoice invoice = (InboundInvoice)identifiableObject;

                return("<strong>" +
                       String.Format(Global.Financial_InboundInvoiceSpecification, invoice.Identity) +
                       ":</strong> " + invoice.Organization.Currency.Code + " " +
                       (invoice.AmountCents / 100.0).ToString("N2") + ". " +
                       GetValidationDetails(invoice.Validations) + " " +
                       GetDocumentDetails(invoice.Documents, invoice));

            case "Salary":
                Salary salary = (Salary)identifiableObject;

                return("<strong>" +
                       String.Format(Global.Financial_SalaryIdentity, salary.Identity) +
                       ":</strong> " +
                       String.Format(Resources.Pages.Ledgers.InspectLedgers_TxDetail_SalaryDetail,
                                     salary.PayrollItem.Organization.Currency.Code,
                                     salary.BaseSalaryCents / 100.0,                             // base salary
                                     (salary.GrossSalaryCents - salary.BaseSalaryCents) / 100.0, // before-tax adjustments
                                     salary.GrossSalaryCents / 100.0,                            // before-tax adjusted salary
                                     salary.SubtractiveTaxCents / 100.0,                         // tax deduction
                                     (salary.NetSalaryCents + salary.SubtractiveTaxCents -
                                      salary.GrossSalaryCents) / 100.0,                          // after-tax adjustments
                                     salary.NetSalaryCents / 100.0) +                            // actual payout amount
                       " " + GetValidationDetails(salary.Validations));

            default:
                throw new NotImplementedException("Unhandled object type in GetObjectDetails: " +
                                                  identifiableObject.GetType().Name);
            }
        }
Example #18
0
        public static Documents ForObject(IHasIdentity identifiableObject)
        {
            Documents newInstance =
                FromArray(
                    SwarmDb.GetDatabaseForReading().GetDocumentsForForeignObject(
                        Document.GetDocumentTypeForObject(identifiableObject), identifiableObject.Identity));

            newInstance.sourceObject = identifiableObject;

            return(newInstance);
        }
Example #19
0
    protected void Page_Load(object sender, EventArgs e)
    {
        _transaction = GetTransaction();

        if (!_authority.HasPermission(Permission.CanDoEconomyTransactions, _transaction.OrganizationId, -1, Authorization.Flag.ExactOrganization))
        {
            throw new UnauthorizedAccessException("Access Denied");
        }


        if (!Page.IsPostBack)
        {
            // Populate all data

            this.DatePicker.DateInput.Culture = new CultureInfo("sv-SE");
            this.DatePicker.SelectedDate      = _transaction.DateTime;
            this.TextDescription.Text         = _transaction.Description;
            this.TextDescription.Style.Add(HtmlTextWriterStyle.Width, "100%");
            this.TextAmount.Style.Add(HtmlTextWriterStyle.Width, "80px");
            this.DropAccounts.Style.Add(HtmlTextWriterStyle.Width, "200px");

            this.TextAmount.Text = (-_transaction.Rows.AmountTotal).ToString("N2", new CultureInfo("sv-SE"));

            PopulateAccounts(_transaction.OrganizationId);
            PopulateGrid();

            IHasIdentity dependency = _transaction.Dependency;

            if (dependency != null)
            {
                this.PanelModifiableTransaction.Visible   = false;
                this.PanelUnmodifiableTransaction.Visible = true;

                if (dependency is ExpenseClaim)
                {
                    this.LabelDependency.Text             = "Expense Claim #" + dependency.Identity.ToString();
                    this.PanelDependencyDocuments.Visible = true;
                    this.DocumentsDependency.Documents    = Documents.ForObject(dependency);
                }
                else if (dependency is Payout)
                {
                    this.PanelDependencyDocuments.Visible = false;
                    this.PanelPayoutDetails.Visible       = true;
                    this.LabelDependency.Text             = "Payout #" + dependency.Identity.ToString();
                    this.LabelPayoutIdentity.Text         = dependency.Identity.ToString();
                    this.LabelPayoutReference.Text        = ((Payout)dependency).Reference;
                }
            }
        }

        this.DocumentList.Documents = _transaction.Documents;

        Page.Title = "Editing Transaction #" + _transaction.Identity.ToString();
    }
Example #20
0
        public static Payout FromDependency(IHasIdentity dependency)
        {
            int payoutId = SwarmDb.GetDatabaseForReading().GetPayoutIdFromDependency(dependency);

            if (payoutId == 0)
            {
                throw new ArgumentException("Supplied item does not have an associated payout");
            }

            return(Payout.FromIdentity(payoutId));
        }
Example #21
0
        internal static int[] ObjectsToIdentifiers (IHasIdentity[] identifiables)
        {
            var result = new List<int>();
            result.Capacity = identifiables.Length*11/10;

            foreach (IHasIdentity identifiable in identifiables)
            {
                result.Add (identifiable.Identity);
            }

            return result.ToArray();
        }
Example #22
0
    private void AddValidations(int parentId, IHasIdentity validatableObject)
    {
        FinancialValidations validations = FinancialValidations.ForObject(validatableObject);

        foreach (FinancialValidation validation in validations)
        {
            transactionEvents.Add(
                new TransactionEvent(transactionEvents.Count + 1, parentId,
                                     validation.ValidationType + " by " + validation.Person.Canonical + " at " +
                                     validation.DateTime.ToString("yyyy-MM-dd HH:mm")));
        }
    }
Example #23
0
 public AttestableItem(string identity, string beneficiary, Int64 amountCents, FinancialAccount account,
                       string description, string identityDisplay, bool hasDox, IHasIdentity item)
 {
     IdentityDisplay      = identityDisplay;
     Identity             = identity;
     Beneficiary          = beneficiary;
     AmountRequestedCents = amountCents;
     Budget      = account;
     Description = description;
     HasDox      = hasDox;
     Item        = item;
 }
Example #24
0
        private static FinancialDependencyType GetDependencyType(IHasIdentity foreignObject)
        {
            if (foreignObject is ExpenseClaim)
            {
                return(FinancialDependencyType.ExpenseClaim);
            }
            if (foreignObject is InboundInvoice)
            {
                return(FinancialDependencyType.InboundInvoice);
            }

            throw new NotImplementedException("Unimplemented dependency type:" + foreignObject.GetType());
        }
Example #25
0
        /// <summary>
        /// Returns a detailed string representation of this transaction.
        /// </summary>
        /// <returns>A detailed string representation of this transaction.</returns>
        public string Detail()
        {
            string       tagString = "";
            IHasIdentity tag       = m_tag as IHasIdentity;

            if (tag != null)
            {
                tagString = ", " + tag.Name + "(" + tag.Guid + ")";
            }

            return(When + " : " + (m_resource == null?"<unknown>":m_resource.Name) + ", " + m_quantityObtained
                   + ", " + m_quantityDesired + ", " + m_capacity + ", " + Available + ", "
                   + (Requester == null?"<unknown>":Requester.Name) + ", " + Action + tagString);
        }
Example #26
0
        public bool CanAccess(IHasIdentity identifiableObject, AccessType accessType = AccessType.Write)
        {
            // Tests if this Authority can access a certain object. Add new object types as needed by the logic.
            // This is a very general case of the CanSeePerson() function.

            PositionAssignment testAssignment = identifiableObject as PositionAssignment;

            if (testAssignment != null)
            {
                // shortcut, for now

                return(HasSystemAccess(accessType));
            }

            throw new NotImplementedException("Authority.CanAccess is not implemented for type " + identifiableObject.GetType().FullName);
        }
Example #27
0
        private static string GetDocumentDetails(Documents documents, IHasIdentity identifiableObject)
        {
            string docLink        = string.Empty;
            string objectIdString = identifiableObject.GetType().Name + identifiableObject.Identity;

            foreach (Document document in documents)
            {
                docLink += "<a href='/Pages/v5/Support/StreamUpload.aspx?DocId=" + document.Identity +
                           "' class='FancyBox_Gallery' rel='" + objectIdString + "'>&nbsp;</a>";
            }

            return("Documents were uploaded by " + documents[0].UploadedByPerson.Canonical + " at " +
                   documents[0].UploadedDateTime.ToString("yyyy-MMM-dd HH:mm") +
                   ". <a href='#' class='linkViewDox' objectId='" + objectIdString +
                   "'>View documents.</a><span class='hiddenDocLinks'>" + docLink + "</span>");
        }
Example #28
0
        public static object FromBasic(IHasIdentity basic)
        {
            // ASSUMPTION: We're assuming that the type to be created exists in the "Logic" assembly, and that we can bind permanently in a lookup

            MethodInfo basicConverterMethod = null;
            Type       basicType            = basic.GetType();

            if (_converterLookup.ContainsKey(basicType))
            {
                basicConverterMethod = _converterLookup[basicType];
            }
            else
            {
                Assembly logicAssembly = typeof(SingularFactory).Assembly;
                Assembly basicAssembly = typeof(BasicPerson).Assembly;

                System.Type[] logicTypes =
                    logicAssembly.GetTypes().Where(type => type.IsSubclassOf(basicType)).ToArray();

                if (logicTypes.Length > 1)
                {
                    throw new InvalidOperationException("More than one type in Swarmops.Logic derives from " +
                                                        basicType.ToString());
                }
                if (logicTypes.Length == 0)
                {
                    throw new InvalidOperationException(
                              "Unable to find higher-order class in Swarmops.Logic for base type " + basicType.ToString());
                }

                Type logicType = logicTypes[0];

                basicConverterMethod = logicType.GetMethod("FromBasic", BindingFlags.Static | BindingFlags.Public);

                if (basicConverterMethod == null)
                {
                    throw new InvalidOperationException(
                              "Unable to find a public static method named \"" + logicType.ToString() + ".FromBasic (" + basicType.ToString() + ")\" in the Swarmops.Logic assembly");
                }

                _converterLookup[basicType] = basicConverterMethod;
            }

            object result = basicConverterMethod.Invoke(null, new object[] { basic });

            return(result);
        }
        public void SetObjectOptionalData(IHasIdentity thisObject, ObjectOptionalDataType dataType, string data)
        {
            using (DbConnection connection = GetMySqlDbConnection())
            {
                connection.Open();

                DbCommand command = GetDbCommand("SetObjectOptionalData", connection);
                command.CommandType = CommandType.StoredProcedure;

                AddParameterWithName(command, "objectType", GetObjectTypeForObject(thisObject).ToString());
                AddParameterWithName(command, "objectId", thisObject.Identity);
                AddParameterWithName(command, "objectOptionalDataType", dataType.ToString());
                AddParameterWithName(command, "data", data);

                command.ExecuteNonQuery();
            }
        }
Example #30
0
        public BasicAuthority GetPersonAuthority(IHasIdentity person)
        {
            List <BasicPersonRole> systemRoles       = new List <BasicPersonRole>();
            List <BasicPersonRole> organizationRoles = new List <BasicPersonRole>();
            List <BasicPersonRole> localRoles        = new List <BasicPersonRole>();

            using (DbConnection connection = GetMySqlDbConnection())
            {
                connection.Open();

                DbCommand command =
                    GetDbCommand("SELECT " + personRoleFieldSequence + ConstructWhereClause("PersonRoles", person),
                                 connection);

                using (DbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        BasicPersonRole newPersonRole = ReadPersonRoleFromDataReader(reader);

                        switch (RoleTypes.ClassOfRole(newPersonRole.Type))
                        {
                        case RoleClass.System:
                            systemRoles.Add(newPersonRole);
                            break;

                        case RoleClass.Organization:
                            organizationRoles.Add(newPersonRole);
                            break;

                        case RoleClass.Local:
                            localRoles.Add(newPersonRole);
                            break;

                        default:
                            throw new InvalidOperationException("Invalid RoleTypeId (" + newPersonRole.Type +
                                                                ") in database for PersonId " +
                                                                person.Identity.ToString());
                        }
                    }

                    return(new BasicAuthority(person.Identity, systemRoles.ToArray(), organizationRoles.ToArray(),
                                              localRoles.ToArray()));
                }
            }
        }
        static FinancialDependencyType GetDependencyType(IHasIdentity foreignObject)
        {
            if (foreignObject is ExpenseClaim)
            {
                return(FinancialDependencyType.ExpenseClaim);
            }
            if (foreignObject is InboundInvoice)
            {
                return(FinancialDependencyType.InboundInvoice);
            }
            if (foreignObject is Salary)
            {
                return(FinancialDependencyType.Salary);
            }

            throw new NotImplementedException("Unknown dependency: " + foreignObject.GetType().ToString());
        }
Example #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MaterialResourceRequest"/> class.
        /// </summary>
        /// <param name="byWhom">The identity of the entity making the reqest.</param>
        /// <param name="mt">The Material Type being requested.</param>
        /// <param name="materialSpecs">The material specs, if any, being requested. Note: See the tech note on Material Specifications.</param>
        /// <param name="quantity">The quantity of Material being requested.</param>
        /// <param name="direction">The <see cref="MaterialResourceRequest.Direction "/> of the request - Augment or Deplete.</param>
        public MaterialResourceRequest(IHasIdentity byWhom, MaterialType mt, ICollection materialSpecs, double quantity, Direction direction)
        {
            AsyncGrantConfirmationCallback = DefaultGrantConfirmationRequest_Refuse;

            Status          = RequestStatus.Free;
            Replicate       = DefaultReplicator;
            Requester       = byWhom;
            m_materialType  = mt;
            m_materialSpecs = materialSpecs ?? new ArrayList();
            if (direction.Equals(Direction.Deplete))
            {
                m_quantityDesired = quantity;
            }
            else
            {
                m_quantityDesired = -quantity;
            }
        }
Example #33
0
        public BasicAuthority GetPersonAuthority (IHasIdentity person)
        {
            List<BasicPersonRole> systemRoles = new List<BasicPersonRole>();
            List<BasicPersonRole> organizationRoles = new List<BasicPersonRole>();
            List<BasicPersonRole> localRoles = new List<BasicPersonRole>();

            using (DbConnection connection = GetMySqlDbConnection())
            {
                connection.Open();

                DbCommand command = GetDbCommand("SELECT " + personRoleFieldSequence + ConstructWhereClause("PersonRoles", person),
                                                 connection);

                using (DbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        BasicPersonRole newPersonRole = ReadPersonRoleFromDataReader(reader);

                        switch (RoleTypes.ClassOfRole(newPersonRole.Type))
                        {
                            case RoleClass.System:
                                systemRoles.Add(newPersonRole);
                                break;

                            case RoleClass.Organization:
                                organizationRoles.Add(newPersonRole);
                                break;

                            case RoleClass.Local:
                                localRoles.Add(newPersonRole);
                                break;

                            default:
                                throw new InvalidOperationException("Invalid RoleTypeId (" + newPersonRole.Type +
                                                                    ") in database for PersonId " + person.Identity.ToString());
                        }
                    }

                    return new BasicAuthority(person.Identity, systemRoles.ToArray(), organizationRoles.ToArray(),
                                              localRoles.ToArray());
                }
            }
        }
Example #34
0
        public static Payout FromDependency(IHasIdentity dependency, FinancialDependencyType dependencyType = FinancialDependencyType.Unknown)
        {
            int payoutId = 0;

            if (dependencyType == FinancialDependencyType.Unknown)
            {
                payoutId = SwarmDb.GetDatabaseForReading().GetPayoutIdFromDependency(dependency);
            }
            else
            {
                payoutId = SwarmDb.GetDatabaseForReading().GetPayoutIdFromDependency(dependency, dependencyType);
            }

            if (payoutId == 0)
            {
                throw new ArgumentException("Supplied item does not have an associated payout");
            }

            return(Payout.FromIdentity(payoutId));
        }
Example #35
0
        public static VatReportItem Create(VatReport report, FinancialTransaction transaction, Int64 turnoverCents,
                                           Int64 vatInboundCents, Int64 vatOutboundCents)
        {
            // Assumes there's a dependency of some sort

            IHasIdentity            foreignObject  = transaction.Dependency;
            FinancialDependencyType dependencyType =
                (foreignObject != null
                ? FinancialTransaction.GetFinancialDependencyType(transaction.Dependency)
                : FinancialDependencyType.Unknown);

            // The transaction dependency is stored for quick lookup; it duplicates information in the database
            // to save an expensive query as a mere optimization.

            int newVatReportItemId = SwarmDb.GetDatabaseForWriting()
                                     .CreateVatReportItem(report.Identity, transaction.Identity, foreignObject?.Identity ?? 0,
                                                          dependencyType, turnoverCents, vatInboundCents, vatOutboundCents);

            return(FromIdentityAggressive(newVatReportItemId));
        }
Example #36
0
        public static DocumentType GetDocumentTypeForObject (IHasIdentity foreignObject)
        {
            if (foreignObject == null)
            {
                // docs uploaded; foreign object not yet constructed

                return DocumentType.Unknown;
            }
            else if (foreignObject is Person)
            {
                return DocumentType.PersonPhoto;
            }
            else if (foreignObject is ExpenseClaim)
            {
                return DocumentType.ExpenseClaim;
            }
            else if (foreignObject is FinancialTransaction)
            {
                return DocumentType.FinancialTransaction;
            }
            else if (foreignObject is TemporaryIdentity)
            {
                return DocumentType.Temporary;
            }
            else if (foreignObject is InboundInvoice)
            {
                return DocumentType.InboundInvoice;
            }
            else if (foreignObject is PaperLetter)
            {
                return DocumentType.PaperLetter;
            }
            else if (foreignObject is ExternalActivity)
            {
                return DocumentType.ExternalActivityPhoto;
            }
            else
            {
                throw new ArgumentException("Unrecognized foreign object type:" + foreignObject.GetType().ToString());
            }
        }
Example #37
0
        private static string GetWhereClauseForObject (IHasIdentity foreignObject)
        {
            // This is kind of dangerous and assumes that foreignObject has the same TYPE NAME,
            // including casing, as part of the DATABASE FIELD used for primary key.

            // Also, it shifts the burden of error from the logic layer with hard function 
            // typing ("no such function: ForOrganization") at compile time, to the database layer 
            // ("No such field: OrganizationId") at runtime.

            // As such, it is not a good design choice for robustness, but a good design choice
            // for quick developability and expandability, as it reduces plumbing considerably.

            // Example: for an object of type Person with Identity 4711, this returns " PersonId=4711 ".

            if (foreignObject == null)
            {
                return string.Empty;
            }

            return " " + GetForeignTypeString(foreignObject) + "Id=" + foreignObject.Identity.ToString() + " ";
        }
        public BasicObjectOptionalData GetObjectOptionalData (IHasIdentity forObject)
        {
            Dictionary<ObjectOptionalDataType, string> initialData = new Dictionary<ObjectOptionalDataType, string>();
            ObjectType objectType = GetObjectTypeForObject(forObject);
            int objectId = forObject.Identity;

            using (DbConnection connection = GetMySqlDbConnection())
            {
                connection.Open();

                DbCommand command =
                    GetDbCommand(
                        "SELECT" + objectOptionalDataFieldSequence + "WHERE ObjectTypes.Name='" + objectType.ToString() + "' " +
                        "AND ObjectOptionalData.ObjectId=" + objectId.ToString() + ";", connection);

                using (DbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string objectOptionalDataTypeString = reader.GetString(2);
                        string data = reader.GetString(3);

                        try 
                        {
                            ObjectOptionalDataType objectOptionalDataType =
                                (ObjectOptionalDataType)
                                Enum.Parse(typeof(ObjectOptionalDataType), objectOptionalDataTypeString);

                            initialData[objectOptionalDataType] = data;
                        }
                        catch (Exception)
                        {
                            // Ignore unknown enums at this point - too many disconnects between v4 and v5  -Rick
                        }
                    }

                    return new BasicObjectOptionalData(objectType, objectId, initialData);
                }
            }
        }
Example #39
0
 public int GetPayoutIdFromDependency(IHasIdentity foreignObject)
 {
     return GetPayoutIdFromDependency(foreignObject.Identity, GetForeignTypeString(foreignObject));
 }
        static private FinancialDependencyType GetFinancialDependencyType (IHasIdentity foreignObject)
        {
            if (foreignObject is ExpenseClaim)
            {
                return FinancialDependencyType.ExpenseClaim;
            }
            else if (foreignObject is InboundInvoice)
            {
                return FinancialDependencyType.InboundInvoice;
            }
            else if (foreignObject is OutboundInvoice)
            {
                return FinancialDependencyType.OutboundInvoice;
            }
            else if (foreignObject is Salary)
            {
                return FinancialDependencyType.Salary;
            }
            else if (foreignObject is Payout)
            {
                return FinancialDependencyType.Payout;
            }
            else if (foreignObject is PaymentGroup)
            {
                return FinancialDependencyType.PaymentGroup;
            }
            else if (foreignObject is FinancialTransaction)
            {
                return FinancialDependencyType.FinancialTransaction;
            }

            throw new NotImplementedException("Unidentified dependency encountered in GetFinancialDependencyType:" +
                                          foreignObject.GetType().ToString());
        }
 public static FinancialTransaction FromDependency(IHasIdentity dependency)
 {
     return FromBasic(SwarmDb.GetDatabaseForReading().GetFinancialTransactionFromDependency(dependency));
 }
Example #42
0
 public void SetForeignObject (IHasIdentity foreignObject)
 {
     SwarmDb.GetDatabaseForWriting().SetDocumentForeignObject(this.Identity, GetDocumentTypeForObject(foreignObject), foreignObject.Identity);
 }
Example #43
0
 public static ObjectOptionalData ForObject (IHasIdentity identifiableObject)
 {
     ObjectOptionalData thisObject = FromBasic(SwarmDb.GetDatabaseForReading().GetObjectOptionalData((IHasIdentity)identifiableObject));
     thisObject.forObject = identifiableObject;
     return thisObject;
 }
 public BasicMembership[] GetExpiringMemberships (IHasIdentity organization, DateTime lowerBound, DateTime upperBound)
 {
     return GetExpiringMemberships(organization, lowerBound, upperBound, DatabaseCondition.ActiveTrue);
 }
Example #45
0
        public BasicFinancialTransaction GetFinancialTransactionFromDependency (IHasIdentity foreignObject)
        {
            using (DbConnection connection = GetMySqlDbConnection())
            {
                connection.Open();

                string commandString = "SELECT FinancialTransactionId FROM FinancialTransactionDependencies " +
                                       "JOIN FinancialDependencyTypes ON (FinancialDependencyTypes.FinancialDependencyTypeId=FinancialTransactionDependencies.FinancialDependencyTypeId) " +
                                       "WHERE FinancialDependencyTypes.Name='" + GetForeignTypeString(foreignObject) +
                                       "' AND FinancialTransactionDependencies.ForeignId=" + foreignObject.Identity + ";";


                DbCommand command = GetDbCommand(commandString, connection);

                using (DbDataReader reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        return GetFinancialTransaction(reader.GetInt32(0)); // Warning: opens another datareader before closing both
                    }

                    throw new ArgumentException(
                        String.Format("No financial transaction for specified dependency: {0} #{1}",
                                      GetForeignTypeString(foreignObject), foreignObject.Identity));
                }
            }
            


        }
        static private ObjectType GetObjectTypeForObject (IHasIdentity objectToIdentify)
        {
            //string objectTypeString = objectToIdentify.GetType().ToString();

            //// Strip namespace

            //int lastPeriodIndex = objectTypeString.LastIndexOf('.');
            //objectTypeString = objectTypeString.Substring(lastPeriodIndex + 1);

            string objectTypeString = objectToIdentify.GetType().Name;

            // At this point, we should be able to cast the string to an ObjectType enum
            try
            {
                return (ObjectType)Enum.Parse(typeof(ObjectType), objectTypeString);
            }
            catch
            {
                //That failed. This could be a subclass, try upwards.
                Type parentType = objectToIdentify.GetType().BaseType; 
                while (parentType != typeof(Object))
                {
                    try
                    {
                        return (ObjectType)Enum.Parse(typeof(ObjectType), parentType.Name);
                    }
                    catch
                    {
                        parentType = parentType.BaseType;
                    }
                }
            }
            throw new InvalidCastException("GetObjectTypeForObject could not identify object of type " + objectToIdentify.GetType().Name);
        }
        public void SetObjectOptionalData (IHasIdentity thisObject, ObjectOptionalDataType dataType, string data)
        {
            using (DbConnection connection = GetMySqlDbConnection())
            {
                connection.Open();

                DbCommand command = GetDbCommand("SetObjectOptionalData", connection);
                command.CommandType = CommandType.StoredProcedure;

                AddParameterWithName(command, "objectType", GetObjectTypeForObject(thisObject).ToString());
                AddParameterWithName(command, "objectId", thisObject.Identity);
                AddParameterWithName(command, "objectOptionalDataType", dataType.ToString());
                AddParameterWithName(command, "data", data);

                command.ExecuteNonQuery();
            }
        }
Example #48
0
 public int GetPayoutIdFromDependency(IHasIdentity foreignObject, FinancialDependencyType typeName)
 {
     return GetPayoutIdFromDependency(foreignObject.Identity, typeName.ToString());
 }
Example #49
0
        private static string GetForeignTypeString (IHasIdentity foreignObject)
        {
            string typeString = "";
            foreach (object attribute in foreignObject.GetType().GetCustomAttributes(typeof(DbRecordType), true))
            {
                if (attribute is DbRecordType)
                {
                    typeString = ((DbRecordType)attribute).TypeName;
                }
            }
            if (typeString == "")
            {
                typeString = foreignObject.GetType().ToString();

                if (typeString.Contains("."))
                {
                    int periodIndex = typeString.LastIndexOf('.');
                    typeString = typeString.Substring(periodIndex + 1);
                }
            }

            return typeString;
        }
 public BasicMembership[] GetExpiringMemberships (IHasIdentity organization, DateTime expiry)
 {
     return GetExpiringMemberships(organization, expiry, expiry);
 }
        public BasicMembership[] GetExpiringMemberships (IHasIdentity organization, DateTime lowerBound, DateTime upperBound, DatabaseCondition condition)
        {
            // Since I don't trust SQL Server to make correct date comparisons, especially given
            // that the dates are passed in text in SQL, we get ALL the memberships and do
            // the comparison in code instead. This is a run-seldom function, anyway, and getting
            // some 50k records with four short unlinked fields isn't that expensive.

            BasicMembership[] memberships = this.GetMemberships(organization, condition);

            DateTime minimumDateTime = lowerBound.Date;
            DateTime maximumDateTime = upperBound.Date.AddDays(1);

            List<BasicMembership> result = new List<BasicMembership>();

            foreach (BasicMembership membership in memberships)
            {
                // It is important that the lower border is inclusive and the upper exclusive in this
                // comparison:

                if (membership.Expires >= minimumDateTime && membership.Expires < maximumDateTime)
                {
                    result.Add(membership);
                }
            }

            return result.ToArray();
        }
    private void AddValidations (int parentId, IHasIdentity validatableObject)
    {
        FinancialValidations validations = FinancialValidations.ForObject(validatableObject);

        foreach (FinancialValidation validation in validations)
        {
            transactionEvents.Add(
                new TransactionEvent(transactionEvents.Count + 1, parentId,
                                     validation.ValidationType + " by " + validation.Person.Canonical + " at " +
                                     validation.DateTime.ToString("yyyy-MM-dd HH:mm")));

        }
    }
Example #53
0
        static public object FromBasic(IHasIdentity basic)
        {
            string argumentType = basic.GetType().ToString();

            switch (argumentType)
            {
                // ----- Is there any way to make self-writing code here through replication or similar, so
                // ----- that every case doesn't need to be listed?


                // ------------ COMMUNICATION CLASSES ------------

                case "Swarmops.Basic.Types.BasicCommunicationTurnaround":
                    return CommunicationTurnaround.FromBasic((BasicCommunicationTurnaround)basic);

                case "Swarmops.Basic.Types.Communications.BasicOutboundComm":
                    return OutboundComm.FromBasic((BasicOutboundComm)basic);

                case "Swarmops.Basic.Types.Communications.BasicOutboundCommRecipient":
                    return OutboundCommRecipient.FromBasic((BasicOutboundCommRecipient)basic);


                // ----------- FINANCIAL CLASSES ----------

                case "Swarmops.Basic.Types.BasicExpenseClaim":
                    return ExpenseClaim.FromBasic((BasicExpenseClaim)basic);

                case "Swarmops.Basic.Types.Financial.BasicCashAdvance":
                    return CashAdvance.FromBasic((BasicCashAdvance)basic);

                case "Swarmops.Basic.Types.BasicInboundInvoice":
                    return InboundInvoice.FromBasic((BasicInboundInvoice) basic);

                case "Swarmops.Basic.Types.Financial.BasicFinancialAccount":
                    return FinancialAccount.FromBasic((BasicFinancialAccount)basic);

                case "Swarmops.Basic.Types.Financial.BasicFinancialTransaction":
                    return FinancialTransaction.FromBasic((BasicFinancialTransaction)basic);

                case "Swarmops.Basic.Types.BasicFinancialValidation":
                    return FinancialValidation.FromBasic((BasicFinancialValidation)basic);

                case "Swarmops.Basic.Types.BasicOutboundInvoice":
                    return OutboundInvoice.FromBasic((BasicOutboundInvoice)basic);

                case "Swarmops.Basic.Types.BasicOutboundInvoiceItem":
                    return OutboundInvoiceItem.FromBasic((BasicOutboundInvoiceItem)basic);

                case "Swarmops.Basic.Types.BasicPayment":
                    return Payment.FromBasic((BasicPayment)basic);

                case "Swarmops.Basic.Types.BasicPaymentGroup":
                    return PaymentGroup.FromBasic((BasicPaymentGroup)basic);

                case "Swarmops.Basic.Types.BasicPayout":
                    return Payout.FromBasic((BasicPayout)basic);

                case "Swarmops.Basic.Types.BasicPayrollAdjustment":
                    return PayrollAdjustment.FromBasic((BasicPayrollAdjustment) basic);

                case "Swarmops.Basic.Types.BasicPayrollItem":
                    return PayrollItem.FromBasic((BasicPayrollItem)basic);

                case "Swarmops.Basic.Types.BasicSalary":
                    return Salary.FromBasic((BasicSalary) basic);

                case "Swarmops.Basic.Types.Financial.BasicFinancialTransactionTagSet":
                    return FinancialTransactionTagSet.FromBasic ((BasicFinancialTransactionTagSet) basic);

                case "Swarmops.Basic.Types.Financial.BasicFinancialTransactionTagType":
                    return FinancialTransactionTagType.FromBasic((BasicFinancialTransactionTagType) basic);

                // ------------ GOVERNANCE CLASSES ------------

                case "Swarmops.Basic.Types.BasicBallot":
                    return Ballot.FromBasic((BasicBallot)basic);

                case "Swarmops.Basic.Types.BasicMeetingElectionCandidate":
                    return MeetingElectionCandidate.FromBasic((BasicInternalPollCandidate)basic);

                case "Swarmops.Basic.Types.BasicMeetingElection":
                    return MeetingElection.FromBasic((BasicInternalPoll)basic);

                case "Swarmops.Basic.Types.BasicMeetingElectionVote":
                    return MeetingElectionVote.FromBasic((BasicInternalPollVote)basic);

                    case "Swarmops.Basic.Types.Governance.BasicMotion":
                    return Motion.FromBasic((BasicMotion)basic);

                case "Swarmops.Basic.Types.Governance.BasicMotionAmendment":
                    return MotionAmendment.FromBasic((BasicMotionAmendment)basic);


                // ------------ PARLEY/ACTIVISM CLASSES ------------

                case "Swarmops.Basic.Types.BasicExternalActivity":
                    return ExternalActivity.FromBasic((BasicExternalActivity) basic);

                case "Swarmops.Basic.Types.BasicParley":
                    return Parley.FromBasic((BasicParley)basic);

                case "Swarmops.Basic.Types.BasicParleyAttendee":
                    return ParleyAttendee.FromBasic((BasicParleyAttendee)basic);

                case "Swarmops.Basic.Types.BasicParleyOption":
                    return ParleyOption.FromBasic((BasicParleyOption)basic);

                case "Swarmops.Basic.Types.BasicPerson":
                    return Person.FromBasic((BasicPerson)basic);

                // ------------------ FAIL ----------------

                default:
                    throw new NotImplementedException("Unimplemented argument type: " + argumentType);

            }


        }