Added enties, dtos and something like it(with //)

This commit is contained in:
Andrey 2025-02-19 12:02:56 +03:00
parent a7ba596d97
commit 4dd2794b35
59 changed files with 1666 additions and 797 deletions

View File

@ -1,108 +0,0 @@
package ru.myitschool.work.api;
import android.util.Log;
import androidx.annotation.NonNull;
import java.io.IOException;
import java.util.Objects;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import ru.myitschool.work.core.Constants;
import ru.myitschool.work.api.entity.Code;
import ru.myitschool.work.api.entity.Employee;
public class ControllerAPI<T extends HandlersResultAPI> {
// Главный класс по работе с сервером. В качестве дженерик типа передаётся класс, в котором надо
// имплементировать HandlersResultAPI. Потом нужно прописать в полученных методах работу
// с результатами вызова API. И создав экземпляр этого класса вызвать нужный метод.
//
// Примерно так все должно выглядеть:
//
// public class LoginActivity ... implements HandlersResultAPI {
// private ControllerAPI controllerAPI;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// ...
// controllerAPI = new ControllerAPI<LoginActivity>();
// ...
// controllerAPI.verificationLogin("Логин пользователя", LoginActivity.this);
// }
//
// @Override
// public void handlerVerificationLogin(boolean result) {
// // Тут работа с результатами controllerAPI.verificationLogin
// }
//
// @Override
// public void handlerGetEmployee(Employee employee) { }
//
// @Override
// public void handlerVisit(boolean result) { }
// }
//
// Всё это по факту один большой костыль, который придуман, чтобы обойти многопоточность.
private final RequestsAPI managerAPI;
public ControllerAPI() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.SERVER_ADDRESS)
.addConverterFactory(GsonConverterFactory.create())
.build();
managerAPI = retrofit.create(RequestsAPI.class);
}
public void verificationLogin(String login, T handler) {
managerAPI.verificationLogin(login).enqueue(new Callback<>() {
@Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
Log.d("Test", "(Верификация логина) - Ответ от сервера: " + response.code());
handler.handlerVerificationLogin(login, response.code() == 200);
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Log.e("Test", "(Верификация логина) - " + Objects.requireNonNull(t.getMessage()));
handler.handlerVerificationLogin(login, false);
}
});
}
public void getEmployee(String login, T handler) {
managerAPI.getEmployee(login).enqueue(new Callback<>() {
@Override
public void onResponse(@NonNull Call<Employee> call, @NonNull Response<Employee> response) {
Log.d("Test", "(Получение пользователя) - Ответ от сервера: Тело - " + response.body() + " Код - " + response.code());
handler.handlerGetEmployee(response.body());
}
@Override
public void onFailure(@NonNull Call<Employee> call, @NonNull Throwable t) {
Log.e("Test", "(Получение пользователя) - " + Objects.requireNonNull(t.getMessage()));
handler.handlerGetEmployee(null);
}
});
}
public void visit(String login, Code code, T handler) throws IOException {
managerAPI.visit(login, code).enqueue(new Callback<>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
Log.d("Test", "(Проверка кода) - Ответ от сервера: Код - " + response.code());
handler.handlerVisit(response.code());
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
Log.e("Test", "(Получение пользователя) - " + Objects.requireNonNull(t.getMessage()));
handler.handlerVisit(400);
}
});
}
}

View File

@ -1,9 +0,0 @@
package ru.myitschool.work.api;
import ru.myitschool.work.api.entity.Employee;
public interface HandlersResultAPI {
void handlerVerificationLogin(String login, boolean result);
void handlerGetEmployee(Employee employee);
void handlerVisit(int result);
}

View File

@ -1,23 +0,0 @@
package ru.myitschool.work.api;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.PATCH;
import retrofit2.http.Path;
import ru.myitschool.work.api.entity.Code;
import ru.myitschool.work.api.entity.Employee;
public interface RequestsAPI {
// Тут будут пути и типы api-запросов.
// Запрос для проверки пользователя, используется при входе.
@GET("/api/{login}/auth")
Call<Void> verificationLogin(@Path("login") String login);
@GET("/api/{login}/info")
Call<Employee> getEmployee(@Path("login") String login);
@PATCH("/api/{login}/open")
Call<Void> visit(@Path("login") String login, @Body Code code);
}

View File

@ -0,0 +1,36 @@
package ru.myitschool.work.api.data;
import androidx.annotation.NonNull;
import org.jetbrains.annotations.Nullable;
import okhttp3.Credentials;
import ru.myitschool.work.api.data.network.RetrofitFactory;
import ru.myitschool.work.api.data.source.SignApi;
public class CredentialsDataSource {
private static CredentialsDataSource INSTANCE;
private final SignApi signApi = RetrofitFactory.getInstance().getSignApi();
private CredentialsDataSource() {
}
public static synchronized CredentialsDataSource getInstance() {
if (INSTANCE == null) INSTANCE = new CredentialsDataSource();
return INSTANCE;
}
@Nullable private String authData = null;
public @Nullable String getAuthData() {
return authData;
}
public void updateLogin(@NonNull String email, @Nullable String password) {
authData = Credentials.basic(email, password);
}
public void logout() {
authData = null;
}
}

View File

@ -0,0 +1,121 @@
package ru.myitschool.work.api.data;
import androidx.annotation.NonNull;
import ru.myitschool.work.api.data.dto.employee.EmployeeDTO;
import ru.myitschool.work.api.data.network.RetrofitFactory;
import ru.myitschool.work.api.data.source.EmployeeApi;
import ru.myitschool.work.api.data.utils.CallToConsumer;
import ru.myitschool.work.api.domain.EmployeeRepository;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.employee.EmpolyeeEntity;
import ru.myitschool.work.api.domain.entity.employee.ItemEmployeeEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class EmployeeRepositoryImpl implements EmployeeRepository {
private static EmployeeRepositoryImpl INSTANCE;
private final EmployeeApi employeeApi = RetrofitFactory.getInstance().getEmployeeApi();
private EmployeeRepositoryImpl() {
}
public static synchronized EmployeeRepositoryImpl getInstance() {
if (INSTANCE == null) INSTANCE = new EmployeeRepositoryImpl();
return INSTANCE;
}
// @Override
// public void getAllEmployees(@NonNull Consumer<Status<List<EmpolyeeEntity>>> callback) {
// employeeApi.getAll().enqueue(new CallToConsumer<>(
// callback,
// employeeDTOS -> {
// if (employeeDTOS == null) return null;
//
// ArrayList<ItemEmployeeEntity> result = new ArrayList<>(employeeDTOS.size());
//
// for (EmployeeDTO employeeDTO : employeeDTOS) {
// if (employeeDTO == null) continue;
//
// final long id_ = employeeDTO.id;
// final String name = employeeDTO.name;
// final String surname = employeeDTO.surname;
// final String patronymic = employeeDTO.patronymic;
// final String profileImageUrl = employeeDTO.profileImageUrl;
// final String officeName = employeeDTO.officeName;
// final String position = employeeDTO.position;
// final boolean visitStatus = employeeDTO.visitStatus;
//
// if (name != null && surname != null && profileImageUrl != null &&
// officeName != null && position != null) {
//
// result.add(new ItemEmployeeEntity(id_, name, surname, patronymic,
// profileImageUrl, officeName, position, visitStatus));
// }
// }
// return result;
// }
// ));
// }
// @Override
// public ItemEmployeeEntity getEmployeeById(long id, @NonNull Consumer<Status<EmpolyeeEntity>> callback) {
// employeeApi.getEmployeeById(id).enqueue(new CallToConsumer<>(
// callback,
// employeeDTO -> {
//
// final long id_ = employeeDTO.id;
// final String name = employeeDTO.name;
// final String surname = employeeDTO.surname;
// final String patronymic = employeeDTO.patronymic;
// final String profileImageUrl = employeeDTO.profileImageUrl;
// final String officeName = employeeDTO.officeName;
// final String role = employeeDTO.role; // строка либо user, либо admin
// final boolean visitStatus =employeeDTO.visitStatus;
// if (name != null && surname != null &&
// role != null && officeName != null) {
//
// assert profileImageUrl != null;
// return new ItemEmployeeEntity(id_, name, surname, patronymic, profileImageUrl, officeName, role,visitStatus);
// } else return null;
// }
// ));
// }
@Override
public void getAllEmployees(@NonNull Consumer<Status<List<EmpolyeeEntity>>> callback) {
}
@Override
public ItemEmployeeEntity getEmployeeById(long id, @NonNull Consumer<Status<EmpolyeeEntity>> callback) {
return null;
}
@Override
public void getEmployeeByEmail(@NonNull String email, @NonNull Consumer<Status<EmpolyeeEntity>> callback) {
}
@Override
public void getEmployeeByTelephone(@NonNull String telephone, @NonNull Consumer<Status<EmpolyeeEntity>> callback) {
}
@Override
public void updateEmployee(long id, @NonNull EmployeeDTO employeeDTO, @NonNull Consumer<Status<Void>> callback) {
}
@Override
public void deleteEmployee(long id, @NonNull Consumer<Status<EmpolyeeEntity>> callback) {
}
@Override
public void patchEmployeerOfficeId(long id, long officeId, @NonNull Consumer<Status<Void>> callback) {
}
}

