/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans.user.collaborator;
import beans.UserRightsSet;
import beans.directory.lpu.entity.Lpu;
import framework.beans.EntityDetails;
import beans.directory.simple.entities.Dvr;
import beans.directory.simple.entities.MedicalAidType;
import beans.directory.simple.entities.ReceptionType;
import beans.directory.simple.entities.Speciality;
import beans.user.client.entity.Client;
import beans.user.collaborator.entities.CollaboratorFunctionsDetails;
import beans.user.collaborator.entities.Collaborator;
import beans.user.collaborator.entities.CollaboratorDetails;
import beans.user.collaborator.entities.CollaboratorFunctions;
import framework.audit.AuditDoc;
import framework.beans.ModificationInfo;
import framework.generic.ClipsServerException;
import framework.security.UserRight;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.ejb.Stateful;
import framework.beans.collaborator.CollaboratorBeanAbstract;
import framework.beans.security.entities.CollaboratorRightId;
import framework.generic.EDataIntegrity;
import framework.generic.ESecurity;
/**
* @security - Ok.
* @author axe
*/
@Stateful(mappedName="clips-beans/CollaboratorBean")
public class CollaboratorBean extends CollaboratorBeanAbstract<Collaborator, Client>
implements CollaboratorBeanRemote {
public CollaboratorBean() {
super(Collaborator.class, Client.class);
}
/**
* Обновляет или создает запись сотрудника.
* Если поля пароля в деталях не НУЛЛ, имеет место попытка сохранения пароля
* @param details - CollaboratorDetails
* @throws generic.ClipsServerException
*/
@Override
protected void onUpdate(Collaborator entity, EntityDetails details,
AuditDoc auditDoc, List<AuditDoc> auditDocList)
throws ClipsServerException {
super.onUpdate(entity, details, auditDoc, auditDocList);
CollaboratorDetails d = (CollaboratorDetails) details;
if (d.id != 0) {
//проверка на попытку смены ЛПУ
if (d.lpuID != entity.getLpu().getId() ) {
throwNeedAdminSecurityException("У вас недостаточно прав, что б перевести сотрудника из одного ЛПУ в другое");
}
}
entity.setSheduled(d.sheduled);
//entity.setLoginGroup(findEntity(LoginGroup.class, d.loginGroup));
if (d.code == null || d.code.isEmpty()) {
throw new ClipsServerException("Не указан табельный номер сотрудника");
}
//Проверка Существует ли другой сотрудник с таким табельным номером
Collaborator coll = findEntity(Collaborator.class, getCollaboratorId());
Lpu lpu = coll.getLpu();
Field[] f = {new Field("code", d.code), new Field("lpu", lpu)};
List<Collaborator> collabList = findEntityList(Collaborator.class, f);
boolean founded = false;
for (Collaborator collaborator : collabList) {
if (collaborator.getId() != d.id) {
founded = true;
break;
}
}
if (founded) {
throw new ClipsServerException("Существует сотрудник с таким табельным номером в данной поликлинике");
}
entity.setCode(d.code);
entity.setDlo(d.dlo);
entity.setLpu(findEntity(Lpu.class, d.lpuID));
}
@Override
public List<CollaboratorFunctionsDetails> getFunctions() throws ClipsServerException {
ArrayList<CollaboratorFunctionsDetails> list = new ArrayList<CollaboratorFunctionsDetails>();
List<CollaboratorFunctions> functionses
= findEntityList(CollaboratorFunctions.class, new Field[]{new Field("collaborator", getExistentEntity()),
new Field("trash", false)});
list = this.getEntytyDetailsList(functionses);
return list;
}
@Override
public ModificationInfo addFunctions(CollaboratorFunctionsDetails cfd) throws ClipsServerException {
Collaborator collaborator = getExistentEntity();
if (collaborator.getId() != cfd.collaboratorID){
throw new EDataIntegrity("Попытка добавить исполняемые обязанности другому сотруднику");
}
int count = getEntityCount(CollaboratorFunctions.class,
new Field[]{new Field("collaborator", collaborator),
new Field("dvr.id", cfd.dvrID),
new Field("firstMedicalAid.id", cfd.firstMedicalAidID),
new Field("receptionType.id", cfd.receptionTypeID),
new Field("speciality.id", cfd.specialityID),
new Field("trash", false)});
if (count > 0){
throw new EDataIntegrity("У данного сотрудника уже есть исполняемые обязанности с указанными параметрами");
}
CollaboratorFunctions functions;
if (cfd.id == 0){
functions = new CollaboratorFunctions(collaborator,
cfd.dvrID != 0 ? findEntity(Dvr.class, cfd.dvrID) : null,
cfd.firstMedicalAidID != 0 ? findEntity(MedicalAidType.class, cfd.firstMedicalAidID) : null,
findEntity(ReceptionType.class, cfd.receptionTypeID),
findEntity(Speciality.class, cfd.specialityID),
cfd.external_key);
collaborator.addFunction(functions);
}else{
throw new EDataIntegrity("Данные не могут быть изменены");
}
manager.flush();
AuditDoc<CollaboratorFunctions> auditDoc = new AuditDoc<CollaboratorFunctions>(null, getCollaborator());
auditDoc.check(functions);
return new ModificationInfo(functions.getId(), persistAudit(auditDoc));
}
@Override
public ModificationInfo removeFunctions(CollaboratorFunctionsDetails item) throws ClipsServerException {
int count = getEntityCount(CollaboratorFunctions.class,
new Field[]{new Field("collaborator", getExistentEntity()),
new Field("trash", false)});
if (count <= 1){
throw new EDataIntegrity("У сотрудника должна быть хотя бы одна исполняемая обязанность");
}
CollaboratorFunctions functions = findEntity(CollaboratorFunctions.class, item.id);
AuditDoc<CollaboratorFunctions> auditDoc = new AuditDoc<CollaboratorFunctions>(functions, getCollaborator());
functions.setTrash(true);
manager.merge(functions);
manager.flush();
auditDoc.check(functions);
return new ModificationInfo(persistAudit(auditDoc));
}
/**
* Назанчает список идентификаторов прав сотрудника
* @return
* @throws generic.EDataIntegrity
*/
@Override
public ModificationInfo setRights(Set<Integer> rights) throws ClipsServerException {
checkCommandAccessibility(COMMAND_WRITE_COLLABORATOR_RIGHTS);
Collaborator entity = getExistentEntity();
checkDischarge();
Set<Integer> backup = new HashSet<Integer>(rights);
Set<Integer> oldRights = getRights();
//make rights to add
rights.removeAll(oldRights);
//make rights to delete
oldRights.removeAll(backup);
ArrayList<AuditDoc> auditDocList = new ArrayList<AuditDoc>();
int eid = entity.getId();
for (Integer id : rights) {
/*Проверка дополнительного ограничения:
* дать право можно только в том случае если у раздающего права есть такое право */
UserRight right = UserRightsSet.getRightFromID(id);
if (!isSuperUser() && !hasRight(right)) {
throw new ESecurity("Вы не можете назначать права, которыми не обладаете сами \n" +
"(" + right + ")");
}
CollaboratorRight r = new CollaboratorRight();
AuditDoc<CollaboratorRight> auditDoc = new AuditDoc<CollaboratorRight>(null, getCollaborator());
auditDocList.add(auditDoc);
r.setId(new CollaboratorRightId(eid, id));
manager.persist(r);
manager.flush();
manager.refresh(r);
auditDoc.check(r);
}
if (oldRights.size() > 0) {
Field f[] = {
new Field("id.collId", eid),
new Field("id.rightId", oldRights, Field.OPERATOR_IN)
};
deleteEntityList2(CollaboratorRight.class, f, auditDocList);
}
return new ModificationInfo(0, persistAudit(auditDocList));
}
}