1

我希望能够计算并在我的联系表格上显示该联系人约会的最新实际结束日期。

以下查询显示了我如何针对帐户实体实现相同的功能。

使用 JavaScript 和 REST OData 查询 CRM 2011 AppointmentSet 时如何测试 d.data.results 中存在哪些数据

现在我尝试对联系人做同样的事情,但关于objectid 与任何联系人都不匹配。所以我在问我该怎么做。

我是否需要为组织者、可选参加者和必需参加者打开和展开每个派对列表?如果是这样,我将如何为此创建查询?使用 $expand 功能?

请帮助一个困扰的头脑!

撞!

4

1 回答 1

1

好的,所以我已经在这个问题上工作了几天了。

我发现可以借助以下工具XRM Dynamics Tools来帮助生成我的 OData 查询代码来完成此任务。

本质上,我遇到的问题是了解联系人如何与约会相关联。一旦我了解约会的所有参与者都将包含在约会的“appointment_activity_parties”字段中,我就能够看到如何创建合适的查询来处理这个问题。

通过选择 activityid、actualEnd 字段并使用 Appointment_activity_parties 上的扩展功能,从该扩展字段中选择 PartyId 使我能够检查派对类型是否为联系人,派对的 contactId 是否与我们正在查看的当前联系人匹配。这样我就可以计算匹配的总数并记录该联系人完成约会的最近日期。

最后,我还将问题分解为 2 个查询。每年一个:当前和以前。我在联系表单中添加了三个新字段。两个保存 VisitsLastYear 和 VisitsThisYear 的整数,以及保存到 Appointment 的链接的查找,如以下屏幕截图所示:

在此处输入图像描述

我的代码如下:

/// <reference path="XrmPageTemplate.js" />
/// <reference path="JQuery.js" />
/// <reference path="SDK.REST.js" />
/// <reference path="json2.js" />
function HarrionAB_ContactForm_OnLoad() {

    // get the contact id from the page
    var contactId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "")
    // if we got a value
    if (contactId != "") {
        var currentYear = new Date().getFullYear();
        var query = "/AppointmentSet?";                                                                         // Appointments table
            query += "$select=ActualEnd,ActivityId,appointment_activity_parties/PartyId";                       // Select
            query += "&$expand=appointment_activity_parties";                                                   // Expand sub tables
            query += "&$filter=ActivityTypeCode eq 'appointment' and StateCode/Value eq 1 and ";                // Where

        CountVisitsThisYear(query, currentYear);
        CountVisitsLastYear(query, currentYear - 1);
    }
}

function CountVisitsThisYear(query, currentYear) {

    var start = currentYear.toString() + "-01-01T00:00:00";
    var end = currentYear.toString() + "-12-31T00:00:00";

    query += "ActualStart ge datetime'" + start + "' or ActualStart le datetime'" + start + "' and ";   // Where  
    query += "ActualEnd ge datetime'" + end + "' or ActualEnd le datetime'" + end + "'";                // Where

    // call function to execute the odata query
    ExecuteVisitsThisYearQuery(query);
}

function CountVisitsLastYear(query, lastYear) {

    var start = lastYear.toString() + "-01-01T00:00:00";
    var end = lastYear.toString() + "-12-31T00:00:00";
    query += "ActualStart ge datetime'" + start + "' or ActualStart le datetime'" + start + "' and ";   // Where  
    query += "ActualEnd ge datetime'" + end + "' or ActualEnd le datetime'" + end + "'";                // Where

    // call function to execute the odata query
    ExecuteVisitsLastYearQuery(query);
}