View File

@ -0,0 +1,94 @@
package ru.myitschool.work.api.data;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import retrofit2.Call;
import ru.myitschool.work.api.data.dto.OfficeDTO;
import ru.myitschool.work.api.data.dto.TerminalDTO;
import ru.myitschool.work.api.data.dto.employee.EmployeeItemDTO;
import ru.myitschool.work.api.data.network.RetrofitFactory;
import ru.myitschool.work.api.data.source.OfficeApi;
import ru.myitschool.work.api.data.utils.CallToConsumer;
import ru.myitschool.work.api.domain.entity.office.OfficeEntity;
public class OfficeRepositoryImpl implements OfficeApi{
private static OfficeRepositoryImpl INSTANCE;
private final OfficeApi officeApi = RetrofitFactory.getInstance().getOfficeApi();
private OfficeRepositoryImpl() {
}
public static synchronized OfficeRepositoryImpl getInstance() {
if (INSTANCE == null) INSTANCE = new OfficeRepositoryImpl();
return INSTANCE;
}
// @Override
// public Call<List<OfficeDTO>> getAllOffices() {
// officeApi.getAllOffices().enqueue(new CallToConsumer<>(
// officeDTOS -> {
// if (officeDTOS == null) return null;
//
// ArrayList<OfficeEntity> result = new ArrayList<>(officeDTOS.size());
//
// for (OfficeDTO officeDTO : officeDTOS) {
// if (officeDTO == null) continue;
//
// final long id = officeDTO.id;
// final String name = officeDTO.name;
// final String description = officeDTO.description;
// final String address = officeDTO.address;
// final Double latitude = officeDTO.latitude;
// final Double longitude = officeDTO.longitude;
// final String linkLogo = officeDTO.linkLogo;
// final String telephone = officeDTO.telephone;
// final String email = officeDTO.email;
// final List<EmployeeItemDTO> employeers = officeDTO.employees;
// final List<TerminalDTO> terminals = officeDTO.terminals;
//
//
// if (name != null && address != null && linkLogo != null && telephone != null && employeers != null && terminals !=null) {
//
// result.add(new OfficeEntity(id, name, description, address,
// latitude, longitude, linkLogo, telephone,email, employeers,terminals));
// }
// }
// return result;
// }
// ));
// }
@Override
public Call<List<OfficeDTO>> getAllOffices() {
return null;
}
@Override
public Call<OfficeDTO> getOfficesById(long id) {
return null;
}
@Override
public Call<List<OfficeDTO>> getSortedOffices(double latitude, double longitude) {
return null;
}
@Override
public Call<OfficeDTO> createOffice(OfficeDTO centerDTO) {
return null;
}
@Override
public Call<OfficeDTO> updateOffice(long id, OfficeDTO centerDTO) {
return null;
}
@Override
public Call<Void> deleteEmployee(long id) {
return null;
}
}

View File

@ -0,0 +1,111 @@
package ru.myitschool.work.api.data;
import androidx.annotation.NonNull;
import java.util.List;
import java.util.function.Consumer;
import ru.myitschool.work.api.data.dto.employee.EmployeeCreateDTO;
import ru.myitschool.work.api.data.network.RetrofitFactory;
import ru.myitschool.work.api.data.source.SignApi;
import ru.myitschool.work.api.data.utils.CallToConsumer;
import ru.myitschool.work.api.domain.SignRepository;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.employee.EmpolyeeEntity;
public class SignRepositoryImpl implements SignRepository {
private static SignRepositoryImpl INSTANCE;
private final SignApi signApi = RetrofitFactory.getInstance().getSignApi();
private final CredentialsDataSource credentialsDataSource = CredentialsDataSource.getInstance();
private SignRepositoryImpl() {
}
public static synchronized SignRepositoryImpl getInstance() {
if (INSTANCE == null) INSTANCE = new SignRepositoryImpl();
return INSTANCE;
}
@Override
public void createEmployee(@NonNull EmployeeCreateDTO employeeCreateDTO, @NonNull Consumer<Status<EmpolyeeEntity>> callback) {
signApi.register(employeeCreateDTO).enqueue(new CallToConsumer<>(
callback,
employeeDTO -> {
if (employeeDTO == null) return null;
final long id_ = employeeDTO.id;
final String name = employeeDTO.name;
final String surname = employeeDTO.surname;
final String patronymic = employeeDTO.patronymic;
final String telephone = employeeDTO.telephone;
final String email_= employeeDTO.email;
final long officeId = employeeDTO.officeId;
final String officeName = employeeDTO.officeName;
final String officeUrl= employeeDTO.officeImageUrl;
final String possition = employeeDTO.position;
final String role = employeeDTO.role;
final String profileImageUrl= employeeDTO.profileImageUrl;
final boolean visitStatus= employeeDTO.visitStatus;
final String startVisit= employeeDTO.startVisitDateTime;
final List<Long> visitIdLast30Days = employeeDTO.visitsIdLast30Days;
final long totalVisitTimeLast30Days = employeeDTO.totalTimeVisitsLast30Days;
final String curentOfficeName = employeeDTO.currentOfficeName;
final String createdAt= employeeDTO.createAt;
if (name != null && surname != null && telephone != null &&
email_ != null && officeName != null && officeUrl != null &&
possition != null && role != null && startVisit != null &&
visitIdLast30Days != null && curentOfficeName != null &&
createdAt != null) {
return new EmpolyeeEntity(id_, name, surname, patronymic,
telephone, email_, officeId, officeName, officeUrl, possition, role, profileImageUrl,
visitStatus, startVisit, visitIdLast30Days, totalVisitTimeLast30Days, curentOfficeName, createdAt);
} else return null;
})
);
}
@Override
public void login(@NonNull String email, @NonNull String password, @NonNull Consumer<Status<EmpolyeeEntity>> callback) {
credentialsDataSource.updateLogin(email, password);
signApi.login().enqueue(new CallToConsumer<>(callback, employeeDTO -> {
if (employeeDTO == null) return null;
final long id_ = employeeDTO.id;
final String name = employeeDTO.name;
final String surname = employeeDTO.surname;
final String patronymic = employeeDTO.patronymic;
final String telephone = employeeDTO.telephone;
final String email_= employeeDTO.email;
final long officeId = employeeDTO.officeId;
final String officeName = employeeDTO.officeName;
final String officeUrl= employeeDTO.officeImageUrl;
final String possition = employeeDTO.position;
final String role = employeeDTO.role;
final String profileImageUrl= employeeDTO.profileImageUrl;
final boolean visitStatus= employeeDTO.visitStatus;
final String startVisit= employeeDTO.startVisitDateTime;
final List<Long> visitIdLast30Days = employeeDTO.visitsIdLast30Days;
final long totalVisitTimeLast30Days = employeeDTO.totalTimeVisitsLast30Days;
final String curentOfficeName = employeeDTO.currentOfficeName;
final String createdAt= employeeDTO.createAt;
if (name != null && surname != null && telephone != null &&
email_ != null && officeName != null && officeUrl != null &&
possition != null && role != null && startVisit != null &&
visitIdLast30Days != null && curentOfficeName != null &&
createdAt != null) {
return new EmpolyeeEntity(id_, name, surname, patronymic,
telephone, email_, officeId, officeName, officeUrl, possition, role, profileImageUrl,
visitStatus, startVisit, visitIdLast30Days, totalVisitTimeLast30Days, curentOfficeName, createdAt);
} else return null;
}));
}
@Override
public void logout() {
credentialsDataSource.logout();
}
}

View File

