protected void Page_Load(object sender, EventArgs e)
        {
            Guid[] personIds = ((List <Guid>)HttpContext.Current.Application["personIds"]).ToArray();
            Dictionary <Guid, pNode> nodes = new Dictionary <Guid, pNode>(personIds.Length);

            for (int g = 0; g < personIds.Length; g++)
            {
                nodes.Add(personIds[g], new pNode());
            }
            IntegrationService igServ         = new IntegrationService();
            string             parsecDomain   = ConfigurationManager.AppSettings.Get("domain");
            string             parsecUser     = ConfigurationManager.AppSettings.Get("user");
            string             parsecPassword = ConfigurationManager.AppSettings.Get("password");
            string             turniketString = ConfigurationManager.AppSettings.Get("turniket");
            Guid turniket = new Guid(turniketString);

            EventHistoryQueryParams param = new EventHistoryQueryParams();

            param.StartDate         = DateTime.Today.ToUniversalTime();
            param.EndDate           = DateTime.Today.AddDays(1).ToUniversalTime();
            param.Territories       = new Guid[] { turniket };
            param.EventsWithoutUser = false;
            param.TransactionTypes  = new uint[] { 590144, 590152, 65867, 590165, 590145, 590153, 65866, 590166 };
            param.MaxResultSize     = (10000);
            param.Organizations     = ((List <Guid>)HttpContext.Current.Application["orgIds"]).ToArray();
            param.Users             = ((List <Guid>)HttpContext.Current.Application["personIds"]).ToArray();
            List <Guid> fields = new List <Guid>();

            fields.Add(EventHistoryFields.EVENT_TIME);
            fields.Add(EventHistoryFields.EVENT_CODE_HEX);
            fields.Add(new Guid("7C6D82A0-C8C8-495B-9728-357807193D23")); //ID юзера
            EventObject[] events = null;

            //дергаем Парсек
            SessionResult res = igServ.OpenSession(parsecDomain, parsecUser, parsecPassword);

            if (res.Result != 0)
            {
                Response.Write("{\"err\":\"Can not open session to Parsec\"}"); return;
            }
            Guid sessionID = res.Value.SessionID;
//сессия истории с Парсеком
            GuidResult res1 = igServ.OpenEventHistorySession(sessionID, param);

            if (res1.Result != 0)
            {
                Response.Write("{\"err\":\"Can not OpenEventHistorySession in Parsec\"}"); return;
            }
//получить события дня
            events = igServ.GetEventHistoryResult(sessionID, res1.Value /*сессия истории*/, fields.ToArray(), 0, 10000);
            igServ.CloseEventHistorySession(sessionID, res1.Value);
            igServ.CloseSession(sessionID);

            //ищем последний выход (просматриваем список с начала к концу)
            for (int ii = 0; ii < events.Length; ii++)
            {
                switch ((string)events[ii].Values[1])
                {
                case "90141":
                case "90149":
                case "90142":
                case "901A4":
                case "90156":
                case "901A5":      //КОДЫ ВЫХОДА
                    if (events[ii].Values[2] != null)
                    {
                        Guid nodeid = new Guid(events[ii].Values[2].ToString());
                        if (nodes.ContainsKey(nodeid))
                        {
                            nodes[nodeid].exit = events[ii].Values[0].ToString();
                        }
                    }
                    break;

                case "90140":
                case "90148":
                case "1014B":
                case "90155":      //КОДЫ ВХОДА - если был вход после выхода, значит выхода не было ;)
                    if (events[ii].Values[2] != null)
                    {
                        Guid nodeid = new Guid(events[ii].Values[2].ToString());
                        if (nodes.ContainsKey(nodeid))
                        {
                            nodes[nodeid].exit = null;
                        }
                    }
                    break;
                }
            }
            //ищем первый вход (просматриваем с конца к началу)
            for (int ii = events.Length - 1; ii >= 0; ii--)
            {
                switch ((string)events[ii].Values[1])
                {
                case "90140":
                case "90148":
                case "1014B":
                case "90155":      //КОДЫ ВХОДА
                    if (events[ii].Values[2] != null)
                    {
                        Guid nodeid = new Guid(events[ii].Values[2].ToString());
                        if (nodes.ContainsKey(nodeid))
                        {
                            nodes[nodeid].enter = events[ii].Values[0].ToString();
                        }
                    }
                    break;
                }
            }

            List <pNode> pl = nodes.Values.ToList <pNode>();
            DateTime     vhod, vihod;

            for (int k = 0; k < pl.Count; k++)
            {
                if (!DateTime.TryParse(pl[k].enter, out vhod))
                {
                    pl[k].tag = "absent";
                    continue;
                }
                if (!DateTime.TryParse(pl[k].exit, out vihod))
                {
                    pl[k].tag = "in";
                    continue;
                }
                if (vihod > vhod)
                {
                    pl[k].tag = "out";
                }
            }


            Response.Clear();
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write(JsonConvert.SerializeObject(nodes,
                                                       Newtonsoft.Json.Formatting.None,
                                                       new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            })
                           );
            Response.End();
        }