//
// ExecuteQuery executes the specified OData Query asyncronously
//
// NOTE: Requires JSON and jQuery libraries. Review this Microsoft MSDN article before 
//       using this script http://msdn.microsoft.com/en-us/library/gg328025.aspx
//
function ExecuteVisitsThisYearQuery(ODataQuery) {

    // get the server url
    var serverUrl = Xrm.Page.context.getServerUrl();

    // Adjust URL for differences between on premise and online 
    if (serverUrl.match(/\/$/)) {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    }

    var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: ODataURL,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //
            // Handle result from successful execution
            //
            // e.g. data.d.results
            var contactId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");
            var lastVisitDate;
            var activityId;

            var count = 0;
            // if we have results
            if (data.d.results.length > 0) {
                // loop through the appointment results
                for (i = 0; i < data.d.results.length; i++) {
                    // if we have results
                    if (data.d.results[i].appointment_activity_parties.results.length > 0) {
                        // loop through the appointment_activity_parties
                        for (j = 0; j < data.d.results[i].appointment_activity_parties.results.length; j++) {
                            // if the party id type is contact and the contact ids match
                            if (data.d.results[i].appointment_activity_parties.results[j].PartyId.LogicalName == "contact" && contactId.toLowerCase() == data.d.results[i].appointment_activity_parties.results[j].PartyId.Id.toLowerCase()) {
                                // if we have not got a date yet
                                if (lastVisitDate == null) {
                                    // set the date as this is the first date we found
                                    lastVisitDate = data.d.results[i].ActualEnd;
                                    activityId = data.d.results[i].ActivityId;
                                } else {
                                    // if the current date is < new date
                                    if (lastVisitDate < data.d.results[i].ActualEnd) {
                                        // reset the date as we have found a later one
                                        lastVisitDate = data.d.results[i].ActualEnd;
                                        activityId = data.d.results[i].ActivityId;
                                    }
                                }
                                ++count;
                            }
                        }
                    }
                }
            }

            Xrm.Page.getAttribute("new_visitsthisyear").setValue(count);
            // if we found a completed appointment
            if (count > 0) {
                SetLookup("new_lastvisitcompleted", activityId, ParseJsonDate(lastVisitDate).toString('dd/MM/yyyy'), "Appointment");
            }
        },
        error: function (XmlHttpRequest, textStatus, errorObject) {
            //
            // Handle result from unsuccessful execution
            //
            alert("OData Execution Error Occurred");
        }
    });
}

//
// ExecuteQuery executes the specified OData Query asyncronously
//
// NOTE: Requires JSON and jQuery libraries. Review this Microsoft MSDN article before 
//       using this script http://msdn.microsoft.com/en-us/library/gg328025.aspx
//
function ExecuteVisitsLastYearQuery(ODataQuery) {

    // get the server url
    var serverUrl = Xrm.Page.context.getServerUrl();

    // Adjust URL for differences between on premise and online 
    if (serverUrl.match(/\/$/)) {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    }

    var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: ODataURL,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //
            // Handle result from successful execution
            //
            // e.g. data.d.results
            var contactId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");

            var count = 0;
            // if we have results
            if (data.d.results.length > 0) {
                // loop through the appointment results
                for (i = 0; i < data.d.results.length; i++) {
                    // if we have results
                    if (data.d.results[i].appointment_activity_parties.results.length > 0) {
                        // loop through the appointment_activity_parties
                        for (j = 0; j < data.d.results[i].appointment_activity_parties.results.length; j++) {
                            // if the party id type is contact and the contact ids match
                            if (data.d.results[i].appointment_activity_parties.results[j].PartyId.LogicalName == "contact" && contactId.toLowerCase() == data.d.results[i].appointment_activity_parties.results[j].PartyId.Id.toLowerCase()) {
                                ++count;
                            }
                        }
                    }
                }
            }

            Xrm.Page.getAttribute("new_visitslastyear").setValue(count);
        },
        error: function (XmlHttpRequest, textStatus, errorObject) {
            //
            // Handle result from unsuccessful execution
            //
            alert("OData Execution Error Occurred");
        }
    });
}


// function to parse JSON date into JavaScript Date
function ParseJsonDate(jsonDate) {
    var offset = new Date().getTimezoneOffset() * 60000;
    var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);

    if (parts[2] == undefined)
        parts[2] = 0;

    if (parts[3] == undefined)
        parts[3] = 0;

    return new Date(+parts[1] + offset + parts[2] * 3600000 + parts[3] * 60000);
};

//function to create a lookup control
function SetLookup(fieldName, idValue, textValue, typeValue) {
    var value = new Array();
    value[0] = new Object();
    value[0].id = idValue;
    value[0].name = textValue;
    value[0].typename = typeValue;

    Xrm.Page.getAttribute(fieldName).setValue(value);
}


//
// Error Handler
//
function ErrorHandler(XMLHttpRequest, textStatus, errorObject)
{ alert("Error Occurred : " + textStatus + ": " + JSON.parse(XMLHttpRequest.responseText).error.message.value); }

希望这可以帮助任何有类似问题的人。

于 2013-11-20T16:48:21.713 回答