@ -0,0 +1,99 @@
package ru.myitschool.work.api.data;
import androidx.annotation.NonNull;
import com.example.myapplication.api.domain.entity.visit.VisitEntity;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import ru.myitschool.work.api.data.dto.VisitDTO;
import ru.myitschool.work.api.data.network.RetrofitFactory;
import ru.myitschool.work.api.data.source.VisitApi;
import ru.myitschool.work.api.data.utils.CallToConsumer;
import ru.myitschool.work.api.domain.VisitRepository;
import ru.myitschool.work.api.domain.entity.Status;
import com.example.myapplication.api.domain.entity.visit.VisitEntity;
public class VisitRepositoryImpl implements VisitRepository {
private static VisitRepositoryImpl INSTANCE;
private final VisitApi visitApi = RetrofitFactory.getInstance().getVisitApi();
public static synchronized VisitRepositoryImpl getInstance() {
if (INSTANCE == null) INSTANCE = new VisitRepositoryImpl();
return INSTANCE;
}
@Override
public void getAllVisits(@NonNull Consumer<Status<List<VisitEntity>>> callback) {
visitApi.getAll().enqueue(new CallToConsumer<>(
callback,
visitDTOS -> {
if (visitDTOS == null) return null;
ArrayList<VisitEntity> result = new ArrayList<>(visitDTOS.size());
for (VisitDTO visitDTO : visitDTOS) {
if (visitDTO == null) continue;
final long id = visitDTO.id;
final LocalDateTime startVisit = visitDTO.startVisit;
final LocalDateTime endVisit = visitDTO.endVisit;
final String totalTime =visitDTO.durationVisit;
final boolean isFinished = visitDTO.isFinished;
final long startTerminal = visitDTO.startTertminal;
final long endTerminal = visitDTO.endTerminal;
if (startVisit != null && endVisit != null && totalTime != null && isFinished) {
result.add(new VisitEntity(id, startVisit, endVisit, totalTime, isFinished,startTerminal,endTerminal));
}
}
return result;
}
));
}
@Override
public void getAllByVisitId(long id, @NonNull Consumer<Status<List<VisitEntity>>> callback) {
}
// @Override
// public void getAllByVisitId(long id, @NonNull Consumer<Status<List<VisitEntity>>> callback) {
// visitApi.getVisitById(id).enqueue(new CallToConsumer<>(
// callback,
// visitDTOS -> {
// if (visitDTOS == null) return null;
//
// ArrayList<VisitEntity> result = new ArrayList<>(visitDTOS.size());
//
// for (VisitDTO visitDTO : visitDTOS) {
// if (visitDTO == null) continue;
//
// final long Id = visitDTO.id;
// final LocalDateTime startVisit = visitDTO.startVisit;
// final LocalDateTime endVisit = visitDTO.endVisit;
// final String totalTime =visitDTO.durationVisit;
// final boolean isFinished = visitDTO.isFinished;
// final long startTerminal = visitDTO.startTertminal;
// final long endTerminal = visitDTO.endTerminal;
//
// if (startVisit != null && endVisit != null && totalTime != null && isFinished) {
// result.add(new VisitEntity(Id, startVisit, endVisit, totalTime, isFinished,startTerminal,endTerminal));
// }
// }
// return result;
// }
// ));
// }
/* это если время останется. Шаблон есть фуловый, только на сервере надо
@Override
public void createVisit(@NonNull NotificationDTO notificationDTO, @NonNull Consumer<Status<VisitEntity>> callback) {
}*/
}

View File

@ -0,0 +1,47 @@
package ru.myitschool.work.api.data.dto;
import androidx.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import ru.myitschool.work.api.data.dto.employee.EmployeeItemDTO;
public class OfficeDTO {
@Nullable
@SerializedName("id")
public long id;
@Nullable
@SerializedName("name")
public String name;
@Nullable
@SerializedName("description")
public String description;
@Nullable
@SerializedName("address")
public String address;
@Nullable
@SerializedName("latitude")
public Double latitude;
@Nullable
@SerializedName("longitude")
public Double longitude;
@Nullable
@SerializedName("linkLogo")
public String linkLogo;
@Nullable
@SerializedName("telephone")
public String telephone;
@Nullable
@SerializedName("email")
public String email;
@Nullable
@SerializedName("employees")
public List<EmployeeItemDTO> employees;
@Nullable
@SerializedName("terminals")
public List<TerminalDTO> terminals;
}

View File

@ -0,0 +1,23 @@
package ru.myitschool.work.api.data.dto;
import androidx.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import ru.myitschool.work.api.data.dto.employee.EmployeeItemDTO;
public class PositionDTO {
@Nullable
@SerializedName("id")
public long id;
@Nullable
@SerializedName("name")
public String name;
// Список всех сотрудников с этой должностью.
@Nullable
@SerializedName("employeeItemDTOList")
public List<EmployeeItemDTO> employeeItemDTOList;
}

View File

@ -0,0 +1,26 @@
package ru.myitschool.work.api.data.dto;
import androidx.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
public class TerminalDTO {
@Nullable
@SerializedName("id")
public long id;
@Nullable
@SerializedName("name")
public String name;
// ОЧЕНЬ ВАЖНО!!! при создании терминала code не нужен, но отправлять его нужно.
// При создании пиши вместо code, что хочешь он будет просто игнорироваться.
// Мне просто очень лень делать отдельный TerminalCreateDTO ради одного поля.
//Мда, вот это я понимаю КОСТЫЛЬ
@Nullable
@SerializedName("code")
public String code;
@Nullable
@SerializedName("officeName")
public String officeName;
}

View File

@ -0,0 +1,38 @@
package ru.myitschool.work.api.data.dto;
import androidx.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
import java.time.LocalDateTime;
public class VisitDTO {
@Nullable
@SerializedName("id")
public long id;
// Возвращается время начала и конца посещения в формате LocalDateTime.toString(),
// превратить обратно можно с помощью LocalDateTime.parse().
@Nullable
@SerializedName("startVisit")
public LocalDateTime startVisit;
@Nullable
@SerializedName("endVisit")
public LocalDateTime endVisit;
@Nullable
@SerializedName("isFinished")
public boolean isFinished;
// Возвращается длительность посещения в формате LocalDateTime.toString(),
// превратить обратно можно с помощью LocalDateTime.parse().
@Nullable
@SerializedName("durationVisit")
public String durationVisit;
@Nullable
@SerializedName("startTerminal")
public long startTertminal;
@Nullable
@SerializedName("endTerminal")
public long endTerminal;
}

View File

@ -0,0 +1,35 @@
package ru.myitschool.work.api.data.dto.employee;
import androidx.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
public class EmployeeCreateDTO {
@Nullable
@SerializedName("name")
public String name;
@Nullable
@SerializedName("longitude")
public String surname;
@Nullable
@SerializedName("patronymic")
public String patronymic;
@Nullable
@SerializedName("telephone")
public String telephone;
@Nullable
@SerializedName("email")
public String email;
@Nullable
@SerializedName("password")
public String password;
@Nullable
@SerializedName("officeName")
public String officeName; // Имя офиса, к которому присоединится работник.
@Nullable
@SerializedName("positionName")
public String positionName; // Должность работника.
@Nullable
@SerializedName("role")
public String role; // строка либо ROLE_USER, либо ROLE_ADMIN
}

View File

@ -0,0 +1,79 @@
package ru.myitschool.work.api.data.dto.employee;
import androidx.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class EmployeeDTO {
@Nullable
@SerializedName("id")
public long id;
@Nullable
@SerializedName("name")
public String name;
@Nullable
@SerializedName("surname")
public String surname;
@Nullable
@SerializedName("patronymic")
public String patronymic;
@Nullable
@SerializedName("telephone")
public String telephone;
@Nullable
@SerializedName("email")
public String email;
@Nullable
@SerializedName("officeId")
public long officeId;
@Nullable
@SerializedName("officeName")
public String officeName;
@Nullable
@SerializedName("officeImageUrl")
public String officeImageUrl;
@Nullable
@SerializedName("position")
public String position; // Название должности
@Nullable
@SerializedName("role")
public String role; // строка либо ROLE_USER, либо ROLE_ADMIN
@Nullable
@SerializedName("profileImageUrl")
public String profileImageUrl;
// Текущее состояние входа: false - visit (посещение) ещё не началось, true - visit идёт
@Nullable
@SerializedName("visitStatus")
public boolean visitStatus;
// Если visitStatus true, то возвращает дату и время начала посещения в формате LocalDateTime.toString(),
// превратить обратно можно с помощью LocalDateTime.parse().
// Если visitStatus false, то возвращает null.
@Nullable
@SerializedName("startVisitDateTime")
public String startVisitDateTime;
@Nullable
@SerializedName("visitsIdLast30Days")
public List<Long> visitsIdLast30Days; // Список Id посещений за последние 30 дней.
// Возвращает количество отработанных часов за последний месяц.
@Nullable
@SerializedName("totalTimeVisitsLast30Days")
public long totalTimeVisitsLast30Days;
// (Возможно это стоит убрать) Название офиса, в котором сейчас находится работник.
// Если visitStatus false, возвращает null.
@Nullable
@SerializedName("currentOfficeName")
public String currentOfficeName;
// Возвращает время регистрации в формате LocalDateTime.toString(),
// превратить обратно можно с помощью LocalDateTime.parse().
@Nullable
@SerializedName("createAt")
public String createAt;
}

View File

