Skip to content

Commit

Permalink
Merge pull request #114 from korobprog/feature/book-prices
Browse files Browse the repository at this point in the history
Feature/book prices
  • Loading branch information
vraja-nayaka authored Jan 1, 2024
2 parents 8c127f9 + 7aa6093 commit 534d00f
Show file tree
Hide file tree
Showing 44 changed files with 1,163 additions and 396 deletions.
3 changes: 3 additions & 0 deletions packages/admin/src/App.less
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ code {

.page-header {
padding: 4px;
}

.ant-page-header-heading-left {
text-transform: uppercase;
}

Expand Down
6 changes: 6 additions & 0 deletions packages/common/src/app/common.less
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.sticky {
position: sticky;
top: 0;
background: #fff;
z-index: 10;
}
26 changes: 13 additions & 13 deletions packages/common/src/app/offline/service-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.

import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
import { clientsClaim } from "workbox-core";
import { ExpirationPlugin } from "workbox-expiration";
import { precacheAndRoute, createHandlerBoundToURL } from "workbox-precaching";
import { registerRoute } from "workbox-routing";
import { StaleWhileRevalidate } from "workbox-strategies";

declare const self: ServiceWorkerGlobalScope;

Expand All @@ -27,17 +27,17 @@ precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
const fileExtensionRegexp = new RegExp("/[^/?]+\\.[^/]+$");
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }: { request: Request; url: URL }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
if (request.mode !== "navigate") {
return false;
}

// If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
if (url.pathname.startsWith("/_")) {
return false;
}

Expand All @@ -50,17 +50,17 @@ registerRoute(
// Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
createHandlerBoundToURL(process.env.PUBLIC_URL + "/index.html")
);

// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'),
({ url }) => url.origin === self.location.origin && url.pathname.endsWith(".png"),
// Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
cacheName: "images",
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
Expand All @@ -71,8 +71,8 @@ registerRoute(

// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
Expand Down
48 changes: 32 additions & 16 deletions packages/common/src/app/offline/serviceWorkerRegistration.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { notification } from "antd";

// This optional code is used to register a service worker.
// register() is not called by default.

Expand All @@ -11,9 +13,9 @@
// opt-in, read https://cra.link/PWA

const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
window.location.hostname === "[::1]" ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);
Expand All @@ -24,7 +26,7 @@ type Config = {
};

export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
Expand All @@ -34,7 +36,7 @@ export function register(config?: Config) {
return;
}

window.addEventListener('load', () => {
window.addEventListener("load", () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

if (isLocalhost) {
Expand All @@ -45,8 +47,8 @@ export function register(config?: Config) {
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://cra.link/PWA'
"This web app is being served cache-first by a service " +
"worker. To learn more, visit https://cra.link/PWA"
);
});
} else {
Expand All @@ -67,15 +69,22 @@ function registerValidSW(swUrl: string, config?: Config) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://cra.link/PWA.'
"New content is available and will be used when all " +
"tabs for this page are closed. See https://cra.link/PWA."
);
setTimeout(() => {
notification.open({
message: "Появилось новая версия приложения",
description: `Приложение обновится само, когда вы закроете его во всех вкладках браузера и откроете в новой`,
type: "info",
});
}, 2000);

// Execute callback
if (config && config.onUpdate) {
Expand All @@ -85,10 +94,17 @@ function registerValidSW(swUrl: string, config?: Config) {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
console.log("Content is cached for offline use.");

// Execute callback
if (config && config.onSuccess) {
setTimeout(() => {
notification.open({
message: "Загрузилась новая версия приложения",
description: `Спасибо, что пользуетесь нашим приложением`,
type: "success",
});
}, 2000);
config.onSuccess(registration);
}
}
Expand All @@ -97,21 +113,21 @@ function registerValidSW(swUrl: string, config?: Config) {
};
})
.catch((error) => {
console.error('Error during service worker registration:', error);
console.error("Error during service worker registration:", error);
});
}

function checkValidServiceWorker(swUrl: string, config?: Config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
headers: { "Service-Worker": "script" },
})
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
const contentType = response.headers.get("content-type");
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
(contentType != null && contentType.indexOf("javascript") === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => {
Expand All @@ -125,12 +141,12 @@ function checkValidServiceWorker(swUrl: string, config?: Config) {
}
})
.catch(() => {
console.log('No internet connection found. App is running in offline mode.');
console.log("No internet connection found. App is running in offline mode.");
});
}