Example #2
0
        static void Main(string[] args)
        {
            DateTime JudgmentDay;

            if (args.Length < 1)
            {
                Console.WriteLine("USAGE: fromParsec2SQL <DD.MM.YYYY/TODAY/YESTERDAY>");
                return;
            }
            else if (args[0].ToUpper().StartsWith("TODAY"))
            {
                JudgmentDay = DateTime.Today;
            }
            else if (args[0].ToUpper().StartsWith("YESTERDAY"))
            {
                JudgmentDay = DateTime.Today.AddDays(-1);
            }
            else if (!DateTime.TryParse(args[0], out JudgmentDay))
            {
                Console.WriteLine("USAGE: pFillDayEvents <DD.MM.YYYY/TODAY/YESTERDAY>");
                return;
            }
            //штатное время выхода и входа для заданной даты
            DateTime proposedExit = (JudgmentDay.DayOfWeek.ToString() == "Friday") ?
                                    new DateTime(JudgmentDay.Year, JudgmentDay.Month, JudgmentDay.Day, 17, 0, 0)
                : new DateTime(JudgmentDay.Year, JudgmentDay.Month, JudgmentDay.Day, 18, 15, 0);
            DateTime proposedEnter = new DateTime(JudgmentDay.Year, JudgmentDay.Month, JudgmentDay.Day, 9, 0, 0);

            var connectionString = ConfigurationManager.ConnectionStrings["ParsecReport"].ConnectionString;

            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                sqlCon.Open();
                checkTable(sqlCon);
                sqlCon.Close();
            }

            IntegrationService igServ         = new IntegrationService();
            string             parsecdomain   = ConfigurationManager.AppSettings.Get("domain");
            string             parsecuser     = ConfigurationManager.AppSettings.Get("user");
            string             parsecpassword = ConfigurationManager.AppSettings.Get("password");
            string             turniketString = ConfigurationManager.AppSettings.Get("turniket");
            Guid          turniket            = new Guid(turniketString);
            SessionResult res = igServ.OpenSession(parsecdomain, parsecuser, parsecpassword);

            if (res.Result != 0)
            {
                Console.WriteLine("Can not open session to Parsek");
                return;
            }
            Guid sessionID = res.Value.SessionID;

            BaseObject[]            hierarhyList = igServ.GetOrgUnitsHierarhyWithPersons(sessionID);
            EventHistoryQueryParams param        = new EventHistoryQueryParams();

            param.StartDate         = JudgmentDay.ToUniversalTime();
            param.EndDate           = JudgmentDay.AddDays(1).ToUniversalTime();
            param.Territories       = new Guid[] { turniket };
            param.EventsWithoutUser = false;
            param.TransactionTypes  = new uint[] { 590144, 590152, 65867, 590165, 590145, 590153, 65866, 590166 };
            param.MaxResultSize     = (10000);

            EventHistoryFields constants = new EventHistoryFields();
            List <Guid>        fields    = new List <Guid>();

            fields.Add(EventHistoryFields.EVENT_DATE_TIME);
            fields.Add(EventHistoryFields.EVENT_CODE_HEX);

            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                sqlCon.Open();

                int i = 0;
                for (i = hierarhyList.Length - 1; i >= 0; i--)
                {
                    if (hierarhyList[i] == null)
                    {
                        continue;
                    }
                    Person personItem = hierarhyList[i] as Person;
                    if (personItem != null)
                    {
                        Guid          userid = personItem.ID;
                        List <string> hlist  = new List <string>();
                        param.Users = new Guid[] { personItem.ID };
                        GuidResult ev = igServ.OpenEventHistorySession(sessionID, param);
                        if (ev.Result != 0)
                        {
                            continue;
                        }
                        Guid eventSessionID = ev.Value;

                        DateTime?     enter = null, exit = null, lastEventTime = null;
                        DateTime      tmptime;
                        bool          lastEventWasEnter = false;
                        int           eventscount = 0, totalworktime = 0, totalouttime = 0;
                        EventObject[] events = null;
                        events = igServ.GetEventHistoryResult(sessionID, eventSessionID, fields.ToArray(), 0, 10000);
                        for (int ii = 0; ii < events.Length; ii++)
                        {
                            switch ((string)events[ii].Values[1])
                            {
                            case "90140":
                            case "90148":
                            case "1014B":
                            case "90155":      //КОДЫ ВХОДА
                                eventscount++;
                                hlist.Add("Вход: " + events[ii].Values[0].ToString() + "<br>");
                                if (DateTime.TryParse(events[ii].Values[0].ToString(), out tmptime))
                                {
                                    enter             = (enter == null || tmptime < enter) ? tmptime : enter;
                                    totalouttime     += (lastEventWasEnter || lastEventTime == null) ? 0 : (int)(tmptime - (DateTime)lastEventTime).TotalMinutes;
                                    lastEventWasEnter = true;
                                    lastEventTime     = tmptime;
                                }
                                break;

                            case "90141":
                            case "90149":
                            case "90142":
                            case "901A4":
                            case "90156":
                            case "901A5":      //КОДЫ ВЫХОДА
                                eventscount++;
                                hlist.Add("Выход: " + events[ii].Values[0].ToString() + "<br>");
                                if (DateTime.TryParse(events[ii].Values[0].ToString(), out tmptime))
                                {
                                    exit              = (exit == null || tmptime > exit) ? tmptime : exit;
                                    totalworktime    += (!lastEventWasEnter || lastEventTime == null) ? 0 : (int)(tmptime - (DateTime)lastEventTime).TotalMinutes;
                                    lastEventWasEnter = false;
                                    lastEventTime     = tmptime;
                                }
                                break;
                            }
                        }

                        DateTime renter, rexit;
                        if (enter == null || exit == null)
                        {
                            continue;
                        }
                        else
                        {
                            renter = enter ?? DateTime.Now;
                            rexit  = exit ?? DateTime.Now;
                        }

                        int opozd = (int)(renter - proposedEnter).TotalMinutes;
                        int zader = (int)(rexit - proposedExit).TotalMinutes;
                        //                        hlist.Reverse();
                        string history = String.Concat(hlist);
                        string sqlc    = "if not exists "
                                         + "(select * from ParsecOrgHistory where id = @id and sysdate = @sysdate) "
                                         + " insert into ParsecOrgHistory "
                                         + " (id, sysdate, date, enter,eexit, eventscount, totalworktime, totalouttime, opozd, zader, history) "
                                         + " values (@id, @sysdate, @date, @enter,@eexit, @eventscount, @totalworktime,@totalouttime, @opozd, @zader, @history)"
                        ;
                        using (SqlCommand sqlCmd1 = new SqlCommand {
                            CommandText = sqlc, Connection = sqlCon
                        })
                        {
                            sqlCmd1.Parameters.AddWithValue("@id", userid.ToString());
                            sqlCmd1.Parameters.AddWithValue("@sysdate", JudgmentDay);
                            sqlCmd1.Parameters.AddWithValue("@date", JudgmentDay.ToString("dd-MM-yyyy"));
                            sqlCmd1.Parameters.AddWithValue("@enter", renter.ToString("HH-mm"));
                            sqlCmd1.Parameters.AddWithValue("@eexit", rexit.ToString("HH-mm"));
                            sqlCmd1.Parameters.AddWithValue("@eventscount", eventscount);
                            sqlCmd1.Parameters.AddWithValue("@totalworktime", totalworktime);
                            sqlCmd1.Parameters.AddWithValue("@totalouttime", totalouttime);
                            sqlCmd1.Parameters.AddWithValue("@opozd", opozd);
                            sqlCmd1.Parameters.AddWithValue("@zader", zader);
                            sqlCmd1.Parameters.AddWithValue("@history", history);
                            sqlCmd1.ExecuteNonQuery();
                        }
                    }
                }

                sqlCon.Close();
            }
        }
        public static Dictionary <Guid, orgNode> makeOrgDataAndUserimgs(string appPath)
        {
            Dictionary <Guid, orgNode> nodes = new Dictionary <Guid, orgNode>(); //подназорные и подразделения вперемешку
            List <Guid> orgs    = new List <Guid>();                             //список Guid подразделен
            List <Guid> persons = new List <Guid>();                             //список Guid поднадзорных
            Dictionary <string, string> nameMapping = (ConfigurationManager.GetSection("ParsecMapping") as System.Collections.Hashtable)
                                                      .Cast <System.Collections.DictionaryEntry>()
                                                      .ToDictionary(d => (string)d.Key, d => (string)d.Value);

            IntegrationService iServ = new IntegrationService();

            string apidomain      = ConfigurationManager.AppSettings.Get("domain");
            string apiuser        = ConfigurationManager.AppSettings.Get("user");
            string apipassword    = ConfigurationManager.AppSettings.Get("password");
            string turniketString = ConfigurationManager.AppSettings.Get("turniket");
            Guid   turniket       = new Guid(turniketString);
            string orgRootString  = ConfigurationManager.AppSettings.Get("orgRoot");
            Guid   orgRoot        = new Guid(orgRootString);

            SessionResult res = iServ.OpenSession(apidomain, apiuser, apipassword);

            if (res.Result != 0)
            {
                return(null);
            }

            Guid sessionID = res.Value.SessionID;

            Dictionary <Guid, string> extraNames = new Dictionary <Guid, string>();

            PersonExtraFieldTemplate[] extraTempl = iServ.GetPersonExtraFieldTemplates(sessionID);
            for (int j = extraTempl.Length - 1; j >= 0; j--)
            {
                extraNames.Add(extraTempl[j].ID, extraTempl[j].NAME);
            }

            BaseObject[] hierarhyList = iServ.GetOrgUnitSubItemsHierarhyWithPersons(sessionID, orgRoot);
            for (int i = hierarhyList.Length - 1; i >= 0; i--)
            {
                orgNode node = new orgNode();

                Person personItem = hierarhyList[i] as Person;
                if (personItem != null)
                {
                    node.id     = personItem.ID;
                    node.pid    = personItem.ORG_ID;
                    node.name   = personItem.LAST_NAME.Trim();
                    node.mlname = (personItem.FIRST_NAME ?? "") + " " + (personItem.MIDDLE_NAME ?? "");
                    node.sam    = personItem.TAB_NUM;
                    node.type   = "person";
                    ExtraFieldValue[] extraVals = iServ.GetPersonExtraFieldValues(sessionID, node.id);
                    //map extraFields from Parsec to orgNode
                    for (int k = extraVals.Length - 1; k >= 0; k--)
                    {
                        string extraName = extraNames[extraVals[k].TEMPLATE_ID];
                        string propname  = "";
                        if (nameMapping.TryGetValue(extraName, out propname))
                        {
                            node[propname] = (string)extraVals[k].VALUE;
                        }
                    }

                    var pPhoto = iServ.GetPerson(sessionID, node.id);

                    if (pPhoto.PHOTO != null)
                    {
                        using (Image image = Image.FromStream(new MemoryStream(pPhoto.PHOTO)))
                        {
                            image.Save(
                                appPath + "userimg/" + pPhoto.ID.ToString() + ".jpg",
                                ImageFormat.Jpeg
                                );
                            node.img = node.id;
                        }
                    }

                    nodes.Add(node.id, node);
                    persons.Add(node.id);
                    continue;
                }
                OrgUnit orgItem = hierarhyList[i] as OrgUnit;
                if (orgItem != null)
                {
                    node.id   = orgItem.ID;
                    node.pid  = orgItem.PARENT_ID;
                    node.name = orgItem.NAME;
                    var boss = nodes.Values.FirstOrDefault(n => n.name.Equals(orgItem.DESC.Trim()));
                    if (boss != null)
                    {
                        node.boss = boss.id;
                    }
                    node.type = "org";
                    nodes.Add(orgItem.ID, node);
                    orgs.Add(node.id);
                }
            }

            iServ.CloseSession(sessionID);
            HttpContext.Current.Application["orgdata"]   = nodes;
            HttpContext.Current.Application["orgIds"]    = orgs;
            HttpContext.Current.Application["personIds"] = persons;
            return(nodes);
        }