@ -0,0 +1,34 @@
package ru.myitschool.work.api.data.dto.employee;
import androidx.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
public class EmployeeItemDTO {
@Nullable
@SerializedName("id")
public long id;
@Nullable
@SerializedName("name")
public String name;
@Nullable
@SerializedName("surname")
public String surname;
@Nullable
@SerializedName("patronymic")
public String patronymic;
@Nullable
@SerializedName("profileImageUrl")
public String profileImageUrl;
@Nullable
@SerializedName("officeName")
public String officeName;
@Nullable
@SerializedName("position")
public String position; // Название должности
// Текущее состояние входа: false - visit (посещение) ещё не началось, true - visit идёт
@Nullable
@SerializedName("visitStatus")
public boolean visitStatus;
}

View File

@ -0,0 +1,58 @@
package ru.myitschool.work.api.data.network;
import com.example.myapplication.core.UrlConstants;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import ru.myitschool.work.api.data.CredentialsDataSource;
import ru.myitschool.work.api.data.source.EmployeeApi;
import ru.myitschool.work.api.data.source.OfficeApi;
import ru.myitschool.work.api.data.source.SignApi;
import ru.myitschool.work.api.data.source.VisitApi;
public class RetrofitFactory {
private static RetrofitFactory INSTANCE;
private RetrofitFactory() {
}
public static synchronized RetrofitFactory getInstance() {
if (INSTANCE == null) INSTANCE = new RetrofitFactory();
return INSTANCE;
}
private final OkHttpClient.Builder client = new OkHttpClient.Builder()
.addInterceptor(chain -> {
String authData = CredentialsDataSource.getInstance().getAuthData();
if (authData == null) return chain.proceed(chain.request());
else {
Request request = chain.request()
.newBuilder()
.addHeader("Authorization", authData)
.build();
return chain.proceed(request);
}
});
public Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UrlConstants.BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
public EmployeeApi getEmployeeApi() {
return retrofit.create(EmployeeApi.class);
}
public SignApi getSignApi() {
return retrofit.create(SignApi.class);
}
public OfficeApi getOfficeApi() {
return retrofit.create(OfficeApi.class);
}
public VisitApi getVisitApi(){ return retrofit.create(VisitApi.class);}
}

View File

@ -0,0 +1,35 @@
package ru.myitschool.work.api.data.source;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.PATCH;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import ru.myitschool.work.api.data.dto.employee.EmployeeDTO;
public interface EmployeeApi {
@GET("api/v1/employees")
Call<List<EmployeeDTO>> getAll();
@GET("api/v1/employees/{id}")
Call<EmployeeDTO> getEmployeeById(@Path("id") long id);
@GET("api/v1/employees/email/{email}")
Call<EmployeeDTO> getEmployeeByEmail(@Path("email") String email);
@GET("api/v1/employees/telephone/{telephone}")
Call<EmployeeDTO> getEmployeeByTelephone(@Path("telephone") String telephone);
@PUT("api/v1/employees/{id}")
Call<EmployeeDTO> updateEmployee(@Path("id") long id, @Body EmployeeDTO employeeDTO);
@DELETE("api/v1/employees/{id}")
Call<Void> deleteEmployee(@Path("id") long id);
@PATCH("api/v1/employees/{id}/{centerId}")
Call<Void> patchEmployee(@Path("id") long id, @Path("centerId") long centerId); //перепривязка к другому центру
}

View File

@ -0,0 +1,33 @@
package ru.myitschool.work.api.data.source;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import ru.myitschool.work.api.data.dto.OfficeDTO;
public interface OfficeApi {
@GET("api/v1/offices")
Call<List<OfficeDTO>> getAllOffices();
@GET("api/v1/offices/{id}")
Call<OfficeDTO> getOfficesById(@Path("id") long id);
@GET("api/v1/offices/sorted/distance")
Call<List<OfficeDTO>> getSortedOffices(@Query("latitude") double latitude, @Query("longitude") double longitude);
@POST("api/v1/offices")
Call<OfficeDTO> createOffice(@Body OfficeDTO centerDTO);
@PUT("api/v1/offices/{id}")
Call<OfficeDTO> updateOffice(@Path("id") long id, @Body OfficeDTO centerDTO);
@DELETE("api/v1/offices/{id}")
Call<Void> deleteEmployee(@Path("id") long id);
}

View File

@ -0,0 +1,18 @@
package ru.myitschool.work.api.data.source;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import ru.myitschool.work.api.data.dto.employee.EmployeeCreateDTO;
import ru.myitschool.work.api.data.dto.employee.EmployeeDTO;
public interface SignApi {
@POST("api/v1/employees/authorization/register")
Call<EmployeeDTO> register(@Body EmployeeCreateDTO employeeCreateDTO);
@GET("api/v1/employees/authorization//login")
Call<EmployeeDTO> login();
}

View File

@ -0,0 +1,29 @@
package ru.myitschool.work.api.data.source;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import ru.myitschool.work.api.data.dto.VisitDTO;
public interface VisitApi {
@GET("api/v1/visits")
Call<List<VisitDTO>> getAll();
@GET("api/v1/visits/{id}")
Call<VisitDTO> getVisitById(@Path("id") long id);
@GET("api/v1/visits/{empoyee_id}")
Call<VisitDTO> getVisitByEmloyeeId(@Path("id") long empoyee_id);
@POST("api/v1/visits")
Call<VisitDTO> stertVisit(@Body VisitDTO visitDTO);
@PATCH("api/v1/visits/{id}")
Call<VisitDTO> endVisit(@Path("id") long id);
}

View File

@ -0,0 +1,40 @@
package ru.myitschool.work.api.data.utils;
import androidx.annotation.NonNull;
import java.util.function.Consumer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ru.myitschool.work.api.domain.entity.Status;
public class CallToConsumer<SOURCE, DEST> implements Callback<SOURCE> {
@NonNull
private final Consumer<Status<DEST>> callback;
@NonNull
private final Mapper<SOURCE, DEST> mapper;
public CallToConsumer(
@NonNull Consumer<Status<DEST>> callback,
@NonNull Mapper<SOURCE, DEST> mapper
) {
this.callback = callback;
this.mapper = mapper;
}
@Override
public void onResponse(@NonNull Call<SOURCE> call, @NonNull Response<SOURCE> response) {
callback.accept(new Status<>(response.code(), mapper.map(response.body()), null));
}
@Override
public void onFailure(@NonNull Call<SOURCE> call, @NonNull Throwable t) {
callback.accept(new Status<>(-1, null, t));
}
public interface Mapper<SOURCE, DEST> {
DEST map(SOURCE source);
}
}

View File

@ -0,0 +1,21 @@
package ru.myitschool.work.api.domain;
import androidx.annotation.NonNull;
import java.util.List;
import java.util.function.Consumer;
import ru.myitschool.work.api.data.dto.employee.EmployeeDTO;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.employee.EmpolyeeEntity;
import ru.myitschool.work.api.domain.entity.employee.ItemEmployeeEntity;
public interface EmployeeRepository {
void getAllEmployees(@NonNull Consumer<Status<List<EmpolyeeEntity>>> callback);
ItemEmployeeEntity getEmployeeById(long id, @NonNull Consumer<Status<EmpolyeeEntity>> callback);
void getEmployeeByEmail(@NonNull String email, @NonNull Consumer<Status<EmpolyeeEntity>> callback);
void getEmployeeByTelephone(@NonNull String telephone, @NonNull Consumer<Status<EmpolyeeEntity>> callback);
void updateEmployee(long id, @NonNull EmployeeDTO employeeDTO, @NonNull Consumer<Status<Void>> callback);//переделай после dto
void deleteEmployee(long id, @NonNull Consumer<Status<EmpolyeeEntity>> callback);
void patchEmployeerOfficeId(long id, long officeId, @NonNull Consumer<Status<Void>> callback);
}

View File

@ -0,0 +1,13 @@
package ru.myitschool.work.api.domain;
import androidx.annotation.NonNull;
import java.util.List;
import java.util.function.Consumer;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.office.OfficeEntity;
public interface OfficeRepository {
void getAllOffices(@NonNull Consumer<Status<List<OfficeEntity>>> callback);
}

View File

@ -0,0 +1,15 @@
package ru.myitschool.work.api.domain;
import androidx.annotation.NonNull;
import java.util.function.Consumer;
import ru.myitschool.work.api.data.dto.employee.EmployeeCreateDTO;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.employee.EmpolyeeEntity;
public interface SignRepository {
void createEmployee(@NonNull EmployeeCreateDTO employeeRegisterDTO, @NonNull Consumer<Status<EmpolyeeEntity>> callback);
void login(@NonNull String email, @NonNull String password, @NonNull Consumer<Status<EmpolyeeEntity>> callback);
void logout();
}

View File

