Merge pull request #119 from SlimusMinus/feat-post_phone_from_profile
Prefill post phone from user profile
This commit is contained in:
@@ -11,6 +11,7 @@ import MapModal from "./MapModal";
|
|||||||
import ClearableField from "../components/ClearableField";
|
import ClearableField from "../components/ClearableField";
|
||||||
import AddressAutocomplete from "../components/AddressAutocomplete";
|
import AddressAutocomplete from "../components/AddressAutocomplete";
|
||||||
import { useIsDesktop } from "../hooks/useIsDesktop";
|
import { useIsDesktop } from "../hooks/useIsDesktop";
|
||||||
|
import { useAuthContext } from "../context/AuthContext";
|
||||||
|
|
||||||
// Ограничения полей бэкенда (PostFieldLimits): длиннее — 400
|
// Ограничения полей бэкенда (PostFieldLimits): длиннее — 400
|
||||||
const TITLE_MAX_LENGTH = 255;
|
const TITLE_MAX_LENGTH = 255;
|
||||||
@@ -30,8 +31,12 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
|||||||
const isEdit = !!initialData;
|
const isEdit = !!initialData;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const isDesktop = useIsDesktop();
|
const isDesktop = useIsDesktop();
|
||||||
|
const { user } = useAuthContext();
|
||||||
|
// Телефон из профиля подставляем, чтобы не вводить его в каждом объявлении.
|
||||||
|
// В админ-режиме правится чужое объявление — телефон админа туда не нужен.
|
||||||
|
const profilePhone = !adminMode && user?.phone ? formatPhone(user.phone) : "";
|
||||||
|
|
||||||
const [form, setForm] = useState(
|
const [form, setForm] = useState(() => (
|
||||||
isEdit
|
isEdit
|
||||||
? {
|
? {
|
||||||
type: (initialData.type || "loss").toLowerCase(),
|
type: (initialData.type || "loss").toLowerCase(),
|
||||||
@@ -39,15 +44,15 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
|||||||
description: initialData.description || "",
|
description: initialData.description || "",
|
||||||
category: initialData.category || "",
|
category: initialData.category || "",
|
||||||
date: initialData.date || "",
|
date: initialData.date || "",
|
||||||
phone: initialData.phone || "",
|
phone: initialData.phone || profilePhone,
|
||||||
address: initialData.address || initialData.city || "",
|
address: initialData.address || initialData.city || "",
|
||||||
rulesAccepted: true,
|
rulesAccepted: true,
|
||||||
reward: initialData.reward ?? false,
|
reward: initialData.reward ?? false,
|
||||||
rewardText: initialData.rewardText
|
rewardText: initialData.rewardText
|
||||||
|| (initialData.reward ? t('post.rewardDefault') : "")
|
|| (initialData.reward ? t('post.rewardDefault') : "")
|
||||||
}
|
}
|
||||||
: EMPTY_FORM
|
: { ...EMPTY_FORM, phone: profilePhone }
|
||||||
);
|
));
|
||||||
|
|
||||||
const [rulesModalOpen, setRulesModalOpen] = useState(false);
|
const [rulesModalOpen, setRulesModalOpen] = useState(false);
|
||||||
const [mapModalOpen, setMapModalOpen] = useState(false);
|
const [mapModalOpen, setMapModalOpen] = useState(false);
|
||||||
|
|||||||
@@ -2,11 +2,13 @@
|
|||||||
* На десктопе форма объявления закрывается только крестиком: клик по фону
|
* На десктопе форма объявления закрывается только крестиком: клик по фону
|
||||||
* не должен терять заполненные поля. На мобильном клик по фону закрывает.
|
* не должен терять заполненные поля. На мобильном клик по фону закрывает.
|
||||||
* Там же на десктопе фото можно перетащить в форму (drag & drop).
|
* Там же на десктопе фото можно перетащить в форму (drag & drop).
|
||||||
|
* Телефон подставляется из профиля, если в объявлении его нет.
|
||||||
*/
|
*/
|
||||||
import { render, screen, fireEvent } from "@testing-library/react";
|
import { render, screen, fireEvent } from "@testing-library/react";
|
||||||
import CreateUpdatePost from "./CreateUpdatePost";
|
import CreateUpdatePost from "./CreateUpdatePost";
|
||||||
import { useIsDesktop } from "../hooks/useIsDesktop";
|
import { useIsDesktop } from "../hooks/useIsDesktop";
|
||||||
import { compressImage } from "../utils/compressImage";
|
import { compressImage } from "../utils/compressImage";
|
||||||
|
import { useAuthContext } from "../context/AuthContext";
|
||||||
import "../i18n";
|
import "../i18n";
|
||||||
|
|
||||||
jest.mock("../hooks/useIsDesktop", () => ({ useIsDesktop: jest.fn() }));
|
jest.mock("../hooks/useIsDesktop", () => ({ useIsDesktop: jest.fn() }));
|
||||||
@@ -15,10 +17,12 @@ jest.mock("../hooks/usePostMutation", () => ({
|
|||||||
}));
|
}));
|
||||||
// Сжатие через canvas в jsdom не работает и тут не проверяется
|
// Сжатие через canvas в jsdom не работает и тут не проверяется
|
||||||
jest.mock("../utils/compressImage", () => ({ compressImage: jest.fn() }));
|
jest.mock("../utils/compressImage", () => ({ compressImage: jest.fn() }));
|
||||||
|
jest.mock("../context/AuthContext", () => ({ useAuthContext: jest.fn() }));
|
||||||
|
|
||||||
// CRA сбрасывает реализации моков перед каждым тестом — задаём их здесь
|
// CRA сбрасывает реализации моков перед каждым тестом — задаём их здесь
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
compressImage.mockImplementation((file) => Promise.resolve(file));
|
compressImage.mockImplementation((file) => Promise.resolve(file));
|
||||||
|
useAuthContext.mockReturnValue({ user: null });
|
||||||
URL.createObjectURL = jest.fn(() => "blob:preview");
|
URL.createObjectURL = jest.fn(() => "blob:preview");
|
||||||
URL.revokeObjectURL = jest.fn();
|
URL.revokeObjectURL = jest.fn();
|
||||||
});
|
});
|
||||||
@@ -116,3 +120,53 @@ test("на мобильном перетаскивание фото выключ
|
|||||||
expect(compressImage).not.toHaveBeenCalled();
|
expect(compressImage).not.toHaveBeenCalled();
|
||||||
expect(screen.queryByText(/или перетащите фото сюда|or drag photos here/)).toBeNull();
|
expect(screen.queryByText(/или перетащите фото сюда|or drag photos here/)).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const PROFILE_PHONE = "+7 (999) 111-22-33";
|
||||||
|
|
||||||
|
/** Рендерит форму и переходит на второй шаг, где находится поле «Телефон». */
|
||||||
|
function openPhoneStep(props = {}) {
|
||||||
|
useIsDesktop.mockReturnValue(true);
|
||||||
|
render(<CreateUpdatePost onClose={jest.fn()} {...props} />);
|
||||||
|
if (!props.initialData) {
|
||||||
|
fireEvent.change(screen.getByPlaceholderText(/Кошелёк|wallet/i), { target: { value: "Ключи" } });
|
||||||
|
fireEvent.change(screen.getByPlaceholderText(/опишите|describe/i), { target: { value: "Связка ключей" } });
|
||||||
|
}
|
||||||
|
fireEvent.click(screen.getByText(/^(Далее|Next)/));
|
||||||
|
return screen.getByPlaceholderText("+7 (___) ___-__-__");
|
||||||
|
}
|
||||||
|
|
||||||
|
test("новое объявление: телефон подставляется из профиля", () => {
|
||||||
|
useAuthContext.mockReturnValue({ user: { phone: "79991112233" } });
|
||||||
|
|
||||||
|
expect(openPhoneStep().value).toBe(PROFILE_PHONE);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("новое объявление без телефона в профиле: поле пустое", () => {
|
||||||
|
useAuthContext.mockReturnValue({ user: { phone: "" } });
|
||||||
|
|
||||||
|
expect(openPhoneStep().value).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
const POST = { id: 1, type: "LOSS", title: "Ключи", description: "Связка ключей", category: "KEYS" };
|
||||||
|
|
||||||
|
test("редактирование: телефон объявления не заменяется телефоном профиля", () => {
|
||||||
|
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||||||
|
|
||||||
|
const phone = openPhoneStep({ initialData: { ...POST, phone: "+7 (900) 000-00-00" } });
|
||||||
|
|
||||||
|
expect(phone.value).toBe("+7 (900) 000-00-00");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("редактирование объявления без телефона: подставляется телефон профиля", () => {
|
||||||
|
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||||||
|
|
||||||
|
expect(openPhoneStep({ initialData: { ...POST, phone: "" } }).value).toBe(PROFILE_PHONE);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("админ правит чужое объявление: свой телефон не подставляется", () => {
|
||||||
|
useAuthContext.mockReturnValue({ user: { phone: PROFILE_PHONE } });
|
||||||
|
|
||||||
|
const phone = openPhoneStep({ initialData: { ...POST, phone: "" }, adminMode: true });
|
||||||
|
|
||||||
|
expect(phone.value).toBe("");
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user