$(function () {
var form = document.getElementById('message_form');
$('body').on('focus', ".term-picker", function () {
$(this).datepicker({
minDate: 0,
});
})
$("#reserve-button").on("click", function (e) {
e.preventDefault();
$("#reserve-stage-modal").modal('show');
var orderId = $(this).attr('data-order-id');
$.ajax({
url: '/api/stages/',
type: 'GET',
data: {csrfmiddlewaretoken: csrftoken, 'order': orderId},
dataType: 'json',
success: function (json) {
var outputValues = '';
var totalSum = 0;
var stagesIds = '';
var notPaidCount = 0;
$.each(json.results, function (i, v) {
if ((v.status == 'in_process') && (!v.is_paid)) {
totalSum += parseInt(v.cost);
notPaidCount += 1;
outputValues += '';
stagesIds += v.id + ';'
}
});
$("#stagesSelect").html(outputValues);
$(".totalSum").text(totalSum);
if (json.results.length > notPaidCount && notPaidCount > 0) {
$("#choiceWayOrder").hide();
}
$("#choiceWayOrder").val(totalSum);
$("#ordermodalId").val(orderId);
$("#stages-pay-form #stageSumPay").val(totalSum);
$("#stages-pay-form #stagesIds").val(stagesIds);
$("#choiceWayOrder").attr('data-stages-ids', stagesIds);
}
});
});
$("#tab2").on("change", "input[name=choice_way]:radio", function (e) {
var sumStage = $("#stagesSelect").find('option:selected').attr('data-stage-sum');
var currIdStage = $("#stagesSelect").find('option:selected').val();
$("#choiceWayStage").val(sumStage);
var currValue = $(this).val();
$("#stages-pay-form #stageSumPay").val(currValue);
var selectId = ($(this).attr('id'));
if (selectId == 'choiceWayOrder') {
$("#stages-pay-form #stagesIds").val($(this).attr('data-stages-ids'));
$("#stagesSelect").prop('disabled', 'disabled');
} else {
$("#stages-pay-form #stagesIds").val(currIdStage);
$("#stagesSelect").prop('disabled', false);
}
});
$("#tab2").on("change", "#stagesSelect", function (e) {
var sumStage = $(this).find('option:selected').attr("data-stage-sum");
$("#choiceWayStage").val(sumStage);
$("#stages-pay-form #stageSumPay").val(sumStage);
$(".stageSum").text(sumStage);
$("#stages-pay-form #stagesIds").val($(this).val());
});
//Получить заказы
function getStages(orderId, senderId, recipentId, secureOrder) {
$.ajax({
url: '/api/orders/' + orderId + '/',
type: 'GET',
data: {csrfmiddlewaretoken: csrftoken},
dataType: 'json',
}).then(function (data) {
var isReviewLeave = data.has_user_review;
var stagesResults = data.stages;
var stageCount = stagesResults.length;
if (stageCount == 0) {
$("#reserveSpace").hide();
stageCountVal = 1;
} else {
stageCountVal = stageCount;
}
var htmlInbox = "";
var htmlInboxStage = '
Какое кол-во этапов подразумевает работа? ' +
'
';
if (stageCount == 0) {
htmlInboxStage += '';
}
var statusNotAgreed = true;
var stagesInWork = [];
var stagesPaidProcess = [];
var stagesCompleted = [];
var stagePaidCount = 0;
var stagesReservedHtml = "";
$.each(stagesResults, function (i, v) {
if (v.status == "completed") {
stagesCompleted.push(v);
}
if (!data.secure) {
if (v.status == "in_process") {
stagesInWork.push(v);
}
} else if ((v.status == "in_process") && (v.is_paid)) {
stagesInWork.push(v);
stagesPaidProcess.push(v);
}
if (v.is_paid) {
stagePaidCount += 1;
}
if (v.status == "not_agreed" || v.status == 'cancel_approve' || v.status == 'send_approve') {
htmlInbox += '';
} else {
statusNotAgreed = false;
htmlInboxStage = "";
var statusName = "";
switch (v.status) {
case 'completed':
statusName = 'Завершен';
break;
case 'in_process':
statusName = 'Согласовано';
break;
default:
statusName = '';
break;
}
if (v.status == 'completed') {
statusName = 'Завершен';
}
htmlInbox += '' +
'
Этап ' + v.pos + '' + v.name + '
' +
'
Результаты этапа:' + v.result + '
' +
'
Срок до ' + v.term + '
' + v.cost + '' +
'
Cрок заказа рассчитывается с момента резервирования средств
' +
'
';
}
if (data.secure) {
if (v.is_paid) {
stagesReservedHtml += 'Сумма за этап ' + v.pos + '.Зарезервирована.';
} else {
stagesReservedHtml += 'Сумма за этап ' + v.pos + '.Не зарезервирована.';
}
}
});
if (stagesResults.length == stagePaidCount && data.secure) {
$("#reserve-button").parent().hide();
} else {
$("#reserve-button").parent().show();
}
if (statusNotAgreed) {
if (!data.secure) {
htmlInbox += '';
}
htmlInbox += '';
} else if ((stagesResults.length > 0) && (data.secure)) {
$("#reserveSpace").show();
}
htmlInbox = htmlInboxStage + htmlInbox;
$("#order-stages").html(htmlInbox);
$("#completeWork").hide();
if (stagesInWork.length > 0) {
$("#completeWork").show();
var stage = stagesInWork[0];
var stageWork = '' +
'
В работе ' + stage.name + '
' +
'
Результат этапа : ' + stage.result + '
' +
'
Срок сдачи ' + stage.term + '
' + stage.cost + '' +
'
';
if (stage.close_contractor) {
stageWork += '';
}
if (data.secure) {
stageWork += '';
}
$("#stagesWork").html(stageWork);
}
if (!data.secure) {
$("#reserveSpace").hide();
}
if (!data.has_user_review) {
if ((stagesCompleted.length == stagesResults.length) && (stagesCompleted.length > 0) && (!isReviewLeave)) {
$("#leaveReview").show();
} else {
$("#leaveReview").hide();
}
} else {
$("#leaveReview").hide();
}
$(".stages-paid").html(stagesReservedHtml);
});
}
//Закрыть этап
$('#tab2').on('click', '.closeStage', function (e) {
e.preventDefault();
var stageId = $(this).attr('data-stage-id');
var _this = $(this);
$.ajax({
url: '/api/stages/' + stageId + '/',
type: 'PATCH',
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'))
},
data: {close_customer: true, status: 'completed'},
dataType: 'json',
success: function (json) {
socket.send_stages_approve({
"format_type": "approve_stages",
"data": {
"sender_id": _this.attr('data-sender-id'),
"recipent_id": _this.attr('data-recipent-id'),
"order_id": _this.attr('data-order-id'),
"msg": "Заказчик закрыл этап " + json.name,
}
});
console.log(json);
},
error: function (e) {
console.log('error');
console.log(e);
}
});
});
// Добавление этапов
$("#order-stages").on('click', "#addStagesForm", function (e) {
e.preventDefault();
var currentOrderId = $(this).attr('data-order-id');
var secureOrderEl = $("#secureOrder");
if (secureOrderEl.length > 0) {
var secOrderVal = false;
if (secureOrderEl.prop('checked')) {
secOrderVal = true;
}
$.ajax({
url: '/api/orders/' + currentOrderId + '/',
type: 'PATCH',
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'))
},
data: {secure: secOrderVal},
dataType: 'json',
success: function (json) {
},
error: function (e) {
console.log(e);
}
});
}
var callbacks = [];
$(".new-stages-form").each(function (i, v) {
var _this = $(this);
$.ajax({
url: '/api/stages/',
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'))
},
data: $(this).serialize(),
dataType: 'json'
})
.done(function (json) {
_this.removeClass('new-stages-form').addClass('update-stages-form');
_this.find('.error').html("");
console.log(json);
})
.fail(function (xhr, errorMsg, error) {
console.log(xhr);
$.each(xhr.responseJSON, function (i, v) {
_this.find('.error-' + i).html(v).css('color', 'red');
console.log(v);
console.log(i);
});
});
});
$(".update-stages-form").each(function (i, v) {
var _this = $(this);
var currentStageId = parseInt($(this).attr('data-stage-id'));
$.ajax({
url: '/api/stages/' + currentStageId + '/',
type: 'PUT',
beforeSend: function (xhr) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'))
},
data: $(this).serialize(),
dataType: 'json'
})
.done(function (json) {
_this.find('.error').html("");
})
.fail(function (xhr, errorMsg, error) {
$.each(xhr.responseJSON, function (i, v) {
_this.find('.error-' + i).html(v).css('color', 'red');
console.log(v);
console.log(i);
});
});
});
var currentRecipentId = $(this).attr('data-recipent-id');
var secureOrder = true
socket.send_stages_approve({
"format_type": "approve_stages",
"data": {
"sender_id": userId,
"recipent_id": currentRecipentId,
"order_id": currentOrderId,
"msg": "Этапы для заказа " + currentOrderId + " изменены",
}
});
$.jGrowl("Этапы для заказа изменены и отправлены исполнителю", { life: 15000});
});
//Изменение счетчика
$('#order-stages-tab').on('change', '#countStage', function () {
var countStage = parseInt($(this).val());
var currentCountStage = $("#order-stages .numberStepp").length;
if ((countStage < 1) || isNaN(countStage)) {
countStage = 1;
$('#order-stages-tab #countStage').val(currentCountStage);
} else {
if (countStage > currentCountStage) {
for (var jj = currentCountStage; jj < countStage; jj++) {
var pos = jj + 1;
var lastFormStage = $("#order-stages .numberStepp").last();
var orderId = lastFormStage.find('.orderStagesInput').val();
var addFormTemplate = '';
lastFormStage.after(addFormTemplate);
}
} else if (countStage < currentCountStage) {
var ii = currentCountStage;
$($("#order-stages .numberStepp").get().reverse()).each(function () {
var currenFormName = ($(this).find('form').attr('class'));
if (ii > countStage) {
$(this).remove();
}
ii--;
});
}
}
});
// Нажимаем на кнопку архивные сообщения
$("#trashed-button").on('click',function(e){
e.preventDefault();
var state = $(this).attr('data-show');
var trashedOrderHtml = "";
if (state == 'true') {
$(this).attr('data-show','false');
$(this).text("Скрыть архивные заказы");
$.ajax({
url: '/api/orders/',
type: 'GET',
dataType: 'json',
success: function (json) {
console.log(json.results);
$.each(json.results, function (i, v) {
var temp = '' +
'
' + v.project.name + '
';
trashedOrderHtml += temp;
});
$("#trashed-orders").html(trashedOrderHtml);
},
error: function (e, jqxhr) {
console.log(e);
}
});
}else {
$(this).attr('data-show','true');
$(this).text("Показать архивные заказы");
$("#trashed-orders").html("");
}
});
// Нажимаем на заказ в архмвных заказах
$(".messageBlock").on('click','.trashedOrderBlock',function(){
$("#chat-order-add").css("display", "none");
$('.order-block, .trashedOrderBlock').each(function () {
$(this).removeClass('orAct');
});
$(this).addClass('orAct');
var inbox = document.getElementById('message-chat-order-space');
var docList = document.getElementById('documentOrderSpace');
inbox.innerHTML = '';
docList.innerHTML = '';
var orderId = $(this).attr('data-id');
location.hash = '#order' + orderId;
$.ajax({
url: '/api/message',
type: 'GET',
data: {csrfmiddlewaretoken: csrftoken, 'order': orderId, 'team__isnull': 'true'},
dataType: 'json',
success: function (json) {
$.each(json.results, function (i, v) {
var senderName = 'Вы';
var className = 'youChat';
if (v.sender.id !== userId) {
senderName = v.sender.username;
className = '';
}
inbox.innerHTML += '' +
'
' + senderName + '
' + v.created + '' +
'
' + v.text + '
';
});
var height = inbox.scrollHeight;
inbox.scrollTop = height;
}
});
$("#order-stages").html("");
$("#completeWork").hide();
$("#add-form-order-note").hide();
$("#reserveSpace").hide();
});
// Для заказов все вытащить
$('.order-block').on('click', function () {
$("#chat-order-add").css("display", "block");
$("#add-form-order-note").css("display", "block");
$("#formsetStage").css("display", "block");
$('.order-block').each(function () {
$(this).removeClass('orAct');
});
$(this).addClass('orAct');
var orderId = $(this).attr('data-id');
location.hash = '#order' + orderId;
var projectId = $(this).attr('data-project-id');
var recipentId = $(this).attr('data-recipent-id');
var secureOrder = $(this).attr('data-secure-deal');
secureOrder = Boolean(secureOrder);
$("#chat-order-add #orderId").val(orderId);
$("#add-form-order-note #orderNote").val(orderId);
$("#orderArbitrationId").val(orderId);
$("#projectReviewId").val(projectId);
$("#reserve-button").attr('data-order-id', orderId);
$("#targetContractorId").val(recipentId);
$("#chat-order-add #recipentId").val(recipentId);
$("#add-form-order-note #recipentNote").val(recipentId);
$(".orderStagesInput").val(orderId);
var inbox = document.getElementById('message-chat-order-space');
var docList = document.getElementById('documentOrderSpace');
inbox.innerHTML = '';
docList.innerHTML = '';
$.ajax({
url: '/api/message',
type: 'GET',
data: {csrfmiddlewaretoken: csrftoken, 'order': orderId, 'team__isnull': 'true'},
dataType: 'json',
success: function (json) {
$.each(json.results, function (i, v) {
var senderName = 'Вы';
var className = 'youChat';
if (v.sender.id !== userId) {
senderName = v.sender.username;
className = '';
}
inbox.innerHTML += '' +
'
' + senderName + '
' + v.created + '' +
'
' + v.text + '
';
});
var height = inbox.scrollHeight;
inbox.scrollTop = height;
}
});
$.ajax({
url: '/api/users/' + userId + '/',
type: 'GET',
data: {
csrfmiddlewaretoken: csrftoken,
},
dataType: 'json',
success: function (json) {
var score = json.score;
$("#order-stages-tab").attr('data-score', score);
},
error: function (e, jqxhr) {
console.log(jqxhr);
}
})
$.ajax({
url: '/api/documents',
type: 'GET',
data: {
csrfmiddlewaretoken: csrftoken,
'order': orderId,
'is_delete': false,
'is_send': true,
},
dataType: 'json',
success: function (json) {
$.each(json.results, function (i, v) {
docList.innerHTML += '' + v.file + '';
});
},
error: function (e) {
console.log(e);
}
});
$.ajax({
url: '/api/note/',
type: 'GET',
data: {
csrfmiddlewaretoken: csrftoken,
'order': orderId,
},
dataType: 'json',
success: function (json) {
var noteHtmlInbox = '';
$.each(json.results, function (i, v) {
noteHtmlInbox += '' + v.text + '';
});
$(".order-notes-block").html(noteHtmlInbox);
}
});
getStages(orderId, userId, recipentId, secureOrder);
});
})
;