@ -0,0 +1,17 @@
package ru.myitschool.work.api.domain;
import androidx.annotation.NonNull;
import com.example.myapplication.api.domain.entity.visit.VisitEntity;
import java.util.List;
import java.util.function.Consumer;
import ru.myitschool.work.api.domain.entity.Status;
public interface VisitRepository {
void getAllVisits(@NonNull Consumer<Status<List<VisitEntity>>> callback);
void getAllByVisitId(long id, @NonNull Consumer<Status<List<VisitEntity>>> callback);
//void createVisit(@NonNull NotificationDTO notificationDTO, @NonNull Consumer<Status<VisitEntity>> callback); если время останется
}

View File

@ -0,0 +1,30 @@
package ru.myitschool.work.api.domain.entity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class Status<T> {
final int statusCod;
@Nullable private final T value;
@Nullable private final Throwable errors;
public Status(int statusCod, @Nullable T value, @Nullable Throwable errors) {
this.statusCod = statusCod;
this.value = value;
this.errors = errors;
}
public int getStatusCod() {
return statusCod;
}
@Nullable
public T getValue() {
return value;
}
@Nullable
public Throwable getErrors() {
return errors;
}
}

View File

@ -0,0 +1,152 @@
package ru.myitschool.work.api.domain.entity.employee;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Date;
import java.util.List;
public class EmpolyeeEntity {
@NonNull private final long id;
@NonNull private final String name;
@NonNull private final String surname;
@NonNull private final String patronymic;
@NonNull private final String telephone;
@NonNull private final String email;
@NonNull private final long officeId;
@NonNull private final String officeName;
@NonNull private final String officeImageUrl;
@NonNull private final String position; // Название должности
@NonNull private final String role; // строка либо ROLE_USER, либо ROLE_ADMIN
@NonNull private final String profileImageUrl;
// Текущее состояние входа: false - visit (посещение) ещё не началось, true - visit идёт
@NonNull private final boolean visitStatus;
// Если visitStatus true, то возвращает дату и время начала посещения в формате LocalDateTime.toString(),
// превратить обратно можно с помощью LocalDateTime.parse().
// Если visitStatus false, то возвращает null.
@NonNull private final String startVisitDateTime;
@NonNull private final List<Long> visitsIdLast30Days; // Список Id посещений за последние 30 дней.
// Возвращает количество отработанных часов за последний месяц.
@NonNull private final long totalTimeVisitsLast30Days;
// (Возможно это стоит убрать) Название офиса, в котором сейчас находится работник.
// Если visitStatus false, возвращает null.
@NonNull private final String currentOfficeName;
// Возвращает время регистрации в формате LocalDateTime.toString(),
// превратить обратно можно с помощью LocalDateTime.parse().
@NonNull private final String createAt;
public EmpolyeeEntity(long id, @NonNull String name, @NonNull String surname, @NonNull String patronymic, @NonNull String telephone, @NonNull String email, long officeId, @NonNull String officeName, @NonNull String officeImageUrl, @NonNull String position, @NonNull String role, @NonNull String profileImageUrl, boolean visitStatus, @NonNull String startVisitDateTime, @NonNull List<Long> visitsIdLast30Days, long totalTimeVisitsLast30Days, @NonNull String currentOfficeName, @NonNull String createAt) {
this.id = id;
this.name = name;
this.surname = surname;
this.patronymic = patronymic;
this.telephone = telephone;
this.email = email;
this.officeId = officeId;
this.officeName = officeName;
this.officeImageUrl = officeImageUrl;
this.position = position;
this.role = role;
this.profileImageUrl = profileImageUrl;
this.visitStatus = visitStatus;
this.startVisitDateTime = startVisitDateTime;
this.visitsIdLast30Days = visitsIdLast30Days;
this.totalTimeVisitsLast30Days = totalTimeVisitsLast30Days;
this.currentOfficeName = currentOfficeName;
this.createAt = createAt;
}
public long getId() {
return id;
}
@NonNull
public String getName() {
return name;
}
@NonNull
public String getSurname() {
return surname;
}
@NonNull
public String getPatronymic() {
return patronymic;
}
@NonNull
public String getTelephone() {
return telephone;
}
@NonNull
public String getEmail() {
return email;
}
public long getOfficeId() {
return officeId;
}
@NonNull
public String getOfficeName() {
return officeName;
}
@NonNull
public String getOfficeImageUrl() {
return officeImageUrl;
}
@NonNull
public String getPosition() {
return position;
}
@NonNull
public String getRole() {
return role;
}
@NonNull
public String getProfileImageUrl() {
return profileImageUrl;
}
public boolean isVisitStatus() {
return visitStatus;
}
@NonNull
public String getStartVisitDateTime() {
return startVisitDateTime;
}
@NonNull
public List<Long> getVisitsIdLast30Days() {
return visitsIdLast30Days;
}
public long getTotalTimeVisitsLast30Days() {
return totalTimeVisitsLast30Days;
}
@NonNull
public String getCurrentOfficeName() {
return currentOfficeName;
}
@NonNull
public String getCreateAt() {
return createAt;
}
}

View File

@ -0,0 +1,66 @@
package ru.myitschool.work.api.domain.entity.employee;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class ItemEmployeeEntity {
@NonNull private final long id;
@NonNull private final String name;
@NonNull private final String surname;
@NonNull private final String patronymic;
@NonNull private final String profileImageUrl;
@NonNull private final String officeName;
@NonNull private final String position; // Название должности
// Текущее состояние входа: false - visit (посещение) ещё не началось, true - visit идёт
@NonNull private final boolean visitStatus;
public ItemEmployeeEntity(long id, @NonNull String name, @NonNull String surname, @Nullable String patronymic, @NonNull String profileImageUrl, @NonNull String officeName, @NonNull String position, boolean visitStatus) {
this.id = id;
this.name = name;
this.surname = surname;
this.patronymic = patronymic;
this.profileImageUrl = profileImageUrl;
this.officeName = officeName;
this.position = position;
this.visitStatus = visitStatus;
}
public long getId() {
return id;
}
@NonNull
public String getName() {
return name;
}
@NonNull
public String getSurname() {
return surname;
}
@NonNull
public String getPatronymic() {
return patronymic;
}
@NonNull
public String getProfileImageUrl() {
return profileImageUrl;
}
@NonNull
public String getOfficeName() {
return officeName;
}
@NonNull
public String getPosition() {
return position;
}
public boolean isVisitStatus() {
return visitStatus;
}
}

View File

@ -0,0 +1,88 @@
package ru.myitschool.work.api.domain.entity.office;
import androidx.annotation.NonNull;
import java.util.List;
import ru.myitschool.work.api.data.dto.TerminalDTO;
import ru.myitschool.work.api.data.dto.employee.EmployeeItemDTO;
public class OfficeEntity {
@NonNull private final long id;
@NonNull private final String name;
@NonNull private final String description;
@NonNull private final String address;
@NonNull private final Double latitude;
@NonNull private final Double longitude;
@NonNull private final String linkLogo;
@NonNull private final String telephone;
@NonNull private final String email;
@NonNull private final List<EmployeeItemDTO> empoyers; // Список id имплоев
@NonNull private final List<TerminalDTO> terminals;
public OfficeEntity(long id, @NonNull String name, @NonNull String description, @NonNull String address, @NonNull Double latitude, @NonNull Double longitude, @NonNull String linkLogo, @NonNull String telephone, @NonNull String email, @NonNull List<EmployeeItemDTO> employers, @NonNull List<TerminalDTO> terminals) {
this.id = id;
this.name = name;
this.description = description;
this.address = address;
this.linkLogo = linkLogo;
this.latitude = latitude;
this.longitude = longitude;
this.telephone = telephone;
this.email = email;
this.empoyers = employers;
this.terminals = terminals;
}
public long getId() {
return id;
}
@NonNull
public String getName() {
return name;
}
@NonNull
public String getAddress() {
return address;
}
@NonNull
public String getLinkLogo() {
return linkLogo;
}
@NonNull
public Double getLatitude() {
return latitude;
}
@NonNull
public Double getLongitude() {
return longitude;
}
@NonNull
public List<EmployeeItemDTO> getEmpoyers(){ return empoyers;}
@NonNull
public String getDescription() {
return description;
}
@NonNull
public List<TerminalDTO> getTerminals() {
return terminals;
}
@NonNull
public String getTelephone() {
return telephone;
}
@NonNull
public String getEmail() {
return email;
}
}

View File