export function unregister() {
if ('serviceWorker' in navigator) {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
Expand Down
49 changes: 37 additions & 12 deletions packages/common/src/components/BaseLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,35 @@
import React, { useEffect } from "react";
import { useTransitionNavigate } from "common/src/utils/hooks/useTransitionNavigate";
import { Button, Layout, Tooltip, Avatar } from "antd";
import { Button, Layout, Tooltip, Avatar, Typography } from "antd";
import { UserOutlined } from "@ant-design/icons";
import { PageHeader } from "@ant-design/pro-layout";
import { getViewTransitionStyles } from "../utils/transition";
import Logo from "../images/logo.png";

type BaseLayoutProps = {
export type BaseLayoutProps = {
title: string;
backPath?: string;
headerActions?: React.ReactNode;
headerActions?: React.ReactNode[];
userDocLoading?: boolean;
avatar?: string;
isAdmin?: boolean;
version?: string;
transitionName?: string;
onAvatarClick?: () => void;
};

export const BaseLayout = (props: React.PropsWithChildren<BaseLayoutProps>) => {
const { children, title, backPath, headerActions, userDocLoading, isAdmin, avatar } = props;
const {
children,
title,
backPath,
headerActions,
userDocLoading,
isAdmin,
avatar,
version,
onAvatarClick,
} = props;
const { Content, Header } = Layout;
const navigate = useTransitionNavigate();
const onBack = backPath ? () => navigate(backPath) : undefined;
Expand All @@ -35,32 +47,45 @@ export const BaseLayout = (props: React.PropsWithChildren<BaseLayoutProps>) => {
onBack={onBack}
avatar={{
src: Logo,
style: { minWidth: 32, ...getViewTransitionStyles("logo-icon") },
style: {
minWidth: 32,
...getViewTransitionStyles("logo-icon"),
...(onAvatarClick && { cursor: "pointer" }),
},
onClick: onAvatarClick,
}}
extra={
headerActions ?? [
extra={[
...(version
? [
<Typography.Text key="version" type="secondary">
v.{version}
</Typography.Text>,
]
: []),
...(headerActions ?? [
<Tooltip title="Профиль" key="profile">
<Button
type="text"
size="middle"
size="large"
shape="circle"
icon={
avatar ? (
<Avatar src={avatar} style={getViewTransitionStyles("avatar")} />
<Avatar src={avatar} size="large" style={getViewTransitionStyles("avatar")} />
) : (
<UserOutlined />
)
}
onClick={() => navigate("/profile")}
loading={userDocLoading}
style={{ padding: 0 }}
/>
</Tooltip>,
]
}
]),
]}
/>
</Header>
<Content>
<div className="site-layout-content">{children}</div>
<div className="site-layout-content">{userDocLoading ? "loading" : children}</div>
</Content>
</Layout>
);
Expand Down
10 changes: 6 additions & 4 deletions packages/common/src/components/HolderTransferList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export const HolderTransferList = (props: Props) => {
);
};

const { totalCount, length } = calcBooksCounts(holderTransfer.books);
const { totalCount, length } = calcBooksCounts(Object.entries(holderTransfer.books));

const popoverContent = () => {
const transferBooks = Object.entries(holderTransfer.books);
Expand All @@ -98,11 +98,13 @@ export const HolderTransferList = (props: Props) => {
) : (
<MinusOutlined />
);
const price = holderTransfer.totalPrice ? ` на ${holderTransfer.totalPrice} руб.` : "";
const title = HolderTransferMap[holderTransfer.type].title;
return (
<List.Item key={holderTransfer.id}>
{Icon && <Icon size={50} style={{ fontSize: "24px", marginRight: 12 }} />}
<List.Item.Meta
title={HolderTransferMap[holderTransfer.type].title}
title={`${title} ${price}`}
description={moment(holderTransfer.date).calendar()}
/>

Expand All @@ -123,8 +125,8 @@ export const HolderTransferList = (props: Props) => {
<>
{dataSource.length > 0 && (
<div>
<Row justify={"space-between"}>
<Typography.Title level={3}>{title}</Typography.Title>
<Row justify={"space-between"} className="sticky">
<Typography.Title level={4}>{title}</Typography.Title>
{sortedHolderTransfers.length > displayedTransersCount && (
<Button
shape="circle"
Expand Down
Loading

0 comments on commit 534d00f

Please sign in to comment.