@ -0,0 +1,57 @@
package com.example.myapplication.api.domain.entity.visit;
import androidx.annotation.NonNull;
import java.time.LocalDateTime;
public class VisitEntity {
@NonNull private final long id;
@NonNull private final LocalDateTime startVisit;
@NonNull private final LocalDateTime endVisit;
@NonNull private final String totalTime;
@NonNull private final boolean isFinished;
@NonNull private final long startTerminalId;
@NonNull private final long endTerminalId;
public VisitEntity(long id, @NonNull LocalDateTime startVisit, @NonNull LocalDateTime endVisit, @NonNull String totalTime, boolean isFinished, long startTerminalId, long endTerminalId) {
this.id = id;
this.startVisit = startVisit;
this.endVisit = endVisit;
this.totalTime = totalTime;
this.isFinished = isFinished;
this.startTerminalId = startTerminalId;
this.endTerminalId = endTerminalId;
}
public long getId() {
return id;
}
@NonNull
public LocalDateTime getStartVisit() {
return startVisit;
}
@NonNull
public LocalDateTime getEndVisit() {
return endVisit;
}
@NonNull
public String getTotalTime() {
return totalTime;
}
public boolean isFinished() {
return isFinished;
}
public long getStartTerminalId() {
return startTerminalId;
}
public long getEndTerminalId() {
return endTerminalId;
}
}

View File

@ -0,0 +1,22 @@
package ru.myitschool.work.api.domain.useCases.employee;
import androidx.annotation.NonNull;
import java.util.function.Consumer;
import ru.myitschool.work.api.domain.EmployeeRepository;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.employee.EmpolyeeEntity;
public class DeleteEmployeeUseCase {
private final EmployeeRepository employeeRepository;
public DeleteEmployeeUseCase(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public void execute(long id, @NonNull Consumer<Status<EmpolyeeEntity>> callback) {
employeeRepository.deleteEmployee(id,callback);
}
}

View File

@ -0,0 +1,22 @@
package ru.myitschool.work.api.domain.useCases.employee;
import androidx.annotation.NonNull;
import java.util.List;
import java.util.function.Consumer;
import ru.myitschool.work.api.domain.EmployeeRepository;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.employee.EmpolyeeEntity;
public class GetAllEmployees {
private final EmployeeRepository employeeRepository;
public GetAllEmployees(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public void execute(@NonNull Consumer<Status<List<EmpolyeeEntity>>> callback) {
employeeRepository.getAllEmployees(callback);
}
}

View File

@ -0,0 +1,23 @@
package ru.myitschool.work.api.domain.useCases.employee;
import androidx.annotation.NonNull;
import java.util.function.Consumer;
import ru.myitschool.work.api.domain.EmployeeRepository;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.employee.EmpolyeeEntity;
public class GetEmloyeeByIdUseCase {
private final EmployeeRepository employeeRepository;
public GetEmloyeeByIdUseCase(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public void execute(long id, @NonNull Consumer<Status<EmpolyeeEntity>> callback) {
employeeRepository.getEmployeeById(id, callback);
}
}

View File

@ -0,0 +1,20 @@
package ru.myitschool.work.api.domain.useCases.employee;
import androidx.annotation.NonNull;
import java.util.function.Consumer;
import ru.myitschool.work.api.domain.EmployeeRepository;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.employee.EmpolyeeEntity;
public class GetEmployeeByEmailUseCase {
private final ru.myitschool.work.api.domain.EmployeeRepository employeeRepository;
public GetEmployeeByEmailUseCase(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public void execute(@NonNull String email, @NonNull Consumer<Status<EmpolyeeEntity>> callback) {
employeeRepository.getEmployeeByEmail(email, callback);
}}

View File

@ -0,0 +1,20 @@
package ru.myitschool.work.api.domain.useCases.employee;
import androidx.annotation.NonNull;
import java.util.function.Consumer;
import ru.myitschool.work.api.domain.EmployeeRepository;
import ru.myitschool.work.api.domain.entity.Status;
public class PatchEmployeeOfficeId {
private final EmployeeRepository employeeRepository;
public PatchEmployeeOfficeId(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public void execute(long id, long centerId, @NonNull Consumer<Status<Void>> callback) {
employeeRepository.patchEmployeerOfficeId(id, centerId, callback);
}
}

View File

@ -0,0 +1,21 @@
package ru.myitschool.work.api.domain.useCases.employee;
import androidx.annotation.NonNull;
import java.util.function.Consumer;
import ru.myitschool.work.api.data.dto.employee.EmployeeDTO;
import ru.myitschool.work.api.domain.EmployeeRepository;
import ru.myitschool.work.api.domain.entity.Status;
public class UpdateEmployeeUseCase {
private final EmployeeRepository employeeRepository;
public UpdateEmployeeUseCase(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public void execute(long id, @NonNull EmployeeDTO employeeDTO, @NonNull Consumer<Status<Void>> callback) {
employeeRepository.updateEmployee(id, employeeDTO, callback);
}
}

View File

@ -0,0 +1,22 @@
package ru.myitschool.work.api.domain.useCases.office;
import androidx.annotation.NonNull;
import java.util.List;
import java.util.function.Consumer;
import ru.myitschool.work.api.domain.OfficeRepository;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.office.OfficeEntity;
public class GetAllOficiesUseCase {
private final OfficeRepository officeRepository;
public GetAllOficiesUseCase(OfficeRepository officeRepository) {
this.officeRepository = officeRepository;
}
public void execute(@NonNull Consumer<Status<List<OfficeEntity>>> callback) {
officeRepository.getAllOffices(callback);
}
}

View File

@ -0,0 +1,22 @@
package ru.myitschool.work.api.domain.useCases.sign;
import androidx.annotation.NonNull;
import java.util.function.Consumer;
import ru.myitschool.work.api.data.dto.employee.EmployeeCreateDTO;
import ru.myitschool.work.api.domain.SignRepository;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.employee.EmpolyeeEntity;
public class CreateEmployeeUseCase {
private final SignRepository signRepository;
public CreateEmployeeUseCase(SignRepository signRepository) {
this.signRepository = signRepository;
}
public void execute(@NonNull EmployeeCreateDTO employeeRegisterDTO, Consumer<Status<EmpolyeeEntity>> callback) {
signRepository.createEmployee(employeeRegisterDTO, callback);
}
}

View File

@ -0,0 +1,24 @@
package ru.myitschool.work.api.domain.useCases.sign;
import androidx.annotation.NonNull;
import java.util.function.Consumer;
import ru.myitschool.work.api.domain.SignRepository;
import ru.myitschool.work.api.domain.entity.Status;
import ru.myitschool.work.api.domain.entity.employee.EmpolyeeEntity;
public class LoginEmployeeUseCase {
private final SignRepository signRepository;
public LoginEmployeeUseCase(SignRepository signRepository) {
this.signRepository = signRepository;
}
public void execute(@NonNull String email, @NonNull String password, Consumer<Status<EmpolyeeEntity>> callback) {
signRepository.login(email, password, employeeEntityStatus -> {
//if (employeeEntityStatus.getStatusCode() != 200) signRepository.logout();
callback.accept(employeeEntityStatus);
});
}
}

View File

@ -1,14 +0,0 @@
package ru.myitschool.work.api.entity;
import kotlinx.serialization.Serializable;
@Serializable
public class Code {
private long value;
public Code() { }
public Code(long value) { this.value = value;}
public long getValue() { return value; }
public void setValue(long value) { this.value = value; }
}

View File

@ -1,87 +0,0 @@
package ru.myitschool.work.api.entity;
import androidx.annotation.NonNull;
import kotlinx.serialization.Serializable;
@Serializable
public class Employee {
private long id;
private String login;
private String name;
private String photo;
private String position;
private String lastVisit;
public Employee() {
}
public Employee(long id, String login, String name, String photo, String position, String lastVisit) {
this.id = id;
this.login = login;
this.name = name;
this.photo = photo;
this.position = position;
this.lastVisit = lastVisit;
}
@NonNull
@Override
public String toString() {
return "id: " + id +
", login: " + login +
", name: " + name +
", photo: " + photo +
", position: " + position +
", lastVisit: " + lastVisit;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getLastVisit() {
return lastVisit;
}
public void setLastVisit(String lastVisit) {
this.lastVisit = lastVisit;
}
}

View File

@ -0,0 +1,7 @@
package com.example.myapplication.core
object BundleConstants {
const val EVENT_ID: String = "eventId"
const val EVENT_COORDINATES: String = "coordinate"
const val VOLUNTEER_ID: String = "volunteerId"
}

View File

@ -1,6 +0,0 @@
package ru.myitschool.work.core
// БЕРИТЕ И ИЗМЕНЯЙТЕ ХОСТ ТОЛЬКО ЗДЕСЬ И НЕ БЕРИТЕ ИЗ ДРУГИХ МЕСТ. ФАЙЛ ПЕРЕМЕЩАТЬ НЕЛЬЗЯ
object Constants {
// const val SERVER_ADDRESS = "http://localhost:8090"
const val SERVER_ADDRESS = "http://192.168.0.105:8080"
}

View File

@ -1,7 +0,0 @@
package ru.myitschool.work.core
object MyConstants {
const val PREFS_FILE: String = "account"
const val PREF_LOGIN: String = "login"
val DEF_VALUE: Nothing? = null
}

View File

@ -0,0 +1,7 @@
package com.example.myapplication.core
object RoleConstants {
const val ROLE_USER: String = "ROLE_USER"
const val ROLE_ADMIN: String = "ROLE_ADMIN"
const val ROLE_GUEST: String = "ROLE_GUEST"
}

View File

@ -0,0 +1,10 @@
package com.example.myapplication.core
object SettingConstants {
// Для сохранения факта входа в систему.
const val PREFS_FILE: String = "account"
const val PREF_ID: String = "id"
const val PREF_ROLE: String = "role"
const val ERROR_ID: Long = 1.unaryMinus()
val DEF_VALUE: Nothing? = null
}

View File

@ -0,0 +1,7 @@
package com.example.myapplication.core
object UrlConstants {
// url для эмулятора http://10.0.2.2:8080/
const val BASE_URL: String = "http://192.168.0.105:8080"
const val DOWNLOAD_URL: String = "$BASE_URL/api/v1/images/"
}

View File

@ -1,66 +0,0 @@
package ru.myitschool.work.ui
import ru.myitschool.work.ui.result.ResultFragment
import android.os.Bundle
import android.util.Log
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.createGraph
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.fragment
import dagger.hilt.android.AndroidEntryPoint
import ru.myitschool.work.R
import ru.myitschool.work.ui.login.LoginDestination
import ru.myitschool.work.ui.login.LoginFragment
import ru.myitschool.work.ui.main.MainDestination
import ru.myitschool.work.ui.main.MainFragment
import ru.myitschool.work.ui.qr.scan.QrScanDestination
import ru.myitschool.work.ui.qr.scan.QrScanFragment
import ru.myitschool.work.ui.result.ResultDestination
// НЕ ИЗМЕНЯЙТЕ НАЗВАНИЕ КЛАССА!
@AndroidEntryPoint
class RootActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_root)
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment?
if (navHostFragment != null) {
val navController = navHostFragment.navController
navController.graph = navController.createGraph(
startDestination = MainDestination
) {
fragment<LoginFragment, LoginDestination>()
fragment<MainFragment, MainDestination>()
fragment<QrScanFragment, QrScanDestination>()
fragment<ResultFragment, ResultDestination>()
}
}
onBackPressedDispatcher.addCallback(
this,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
onSupportNavigateUp()
}
}
)
}
override fun onSupportNavigateUp(): Boolean {
Log.d("Test", "(RootActivity) Сработал метод, отвечающий за кнопку назад.")
val navController = findNavController(R.id.nav_host_fragment)
val popBackResult = if (navController.previousBackStackEntry != null) {
navController.popBackStack()
} else {
false
}
return popBackResult || super.onSupportNavigateUp()
}
}

View File

@ -1,6 +0,0 @@
package ru.myitschool.work.ui.login
import kotlinx.serialization.Serializable
@Serializable
data object LoginDestination

View File

@ -1,122 +0,0 @@
package ru.myitschool.work.ui.login
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.text.Editable
import android.util.Log
import android.view.View
import android.widget.EditText
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import dagger.hilt.android.AndroidEntryPoint
import ru.myitschool.work.R
import ru.myitschool.work.api.ControllerAPI
import ru.myitschool.work.api.HandlersResultAPI
import ru.myitschool.work.api.entity.Employee
import ru.myitschool.work.core.MyConstants
import ru.myitschool.work.databinding.FragmentLoginBinding
import java.util.regex.Pattern
@AndroidEntryPoint
class LoginFragment : Fragment(R.layout.fragment_login), HandlersResultAPI {
private var _binding: FragmentLoginBinding? = null
private val binding: FragmentLoginBinding get() = _binding!!
private val viewModel: LoginViewModel by viewModels()
private var controllerAPI: ControllerAPI<LoginFragment>? = null // Работа с API
private var settings: SharedPreferences? = null // Настройки приложения. Нужны для сохранения логина при входе.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = FragmentLoginBinding.bind(view)
// ТЗ:
// >>> ✅ В пустом поле ввода должна отображаться подсказка, что требуется ввести пользователю.
// >>> ✅ Если хотя бы одно из условий ниже соблюдено - кнопка должна быть неактивной:
// ✅ Поле ввода пустое.
// ✅ Количество символов менее 3-х.
// ✅ Логин начинается с цифры.
// ✅ Логин содержит символы, отличные от латинского алфавита и цифр.
// >>> ✅ Поле ввода и кнопку должно быть видно при раскрытии клавиатуры.
// >>> ✅ При нажатии на кнопку входа необходимо проверить, что данный пользователь существует
// с помощью запроса api/<LOGIN>/auth.
// >>> ✅ В случае отсутствия логина или любой другой неполадки - необходимо вывести ошибку,
// пока пользователь не изменит текстовое поле или повторно не нажмёт на кнопку.
// >>> ✅ После нажатия на кнопку - логин должен быть сохранён и при следующем открытии
// приложения экран авторизации не должен быть показан.
// >>> ✅ После нажатия на кнопку - при нажатии стрелки назад - экран авторизации не
// должен быть показан повторно.
// >>> ✅ Экран авторизации показывается только в случае, если пользователь не авторизован.
// usernameEditText = findViewById<EditText>(R.id.username)
// loginButton = findViewById<Button>(R.id.login)
// errorTextView = findViewById<TextView>(R.id.error)
controllerAPI = ControllerAPI<LoginFragment>()
settings = this.requireActivity().getSharedPreferences(MyConstants.PREFS_FILE, Context.MODE_PRIVATE)
// Этот код отвечает за прослушивание ввода логина. Нужен для 2 задания из ТЗ.
// Он использует абстрактный класс UsernameEditTextListener, который просто сокращает TextWatcher.
binding.username.addTextChangedListener(object : UsernameEditTextListener<EditText>(binding.username) {
override fun onTextChanged(target: EditText, s: Editable) {
val userLogin = s.toString()
val pattern = Pattern.compile("[^a-zA-Z0-9]")
val result = !(userLogin.isEmpty() || userLogin.length < 3 ||
Character.isDigit(userLogin[0]) ||
pattern.matcher(userLogin).find())
binding.login.setEnabled(result)
// ТЗ: Необходимо вывести ошибку, пока пользователь не изменит текстовое поле
binding.error.visibility = View.GONE
}
})
// Прослушиваем нажатие на кнопку `Вход`.
binding.login.setOnClickListener {
controllerAPI!!.verificationLogin(binding.username.text.toString(), this)
}
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
override fun handlerVerificationLogin(login: String?, result: Boolean) {
binding.error.visibility = View.GONE // Тз: необходимо вывести ошибку, пока пользователь
// не изменит текстовое поле или повторно не нажмёт на кнопку.
if (result) {
// Этот код отвечает за сохранения факта входа.
// Код копировал отсюда -> https://metanit.com/java/android/12.1.php
val prefEditor = settings!!.edit()
prefEditor.putString(MyConstants.PREF_LOGIN, login)
prefEditor.apply()
Log.d(
"Test",
"(LoginActivity) Проверка сохранения логина: " + settings!!.getString(
MyConstants.PREF_LOGIN,
"Не сохранилось"
)
)
Log.d("Test", "(LoginActivity) Начало перехода на главную активность.")
// findNavController().navigate(MainDestination)
findNavController().popBackStack()
} else {
Log.d("Test", "(LoginActivity) Введён неправильный логин! login: $login")
binding.error.visibility = View.VISIBLE
}
}
override fun handlerGetEmployee(employee: Employee?) {
}
override fun handlerVisit(result: Int) {
}
}

View File

@ -1,17 +0,0 @@
package ru.myitschool.work.ui.login
import android.content.Context
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(
@ApplicationContext private val context: Context,
) : ViewModel() {
private val _state = MutableStateFlow(true)
val state = _state.asStateFlow()
}

View File

@ -1,24 +0,0 @@
package ru.myitschool.work.ui.login;
import android.text.Editable;
import android.text.TextWatcher;
public abstract class UsernameEditTextListener<T> implements TextWatcher {
// Нужен, чтобы убрать ненужные мне методы beforeTextChanged и onTextChanged.
// https://stackoverflow.com/questions/11134144/android-edittext-onchange-listener
private final T target;
public UsernameEditTextListener(T target) { this.target = target; }
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) { this.onTextChanged(target, s); }
public abstract void onTextChanged(T target, Editable s);
}

View File

@ -1,6 +0,0 @@
package ru.myitschool.work.ui.main
import kotlinx.serialization.Serializable
@Serializable
data object MainDestination

View File

@ -1,184 +0,0 @@
package ru.myitschool.work.ui.main
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity.MODE_PRIVATE
import androidx.fragment.app.Fragment
import androidx.fragment.app.clearFragmentResultListener
import androidx.fragment.app.setFragmentResultListener
import androidx.navigation.fragment.findNavController
import ru.myitschool.work.R
import ru.myitschool.work.api.ControllerAPI
import ru.myitschool.work.api.HandlersResultAPI
import ru.myitschool.work.api.entity.Employee
import ru.myitschool.work.core.MyConstants
import ru.myitschool.work.databinding.FragmentMainBinding
import ru.myitschool.work.ui.login.LoginDestination
import ru.myitschool.work.ui.qr.scan.QrScanDestination
import ru.myitschool.work.ui.result.ResultDestination
import ru.myitschool.work.utils.DownloadImage
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class MainFragment : Fragment(R.layout.fragment_main), HandlersResultAPI {
private var _binding: FragmentMainBinding? = null
private val binding: FragmentMainBinding get() = _binding!!
private lateinit var controllerAPI: ControllerAPI<MainFragment>
private lateinit var settings: SharedPreferences
private lateinit var login: String
private var flag = false
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = FragmentMainBinding.bind(view)
controllerAPI = ControllerAPI<MainFragment>()
settings = this.requireActivity().getSharedPreferences(MyConstants.PREFS_FILE, MODE_PRIVATE)
if (flag && savedInstanceState == null) {
Log.d("Test", "(1)")
val editor = settings.edit()
editor.putString("code", "Отмена")
editor.putString("login", login)
editor.apply()
flag = false
findNavController().navigate(ResultDestination)
clearFragmentResultListener("qr_result")
}
init()
}
private fun init() {
Log.d("Test", "(MainFragment) Проверяем зарегистрирован пользователь или нет.")
if (settings.getString(MyConstants.PREF_LOGIN, MyConstants.DEF_VALUE) == MyConstants.DEF_VALUE) {
Log.d("Test", "(MainFragment) Пользователь не зарегистрирован, запускаем активность регистрации.")
findNavController().navigate(LoginDestination)
return
}
login = settings.getString(MyConstants.PREF_LOGIN, MyConstants.DEF_VALUE).toString()
Log.d("Test", "(MainFragment) Пользователь зарегистрирован, его login - $login")
Log.d("Test", "(MainFragment) Отправляем запрос на получение данных пользователя.")
controllerAPI.getEmployee(login, this)
binding.logout.setOnClickListener {
Log.d("Test", "(MainFragment) Запущен обработчик кнопки `Выход`.")
settings.edit().clear().apply()
Log.d("Test",
"(MainFragment) Теперь логин пользователя: " + settings.getString(
MyConstants.PREF_LOGIN,
MyConstants.DEF_VALUE
).toString()
)
findNavController().navigate(LoginDestination)
}
binding.refresh.setOnClickListener {
Log.d("Test", "(MainFragment) Запущен обработчик кнопки `Обновить`.")
Log.d("Test", "(MainFragment) Отправляем запрос на получение данных пользователя.")
controllerAPI.getEmployee(login, this)
}
binding.scan.setOnClickListener {
setFragmentResultListener("qr_result") { _, bundle ->
Log.d("Test", bundle.toString())
val code: String = QrScanDestination.getDataIfExist(bundle) ?: return@setFragmentResultListener
val editor = settings.edit()
editor.putString("code", code)
editor.putString("login", login)
editor.apply()
Log.d("Test", "(2)")
flag = false
findNavController().navigate(ResultDestination)
clearFragmentResultListener("qr_result")
}
flag = true
findNavController().navigate(QrScanDestination)
}
}
override fun handlerVerificationLogin(login: String?, result: Boolean) {
}
@RequiresApi(Build.VERSION_CODES.O)
override fun handlerGetEmployee(employee: Employee?) {
if (employee == null) {
Log.e("Test", "(MainFragment) Сервер не вернул работника, вероятно, он не запущен.")
allGone()
binding.error.visibility = View.VISIBLE
binding.refresh.visibility = View.VISIBLE
return
}
Log.d("Test", "(MainFragment) Обработчик получения данных работника запустился!")
Log.d("Test", "(MainFragment) employee: $employee")
allVisibility()
binding.error.visibility = View.GONE
binding.fullname.text = employee.name
binding.position.text = employee.position
// Форматируем дату и время в вид yyyy-MM-dd HH:mm
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
val dateTime = LocalDateTime.parse(employee.lastVisit)
val lastVisit = dateTime.format(formatter)
binding.lastEntry.text = lastVisit
downloadImage(employee.photo)
Log.d(
"Test", "(MainFragment) Записанные данные: fullname: ${binding.fullname.text}, " +
"position: ${binding.position.text}, lastEntry: ${binding.lastEntry.text}"
)
}
override fun handlerVisit(result: Int) {
// Тут ничего не должно быть.
}
private fun allGone() {
binding.refresh.visibility = View.GONE
binding.scan.visibility = View.GONE
binding.logout.visibility = View.GONE
binding.error.visibility = View.GONE
binding.position.visibility = View.GONE
binding.lastEntry.visibility = View.GONE
binding.fullname.visibility = View.GONE
binding.photo.visibility = View.GONE
}
private fun allVisibility() {
binding.refresh.visibility = View.VISIBLE
binding.scan.visibility = View.VISIBLE
binding.logout.visibility = View.VISIBLE
binding.error.visibility = View.VISIBLE
binding.position.visibility = View.VISIBLE
binding.lastEntry.visibility = View.VISIBLE
binding.fullname.visibility = View.VISIBLE
binding.photo.visibility = View.VISIBLE
}
private fun downloadImage(urlImage: String) {
Log.d("Test", "(MainFragment) Начинаем скачивать изображение с URl: $urlImage")
DownloadImage(binding.photo).execute(urlImage)
}
}

View File

@ -1,6 +0,0 @@
package ru.myitschool.work.ui.result
import kotlinx.serialization.Serializable
@Serializable
data object ResultDestination

View File

@ -1,75 +0,0 @@
package ru.myitschool.work.ui.result
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity.MODE_PRIVATE
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import ru.myitschool.work.R
import ru.myitschool.work.api.ControllerAPI
import ru.myitschool.work.api.HandlersResultAPI
import ru.myitschool.work.api.entity.Code
import ru.myitschool.work.api.entity.Employee
import ru.myitschool.work.core.MyConstants
import ru.myitschool.work.databinding.FragmentResultBinding
import ru.myitschool.work.ui.main.MainDestination
import java.io.IOException
class ResultFragment : Fragment(R.layout.fragment_result), HandlersResultAPI {
private var _binding: FragmentResultBinding? = null
private val binding: FragmentResultBinding get() = _binding!!
private lateinit var controllerAPI: ControllerAPI<ResultFragment> // Работа с API
private lateinit var settings: SharedPreferences
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = FragmentResultBinding.bind(view)
controllerAPI = ControllerAPI<ResultFragment>()
settings = this.requireActivity().getSharedPreferences(MyConstants.PREFS_FILE, MODE_PRIVATE)
val code = settings.getString("code", "").toString()
val login = settings.getString("login", "").toString()
Log.d("Test", "(ResultLayoutActivity) code: $code, login: $login")
if (code == "Отмена" || code == "") {
binding.result.setText(R.string.cancelled)
} else {
try {
controllerAPI.visit(login, Code(code.toLong()), this)
} catch (e: NumberFormatException) {
binding.result.setText(R.string.wrong)
} catch (e: IOException) {
binding.result.setText(R.string.wrong)
}
}
binding.close.setOnClickListener {
findNavController().navigate(MainDestination)
}
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
override fun handlerVerificationLogin(login: String?, result: Boolean) {
}
override fun handlerGetEmployee(employee: Employee?) {
}
override fun handlerVisit(result: Int) {
if (result == 200) {
binding.result.setText(R.string.success)
} else {
binding.result.setText(R.string.wrong)
}
}
}

View File

@ -1,37 +0,0 @@
package ru.myitschool.work.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.URL;
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public DownloadImage(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(String... imageUrls) {
String imageUrl = imageUrls[0];
try {
InputStream inputStream = new URL(imageUrl).openStream();
return BitmapFactory.decodeStream(inputStream);
} catch (Exception e) {
Log.e("Test", "(DownloadImage) При скачивании изображения произошла ошибка: " + e);
return null;
}
}
protected void onPostExecute(Bitmap result) {
Log.d("Test", "(DownloadImage) Устанавливаем изображение в imageView (" + imageView.getId() + ")");
imageView.setImageBitmap(result);
}
}

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="-29dp"
android:layout_marginBottom="0dp"
android:fontFamily="monospace"
android:text="ccddddvvvve"
android:textColor="@color/black"
android:textSize="75dp" />
</RelativeLayout>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.constraintlayout.widget.ConstraintLayout>