Repository: newbee-ltd/newbee-mall-cloud
Branch: main
Commit: e2f89906e7bb
Files: 225
Total size: 769.5 KB
Directory structure:
gitextract_bb6zddio/
├── .gitignore
├── LICENSE
├── README.md
├── newbee-mall-cloud-common/
│ ├── pom.xml
│ └── src/
│ └── main/
│ └── java/
│ └── ltd/
│ └── common/
│ └── cloud/
│ └── newbee/
│ ├── dto/
│ │ ├── PageQueryUtil.java
│ │ ├── PageResult.java
│ │ ├── Result.java
│ │ └── ResultGenerator.java
│ ├── enums/
│ │ ├── IndexConfigTypeEnum.java
│ │ ├── NewBeeMallCategoryLevelEnum.java
│ │ ├── NewBeeMallOrderStatusEnum.java
│ │ ├── PayStatusEnum.java
│ │ ├── PayTypeEnum.java
│ │ └── ServiceResultEnum.java
│ ├── exception/
│ │ └── NewBeeMallException.java
│ ├── pojo/
│ │ ├── AdminUserToken.java
│ │ └── MallUserToken.java
│ └── util/
│ ├── BeanUtil.java
│ ├── MD5Util.java
│ ├── NewBeeMallUtils.java
│ ├── NumberUtil.java
│ └── SystemUtil.java
├── newbee-mall-cloud-gateway-admin/
│ ├── pom.xml
│ └── src/
│ └── main/
│ ├── java/
│ │ └── ltd/
│ │ └── gateway/
│ │ └── cloud/
│ │ └── newbee/
│ │ ├── NewBeeMallCloudAdminGatewayApplication.java
│ │ ├── config/
│ │ │ ├── PolymerizeSwaggerProvider.java
│ │ │ └── RedisConfig.java
│ │ └── filter/
│ │ └── ValidTokenGlobalFilter.java
│ └── resources/
│ └── application.properties
├── newbee-mall-cloud-gateway-mall/
│ ├── pom.xml
│ └── src/
│ └── main/
│ ├── java/
│ │ └── ltd/
│ │ └── gateway/
│ │ └── cloud/
│ │ └── newbee/
│ │ ├── NewBeeMallCloudMallGatewayApplication.java
│ │ ├── config/
│ │ │ ├── PolymerizeSwaggerProvider.java
│ │ │ └── RedisConfig.java
│ │ └── filter/
│ │ └── ValidMallUserTokenGlobalFilter.java
│ └── resources/
│ └── application.properties
├── newbee-mall-cloud-goods-service/
│ ├── newbee-mall-cloud-goods-api/
│ │ ├── pom.xml
│ │ └── src/
│ │ └── main/
│ │ └── java/
│ │ └── ltd/
│ │ └── goods/
│ │ └── cloud/
│ │ └── newbee/
│ │ ├── dto/
│ │ │ ├── NewBeeMallGoodsDTO.java
│ │ │ ├── StockNumDTO.java
│ │ │ └── UpdateStockNumDTO.java
│ │ └── openfeign/
│ │ └── NewBeeCloudGoodsServiceFeign.java
│ ├── newbee-mall-cloud-goods-web/
│ │ ├── pom.xml
│ │ └── src/
│ │ └── main/
│ │ ├── java/
│ │ │ └── ltd/
│ │ │ └── goods/
│ │ │ └── cloud/
│ │ │ └── newbee/
│ │ │ ├── NewBeeMallCloudGoodsServiceApplication.java
│ │ │ ├── config/
│ │ │ │ ├── GoodsServiceExceptionHandler.java
│ │ │ │ ├── GoodsServiceSwagger3Config.java
│ │ │ │ ├── GoodsServiceWebMvcConfigurer.java
│ │ │ │ ├── OpenFeignConfiguration.java
│ │ │ │ ├── SeataProxyConfiguration.java
│ │ │ │ ├── annotation/
│ │ │ │ │ ├── TokenToAdminUser.java
│ │ │ │ │ └── TokenToMallUser.java
│ │ │ │ └── handler/
│ │ │ │ ├── TokenToAdminUserMethodArgumentResolver.java
│ │ │ │ └── TokenToMallUserMethodArgumentResolver.java
│ │ │ ├── controller/
│ │ │ │ ├── NewBeeAdminGoodsCategoryController.java
│ │ │ │ ├── NewBeeAdminGoodsInfoController.java
│ │ │ │ ├── NewBeeMallGoodsCategoryController.java
│ │ │ │ ├── NewBeeMallGoodsController.java
│ │ │ │ ├── param/
│ │ │ │ │ ├── BatchIdParam.java
│ │ │ │ │ ├── GoodsAddParam.java
│ │ │ │ │ ├── GoodsCategoryAddParam.java
│ │ │ │ │ ├── GoodsCategoryEditParam.java
│ │ │ │ │ └── GoodsEditParam.java
│ │ │ │ └── vo/
│ │ │ │ ├── NewBeeMallGoodsDetailVO.java
│ │ │ │ ├── NewBeeMallIndexCategoryVO.java
│ │ │ │ ├── NewBeeMallSearchGoodsVO.java
│ │ │ │ ├── SecondLevelCategoryVO.java
│ │ │ │ └── ThirdLevelCategoryVO.java
│ │ │ ├── dao/
│ │ │ │ ├── GoodsCategoryMapper.java
│ │ │ │ └── NewBeeMallGoodsMapper.java
│ │ │ ├── entity/
│ │ │ │ ├── GoodsCategory.java
│ │ │ │ ├── LoginAdminUser.java
│ │ │ │ ├── NewBeeMallGoods.java
│ │ │ │ ├── StockNumDTO.java
│ │ │ │ └── UpdateStockNumDTO.java
│ │ │ └── service/
│ │ │ ├── NewBeeMallCategoryService.java
│ │ │ ├── NewBeeMallGoodsService.java
│ │ │ └── impl/
│ │ │ ├── NewBeeMallCategoryServiceImpl.java
│ │ │ └── NewBeeMallGoodsServiceImpl.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── logback.xml
│ │ └── mapper/
│ │ ├── GoodsCategoryMapper.xml
│ │ └── NewBeeMallGoodsMapper.xml
│ └── pom.xml
├── newbee-mall-cloud-order-service/
│ ├── newbee-mall-cloud-order-api/
│ │ └── pom.xml
│ ├── newbee-mall-cloud-order-web/
│ │ ├── pom.xml
│ │ └── src/
│ │ └── main/
│ │ ├── java/
│ │ │ └── ltd/
│ │ │ └── order/
│ │ │ └── cloud/
│ │ │ └── newbee/
│ │ │ ├── NewBeeMallCloudOrderServiceApplication.java
│ │ │ ├── config/
│ │ │ │ ├── OpenFeignConfiguration.java
│ │ │ │ ├── OrderServiceExceptionHandler.java
│ │ │ │ ├── OrderServiceSwagger3Config.java
│ │ │ │ ├── OrderServiceWebMvcConfigurer.java
│ │ │ │ ├── SeataProxyConfiguration.java
│ │ │ │ ├── annotation/
│ │ │ │ │ ├── TokenToAdminUser.java
│ │ │ │ │ └── TokenToMallUser.java
│ │ │ │ └── handler/
│ │ │ │ ├── TokenToAdminUserMethodArgumentResolver.java
│ │ │ │ └── TokenToMallUserMethodArgumentResolver.java
│ │ │ ├── controller/
│ │ │ │ ├── NewBeeAdminOrderController.java
│ │ │ │ ├── NewBeeMallOrderController.java
│ │ │ │ ├── NewBeeMallUserAddressController.java
│ │ │ │ ├── param/
│ │ │ │ │ ├── BatchIdParam.java
│ │ │ │ │ ├── SaveMallUserAddressParam.java
│ │ │ │ │ ├── SaveOrderParam.java
│ │ │ │ │ └── UpdateMallUserAddressParam.java
│ │ │ │ └── vo/
│ │ │ │ ├── NewBeeMallOrderDetailVO.java
│ │ │ │ ├── NewBeeMallOrderItemVO.java
│ │ │ │ ├── NewBeeMallOrderListVO.java
│ │ │ │ └── NewBeeMallUserAddressVO.java
│ │ │ ├── dao/
│ │ │ │ ├── MallUserAddressMapper.java
│ │ │ │ ├── NewBeeMallOrderAddressMapper.java
│ │ │ │ ├── NewBeeMallOrderItemMapper.java
│ │ │ │ └── NewBeeMallOrderMapper.java
│ │ │ ├── entity/
│ │ │ │ ├── LoginAdminUser.java
│ │ │ │ ├── MallUserAddress.java
│ │ │ │ ├── NewBeeMallOrder.java
│ │ │ │ ├── NewBeeMallOrderAddress.java
│ │ │ │ └── NewBeeMallOrderItem.java
│ │ │ └── service/
│ │ │ ├── NewBeeMallOrderService.java
│ │ │ ├── NewBeeMallUserAddressService.java
│ │ │ └── impl/
│ │ │ ├── NewBeeMallOrderServiceImpl.java
│ │ │ └── NewBeeMallUserAddressServiceImpl.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── logback.xml
│ │ └── mapper/
│ │ ├── MallUserAddressMapper.xml
│ │ ├── NewBeeMallOrderAddressMapper.xml
│ │ ├── NewBeeMallOrderItemMapper.xml
│ │ └── NewBeeMallOrderMapper.xml
│ └── pom.xml
├── newbee-mall-cloud-recommend-service/
│ ├── newbee-mall-cloud-recommend-api/
│ │ └── pom.xml
│ ├── newbee-mall-cloud-recommend-web/
│ │ ├── pom.xml
│ │ └── src/
│ │ └── main/
│ │ ├── java/
│ │ │ └── ltd/
│ │ │ └── recommend/
│ │ │ └── cloud/
│ │ │ └── newbee/
│ │ │ ├── NewBeeMallCloudRecommendServiceApplication.java
│ │ │ ├── config/
│ │ │ │ ├── OpenFeignConfiguration.java
│ │ │ │ ├── RecommendServiceExceptionHandler.java
│ │ │ │ ├── RecommendServiceSwagger3Config.java
│ │ │ │ ├── RecommendServiceWebMvcConfigurer.java
│ │ │ │ ├── annotation/
│ │ │ │ │ └── TokenToAdminUser.java
│ │ │ │ └── handler/
│ │ │ │ └── TokenToAdminUserMethodArgumentResolver.java
│ │ │ ├── controller/
│ │ │ │ ├── NewBeeAdminCarouselController.java
│ │ │ │ ├── NewBeeAdminIndexConfigController.java
│ │ │ │ ├── NewBeeMallIndexController.java
│ │ │ │ ├── param/
│ │ │ │ │ ├── BatchIdParam.java
│ │ │ │ │ ├── CarouselAddParam.java
│ │ │ │ │ ├── CarouselEditParam.java
│ │ │ │ │ ├── IndexConfigAddParam.java
│ │ │ │ │ └── IndexConfigEditParam.java
│ │ │ │ └── vo/
│ │ │ │ ├── IndexInfoVO.java
│ │ │ │ ├── NewBeeMallIndexCarouselVO.java
│ │ │ │ ├── NewBeeMallIndexCategoryVO.java
│ │ │ │ ├── NewBeeMallIndexConfigGoodsVO.java
│ │ │ │ ├── SecondLevelCategoryVO.java
│ │ │ │ └── ThirdLevelCategoryVO.java
│ │ │ ├── dao/
│ │ │ │ ├── CarouselMapper.java
│ │ │ │ └── IndexConfigMapper.java
│ │ │ ├── entity/
│ │ │ │ ├── Carousel.java
│ │ │ │ ├── IndexConfig.java
│ │ │ │ └── LoginAdminUser.java
│ │ │ └── service/
│ │ │ ├── NewBeeMallCarouselService.java
│ │ │ ├── NewBeeMallIndexConfigService.java
│ │ │ └── impl/
│ │ │ ├── NewBeeMallCarouselServiceImpl.java
│ │ │ └── NewBeeMallIndexConfigServiceImpl.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── logback.xml
│ │ └── mapper/
│ │ ├── CarouselMapper.xml
│ │ └── IndexConfigMapper.xml
│ └── pom.xml
├── newbee-mall-cloud-shop-cart-service/
│ ├── newbee-mall-cloud-shop-cart-api/
│ │ ├── pom.xml
│ │ └── src/
│ │ └── main/
│ │ └── java/
│ │ └── ltd/
│ │ └── shopcart/
│ │ └── cloud/
│ │ └── newbee/
│ │ ├── dto/
│ │ │ └── NewBeeMallShoppingCartItemDTO.java
│ │ └── openfeign/
│ │ └── NewBeeCloudShopCartServiceFeign.java
│ ├── newbee-mall-cloud-shop-cart-web/
│ │ ├── pom.xml
│ │ └── src/
│ │ └── main/
│ │ ├── java/
│ │ │ └── ltd/
│ │ │ └── shopcart/
│ │ │ └── cloud/
│ │ │ └── newbee/
│ │ │ ├── NewBeeMallCloudShopCartServiceApplication.java
│ │ │ ├── config/
│ │ │ │ ├── OpenFeignConfiguration.java
│ │ │ │ ├── SeataProxyConfiguration.java
│ │ │ │ ├── ShopCartServiceExceptionHandler.java
│ │ │ │ ├── ShopCartServiceSwagger3Config.java
│ │ │ │ ├── ShopCartServiceWebMvcConfigurer.java
│ │ │ │ ├── annotation/
│ │ │ │ │ └── TokenToMallUser.java
│ │ │ │ └── handler/
│ │ │ │ └── TokenToMallUserMethodArgumentResolver.java
│ │ │ ├── controller/
│ │ │ │ ├── NewBeeMallShoppingCartController.java
│ │ │ │ ├── param/
│ │ │ │ │ ├── SaveCartItemParam.java
│ │ │ │ │ └── UpdateCartItemParam.java
│ │ │ │ └── vo/
│ │ │ │ └── NewBeeMallShoppingCartItemVO.java
│ │ │ ├── dao/
│ │ │ │ └── NewBeeMallShoppingCartItemMapper.java
│ │ │ ├── entity/
│ │ │ │ └── NewBeeMallShoppingCartItem.java
│ │ │ └── service/
│ │ │ ├── NewBeeMallShoppingCartService.java
│ │ │ └── impl/
│ │ │ └── NewBeeMallShoppingCartServiceImpl.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── logback.xml
│ │ └── mapper/
│ │ └── NewBeeMallShoppingCartItemMapper.xml
│ └── pom.xml
├── newbee-mall-cloud-user-service/
│ ├── newbee-mall-cloud-user-api/
│ │ ├── pom.xml
│ │ └── src/
│ │ └── main/
│ │ └── java/
│ │ └── ltd/
│ │ └── user/
│ │ └── cloud/
│ │ └── newbee/
│ │ ├── dto/
│ │ │ └── MallUserDTO.java
│ │ └── openfeign/
│ │ └── NewBeeCloudUserServiceFeign.java
│ ├── newbee-mall-cloud-user-web/
│ │ ├── pom.xml
│ │ └── src/
│ │ └── main/
│ │ ├── java/
│ │ │ └── ltd/
│ │ │ └── user/
│ │ │ └── cloud/
│ │ │ └── newbee/
│ │ │ ├── NewBeeMallCloudUserServiceApplication.java
│ │ │ ├── config/
│ │ │ │ ├── RedisConfig.java
│ │ │ │ ├── UserServiceExceptionHandler.java
│ │ │ │ ├── UserServiceWebMvcConfigurer.java
│ │ │ │ ├── UserSwagger3Config.java
│ │ │ │ ├── annotation/
│ │ │ │ │ ├── TokenToAdminUser.java
│ │ │ │ │ └── TokenToMallUser.java
│ │ │ │ └── handler/
│ │ │ │ ├── TokenToAdminUserMethodArgumentResolver.java
│ │ │ │ └── TokenToMallUserMethodArgumentResolver.java
│ │ │ ├── controller/
│ │ │ │ ├── NewBeeMallCloudAdminUserController.java
│ │ │ │ ├── NewBeeMallCloudPersonalController.java
│ │ │ │ ├── param/
│ │ │ │ │ ├── AdminLoginParam.java
│ │ │ │ │ ├── MallUserLoginParam.java
│ │ │ │ │ ├── MallUserRegisterParam.java
│ │ │ │ │ ├── MallUserUpdateParam.java
│ │ │ │ │ ├── UpdateAdminNameParam.java
│ │ │ │ │ └── UpdateAdminPasswordParam.java
│ │ │ │ └── vo/
│ │ │ │ └── NewBeeMallUserVO.java
│ │ │ ├── dao/
│ │ │ │ ├── AdminUserMapper.java
│ │ │ │ └── MallUserMapper.java
│ │ │ ├── entity/
│ │ │ │ ├── AdminUser.java
│ │ │ │ └── MallUser.java
│ │ │ └── service/
│ │ │ ├── AdminUserService.java
│ │ │ ├── NewBeeMallUserService.java
│ │ │ └── impl/
│ │ │ ├── AdminUserServiceImpl.java
│ │ │ └── NewBeeMallUserServiceImpl.java
│ │ └── resources/
│ │ ├── application.properties
│ │ ├── logback.xml
│ │ └── mapper/
│ │ ├── AdminUserMapper.xml
│ │ └── MallUserMapper.xml
│ └── pom.xml
├── pom.xml
└── static-files/
├── newbee_mall_cloud_cart_db.sql
├── newbee_mall_cloud_goods_db.sql
├── newbee_mall_cloud_order_db.sql
├── newbee_mall_cloud_recommend_db.sql
└── newbee_mall_cloud_user_db.sql
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================



[](https://github.com/newbee-ltd/newbee-mall-cloud/blob/main/LICENSE)
newbee-mall-cloud 项目是新蜂商城 newbee-mall 项目的微服务版本,一款基于 Spring Cloud Alibaba + Nacos + Sentinel + Seata + Spring Cloud Gateway + OpenFeign + Spring Cloud Seluth + Zipkin + ELK 等技术的大型微服务实战项目。
当前分支的 Spring Boot 版本为 2.6.3,Spring Cloud 版本为 2021.0.1,想要学习和使用其它版本可以直接点击下方的分支名称跳转至对应的仓库分支中。
| 分支名称 | Spring Boot Version | Spring Cloud Version | Spring Cloud Alibaba Version |
|:----------------------------------------------------------------------------------------------:|:----------------:|:----------------:|:----------------:|
| [main](https://github.com/newbee-ltd/newbee-mall-cloud) | 2.6.3 | 2021.0.1 | 2021.0.1.0 |
| [2022.x](https://github.com/newbee-ltd/newbee-mall-cloud/tree/spring-cloud-2022.x) | 3.0.2 | 2022.0.0 | 2022.0.0.0 |
2019 年开源了第一个单体版本,由最初新蜂商城单体项目,逐步过渡到前后端分离和微服务架构的项目,到现在已经“开枝散叶”,成长为一系列的项目集合,下图为新蜂商城项目由 2019 年至 2023 年的开源历程。由基础项目慢慢优化,不断地增加技术栈,让用户学习到越来越多知识点的同时,对开源作者的技术提升也是一个很大的帮助。

**坚持不易,如果觉得项目还不错的话可以给项目一个 Star 吧,也是对我自 2019 年开始一直更新这个项目的一种鼓励啦,谢谢各位的支持。**
| 项目名称 | 仓库地址 | 备注 |
| :------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| newbee-mall | [newbee-mall in GitHub](https://github.com/newbee-ltd/newbee-mall)
[newbee-mall in Gitee](https://gitee.com/newbee-ltd/newbee-mall) | 初始版本、Spring Boot、Thymeleaf、MyBatis、MySQL |
| newbee-mall-plus | [newbee-mall-plus in GitHub](https://github.com/newbee-ltd/newbee-mall-plus)
[newbee-mall-plus in Gitee](https://gitee.com/newbee-ltd/newbee-mall-plus) | 升级版本、优惠券、秒杀、支付、Spring Boot、Thymeleaf、MyBatis、MySQL、Redis |
| newbee-mall-cloud | [newbee-mall-cloud in GitHub](https://github.com/newbee-ltd/newbee-mall-cloud)
[newbee-mall-cloud in Gitee](https://gitee.com/newbee-ltd/newbee-mall-cloud) | 微服务版本、分布式事务、Spring Cloud Alibaba、Nacos、Sentinel、OpenFeign、Seata |
| newbee-mall-api | [newbee-mall-api in GitHub](https://github.com/newbee-ltd/newbee-mall-api)
[newbee-mall-api in Gitee](https://gitee.com/newbee-ltd/newbee-mall-api) | 前后端分离、Spring Boot、MyBatis、Swagger、MySQL |
| newbee-mall-api-go | [newbee-mall-api-go in GitHub](https://github.com/newbee-ltd/newbee-mall-api-go)
[newbee-mall-api-go in Gitee](https://gitee.com/newbee-ltd/newbee-mall-api-go) | 前后端分离、Go、Gin、MySQL |
| newbee-mall-vue-app | [newbee-mall-vue-app in GitHub](https://github.com/newbee-ltd/newbee-mall-vue-app)
[newbee-mall-vue-app in Gitee](https://gitee.com/newbee-ltd/newbee-mall-vue-app) | 前后端分离、Vue2、Vant |
| newbee-mall-vue3-app | [newbee-mall-vue3-app in GitHub](https://github.com/newbee-ltd/newbee-mall-vue3-app)
[newbee-mall-vue3-app in Gitee](https://gitee.com/newbee-ltd/newbee-mall-vue3-app) | 前后端分离、Vue3、Vue-Router4、Pinia、Vant4 |
| vue3-admin | [vue3-admin in GitHub](https://github.com/newbee-ltd/vue3-admin)
[vue3-admin in Gitee](https://gitee.com/newbee-ltd/vue3-admin) | 前后端分离、Vue3、Element-Plus、Vue-Router4、Vite |
## 技术选型
当前分支下的开发框架选择如下所示。
| 开发框架 | 版本 |
| :----------------: | :----------------: |
| Spring Boot | 2.6.3 |
| Spring Cloud | 2021.0.1 |
| Spring Cloud Alibaba | 2021.0.1.0 |
| MyBatis | 3.5.9 |
| Swagger | 3.0.0 |
| Lombok | 1.18.16 |
当前分支下的微服务组件技术选型如下所示。
| 技术 | 组件实现 | 版本 | 备注 |
| :----------------: | :-----------------------------: |:------:| :----: |
| 服务注册与服务发现 | Nacos | 1.4.2 | 已整合 |
| 配置中心 | Nacos | 1.4.2 | 已整合 |
| 服务通信 | Open Feign | 3.1.1 | 已整合 |
| 负载均衡器 | Spring Cloud Loadbalancer | 3.1.1 | 已整合 |
| 服务网关 | Spring Cloud Gateway | 3.1.1 | 已整合 |
| 断路器 | Sentinel | 1.8.4 | 已整合 |
| 链路追踪 | Spring Cloud Sleuth、Zipkin | 3.1.1 | 已整合 |
| 分布式事务 | Seata | 1.4.2 | 已整合 |
| 日志中心 | ElasticSearch、Logstash、Kibana | 7.17.8 | 已整合 |

## 架构图简版

## 开发及部署文档
1. [**Spring Cloud Alibaba 项目实战:点亮微服务技能点!**](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
2. [项目须知和课程约定](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
3. [漫谈微服务架构(一)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
4. [漫谈微服务架构(二)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
5. [漫谈微服务架构(三)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
6. [微服务落地一站式解决方案——Spring Cloud](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
7. [实战基础1-代码运行环境及开发工具介绍](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
8. [实战基础2-Spring Boot 开发介绍及Spring Cloud Alibaba模板项目构建](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
9. [服务通信基础讲解](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
10. [微服务架构中的服务治理](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
11. [Nacos安装与配置](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
12. [Nacos整合之服务注册编码实践](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
13. [Nacos整合之服务发现编码实践](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
13. [(补充章节)谈一谈配置中心](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
13. [(补充章节)整合Nacos配置中心编码实践](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
13. [(补充章节)配置动态刷新及多配置读取编码实践](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
14. [服务通信之负载均衡器](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
15. [负载均衡器的源码分析及自定义负载均衡算法](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
16. [服务治理与服务通信总结](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
17. [OpenFeign介绍与整合](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
18. [OpenFeign参数传递编码实践](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
19. [服务网关之Spring Cloud Gateway](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
20. [整合Spring Cloud Gateway编码实践](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
21. [服务网关Spring Cloud Gateway之Predicate(断言)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
22. [服务网关Spring Cloud Gateway之Filter(过滤器)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
23. [微服务最终实战项目的启动和运行注意事项](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
24. [最终实战项目的功能介绍与功能演示](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
25. [分布式事务问题演示](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
26. [分布式事务解决方案及Seata搭建](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
27. [整合Seata编码实践](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
28. [Seata的运行流程分析](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
29. [服务容错之限流与熔断](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
30. [服务容错之Sentinel限流配置实践](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
31. [服务容错之Sentinel降级熔断配置实践](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
32. [链路追踪之Sleuth+Zipkin整合](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
33. [从零到一搭建微服务项目编码实战(一)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
34. [从零到一搭建微服务项目编码实战(二)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
35. [从零到一搭建微服务项目编码实战(三)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
36. [从零到一搭建微服务项目编码实战(四)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
37. [从零到一搭建微服务项目编码实战(五)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
38. [从零到一搭建微服务项目编码实战(六)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
39. [从零到一搭建微服务项目编码实战(七)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
40. [从零到一搭建微服务项目编码实战(八)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
41. [从零到一搭建微服务项目编码实战(九)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
42. [从零到一搭建微服务项目编码实战(十)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
43. [从零到一搭建微服务项目编码实战(十一)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
44. [从零到一搭建微服务项目编码实战(十二)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
45. [从零到一搭建微服务项目编码实战(十三)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
46. [从零到一搭建微服务项目编码实战(十四)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
47. [从零到一搭建微服务项目编码实战(十五)](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
49. [(补充章节)Spring Cloud Gateway聚合Swagger接口](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
50. [(补充章节)微服务架构实战项目中整合Seata](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
51. [(补充章节)微服务架构实战项目打包及部署](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
52. [(补充章节)微服务架构实战项目中整合Sentinel](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
53. [(补充章节)微服务架构实战项目中整合Seluth、Zipkin](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
54. [(补充章节)链路追踪之ELK日志中心搭建](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
55. [(补充章节)微服务架构实战项目中整合ELK日志中心](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
55. [课程总结](https://juejin.cn/book/7085254558678515742?suid=1996368849416216&source=android)
## 联系作者
关注公众号:**程序员十三**,回复"勾搭"进群交流。

> 大家有任何问题或者建议都可以在 [issues](https://github.com/newbee-ltd/newbee-mall-cloud/issues) 中反馈给我,我会慢慢完善这个项目。
- 我的邮箱:2449207463@qq.com
- QQ技术交流群:791509631
> newbee-mall-cloud 在 GitHub 和国内的码云都创建了代码仓库,如果有人访问 GitHub 比较慢的话,建议在 Gitee 上查看该项目,两个仓库会保持同步更新。
- [newbee-mall-cloud in GitHub](https://github.com/newbee-ltd/newbee-mall-cloud)
- [newbee-mall-cloud in Gitee](https://gitee.com/newbee-ltd/newbee-mall-cloud)
## 软件著作权
本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
## 感谢
- [spring-projects](https://github.com/spring-projects/spring-boot)
- [spring-cloud](https://github.com/spring-cloud)
- [spring-cloud-alibaba](https://github.com/alibaba/spring-cloud-alibaba)
- [alibaba](https://github.com/alibaba)
- [seata](https://github.com/seata/seata)
- [elasticsearch](https://github.com/elastic/elasticsearch)
- [mybatis](https://github.com/mybatis/mybatis-3)
- [projectlombok](https://github.com/projectlombok/lombok)
- [swagger-api](https://github.com/swagger-api)
================================================
FILE: newbee-mall-cloud-common/pom.xml
================================================
4.0.0
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
jar
newbee-mall-cloud-common
公共模块
ltd.newbee.cloud
newbee-mall-cloud
0.0.1-SNAPSHOT
1.8
org.projectlombok
lombok
${lombok.version}
provided
org.springframework
spring-beans
io.swagger
swagger-annotations
1.5.20
compile
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/dto/PageQueryUtil.java
================================================
package ltd.common.cloud.newbee.dto;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 分页查询参数
*
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
public class PageQueryUtil extends LinkedHashMap {
//当前页码
private int page;
//每页条数
private int limit;
public PageQueryUtil(Map params) {
this.putAll(params);
//分页参数
this.page = Integer.parseInt(params.get("page").toString());
this.limit = Integer.parseInt(params.get("limit").toString());
this.put("start", (page - 1) * limit);
this.put("page", page);
this.put("limit", limit);
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
@Override
public String toString() {
return "PageUtil{" +
"page=" + page +
", limit=" + limit +
'}';
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/dto/PageResult.java
================================================
package ltd.common.cloud.newbee.dto;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.List;
/**
* 分页工具类
*
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
public class PageResult implements Serializable {
@ApiModelProperty("总记录数")
private int totalCount;
@ApiModelProperty("每页记录数")
private int pageSize;
@ApiModelProperty("总页数")
private int totalPage;
@ApiModelProperty("当前页数")
private int currPage;
@ApiModelProperty("列表数据")
private List list;
/**
* 分页
*
* @param list 列表数据
* @param totalCount 总记录数
* @param pageSize 每页记录数
* @param currPage 当前页数
*/
public PageResult(List list, int totalCount, int pageSize, int currPage) {
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.currPage = currPage;
this.totalPage = (int) Math.ceil((double) totalCount / pageSize);
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/dto/Result.java
================================================
package ltd.common.cloud.newbee.dto;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
public class Result implements Serializable {
private static final long serialVersionUID = 1L;
//业务码,比如成功、失败、权限不足等 code,可自行定义
@ApiModelProperty("返回码")
private int resultCode;
//返回信息,后端在进行业务处理后返回给前端一个提示信息,可自行定义
@ApiModelProperty("返回信息")
private String message;
//数据结果,泛型,可以是列表、单个对象、数字、布尔值等
@ApiModelProperty("返回数据")
private T data;
public Result() {
}
public Result(int resultCode, String message) {
this.resultCode = resultCode;
this.message = message;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "Result{" +
"resultCode=" + resultCode +
", message='" + message + '\'' +
", data=" + data +
'}';
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/dto/ResultGenerator.java
================================================
package ltd.common.cloud.newbee.dto;
import org.springframework.util.StringUtils;
/**
* 响应结果生成工具
*
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
public class ResultGenerator {
private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS";
private static final String DEFAULT_FAIL_MESSAGE = "FAIL";
private static final int RESULT_CODE_SUCCESS = 200;
private static final int RESULT_CODE_SERVER_ERROR = 500;
public static Result genSuccessResult() {
Result result = new Result();
result.setResultCode(RESULT_CODE_SUCCESS);
result.setMessage(DEFAULT_SUCCESS_MESSAGE);
return result;
}
public static Result genSuccessResult(String message) {
Result result = new Result();
result.setResultCode(RESULT_CODE_SUCCESS);
result.setMessage(message);
return result;
}
public static Result genSuccessResult(Object data) {
Result result = new Result();
result.setResultCode(RESULT_CODE_SUCCESS);
result.setMessage(DEFAULT_SUCCESS_MESSAGE);
result.setData(data);
return result;
}
public static Result genFailResult(String message) {
Result result = new Result();
result.setResultCode(RESULT_CODE_SERVER_ERROR);
if (!StringUtils.hasText(message)) {
result.setMessage(DEFAULT_FAIL_MESSAGE);
} else {
result.setMessage(message);
}
return result;
}
public static Result genErrorResult(int code, String message) {
Result result = new Result();
result.setResultCode(code);
result.setMessage(message);
return result;
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/enums/IndexConfigTypeEnum.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.common.cloud.newbee.enums;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
* @apiNote 首页配置项 1-搜索框热搜 2-搜索下拉框热搜 3-(首页)热销商品 4-(首页)新品上线 5-(首页)为你推荐
*/
public enum IndexConfigTypeEnum {
DEFAULT(0, "DEFAULT"),
INDEX_SEARCH_HOTS(1, "INDEX_SEARCH_HOTS"),
INDEX_SEARCH_DOWN_HOTS(2, "INDEX_SEARCH_DOWN_HOTS"),
INDEX_GOODS_HOT(3, "INDEX_GOODS_HOTS"),
INDEX_GOODS_NEW(4, "INDEX_GOODS_NEW"),
INDEX_GOODS_RECOMMOND(5, "INDEX_GOODS_RECOMMOND");
private int type;
private String name;
IndexConfigTypeEnum(int type, String name) {
this.type = type;
this.name = name;
}
public static IndexConfigTypeEnum getIndexConfigTypeEnumByType(int type) {
for (IndexConfigTypeEnum indexConfigTypeEnum : IndexConfigTypeEnum.values()) {
if (indexConfigTypeEnum.getType() == type) {
return indexConfigTypeEnum;
}
}
return DEFAULT;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/enums/NewBeeMallCategoryLevelEnum.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.common.cloud.newbee.enums;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
* @apiNote 分类级别
*/
public enum NewBeeMallCategoryLevelEnum {
DEFAULT(0, "ERROR"),
LEVEL_ONE(1, "一级分类"),
LEVEL_TWO(2, "二级分类"),
LEVEL_THREE(3, "三级分类");
private int level;
private String name;
NewBeeMallCategoryLevelEnum(int level, String name) {
this.level = level;
this.name = name;
}
public static NewBeeMallCategoryLevelEnum getNewBeeMallOrderStatusEnumByLevel(int level) {
for (NewBeeMallCategoryLevelEnum newBeeMallCategoryLevelEnum : NewBeeMallCategoryLevelEnum.values()) {
if (newBeeMallCategoryLevelEnum.getLevel() == level) {
return newBeeMallCategoryLevelEnum;
}
}
return DEFAULT;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/enums/NewBeeMallOrderStatusEnum.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.common.cloud.newbee.enums;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
* @apiNote 订单状态:0.待支付 1.已支付 2.配货完成 3:出库成功 4.交易成功 -1.手动关闭 -2.超时关闭 -3.商家关闭
*/
public enum NewBeeMallOrderStatusEnum {
DEFAULT(-9, "ERROR"),
ORDER_PRE_PAY(0, "待支付"),
ORDER_PAID(1, "已支付"),
ORDER_PACKAGED(2, "配货完成"),
ORDER_EXPRESS(3, "出库成功"),
ORDER_SUCCESS(4, "交易成功"),
ORDER_CLOSED_BY_MALLUSER(-1, "手动关闭"),
ORDER_CLOSED_BY_EXPIRED(-2, "超时关闭"),
ORDER_CLOSED_BY_JUDGE(-3, "商家关闭");
private int orderStatus;
private String name;
NewBeeMallOrderStatusEnum(int orderStatus, String name) {
this.orderStatus = orderStatus;
this.name = name;
}
public static NewBeeMallOrderStatusEnum getNewBeeMallOrderStatusEnumByStatus(int orderStatus) {
for (NewBeeMallOrderStatusEnum newBeeMallOrderStatusEnum : NewBeeMallOrderStatusEnum.values()) {
if (newBeeMallOrderStatusEnum.getOrderStatus() == orderStatus) {
return newBeeMallOrderStatusEnum;
}
}
return DEFAULT;
}
public int getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(int orderStatus) {
this.orderStatus = orderStatus;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/enums/PayStatusEnum.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.common.cloud.newbee.enums;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
* @apiNote 订单状态:0.支付中 1.支付成功 -1.支付失败
*/
public enum PayStatusEnum {
DEFAULT(-1, "支付失败"),
PAY_ING(0, "支付中"),
PAY_SUCCESS(1, "支付成功");
private int payStatus;
private String name;
PayStatusEnum(int payStatus, String name) {
this.payStatus = payStatus;
this.name = name;
}
public static PayStatusEnum getPayStatusEnumByStatus(int payStatus) {
for (PayStatusEnum payStatusEnum : PayStatusEnum.values()) {
if (payStatusEnum.getPayStatus() == payStatus) {
return payStatusEnum;
}
}
return DEFAULT;
}
public int getPayStatus() {
return payStatus;
}
public void setPayStatus(int payStatus) {
this.payStatus = payStatus;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/enums/PayTypeEnum.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.common.cloud.newbee.enums;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
* @apiNote 订单状态:0.无 1.支付宝 2.微信支付
*/
public enum PayTypeEnum {
DEFAULT(-1, "ERROR"),
NOT_PAY(0, "无"),
ALI_PAY(1, "支付宝"),
WEIXIN_PAY(2, "微信支付");
private int payType;
private String name;
PayTypeEnum(int payType, String name) {
this.payType = payType;
this.name = name;
}
public static PayTypeEnum getPayTypeEnumByType(int payType) {
for (PayTypeEnum payTypeEnum : PayTypeEnum.values()) {
if (payTypeEnum.getPayType() == payType) {
return payTypeEnum;
}
}
return DEFAULT;
}
public int getPayType() {
return payType;
}
public void setPayType(int payType) {
this.payType = payType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/enums/ServiceResultEnum.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.common.cloud.newbee.enums;
public enum ServiceResultEnum {
ERROR("error"),
SUCCESS("success"),
DATA_NOT_EXIST("未查询到记录!"),
PARAM_ERROR("参数错误!"),
SAME_CATEGORY_EXIST("已存在同级同名的分类!"),
SAME_LOGIN_NAME_EXIST("用户名已存在!"),
LOGIN_NAME_NULL("请输入登录名!"),
LOGIN_NAME_IS_NOT_PHONE("请输入正确的手机号!"),
LOGIN_PASSWORD_NULL("请输入密码!"),
LOGIN_VERIFY_CODE_NULL("请输入验证码!"),
LOGIN_VERIFY_CODE_ERROR("验证码错误!"),
SAME_INDEX_CONFIG_EXIST("已存在相同的首页配置项!"),
GOODS_CATEGORY_ERROR("分类数据异常!"),
SAME_GOODS_EXIST("已存在相同的商品信息!"),
GOODS_NOT_EXIST("商品不存在!"),
GOODS_PUT_DOWN("商品已下架!"),
SHOPPING_CART_ITEM_LIMIT_NUMBER_ERROR("超出单个商品的最大购买数量!"),
SHOPPING_CART_ITEM_NUMBER_ERROR("商品数量不能小于 1 !"),
SHOPPING_CART_ITEM_TOTAL_NUMBER_ERROR("超出购物车最大容量!"),
SHOPPING_CART_ITEM_EXIST_ERROR("已存在!无需重复添加!"),
LOGIN_ERROR("登录失败!"),
NOT_LOGIN_ERROR("未登录!"),
ADMIN_NOT_LOGIN_ERROR("管理员未登录!"),
TOKEN_EXPIRE_ERROR("无效认证!请重新登录!"),
ADMIN_TOKEN_EXPIRE_ERROR("管理员登录过期!请重新登录!"),
USER_NULL_ERROR("无效用户!请重新登录!"),
LOGIN_USER_LOCKED_ERROR("用户已被禁止登录!"),
ORDER_NOT_EXIST_ERROR("订单不存在!"),
ORDER_ITEM_NOT_EXIST_ERROR("订单项不存在!"),
NULL_ADDRESS_ERROR("地址不能为空!"),
ORDER_PRICE_ERROR("订单价格异常!"),
ORDER_ITEM_NULL_ERROR("订单项异常!"),
ORDER_GENERATE_ERROR("生成订单异常!"),
SHOPPING_ITEM_ERROR("购物车数据异常!"),
SHOPPING_ITEM_COUNT_ERROR("库存不足!"),
ORDER_STATUS_ERROR("订单状态异常!"),
OPERATE_ERROR("操作失败!"),
REQUEST_FORBIDEN_ERROR("禁止该操作!"),
NO_PERMISSION_ERROR("无权限!"),
DB_ERROR("database error");
private String result;
ServiceResultEnum(String result) {
this.result = result;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/exception/NewBeeMallException.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.common.cloud.newbee.exception;
public class NewBeeMallException extends RuntimeException {
public NewBeeMallException() {
}
public NewBeeMallException(String message) {
super(message);
}
/**
* 丢出一个异常
*
* @param message
*/
public static void fail(String message) {
throw new NewBeeMallException(message);
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/pojo/AdminUserToken.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.common.cloud.newbee.pojo;
import lombok.Data;
import java.io.Serializable;
@Data
public class AdminUserToken implements Serializable {
private Long adminUserId;
private String token;
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/pojo/MallUserToken.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.common.cloud.newbee.pojo;
import lombok.Data;
import java.io.Serializable;
@Data
public class MallUserToken implements Serializable {
private Long userId;
private String token;
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/util/BeanUtil.java
================================================
package ltd.common.cloud.newbee.util;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.PropertyAccessorFactory;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.*;
public abstract class BeanUtil {
public static Object copyProperties(Object source, Object target, String... ignoreProperties) {
if (source == null) {
return target;
}
BeanUtils.copyProperties(source, target, ignoreProperties);
return target;
}
public static List copyList(List sources, Class clazz) {
return copyList(sources, clazz, null);
}
public static List copyList(List sources, Class clazz, Callback callback) {
List targetList = new ArrayList<>();
if (sources != null) {
try {
for (Object source : sources) {
T target = clazz.newInstance();
copyProperties(source, target);
if (callback != null) {
callback.set(source, target);
}
targetList.add(target);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return targetList;
}
public static Map toMap(Object bean, String... ignoreProperties) {
Map map = new LinkedHashMap<>();
List ignoreList = new ArrayList<>(Arrays.asList(ignoreProperties));
ignoreList.add("class");
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
for (PropertyDescriptor pd : beanWrapper.getPropertyDescriptors()) {
if (!ignoreList.contains(pd.getName()) && beanWrapper.isReadableProperty(pd.getName())) {
Object propertyValue = beanWrapper.getPropertyValue(pd.getName());
map.put(pd.getName(), propertyValue);
}
}
return map;
}
public static T toBean(Map map, Class beanType) {
BeanWrapper beanWrapper = new BeanWrapperImpl(beanType);
map.forEach((key, value) -> {
if (beanWrapper.isWritableProperty(key)) {
beanWrapper.setPropertyValue(key, value);
}
});
return (T) beanWrapper.getWrappedInstance();
}
public static interface Callback {
void set(Object source, T target);
}
//检查Pojo对象是否有null字段
public static boolean checkPojoNullField(Object o, Class> clz) {
try {
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (field.get(o) == null) {
return false;
}
}
if (clz.getSuperclass() != Object.class) {
return checkPojoNullField(o, clz.getSuperclass());
}
return true;
} catch (IllegalAccessException e) {
return false;
}
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/util/MD5Util.java
================================================
package ltd.common.cloud.newbee.util;
import java.security.MessageDigest;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/util/NewBeeMallUtils.java
================================================
package ltd.common.cloud.newbee.util;
import org.springframework.util.StringUtils;
import java.net.URI;
/**
* @author 13
*/
public class NewBeeMallUtils {
public static URI getHost(URI uri) {
URI effectiveURI = null;
try {
effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
} catch (Throwable var4) {
effectiveURI = null;
}
return effectiveURI;
}
public static String cleanString(String value) {
if (!StringUtils.hasText(value)) {
return "";
}
value = value.toLowerCase();
value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
value = value.replaceAll("'", "& #39;");
value = value.replaceAll("onload", "0nl0ad");
value = value.replaceAll("xml", "xm1");
value = value.replaceAll("window", "wind0w");
value = value.replaceAll("click", "cl1ck");
value = value.replaceAll("var", "v0r");
value = value.replaceAll("let", "1et");
value = value.replaceAll("function", "functi0n");
value = value.replaceAll("return", "retu1n");
value = value.replaceAll("$", "");
value = value.replaceAll("document", "d0cument");
value = value.replaceAll("const", "c0nst");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "scr1pt");
value = value.replaceAll("insert", "1nsert");
value = value.replaceAll("drop", "dr0p");
value = value.replaceAll("create", "cre0ate");
value = value.replaceAll("update", "upd0ate");
value = value.replaceAll("alter", "a1ter");
value = value.replaceAll("from", "fr0m");
value = value.replaceAll("where", "wh1re");
value = value.replaceAll("database", "data1base");
value = value.replaceAll("table", "tab1e");
value = value.replaceAll("tb", "tb0");
return value;
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/util/NumberUtil.java
================================================
package ltd.common.cloud.newbee.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
public class NumberUtil {
private NumberUtil() {
}
/**
* 判断是否为11位电话号码
*
* @param phone
* @return
*/
public static boolean isPhone(String phone) {
Pattern pattern = Pattern.compile("^((13[0-9])|(14[5,7])|(15[^4,\\D])|(17[0-8])|(18[0-9]))\\d{8}$");
Matcher matcher = pattern.matcher(phone);
return matcher.matches();
}
/**
* 生成指定长度的随机数
*
* @param length
* @return
*/
public static int genRandomNum(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
* 生成订单流水号
*
* @return
*/
public static String genOrderNo() {
StringBuffer buffer = new StringBuffer(String.valueOf(System.currentTimeMillis()));
int num = genRandomNum(4);
buffer.append(num);
return buffer.toString();
}
}
================================================
FILE: newbee-mall-cloud-common/src/main/java/ltd/common/cloud/newbee/util/SystemUtil.java
================================================
package ltd.common.cloud.newbee.util;
import java.math.BigInteger;
import java.security.MessageDigest;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
public class SystemUtil {
private SystemUtil() {
}
/**
* 登录或注册成功后,生成保持用户登录状态会话token值
*
* @param src:为用户最新一次登录时的now()+user.id+random(4)
* @return
*/
public static String genToken(String src) {
if (null == src || "".equals(src)) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(src.getBytes());
String result = new BigInteger(1, md.digest()).toString(16);
if (result.length() == 31) {
result = result + "-";
}
System.out.println(result);
return result;
} catch (Exception e) {
return null;
}
}
}
================================================
FILE: newbee-mall-cloud-gateway-admin/pom.xml
================================================
4.0.0
ltd.newbee.cloud
newbee-mall-cloud-gateway-admin
0.0.1-SNAPSHOT
newbee-mall-cloud-gateway-admin
网关模块
ltd.newbee.cloud
newbee-mall-cloud
0.0.1-SNAPSHOT
1.8
org.springframework.cloud
spring-cloud-starter-gateway
org.springframework.cloud
spring-cloud-starter-loadbalancer
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
io.springfox
springfox-boot-starter
org.springframework.boot
spring-boot-starter-data-redis
ltd.user.newbee.cloud
newbee-mall-cloud-user-api
0.0.1-SNAPSHOT
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
================================================
FILE: newbee-mall-cloud-gateway-admin/src/main/java/ltd/gateway/cloud/newbee/NewBeeMallCloudAdminGatewayApplication.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.gateway.cloud.newbee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author 程序员十三
* @qq交流群 791509631
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@SpringBootApplication
@EnableDiscoveryClient
public class NewBeeMallCloudAdminGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(NewBeeMallCloudAdminGatewayApplication.class, args);
}
}
================================================
FILE: newbee-mall-cloud-gateway-admin/src/main/java/ltd/gateway/cloud/newbee/config/PolymerizeSwaggerProvider.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.gateway.cloud.newbee.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
/**
* 在网关层聚合底层微服务的Swagger资源
*
* @author 程序员十三
* @qq交流群 791509631
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@Primary
@Component
public class PolymerizeSwaggerProvider implements SwaggerResourcesProvider {
/**
* Swagger Doc的URL后缀
*/
public static final String API_DOCS_URL = "/v3/api-docs";
@Autowired
private GatewayProperties gatewayProperties;
@Override
public List get() {
List resources = new ArrayList<>();
List routes = new ArrayList<>();
//需要聚合的路由配置
routes.add("user-service-swagger-route");
routes.add("goods-service-swagger-route");
routes.add("recommend-service-swagger-route");
routes.add("order-service-swagger-route");
gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
.forEach(routeDefinition -> routeDefinition.getPredicates().stream()
.filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
.forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
.replace("/**", API_DOCS_URL)))));
return resources;
}
private SwaggerResource swaggerResource(String name, String url) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(url);
swaggerResource.setSwaggerVersion("3.0");
return swaggerResource;
}
}
================================================
FILE: newbee-mall-cloud-gateway-admin/src/main/java/ltd/gateway/cloud/newbee/config/RedisConfig.java
================================================
package ltd.gateway.cloud.newbee.config;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
@Configuration
@EnableCaching
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig extends CachingConfigurerSupport {
@Resource
private LettuceConnectionFactory lettuceConnectionFactory;
public RedisConfig(){}
@Bean
public RedisTemplate redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory){
RedisTemplate template = new RedisTemplate();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
public CacheManager cacheManager() {
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
.fromConnectionFactory(lettuceConnectionFactory);
@SuppressWarnings("serial")
Set cacheNames = new HashSet() {
{
add("codeNameCache");
}
};
builder.initialCacheNames(cacheNames);
return builder.build();
}
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(target.getClass().getName());
stringBuffer.append(method.getName());
for (Object obj : params) {
stringBuffer.append(obj.toString());
}
return stringBuffer.toString();
}
};
}
}
================================================
FILE: newbee-mall-cloud-gateway-admin/src/main/java/ltd/gateway/cloud/newbee/filter/ValidTokenGlobalFilter.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.gateway.cloud.newbee.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.pojo.AdminUserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
/**
* @author 程序员十三
* @qq交流群 791509631
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@Component
public class ValidTokenGlobalFilter implements GlobalFilter, Ordered {
@Autowired
private RedisTemplate redisTemplate;
@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 登录接口、swagger请求,直接放行
if (exchange.getRequest().getURI().getPath().equals("/users/admin/login") || exchange.getRequest().getURI().getPath().contains("/swagger/v3/api-docs")) {
return chain.filter(exchange);
}
HttpHeaders headers = exchange.getRequest().getHeaders();
if (headers == null || headers.isEmpty()) {
// 返回错误提示
return wrapErrorResponse(exchange, chain);
}
String token = headers.getFirst("token");
if (!StringUtils.hasText(token)) {
// 返回错误提示
return wrapErrorResponse(exchange, chain);
}
ValueOperations opsForAdminUserToken = redisTemplate.opsForValue();
AdminUserToken tokenObject = opsForAdminUserToken.get(token);
if (tokenObject == null) {
// 返回错误提示
return wrapErrorResponse(exchange, chain);
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
Mono wrapErrorResponse(ServerWebExchange exchange, GatewayFilterChain chain) {
Result result = ResultGenerator.genErrorResult(419, "无权限访问");
ObjectMapper mapper = new ObjectMapper();
ObjectNode resultNode = mapper.valueToTree(result);
byte[] bytes = resultNode.toString().getBytes(StandardCharsets.UTF_8);
DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(bytes);
exchange.getResponse().setStatusCode(HttpStatus.OK);
return exchange.getResponse().writeWith(Flux.just(dataBuffer));
}
}
================================================
FILE: newbee-mall-cloud-gateway-admin/src/main/resources/application.properties
================================================
server.port=29100
# 服务名称
spring.application.name=newbee-mall-cloud-gateway-admin
# Nacos地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# Nacos登录用户名(默认为nacos,生产环境一定要修改)
spring.cloud.nacos.username=nacos
# Nacos登录密码(默认为nacos,生产环境一定要修改)
spring.cloud.nacos.password=nacos
# 网关开启服务注册与服务发现
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lower-case-service-id=true
# 用户服务的路由配置
spring.cloud.gateway.routes[0].id=user-service-route
spring.cloud.gateway.routes[0].uri=lb://newbee-mall-cloud-user-service
spring.cloud.gateway.routes[0].order=1
spring.cloud.gateway.routes[0].predicates[0]=Path=/users/admin/**
# 商品服务的路由配置-1
spring.cloud.gateway.routes[1].id=categories-admin-service-route
spring.cloud.gateway.routes[1].uri=lb://newbee-mall-cloud-goods-service
spring.cloud.gateway.routes[1].order=1
spring.cloud.gateway.routes[1].predicates[0]=Path=/categories/admin/**
# 商品服务的路由配置-2
spring.cloud.gateway.routes[2].id=goods-admin-service-route
spring.cloud.gateway.routes[2].uri=lb://newbee-mall-cloud-goods-service
spring.cloud.gateway.routes[2].order=1
spring.cloud.gateway.routes[2].predicates[0]=Path=/goods/admin/**
# 推荐服务的路由配置-1
spring.cloud.gateway.routes[3].id=carousels-admin-service-route
spring.cloud.gateway.routes[3].uri=lb://newbee-mall-cloud-recommend-service
spring.cloud.gateway.routes[3].order=1
spring.cloud.gateway.routes[3].predicates[0]=Path=/carousels/admin/**
# 推荐服务的路由配置-2
spring.cloud.gateway.routes[4].id=indexConfigs-admin-service-route
spring.cloud.gateway.routes[4].uri=lb://newbee-mall-cloud-recommend-service
spring.cloud.gateway.routes[4].order=1
spring.cloud.gateway.routes[4].predicates[0]=Path=/indexConfigs/admin/**
# 订单服务的路由配置
spring.cloud.gateway.routes[5].id=order-service-route
spring.cloud.gateway.routes[5].uri=lb://newbee-mall-cloud-order-service
spring.cloud.gateway.routes[5].order=1
spring.cloud.gateway.routes[5].predicates[0]=Path=/orders/admin/**
# 用户服务Swagger的路由配置
spring.cloud.gateway.routes[6].id=user-service-swagger-route
spring.cloud.gateway.routes[6].uri=lb://newbee-mall-cloud-user-service
spring.cloud.gateway.routes[6].order=1
spring.cloud.gateway.routes[6].predicates[0]=Path=/users/swagger/**
spring.cloud.gateway.routes[6].filters[0]=StripPrefix=2
# 商品服务Swagger的路由配置
spring.cloud.gateway.routes[7].id=goods-service-swagger-route
spring.cloud.gateway.routes[7].uri=lb://newbee-mall-cloud-goods-service
spring.cloud.gateway.routes[7].order=1
spring.cloud.gateway.routes[7].predicates[0]=Path=/categories/swagger/**
spring.cloud.gateway.routes[7].filters[0]=StripPrefix=2
# 推荐服务Swagger的路由配置
spring.cloud.gateway.routes[8].id=recommend-service-swagger-route
spring.cloud.gateway.routes[8].uri=lb://newbee-mall-cloud-recommend-service
spring.cloud.gateway.routes[8].order=1
spring.cloud.gateway.routes[8].predicates[0]=Path=/indexConfigs/swagger/**
spring.cloud.gateway.routes[8].filters[0]=StripPrefix=2
# 订单服务Swagger的路由配置
spring.cloud.gateway.routes[9].id=order-service-swagger-route
spring.cloud.gateway.routes[9].uri=lb://newbee-mall-cloud-order-service
spring.cloud.gateway.routes[9].order=1
spring.cloud.gateway.routes[9].predicates[0]=Path=/orders/swagger/**
spring.cloud.gateway.routes[9].filters[0]=StripPrefix=2
##Redis 配置
# Redis数据库索引(默认为0)
spring.redis.database=13
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码
spring.redis.password=123456789
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000
================================================
FILE: newbee-mall-cloud-gateway-mall/pom.xml
================================================
4.0.0
ltd.newbee.cloud
newbee-mall-cloud-gateway-mall
0.0.1-SNAPSHOT
newbee-mall-cloud-gateway-mall
商城端网关模块
ltd.newbee.cloud
newbee-mall-cloud
0.0.1-SNAPSHOT
1.8
UTF-8
UTF-8
org.springframework.cloud
spring-cloud-starter-gateway
org.springframework.cloud
spring-cloud-starter-loadbalancer
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
org.springframework.boot
spring-boot-starter-data-redis
io.springfox
springfox-boot-starter
ltd.user.newbee.cloud
newbee-mall-cloud-user-api
0.0.1-SNAPSHOT
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
================================================
FILE: newbee-mall-cloud-gateway-mall/src/main/java/ltd/gateway/cloud/newbee/NewBeeMallCloudMallGatewayApplication.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.gateway.cloud.newbee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author 程序员十三
* @qq交流群 791509631
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@SpringBootApplication
@EnableDiscoveryClient
public class NewBeeMallCloudMallGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(NewBeeMallCloudMallGatewayApplication.class, args);
}
}
================================================
FILE: newbee-mall-cloud-gateway-mall/src/main/java/ltd/gateway/cloud/newbee/config/PolymerizeSwaggerProvider.java
================================================
package ltd.gateway.cloud.newbee.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
/**
* 在网关层聚合底层微服务的Swagger资源
*
* @author 程序员十三
* @qq交流群 791509631
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@Primary
@Component
public class PolymerizeSwaggerProvider implements SwaggerResourcesProvider {
/**
* Swagger Doc的URL后缀
*/
public static final String API_DOCS_URL = "/v3/api-docs";
@Autowired
private GatewayProperties gatewayProperties;
@Override
public List get() {
List resources = new ArrayList<>();
List routes = new ArrayList<>();
//需要聚合的路由配置
routes.add("user-service-swagger-route");
routes.add("recommend-service-swagger-route");
routes.add("goods-service-swagger-route");
routes.add("order-service-swagger-route");
routes.add("shop-cart-service-swagger-route");
gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
.forEach(routeDefinition -> routeDefinition.getPredicates().stream()
.filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
.forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
.replace("/**", API_DOCS_URL)))));
return resources;
}
private SwaggerResource swaggerResource(String name, String url) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(url);
swaggerResource.setSwaggerVersion("3.0");
return swaggerResource;
}
}
================================================
FILE: newbee-mall-cloud-gateway-mall/src/main/java/ltd/gateway/cloud/newbee/config/RedisConfig.java
================================================
package ltd.gateway.cloud.newbee.config;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
@Configuration
@EnableCaching
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig extends CachingConfigurerSupport {
@Resource
private LettuceConnectionFactory lettuceConnectionFactory;
public RedisConfig(){}
@Bean
public RedisTemplate redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory){
RedisTemplate template = new RedisTemplate();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
public CacheManager cacheManager() {
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
.fromConnectionFactory(lettuceConnectionFactory);
@SuppressWarnings("serial")
Set cacheNames = new HashSet() {
{
add("codeNameCache");
}
};
builder.initialCacheNames(cacheNames);
return builder.build();
}
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(target.getClass().getName());
stringBuffer.append(method.getName());
for (Object obj : params) {
stringBuffer.append(obj.toString());
}
return stringBuffer.toString();
}
};
}
}
================================================
FILE: newbee-mall-cloud-gateway-mall/src/main/java/ltd/gateway/cloud/newbee/filter/ValidMallUserTokenGlobalFilter.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.gateway.cloud.newbee.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* @author 程序员十三
* @qq交流群 791509631
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@Component
public class ValidMallUserTokenGlobalFilter implements GlobalFilter, Ordered {
@Autowired
private RedisTemplate redisTemplate;
@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
final List ignoreURLs = new ArrayList<>();
ignoreURLs.add("/users/mall/login");
ignoreURLs.add("/users/mall/register");
ignoreURLs.add("/categories/mall/listAll");
ignoreURLs.add("/mall/index/recommondInfos");
ignoreURLs.add("/indexConfigs/swagger/v3/api-docs");
ignoreURLs.add("/carts/swagger/v3/api-docs");
ignoreURLs.add("/orders/swagger/v3/api-docs");
ignoreURLs.add("/users/swagger/v3/api-docs");
ignoreURLs.add("/goods/swagger/v3/api-docs");
// 登录注册接口,直接放行
if (ignoreURLs.contains(exchange.getRequest().getURI().getPath())) {
return chain.filter(exchange);
}
HttpHeaders headers = exchange.getRequest().getHeaders();
if (headers == null || headers.isEmpty()) {
// 返回错误提示
return wrapErrorResponse(exchange, chain);
}
String token = headers.getFirst("token");
if (!StringUtils.hasText(token)) {
// 返回错误提示
return wrapErrorResponse(exchange, chain);
}
ValueOperations opsForMallUserToken = redisTemplate.opsForValue();
MallUserToken tokenObject = opsForMallUserToken.get(token);
if (tokenObject == null) {
// 返回错误提示
return wrapErrorResponse(exchange, chain);
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
Mono wrapErrorResponse(ServerWebExchange exchange, GatewayFilterChain chain) {
Result result = ResultGenerator.genErrorResult(416, "无权限访问");
ObjectMapper mapper = new ObjectMapper();
ObjectNode resultNode = mapper.valueToTree(result);
byte[] bytes = resultNode.toString().getBytes(StandardCharsets.UTF_8);
DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(bytes);
exchange.getResponse().setStatusCode(HttpStatus.OK);
return exchange.getResponse().writeWith(Flux.just(dataBuffer));
}
}
================================================
FILE: newbee-mall-cloud-gateway-mall/src/main/resources/application.properties
================================================
server.port=29110
# 服务名称
spring.application.name=newbee-mall-cloud-gateway-mall
# Nacos地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# Nacos登录用户名(默认为nacos,生产环境一定要修改)
spring.cloud.nacos.username=nacos
# Nacos登录密码(默认为nacos,生产环境一定要修改)
spring.cloud.nacos.password=nacos
# 网关开启服务注册与服务发现
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lower-case-service-id=true
# 用户服务的路由配置
spring.cloud.gateway.routes[0].id=user-service-route
spring.cloud.gateway.routes[0].uri=lb://newbee-mall-cloud-user-service
spring.cloud.gateway.routes[0].order=1
spring.cloud.gateway.routes[0].predicates[0]=Path=/users/mall/**
# 首页接口的路由配置
spring.cloud.gateway.routes[1].id=recommend-service-route
spring.cloud.gateway.routes[1].uri=lb://newbee-mall-cloud-recommend-service
spring.cloud.gateway.routes[1].order=1
spring.cloud.gateway.routes[1].predicates[0]=Path=/mall/index/**
# 分类接口的路由配置
spring.cloud.gateway.routes[2].id=goods-service-route
spring.cloud.gateway.routes[2].uri=lb://newbee-mall-cloud-goods-service
spring.cloud.gateway.routes[2].order=1
spring.cloud.gateway.routes[2].predicates[0]=Path=/categories/mall/**
# 商品接口的路由配置
spring.cloud.gateway.routes[3].id=goods-service-route2
spring.cloud.gateway.routes[3].uri=lb://newbee-mall-cloud-goods-service
spring.cloud.gateway.routes[3].order=1
spring.cloud.gateway.routes[3].predicates[0]=Path=/goods/mall/**
# 购物车接口的路由配置
spring.cloud.gateway.routes[4].id=shop-cart-service-route
spring.cloud.gateway.routes[4].uri=lb://newbee-mall-cloud-shop-cart-service
spring.cloud.gateway.routes[4].order=1
spring.cloud.gateway.routes[4].predicates[0]=Path=/shop-cart/**
# 订单接口的路由配置
spring.cloud.gateway.routes[5].id=order-service-route
spring.cloud.gateway.routes[5].uri=lb://newbee-mall-cloud-order-service
spring.cloud.gateway.routes[5].order=1
spring.cloud.gateway.routes[5].predicates[0]=Path=/orders/mall/**
# 收货地址接口的路由配置
spring.cloud.gateway.routes[6].id=order-service-route2
spring.cloud.gateway.routes[6].uri=lb://newbee-mall-cloud-order-service
spring.cloud.gateway.routes[6].order=1
spring.cloud.gateway.routes[6].predicates[0]=Path=/mall/address/**
# 商品服务Swagger的路由配置
spring.cloud.gateway.routes[7].id=goods-service-swagger-route
spring.cloud.gateway.routes[7].uri=lb://newbee-mall-cloud-goods-service
spring.cloud.gateway.routes[7].order=1
spring.cloud.gateway.routes[7].predicates[0]=Path=/goods/swagger/**
spring.cloud.gateway.routes[7].filters[0]=StripPrefix=2
# 推荐服务Swagger的路由配置
spring.cloud.gateway.routes[8].id=recommend-service-swagger-route
spring.cloud.gateway.routes[8].uri=lb://newbee-mall-cloud-recommend-service
spring.cloud.gateway.routes[8].order=1
spring.cloud.gateway.routes[8].predicates[0]=Path=/indexConfigs/swagger/**
spring.cloud.gateway.routes[8].filters[0]=StripPrefix=2
# 订单服务Swagger的路由配置
spring.cloud.gateway.routes[9].id=order-service-swagger-route
spring.cloud.gateway.routes[9].uri=lb://newbee-mall-cloud-order-service
spring.cloud.gateway.routes[9].order=1
spring.cloud.gateway.routes[9].predicates[0]=Path=/orders/swagger/**
spring.cloud.gateway.routes[9].filters[0]=StripPrefix=2
# 用户服务Swagger的路由配置
spring.cloud.gateway.routes[10].id=user-service-swagger-route
spring.cloud.gateway.routes[10].uri=lb://newbee-mall-cloud-user-service
spring.cloud.gateway.routes[10].order=1
spring.cloud.gateway.routes[10].predicates[0]=Path=/users/swagger/**
spring.cloud.gateway.routes[10].filters[0]=StripPrefix=2
# 购物车服务Swagger的路由配置
spring.cloud.gateway.routes[11].id=shop-cart-service-swagger-route
spring.cloud.gateway.routes[11].uri=lb://newbee-mall-cloud-shop-cart-service
spring.cloud.gateway.routes[11].order=1
spring.cloud.gateway.routes[11].predicates[0]=Path=/carts/swagger/**
spring.cloud.gateway.routes[11].filters[0]=StripPrefix=2
##Redis 配置
# Redis数据库索引(默认为0)
spring.redis.database=13
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码
spring.redis.password=123456789
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-api/pom.xml
================================================
4.0.0
ltd.goods.newbee.cloud
newbee-mall-cloud-goods-api
jar
0.0.1-SNAPSHOT
newbee-mall-cloud-goods-api
商品服务openfeign
ltd.newbee.cloud
newbee-mall-cloud-goods-service
0.0.1-SNAPSHOT
1.8
org.springframework.cloud
spring-cloud-starter-openfeign
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-api/src/main/java/ltd/goods/cloud/newbee/dto/NewBeeMallGoodsDTO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.dto;
public class NewBeeMallGoodsDTO {
private Long goodsId;
private String goodsName;
private String goodsIntro;
private Long goodsCategoryId;
private String goodsCoverImg;
private String goodsCarousel;
private Integer originalPrice;
private Integer sellingPrice;
private Integer stockNum;
private String tag;
private Byte goodsSellStatus;
public Long getGoodsId() {
return goodsId;
}
public void setGoodsId(Long goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getGoodsIntro() {
return goodsIntro;
}
public void setGoodsIntro(String goodsIntro) {
this.goodsIntro = goodsIntro;
}
public Long getGoodsCategoryId() {
return goodsCategoryId;
}
public void setGoodsCategoryId(Long goodsCategoryId) {
this.goodsCategoryId = goodsCategoryId;
}
public String getGoodsCoverImg() {
return goodsCoverImg;
}
public void setGoodsCoverImg(String goodsCoverImg) {
this.goodsCoverImg = goodsCoverImg;
}
public String getGoodsCarousel() {
return goodsCarousel;
}
public void setGoodsCarousel(String goodsCarousel) {
this.goodsCarousel = goodsCarousel;
}
public Integer getOriginalPrice() {
return originalPrice;
}
public void setOriginalPrice(Integer originalPrice) {
this.originalPrice = originalPrice;
}
public Integer getSellingPrice() {
return sellingPrice;
}
public void setSellingPrice(Integer sellingPrice) {
this.sellingPrice = sellingPrice;
}
public Integer getStockNum() {
return stockNum;
}
public void setStockNum(Integer stockNum) {
this.stockNum = stockNum;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public Byte getGoodsSellStatus() {
return goodsSellStatus;
}
public void setGoodsSellStatus(Byte goodsSellStatus) {
this.goodsSellStatus = goodsSellStatus;
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-api/src/main/java/ltd/goods/cloud/newbee/dto/StockNumDTO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.dto;
public class StockNumDTO {
private Long goodsId;
private Integer goodsCount;
public Long getGoodsId() {
return goodsId;
}
public void setGoodsId(Long goodsId) {
this.goodsId = goodsId;
}
public Integer getGoodsCount() {
return goodsCount;
}
public void setGoodsCount(Integer goodsCount) {
this.goodsCount = goodsCount;
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-api/src/main/java/ltd/goods/cloud/newbee/dto/UpdateStockNumDTO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.dto;
import java.util.List;
public class UpdateStockNumDTO {
private List stockNumDTOS;
public List getStockNumDTOS() {
return stockNumDTOS;
}
public void setStockNumDTOS(List stockNumDTOS) {
this.stockNumDTOS = stockNumDTOS;
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-api/src/main/java/ltd/goods/cloud/newbee/openfeign/NewBeeCloudGoodsServiceFeign.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.openfeign;
import ltd.common.cloud.newbee.dto.Result;
import ltd.goods.cloud.newbee.dto.NewBeeMallGoodsDTO;
import ltd.goods.cloud.newbee.dto.UpdateStockNumDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@FeignClient(value = "newbee-mall-cloud-goods-service", path = "/goods")
public interface NewBeeCloudGoodsServiceFeign {
@GetMapping(value = "/admin/goodsDetail")
Result getGoodsDetail(@RequestParam(value = "goodsId") Long goodsId);
@GetMapping(value = "/admin/listByGoodsIds")
Result> listByGoodsIds(@RequestParam(value = "goodsIds") List goodsIds);
@PutMapping(value = "/admin/updateStock")
Result updateStock(@RequestBody UpdateStockNumDTO updateStockNumDTO);
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/pom.xml
================================================
4.0.0
ltd.goods.newbee.cloud
newbee-mall-cloud-goods-web
0.0.1-SNAPSHOT
newbee-mall-cloud-goods-web
商品服务
ltd.newbee.cloud
newbee-mall-cloud-goods-service
0.0.1-SNAPSHOT
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
org.springframework.boot
spring-boot-starter-validation
org.mybatis.spring.boot
mybatis-spring-boot-starter
com.alibaba.cloud
spring-cloud-starter-alibaba-seata
org.projectlombok
lombok
${lombok.version}
provided
io.springfox
springfox-boot-starter
mysql
mysql-connector-java
runtime
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
org.springframework.cloud
spring-cloud-starter-sleuth
org.springframework.cloud
spring-cloud-sleuth-zipkin
net.logstash.logback
logstash-logback-encoder
${logstash-logback-encoder.version}
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
org.springframework.cloud
spring-cloud-starter-loadbalancer
ltd.user.newbee.cloud
newbee-mall-cloud-user-api
0.0.1-SNAPSHOT
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/NewBeeMallCloudGoodsServiceApplication.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee;
import ltd.user.cloud.newbee.openfeign.NewBeeCloudUserServiceFeign;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @author 程序员十三
* @qq交流群 791509631
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("ltd.goods.cloud.newbee.dao")
@EnableFeignClients(basePackageClasses = {NewBeeCloudUserServiceFeign.class})
public class NewBeeMallCloudGoodsServiceApplication {
public static void main(String[] args) {
System.setProperty("nacos.logging.default.config.enabled","false");
SpringApplication.run(NewBeeMallCloudGoodsServiceApplication.class, args);
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/config/GoodsServiceExceptionHandler.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.config;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* 全局异常处理
*/
@RestControllerAdvice
public class GoodsServiceExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GoodsServiceExceptionHandler.class);
@ExceptionHandler(BindException.class)
public Object bindException(BindException e) {
log.error("GoodsServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(510);
BindingResult bindingResult = e.getBindingResult();
result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
return result;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object bindException(MethodArgumentNotValidException e) {
log.error("GoodsServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(510);
BindingResult bindingResult = e.getBindingResult();
result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
return result;
}
@ExceptionHandler(Exception.class)
public Object handleException(Exception e, HttpServletRequest req) {
log.error("GoodsServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(500);
//区分是否为自定义异常
if (e instanceof NewBeeMallException) {
result.setMessage(e.getMessage());
if (e.getMessage().equals(ServiceResultEnum.ADMIN_NOT_LOGIN_ERROR.getResult()) || e.getMessage().equals(ServiceResultEnum.ADMIN_TOKEN_EXPIRE_ERROR.getResult())) {
result.setResultCode(419);
}
if (e.getMessage().equals(ServiceResultEnum.NOT_LOGIN_ERROR.getResult()) || e.getMessage().equals(ServiceResultEnum.TOKEN_EXPIRE_ERROR.getResult())) {
result.setResultCode(416);
}
} else {
e.printStackTrace();
result.setMessage("未知异常,请查看控制台日志并检查配置文件。");
}
return result;
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/config/GoodsServiceSwagger3Config.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.config;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import ltd.common.cloud.newbee.pojo.AdminUserToken;
import ltd.goods.cloud.newbee.entity.LoginAdminUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableOpenApi
public class GoodsServiceSwagger3Config{
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.ignoredParameterTypes(AdminUserToken.class, LoginAdminUser.class, MallUserToken.class)
.select()
.apis(RequestHandlerSelectors.basePackage("ltd.goods.cloud.newbee.controller"))
.paths(PathSelectors.any())
.build()
.globalRequestParameters(getGlobalRequestParameters());
}
//生成全局通用参数
private List getGlobalRequestParameters() {
List parameters = new ArrayList<>();
parameters.add(new RequestParameterBuilder()
.name("token")
.description("登录认证token")
.required(false) // 非必传
.in(ParameterType.HEADER) //请求头中的参数,其它类型可以点进ParameterType类中查看
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.build());
return parameters;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("newbee-mall-cloud-goods-service接口文档")
.description("swagger接口文档")
.version("2.0")
.build();
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/config/GoodsServiceWebMvcConfigurer.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.config;
import com.alibaba.cloud.seata.web.SeataHandlerInterceptor;
import com.alibaba.cloud.sentinel.SentinelProperties;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import ltd.goods.cloud.newbee.config.handler.TokenToAdminUserMethodArgumentResolver;
import ltd.goods.cloud.newbee.config.handler.TokenToMallUserMethodArgumentResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
import java.util.Optional;
@Configuration
public class GoodsServiceWebMvcConfigurer extends WebMvcConfigurationSupport {
private static final Logger log = LoggerFactory.getLogger(GoodsServiceWebMvcConfigurer.class);
@Autowired
private SentinelProperties sentinelProperties;
@Autowired
private Optional sentinelWebInterceptorOptional;
@Autowired
@Lazy
private TokenToAdminUserMethodArgumentResolver tokenToAdminUserMethodArgumentResolver;
@Autowired
@Lazy
private TokenToMallUserMethodArgumentResolver tokenToMallUserMethodArgumentResolver;
/**
* @param argumentResolvers
* @tip @TokenToAdminUser 注解处理方法
*/
public void addArgumentResolvers(List argumentResolvers) {
argumentResolvers.add(tokenToAdminUserMethodArgumentResolver);
argumentResolvers.add(tokenToMallUserMethodArgumentResolver);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.
addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
.resourceChain(false);
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SeataHandlerInterceptor()).addPathPatterns("/**");
if (this.sentinelWebInterceptorOptional.isPresent()) {
SentinelProperties.Filter filterConfig = this.sentinelProperties.getFilter();
registry.addInterceptor((HandlerInterceptor) this.sentinelWebInterceptorOptional.get()).order(filterConfig.getOrder()).addPathPatterns(filterConfig.getUrlPatterns());
log.info("[Sentinel Starter] register SentinelWebInterceptor with urlPatterns: {}.", filterConfig.getUrlPatterns());
}
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/config/OpenFeignConfiguration.java
================================================
package ltd.goods.cloud.newbee.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenFeignConfiguration {
@Bean
public Logger.Level openFeignLogLevel() {
// 设置OpenFeign日志级别
return Logger.Level.FULL;
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/config/SeataProxyConfiguration.java
================================================
package ltd.goods.cloud.newbee.config;
import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
@Configuration
public class SeataProxyConfiguration {
//创建Druid数据源
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource() {
return new DruidDataSource();
}
//创建DataSource数据源代理
@Bean("dataSource")
@Primary
public DataSource dataSourceDelegation(DruidDataSource druidDataSource) {
return new DataSourceProxy(druidDataSource);
}
/*
* 解决druid 日志报错:discard long time none received connection:xxx
* */
@PostConstruct
public void setProperties(){
System.setProperty("druid.mysql.usePingMethod","false");
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/config/annotation/TokenToAdminUser.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.config.annotation;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TokenToAdminUser {
/**
* 当前用户在request中的名字
*
* @return
*/
String value() default "adminUser";
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/config/annotation/TokenToMallUser.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.config.annotation;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TokenToMallUser {
/**
* 当前用户在request中的名字
*
* @return
*/
String value() default "user";
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/config/handler/TokenToAdminUserMethodArgumentResolver.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.config.handler;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.goods.cloud.newbee.config.annotation.TokenToAdminUser;
import ltd.goods.cloud.newbee.entity.LoginAdminUser;
import ltd.user.cloud.newbee.openfeign.NewBeeCloudUserServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.LinkedHashMap;
@Component
public class TokenToAdminUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
private NewBeeCloudUserServiceFeign newBeeCloudUserService;
public TokenToAdminUserMethodArgumentResolver() {
}
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(TokenToAdminUser.class)) {
return true;
}
return false;
}
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
if (parameter.getParameterAnnotation(TokenToAdminUser.class) instanceof TokenToAdminUser) {
String token = webRequest.getHeader("token");
if (null != token && !"".equals(token) && token.length() == 32) {
// 通过用户中心获取用户信息
Result result = newBeeCloudUserService.getAdminUserByToken(token);
if (result == null || result.getResultCode() != 200 || result.getData() == null) {
NewBeeMallException.fail(ServiceResultEnum.ADMIN_NOT_LOGIN_ERROR.getResult());
}
LinkedHashMap resultData = (LinkedHashMap) result.getData();
// 将返回的字段封装到LoginAdminUser对象中
LoginAdminUser loginAdminUser = new LoginAdminUser();
loginAdminUser.setAdminUserId(Long.valueOf(resultData.get("adminUserId").toString()));
loginAdminUser.setLoginUserName((String) resultData.get("loginUserName"));
loginAdminUser.setNickName((String) resultData.get("nickName"));
loginAdminUser.setLocked(Byte.valueOf(resultData.get("locked").toString()));
return loginAdminUser;
} else {
NewBeeMallException.fail(ServiceResultEnum.ADMIN_NOT_LOGIN_ERROR.getResult());
}
}
return null;
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/config/handler/TokenToMallUserMethodArgumentResolver.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.config.handler;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import ltd.goods.cloud.newbee.config.annotation.TokenToMallUser;
import ltd.user.cloud.newbee.dto.MallUserDTO;
import ltd.user.cloud.newbee.openfeign.NewBeeCloudUserServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@Component
public class TokenToMallUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
private NewBeeCloudUserServiceFeign newBeeCloudUserService;
public TokenToMallUserMethodArgumentResolver() {
}
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(TokenToMallUser.class)) {
return true;
}
return false;
}
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
if (parameter.getParameterAnnotation(TokenToMallUser.class) instanceof TokenToMallUser) {
String token = webRequest.getHeader("token");
if (null != token && !"".equals(token) && token.length() == 32) {
Result result = newBeeCloudUserService.getMallUserByToken(token);
if (result == null || result.getResultCode() != 200 || result.getData() == null) {
NewBeeMallException.fail(ServiceResultEnum.TOKEN_EXPIRE_ERROR.getResult());
}
MallUserToken mallUserToken = new MallUserToken();
mallUserToken.setToken(token);
mallUserToken.setUserId(result.getData().getUserId());
return mallUserToken;
} else {
NewBeeMallException.fail(ServiceResultEnum.NOT_LOGIN_ERROR.getResult());
}
}
return null;
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/NewBeeAdminGoodsCategoryController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ltd.common.cloud.newbee.enums.NewBeeMallCategoryLevelEnum;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.goods.cloud.newbee.config.annotation.TokenToAdminUser;
import ltd.goods.cloud.newbee.controller.param.BatchIdParam;
import ltd.goods.cloud.newbee.controller.param.GoodsCategoryAddParam;
import ltd.goods.cloud.newbee.controller.param.GoodsCategoryEditParam;
import ltd.goods.cloud.newbee.entity.GoodsCategory;
import ltd.goods.cloud.newbee.entity.LoginAdminUser;
import ltd.goods.cloud.newbee.service.NewBeeMallCategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@RestController
@Api(value = "v1", tags = "后台管理系统分类模块接口")
@RequestMapping("/categories/admin")
public class NewBeeAdminGoodsCategoryController {
private static final Logger logger = LoggerFactory.getLogger(NewBeeAdminGoodsCategoryController.class);
@Resource
private NewBeeMallCategoryService newBeeMallCategoryService;
/**
* 列表
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ApiOperation(value = "商品分类列表", notes = "根据级别和上级分类id查询")
public Result list(@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
@RequestParam(required = false) @ApiParam(value = "每页条数") Integer pageSize,
@RequestParam(required = false) @ApiParam(value = "分类级别") Integer categoryLevel,
@RequestParam(required = false) @ApiParam(value = "上级分类的id") Long parentId, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (pageNumber == null || pageNumber < 1 || pageSize == null || pageSize < 10 || categoryLevel == null || categoryLevel < 0 || categoryLevel > 3 || parentId == null || parentId < 0) {
return ResultGenerator.genFailResult("分页参数异常!");
}
Map params = new HashMap(8);
params.put("page", pageNumber);
params.put("limit", pageSize);
params.put("categoryLevel", categoryLevel);
params.put("parentId", parentId);
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallCategoryService.getCategorisPage(pageUtil));
}
/**
* 列表
*/
@RequestMapping(value = "/list4Select", method = RequestMethod.GET)
@ApiOperation(value = "商品分类列表", notes = "用于三级分类联动效果制作")
public Result listForSelect(@RequestParam("categoryId") Long categoryId, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (categoryId == null || categoryId < 1) {
return ResultGenerator.genFailResult("缺少参数!");
}
GoodsCategory category = newBeeMallCategoryService.getGoodsCategoryById(categoryId);
//既不是一级分类也不是二级分类则为不返回数据
if (category == null || category.getCategoryLevel() == NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel()) {
return ResultGenerator.genFailResult("参数异常!");
}
Map categoryResult = new HashMap(4);
if (category.getCategoryLevel() == NewBeeMallCategoryLevelEnum.LEVEL_ONE.getLevel()) {
//如果是一级分类则返回当前一级分类下的所有二级分类,以及二级分类列表中第一条数据下的所有三级分类列表
//查询一级分类列表中第一个实体的所有二级分类
List secondLevelCategories = newBeeMallCategoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(categoryId), NewBeeMallCategoryLevelEnum.LEVEL_TWO.getLevel());
if (!CollectionUtils.isEmpty(secondLevelCategories)) {
//查询二级分类列表中第一个实体的所有三级分类
List thirdLevelCategories = newBeeMallCategoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(secondLevelCategories.get(0).getCategoryId()), NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel());
categoryResult.put("secondLevelCategories", secondLevelCategories);
categoryResult.put("thirdLevelCategories", thirdLevelCategories);
}
}
if (category.getCategoryLevel() == NewBeeMallCategoryLevelEnum.LEVEL_TWO.getLevel()) {
//如果是二级分类则返回当前分类下的所有三级分类列表
List thirdLevelCategories = newBeeMallCategoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(categoryId), NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel());
categoryResult.put("thirdLevelCategories", thirdLevelCategories);
}
return ResultGenerator.genSuccessResult(categoryResult);
}
/**
* 添加
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ApiOperation(value = "新增分类", notes = "新增分类")
public Result save(@RequestBody @Valid GoodsCategoryAddParam goodsCategoryAddParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
GoodsCategory goodsCategory = new GoodsCategory();
BeanUtil.copyProperties(goodsCategoryAddParam, goodsCategory);
String result = newBeeMallCategoryService.saveCategory(goodsCategory);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 修改
*/
@RequestMapping(value = "/update", method = RequestMethod.PUT)
@ApiOperation(value = "修改分类信息", notes = "修改分类信息")
public Result update(@RequestBody @Valid GoodsCategoryEditParam goodsCategoryEditParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
GoodsCategory goodsCategory = new GoodsCategory();
BeanUtil.copyProperties(goodsCategoryEditParam, goodsCategory);
String result = newBeeMallCategoryService.updateGoodsCategory(goodsCategory);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 详情
*/
@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
@ApiOperation(value = "获取单条分类信息", notes = "根据id查询")
public Result info(@PathVariable("id") Long id, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
GoodsCategory goodsCategory = newBeeMallCategoryService.getGoodsCategoryById(id);
if (goodsCategory == null) {
return ResultGenerator.genFailResult("未查询到数据");
}
return ResultGenerator.genSuccessResult(goodsCategory);
}
/**
* 分类删除
*/
@RequestMapping(value = "/batchDelete", method = RequestMethod.DELETE)
@ApiOperation(value = "批量删除分类信息", notes = "批量删除分类信息")
public Result delete(@RequestBody BatchIdParam batchIdParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (batchIdParam == null || batchIdParam.getIds().length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
if (newBeeMallCategoryService.deleteBatch(batchIdParam.getIds())) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/NewBeeAdminGoodsInfoController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller;
import io.seata.core.context.RootContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.goods.cloud.newbee.config.annotation.TokenToAdminUser;
import ltd.goods.cloud.newbee.controller.param.BatchIdParam;
import ltd.goods.cloud.newbee.controller.param.GoodsAddParam;
import ltd.goods.cloud.newbee.controller.param.GoodsEditParam;
import ltd.goods.cloud.newbee.entity.GoodsCategory;
import ltd.goods.cloud.newbee.entity.LoginAdminUser;
import ltd.goods.cloud.newbee.entity.NewBeeMallGoods;
import ltd.goods.cloud.newbee.entity.UpdateStockNumDTO;
import ltd.goods.cloud.newbee.service.NewBeeMallCategoryService;
import ltd.goods.cloud.newbee.service.NewBeeMallGoodsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@RestController
@Api(value = "v1", tags = "后台管理系统商品模块接口")
@RequestMapping("/goods/admin")
public class NewBeeAdminGoodsInfoController {
private static final Logger logger = LoggerFactory.getLogger(NewBeeAdminGoodsInfoController.class);
@Resource
private NewBeeMallGoodsService newBeeMallGoodsService;
@Resource
private NewBeeMallCategoryService newBeeMallCategoryService;
/**
* 列表
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ApiOperation(value = "商品列表", notes = "可根据名称和上架状态筛选")
public Result list(@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
@RequestParam(required = false) @ApiParam(value = "每页条数") Integer pageSize,
@RequestParam(required = false) @ApiParam(value = "商品名称") String goodsName,
@RequestParam(required = false) @ApiParam(value = "上架状态 0-上架 1-下架") Integer goodsSellStatus, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (pageNumber == null || pageNumber < 1 || pageSize == null || pageSize < 10) {
return ResultGenerator.genFailResult("分页参数异常!");
}
Map params = new HashMap(8);
params.put("page", pageNumber);
params.put("limit", pageSize);
if (StringUtils.hasText(goodsName)) {
params.put("goodsName", goodsName);
}
if (goodsSellStatus != null) {
params.put("goodsSellStatus", goodsSellStatus);
}
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallGoodsService.getNewBeeMallGoodsPage(pageUtil));
}
/**
* 添加
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ApiOperation(value = "新增商品信息", notes = "新增商品信息")
public Result save(@RequestBody @Valid GoodsAddParam goodsAddParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
NewBeeMallGoods newBeeMallGoods = new NewBeeMallGoods();
BeanUtil.copyProperties(goodsAddParam, newBeeMallGoods);
String result = newBeeMallGoodsService.saveNewBeeMallGoods(newBeeMallGoods);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 修改
*/
@RequestMapping(value = "/update", method = RequestMethod.PUT)
@ApiOperation(value = "修改商品信息", notes = "修改商品信息")
public Result update(@RequestBody @Valid GoodsEditParam goodsEditParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
NewBeeMallGoods newBeeMallGoods = new NewBeeMallGoods();
BeanUtil.copyProperties(goodsEditParam, newBeeMallGoods);
String result = newBeeMallGoodsService.updateNewBeeMallGoods(newBeeMallGoods);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 详情
*/
@GetMapping("/detail/{id}")
@ApiOperation(value = "获取单条商品信息", notes = "根据id查询")
public Result info(@PathVariable("id") Long id, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
Map goodsInfo = new HashMap(8);
NewBeeMallGoods goods = newBeeMallGoodsService.getNewBeeMallGoodsById(id);
if (goods == null) {
return ResultGenerator.genFailResult(ServiceResultEnum.DATA_NOT_EXIST.getResult());
}
goodsInfo.put("goods", goods);
GoodsCategory thirdCategory;
GoodsCategory secondCategory;
GoodsCategory firstCategory;
thirdCategory = newBeeMallCategoryService.getGoodsCategoryById(goods.getGoodsCategoryId());
if (thirdCategory != null) {
goodsInfo.put("thirdCategory", thirdCategory);
secondCategory = newBeeMallCategoryService.getGoodsCategoryById(thirdCategory.getParentId());
if (secondCategory != null) {
goodsInfo.put("secondCategory", secondCategory);
firstCategory = newBeeMallCategoryService.getGoodsCategoryById(secondCategory.getParentId());
if (firstCategory != null) {
goodsInfo.put("firstCategory", firstCategory);
}
}
}
return ResultGenerator.genSuccessResult(goodsInfo);
}
/**
* 批量修改销售状态
*/
@RequestMapping(value = "/updateStatus/{sellStatus}", method = RequestMethod.PUT)
@ApiOperation(value = "批量修改销售状态", notes = "批量修改销售状态")
public Result delete(@RequestBody BatchIdParam batchIdParam, @PathVariable("sellStatus") int sellStatus, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (batchIdParam == null || batchIdParam.getIds().length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
if (sellStatus != 0 && sellStatus != 1) {
return ResultGenerator.genFailResult("状态异常!");
}
if (newBeeMallGoodsService.batchUpdateSellStatus(batchIdParam.getIds(), sellStatus)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("修改失败");
}
}
/**
* 详情
*/
@GetMapping("/goodsDetail")
@ApiOperation(value = "获取单条商品信息", notes = "根据id查询")
public Result goodsDetail(@RequestParam("goodsId") Long goodsId) {
NewBeeMallGoods goods = newBeeMallGoodsService.getNewBeeMallGoodsById(goodsId);
return ResultGenerator.genSuccessResult(goods);
}
/**
* 根据ids查询商品列表
*/
@GetMapping("/listByGoodsIds")
@ApiOperation(value = "根据ids查询商品列表", notes = "根据ids查询")
public Result getNewBeeMallGoodsByIds(@RequestParam("goodsIds") List goodsIds) {
List newBeeMallGoods = newBeeMallGoodsService.getNewBeeMallGoodsByIds(goodsIds);
return ResultGenerator.genSuccessResult(newBeeMallGoods);
}
/**
* 修改库存
*/
@PutMapping("/updateStock")
@ApiOperation(value = "修改库存", notes = "")
public Result updateStock(@RequestBody UpdateStockNumDTO updateStockNumDTO) {
System.out.println("RootContext.getXID()="+RootContext.getXID());
return ResultGenerator.genSuccessResult(newBeeMallGoodsService.updateStockNum(updateStockNumDTO.getStockNumDTOS()));
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/NewBeeMallGoodsCategoryController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.goods.cloud.newbee.controller.vo.NewBeeMallIndexCategoryVO;
import ltd.goods.cloud.newbee.service.NewBeeMallCategoryService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
@Api(value = "v1", tags = "新蜂商城分类页面接口")
@RequestMapping("/categories/mall")
public class NewBeeMallGoodsCategoryController {
@Resource
private NewBeeMallCategoryService newBeeMallCategoryService;
@GetMapping("/listAll")
@ApiOperation(value = "获取分类数据", notes = "分类页面使用")
public Result> getCategories() {
List categories = newBeeMallCategoryService.getCategoriesForIndex();
if (CollectionUtils.isEmpty(categories)) {
NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
}
return ResultGenerator.genSuccessResult(categories);
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/NewBeeMallGoodsController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.goods.cloud.newbee.config.annotation.TokenToMallUser;
import ltd.goods.cloud.newbee.controller.vo.NewBeeMallGoodsDetailVO;
import ltd.goods.cloud.newbee.controller.vo.NewBeeMallSearchGoodsVO;
import ltd.goods.cloud.newbee.entity.NewBeeMallGoods;
import ltd.goods.cloud.newbee.service.NewBeeMallGoodsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@Api(value = "v1", tags = "新蜂商城商品相关接口")
@RequestMapping("/goods/mall")
public class NewBeeMallGoodsController {
private static final Logger logger = LoggerFactory.getLogger(NewBeeMallGoodsController.class);
@Resource
private NewBeeMallGoodsService newBeeMallGoodsService;
@GetMapping("/test1")
public Result test1() throws BindException {
throw new BindException(1,"BindException");
}
@GetMapping("/test2")
public Result test2() throws NewBeeMallException {
NewBeeMallException.fail("NewBeeMallException");
return ResultGenerator.genSuccessResult("test2");
}
@GetMapping("/test3")
public Result test3() throws Exception {
int i=1/0;
return ResultGenerator.genSuccessResult("test2");
}
@GetMapping("/search")
@ApiOperation(value = "商品搜索接口", notes = "根据关键字和分类id进行搜索")
public Result>> search(@RequestParam(required = false) @ApiParam(value = "搜索关键字") String keyword,
@RequestParam(required = false) @ApiParam(value = "分类id") Long goodsCategoryId,
@RequestParam(required = false) @ApiParam(value = "orderBy") String orderBy,
@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
@TokenToMallUser MallUserToken loginMallUserToken) {
logger.info("goods search api,keyword={},goodsCategoryId={},orderBy={},pageNumber={},userId={}", keyword, goodsCategoryId, orderBy, pageNumber, loginMallUserToken.getUserId());
Map params = new HashMap(8);
//两个搜索参数都为空,直接返回异常
if (goodsCategoryId == null && !StringUtils.hasText(keyword)) {
NewBeeMallException.fail("非法的搜索参数");
}
if (pageNumber == null || pageNumber < 1) {
pageNumber = 1;
}
params.put("goodsCategoryId", goodsCategoryId);
params.put("page", pageNumber);
params.put("limit", 10);
//对keyword做过滤 去掉空格
if (StringUtils.hasText(keyword)) {
params.put("keyword", keyword);
}
if (StringUtils.hasText(orderBy)) {
params.put("orderBy", orderBy);
}
//搜索上架状态下的商品
params.put("goodsSellStatus", 0);
//封装商品数据
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallGoodsService.searchNewBeeMallGoods(pageUtil));
}
@GetMapping("/detail/{goodsId}")
@ApiOperation(value = "商品详情接口", notes = "传参为商品id")
public Result goodsDetail(@ApiParam(value = "商品id") @PathVariable("goodsId") Long goodsId, @TokenToMallUser MallUserToken loginMallUserToken) {
logger.info("goods detail api,goodsId={},userId={}", goodsId, loginMallUserToken.getUserId());
if (goodsId < 1) {
return ResultGenerator.genFailResult("参数异常");
}
NewBeeMallGoods goods = newBeeMallGoodsService.getNewBeeMallGoodsById(goodsId);
if (0 != goods.getGoodsSellStatus()) {
NewBeeMallException.fail(ServiceResultEnum.GOODS_PUT_DOWN.getResult());
}
NewBeeMallGoodsDetailVO goodsDetailVO = new NewBeeMallGoodsDetailVO();
BeanUtil.copyProperties(goods, goodsDetailVO);
goodsDetailVO.setGoodsCarouselList(goods.getGoodsCarousel().split(","));
return ResultGenerator.genSuccessResult(goodsDetailVO);
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/param/BatchIdParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller.param;
import lombok.Data;
import java.io.Serializable;
@Data
public class BatchIdParam implements Serializable {
//id数组
Long[] ids;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/param/GoodsAddParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
public class GoodsAddParam {
@ApiModelProperty("商品名称")
@NotEmpty(message = "商品名称不能为空")
@Length(max = 128,message = "商品名称内容过长")
private String goodsName;
@ApiModelProperty("商品简介")
@NotEmpty(message = "商品简介不能为空")
@Length(max = 200,message = "商品简介内容过长")
private String goodsIntro;
@ApiModelProperty("分类id")
@NotNull(message = "分类id不能为空")
@Min(value = 1, message = "分类id最低为1")
private Long goodsCategoryId;
@ApiModelProperty("商品主图")
@NotEmpty(message = "商品主图不能为空")
private String goodsCoverImg;
@ApiModelProperty("originalPrice")
@NotNull(message = "originalPrice不能为空")
@Min(value = 1, message = "originalPrice最低为1")
@Max(value = 1000000, message = "originalPrice最高为1000000")
private Integer originalPrice;
@ApiModelProperty("sellingPrice")
@NotNull(message = "sellingPrice不能为空")
@Min(value = 1, message = "sellingPrice最低为1")
@Max(value = 1000000, message = "sellingPrice最高为1000000")
private Integer sellingPrice;
@ApiModelProperty("库存")
@NotNull(message = "库存不能为空")
@Min(value = 1, message = "库存最低为1")
@Max(value = 100000, message = "库存最高为100000")
private Integer stockNum;
@ApiModelProperty("商品标签")
@NotEmpty(message = "商品标签不能为空")
@Length(max = 16,message = "商品标签内容过长")
private String tag;
private Byte goodsSellStatus;
@ApiModelProperty("商品详情")
@NotEmpty(message = "商品详情不能为空")
private String goodsDetailContent;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/param/GoodsCategoryAddParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
public class GoodsCategoryAddParam {
@ApiModelProperty("分类层级")
@NotNull(message = "categoryLevel不能为空")
@Min(value = 1, message = "分类级别最低为1")
@Max(value = 3, message = "分类级别最高为3")
private Byte categoryLevel;
@ApiModelProperty("父类id")
@NotNull(message = "parentId不能为空")
@Min(value = 0, message = "parentId最低为0")
private Long parentId;
@ApiModelProperty("分类名称")
@NotEmpty(message = "categoryName不能为空")
@Length(max = 16,message = "分类名称过长")
private String categoryName;
@ApiModelProperty("排序值")
@Min(value = 1, message = "categoryRank最低为1")
@Max(value = 200, message = "categoryRank最高为200")
@NotNull(message = "categoryRank不能为空")
private Integer categoryRank;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/param/GoodsCategoryEditParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
public class GoodsCategoryEditParam {
@ApiModelProperty("待修改分类id")
@NotNull(message = "分类id不能为空")
@Min(value = 1, message = "分类id不能为空")
private Long categoryId;
@ApiModelProperty("分类层级")
@NotNull(message = "categoryLevel不能为空")
@Min(value = 1, message = "分类级别最低为1")
@Max(value = 3, message = "分类级别最高为3")
private Byte categoryLevel;
@ApiModelProperty("父类id")
@NotNull(message = "parentId不能为空")
@Min(value = 0, message = "parentId最低为0")
private Long parentId;
@ApiModelProperty("分类名称")
@NotEmpty(message = "categoryName不能为空")
@Length(max = 16,message = "分类名称过长")
private String categoryName;
@ApiModelProperty("排序值")
@Min(value = 1, message = "categoryRank最低为1")
@Max(value = 200, message = "categoryRank最高为200")
@NotNull(message = "categoryRank不能为空")
private Integer categoryRank;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/param/GoodsEditParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
public class GoodsEditParam {
@ApiModelProperty("待修改商品id")
@NotNull(message = "商品id不能为空")
@Min(value = 1, message = "商品id不能为空")
private Long goodsId;
@ApiModelProperty("商品名称")
@NotEmpty(message = "商品名称不能为空")
@Length(max = 128,message = "商品名称内容过长")
private String goodsName;
@ApiModelProperty("商品简介")
@NotEmpty(message = "商品简介不能为空")
@Length(max = 200,message = "商品简介内容过长")
private String goodsIntro;
@ApiModelProperty("分类id")
@NotNull(message = "分类id不能为空")
@Min(value = 1, message = "分类id最低为1")
private Long goodsCategoryId;
@ApiModelProperty("商品主图")
@NotEmpty(message = "商品主图不能为空")
private String goodsCoverImg;
@ApiModelProperty("originalPrice")
@NotNull(message = "originalPrice不能为空")
@Min(value = 1, message = "originalPrice最低为1")
@Max(value = 1000000, message = "originalPrice最高为1000000")
private Integer originalPrice;
@ApiModelProperty("sellingPrice")
@NotNull(message = "sellingPrice不能为空")
@Min(value = 1, message = "sellingPrice最低为1")
@Max(value = 1000000, message = "sellingPrice最高为1000000")
private Integer sellingPrice;
@ApiModelProperty("库存")
@NotNull(message = "库存不能为空")
@Min(value = 1, message = "库存最低为1")
@Max(value = 100000, message = "库存最高为100000")
private Integer stockNum;
@ApiModelProperty("商品标签")
@NotEmpty(message = "商品标签不能为空")
@Length(max = 16,message = "商品标签内容过长")
private String tag;
private Byte goodsSellStatus;
@ApiModelProperty("商品详情")
@NotEmpty(message = "商品详情不能为空")
private String goodsDetailContent;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/vo/NewBeeMallGoodsDetailVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 商品详情页VO
*/
@Data
public class NewBeeMallGoodsDetailVO implements Serializable {
@ApiModelProperty("商品id")
private Long goodsId;
@ApiModelProperty("商品名称")
private String goodsName;
@ApiModelProperty("商品简介")
private String goodsIntro;
@ApiModelProperty("商品图片地址")
private String goodsCoverImg;
@ApiModelProperty("商品价格")
private Integer sellingPrice;
@ApiModelProperty("商品标签")
private String tag;
@ApiModelProperty("商品图片")
private String[] goodsCarouselList;
@ApiModelProperty("商品原价")
private Integer originalPrice;
@ApiModelProperty("商品详情字段")
private String goodsDetailContent;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/vo/NewBeeMallIndexCategoryVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 首页分类数据VO
*/
@Data
public class NewBeeMallIndexCategoryVO implements Serializable {
@ApiModelProperty("当前一级分类id")
private Long categoryId;
@ApiModelProperty("当前分类级别")
private Byte categoryLevel;
@ApiModelProperty("当前一级分类名称")
private String categoryName;
@ApiModelProperty("二级分类列表")
private List secondLevelCategoryVOS;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/vo/NewBeeMallSearchGoodsVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 搜索列表页商品VO
*/
@Data
public class NewBeeMallSearchGoodsVO implements Serializable {
@ApiModelProperty("商品id")
private Long goodsId;
@ApiModelProperty("商品名称")
private String goodsName;
@ApiModelProperty("商品简介")
private String goodsIntro;
@ApiModelProperty("商品图片地址")
private String goodsCoverImg;
@ApiModelProperty("商品价格")
private Integer sellingPrice;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/vo/SecondLevelCategoryVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 首页分类数据VO(第二级)
*/
@Data
public class SecondLevelCategoryVO implements Serializable {
@ApiModelProperty("当前二级分类id")
private Long categoryId;
@ApiModelProperty("父级分类id")
private Long parentId;
@ApiModelProperty("当前分类级别")
private Byte categoryLevel;
@ApiModelProperty("当前二级分类名称")
private String categoryName;
@ApiModelProperty("三级分类列表")
private List thirdLevelCategoryVOS;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/controller/vo/ThirdLevelCategoryVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 首页分类数据VO(第三级)
*/
@Data
public class ThirdLevelCategoryVO implements Serializable {
@ApiModelProperty("当前三级分类id")
private Long categoryId;
@ApiModelProperty("当前分类级别")
private Byte categoryLevel;
@ApiModelProperty("当前三级分类名称")
private String categoryName;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/dao/GoodsCategoryMapper.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.dao;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.goods.cloud.newbee.entity.GoodsCategory;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface GoodsCategoryMapper {
int deleteByPrimaryKey(Long categoryId);
int insert(GoodsCategory record);
int insertSelective(GoodsCategory record);
GoodsCategory selectByPrimaryKey(Long categoryId);
GoodsCategory selectByLevelAndName(@Param("categoryLevel") Byte categoryLevel, @Param("categoryName") String categoryName);
int updateByPrimaryKeySelective(GoodsCategory record);
int updateByPrimaryKey(GoodsCategory record);
List findGoodsCategoryList(PageQueryUtil pageUtil);
int getTotalGoodsCategories(PageQueryUtil pageUtil);
int deleteBatch(Long[] ids);
List selectByLevelAndParentIdsAndNumber(@Param("parentIds") List parentIds, @Param("categoryLevel") int categoryLevel, @Param("number") int number);
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/dao/NewBeeMallGoodsMapper.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.dao;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.goods.cloud.newbee.entity.NewBeeMallGoods;
import ltd.goods.cloud.newbee.entity.StockNumDTO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface NewBeeMallGoodsMapper {
int deleteByPrimaryKey(Long goodsId);
int insert(NewBeeMallGoods record);
int insertSelective(NewBeeMallGoods record);
NewBeeMallGoods selectByPrimaryKey(Long goodsId);
NewBeeMallGoods selectByCategoryIdAndName(@Param("goodsName") String goodsName, @Param("goodsCategoryId") Long goodsCategoryId);
int updateByPrimaryKeySelective(NewBeeMallGoods record);
int updateByPrimaryKeyWithBLOBs(NewBeeMallGoods record);
int updateByPrimaryKey(NewBeeMallGoods record);
List findNewBeeMallGoodsList(PageQueryUtil pageUtil);
int getTotalNewBeeMallGoods(PageQueryUtil pageUtil);
List selectByPrimaryKeys(List goodsIds);
List findNewBeeMallGoodsListBySearch(PageQueryUtil pageUtil);
int getTotalNewBeeMallGoodsBySearch(PageQueryUtil pageUtil);
int batchInsert(@Param("newBeeMallGoodsList") List newBeeMallGoodsList);
int updateStockNum(@Param("stockNumDTOS") List stockNumDTOS);
int batchUpdateSellStatus(@Param("orderIds")Long[] orderIds,@Param("sellStatus") int sellStatus);
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/entity/GoodsCategory.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class GoodsCategory {
private Long categoryId;
private Byte categoryLevel;
private Long parentId;
private String categoryName;
private Integer categoryRank;
private Byte isDeleted;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
private Integer createUser;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
private Integer updateUser;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/entity/LoginAdminUser.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.entity;
import lombok.Data;
@Data
public class LoginAdminUser {
private Long adminUserId;
private String loginUserName;
private String loginPassword;
private String nickName;
private Byte locked;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/entity/NewBeeMallGoods.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class NewBeeMallGoods {
private Long goodsId;
private String goodsName;
private String goodsIntro;
private Long goodsCategoryId;
private String goodsCoverImg;
private String goodsCarousel;
private Integer originalPrice;
private Integer sellingPrice;
private Integer stockNum;
private String tag;
private Byte goodsSellStatus;
private Integer createUser;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
private Integer updateUser;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
private String goodsDetailContent;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/entity/StockNumDTO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.entity;
import lombok.Data;
/**
* 库存修改所需实体
*/
@Data
public class StockNumDTO {
private Long goodsId;
private Integer goodsCount;
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/entity/UpdateStockNumDTO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.entity;
import lombok.Data;
import java.util.List;
@Data
public class UpdateStockNumDTO {
private List stockNumDTOS;
public List getStockNumDTOS() {
return stockNumDTOS;
}
public void setStockNumDTOS(List stockNumDTOS) {
this.stockNumDTOS = stockNumDTOS;
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/service/NewBeeMallCategoryService.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.service;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.goods.cloud.newbee.controller.vo.NewBeeMallIndexCategoryVO;
import ltd.goods.cloud.newbee.entity.GoodsCategory;
import java.util.List;
public interface NewBeeMallCategoryService {
String saveCategory(GoodsCategory goodsCategory);
String updateGoodsCategory(GoodsCategory goodsCategory);
GoodsCategory getGoodsCategoryById(Long id);
Boolean deleteBatch(Long[] ids);
/**
* 后台分页
*
* @param pageUtil
* @return
*/
PageResult getCategorisPage(PageQueryUtil pageUtil);
/**
* 根据parentId和level获取分类列表
*
* @param parentIds
* @param categoryLevel
* @return
*/
List selectByLevelAndParentIdsAndNumber(List parentIds, int categoryLevel);
/**
* 返回分类数据(首页调用)
*
* @return
*/
List getCategoriesForIndex();
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/service/NewBeeMallGoodsService.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.service;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.goods.cloud.newbee.entity.NewBeeMallGoods;
import ltd.goods.cloud.newbee.entity.StockNumDTO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface NewBeeMallGoodsService {
/**
* 后台分页
*
* @param pageUtil
* @return
*/
PageResult getNewBeeMallGoodsPage(PageQueryUtil pageUtil);
/**
* 添加商品
*
* @param goods
* @return
*/
String saveNewBeeMallGoods(NewBeeMallGoods goods);
/**
* 批量新增商品数据
*
* @param newBeeMallGoodsList
* @return
*/
void batchSaveNewBeeMallGoods(List newBeeMallGoodsList);
/**
* 修改商品信息
*
* @param goods
* @return
*/
String updateNewBeeMallGoods(NewBeeMallGoods goods);
/**
* 批量修改销售状态(上架下架)
*
* @param ids
* @return
*/
Boolean batchUpdateSellStatus(Long[] ids, int sellStatus);
/**
* 获取商品详情
*
* @param id
* @return
*/
NewBeeMallGoods getNewBeeMallGoodsById(Long id);
/**
* 获取商品数据
*
* @param goodsIds
* @return
*/
List getNewBeeMallGoodsByIds(List goodsIds);
/**
* 商品搜索
*
* @param pageUtil
* @return
*/
PageResult searchNewBeeMallGoods(PageQueryUtil pageUtil);
Boolean updateStockNum(List stockNumDTOS);
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/service/impl/NewBeeMallCategoryServiceImpl.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.service.impl;
import ltd.common.cloud.newbee.enums.NewBeeMallCategoryLevelEnum;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.goods.cloud.newbee.controller.vo.NewBeeMallIndexCategoryVO;
import ltd.goods.cloud.newbee.controller.vo.SecondLevelCategoryVO;
import ltd.goods.cloud.newbee.controller.vo.ThirdLevelCategoryVO;
import ltd.goods.cloud.newbee.dao.GoodsCategoryMapper;
import ltd.goods.cloud.newbee.entity.GoodsCategory;
import ltd.goods.cloud.newbee.service.NewBeeMallCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy;
@Service
public class NewBeeMallCategoryServiceImpl implements NewBeeMallCategoryService {
@Autowired
private GoodsCategoryMapper goodsCategoryMapper;
@Override
public String saveCategory(GoodsCategory goodsCategory) {
GoodsCategory temp = goodsCategoryMapper.selectByLevelAndName(goodsCategory.getCategoryLevel(), goodsCategory.getCategoryName());
if (temp != null) {
return ServiceResultEnum.SAME_CATEGORY_EXIST.getResult();
}
if (goodsCategoryMapper.insertSelective(goodsCategory) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public String updateGoodsCategory(GoodsCategory goodsCategory) {
GoodsCategory temp = goodsCategoryMapper.selectByPrimaryKey(goodsCategory.getCategoryId());
if (temp == null) {
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
GoodsCategory temp2 = goodsCategoryMapper.selectByLevelAndName(goodsCategory.getCategoryLevel(), goodsCategory.getCategoryName());
if (temp2 != null && !temp2.getCategoryId().equals(goodsCategory.getCategoryId())) {
//同名且不同id 不能继续修改
return ServiceResultEnum.SAME_CATEGORY_EXIST.getResult();
}
goodsCategory.setUpdateTime(new Date());
if (goodsCategoryMapper.updateByPrimaryKeySelective(goodsCategory) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public GoodsCategory getGoodsCategoryById(Long id) {
return goodsCategoryMapper.selectByPrimaryKey(id);
}
@Override
public Boolean deleteBatch(Long[] ids) {
if (ids.length < 1) {
return false;
}
//删除分类数据
return goodsCategoryMapper.deleteBatch(ids) > 0;
}
@Override
public PageResult getCategorisPage(PageQueryUtil pageUtil) {
List goodsCategories = goodsCategoryMapper.findGoodsCategoryList(pageUtil);
int total = goodsCategoryMapper.getTotalGoodsCategories(pageUtil);
PageResult pageResult = new PageResult(goodsCategories, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public List selectByLevelAndParentIdsAndNumber(List parentIds, int categoryLevel) {
return goodsCategoryMapper.selectByLevelAndParentIdsAndNumber(parentIds, categoryLevel, 0);//0代表查询所有
}
@Override
public List getCategoriesForIndex() {
List newBeeMallIndexCategoryVOS = new ArrayList<>();
//获取一级分类的固定数量的数据
List firstLevelCategories = goodsCategoryMapper.selectByLevelAndParentIdsAndNumber(Collections.singletonList(0L), NewBeeMallCategoryLevelEnum.LEVEL_ONE.getLevel(), 10);
if (!CollectionUtils.isEmpty(firstLevelCategories)) {
List firstLevelCategoryIds = firstLevelCategories.stream().map(GoodsCategory::getCategoryId).collect(Collectors.toList());
//获取二级分类的数据
List secondLevelCategories = goodsCategoryMapper.selectByLevelAndParentIdsAndNumber(firstLevelCategoryIds, NewBeeMallCategoryLevelEnum.LEVEL_TWO.getLevel(), 0);
if (!CollectionUtils.isEmpty(secondLevelCategories)) {
List secondLevelCategoryIds = secondLevelCategories.stream().map(GoodsCategory::getCategoryId).collect(Collectors.toList());
//获取三级分类的数据
List thirdLevelCategories = goodsCategoryMapper.selectByLevelAndParentIdsAndNumber(secondLevelCategoryIds, NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel(), 0);
if (!CollectionUtils.isEmpty(thirdLevelCategories)) {
//根据 parentId 将 thirdLevelCategories 分组
Map> thirdLevelCategoryMap = thirdLevelCategories.stream().collect(groupingBy(GoodsCategory::getParentId));
List secondLevelCategoryVOS = new ArrayList<>();
//处理二级分类
for (GoodsCategory secondLevelCategory : secondLevelCategories) {
SecondLevelCategoryVO secondLevelCategoryVO = new SecondLevelCategoryVO();
BeanUtil.copyProperties(secondLevelCategory, secondLevelCategoryVO);
//如果该二级分类下有数据则放入 secondLevelCategoryVOS 对象中
if (thirdLevelCategoryMap.containsKey(secondLevelCategory.getCategoryId())) {
//根据二级分类的id取出thirdLevelCategoryMap分组中的三级分类list
List tempGoodsCategories = thirdLevelCategoryMap.get(secondLevelCategory.getCategoryId());
secondLevelCategoryVO.setThirdLevelCategoryVOS((BeanUtil.copyList(tempGoodsCategories, ThirdLevelCategoryVO.class)));
secondLevelCategoryVOS.add(secondLevelCategoryVO);
}
}
//处理一级分类
if (!CollectionUtils.isEmpty(secondLevelCategoryVOS)) {
//根据 parentId 将 thirdLevelCategories 分组
Map> secondLevelCategoryVOMap = secondLevelCategoryVOS.stream().collect(groupingBy(SecondLevelCategoryVO::getParentId));
for (GoodsCategory firstCategory : firstLevelCategories) {
NewBeeMallIndexCategoryVO newBeeMallIndexCategoryVO = new NewBeeMallIndexCategoryVO();
BeanUtil.copyProperties(firstCategory, newBeeMallIndexCategoryVO);
//如果该一级分类下有数据则放入 newBeeMallIndexCategoryVOS 对象中
if (secondLevelCategoryVOMap.containsKey(firstCategory.getCategoryId())) {
//根据一级分类的id取出secondLevelCategoryVOMap分组中的二级级分类list
List tempGoodsCategories = secondLevelCategoryVOMap.get(firstCategory.getCategoryId());
newBeeMallIndexCategoryVO.setSecondLevelCategoryVOS(tempGoodsCategories);
newBeeMallIndexCategoryVOS.add(newBeeMallIndexCategoryVO);
}
}
}
}
}
return newBeeMallIndexCategoryVOS;
} else {
return null;
}
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/java/ltd/goods/cloud/newbee/service/impl/NewBeeMallGoodsServiceImpl.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.goods.cloud.newbee.service.impl;
import ltd.common.cloud.newbee.enums.NewBeeMallCategoryLevelEnum;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.goods.cloud.newbee.controller.vo.NewBeeMallSearchGoodsVO;
import ltd.goods.cloud.newbee.dao.GoodsCategoryMapper;
import ltd.goods.cloud.newbee.dao.NewBeeMallGoodsMapper;
import ltd.goods.cloud.newbee.entity.GoodsCategory;
import ltd.goods.cloud.newbee.entity.NewBeeMallGoods;
import ltd.goods.cloud.newbee.entity.StockNumDTO;
import ltd.goods.cloud.newbee.service.NewBeeMallGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class NewBeeMallGoodsServiceImpl implements NewBeeMallGoodsService {
@Autowired
private NewBeeMallGoodsMapper goodsMapper;
@Autowired
private GoodsCategoryMapper goodsCategoryMapper;
@Override
public PageResult getNewBeeMallGoodsPage(PageQueryUtil pageUtil) {
List goodsList = goodsMapper.findNewBeeMallGoodsList(pageUtil);
int total = goodsMapper.getTotalNewBeeMallGoods(pageUtil);
PageResult pageResult = new PageResult(goodsList, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public String saveNewBeeMallGoods(NewBeeMallGoods goods) {
GoodsCategory goodsCategory = goodsCategoryMapper.selectByPrimaryKey(goods.getGoodsCategoryId());
// 分类不存在或者不是三级分类,则该参数字段异常
if (goodsCategory == null || goodsCategory.getCategoryLevel().intValue() != NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel()) {
return ServiceResultEnum.GOODS_CATEGORY_ERROR.getResult();
}
if (goodsMapper.selectByCategoryIdAndName(goods.getGoodsName(), goods.getGoodsCategoryId()) != null) {
return ServiceResultEnum.SAME_GOODS_EXIST.getResult();
}
if (goodsMapper.insertSelective(goods) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public void batchSaveNewBeeMallGoods(List newBeeMallGoodsList) {
if (!CollectionUtils.isEmpty(newBeeMallGoodsList)) {
goodsMapper.batchInsert(newBeeMallGoodsList);
}
}
@Override
public String updateNewBeeMallGoods(NewBeeMallGoods goods) {
GoodsCategory goodsCategory = goodsCategoryMapper.selectByPrimaryKey(goods.getGoodsCategoryId());
// 分类不存在或者不是三级分类,则该参数字段异常
if (goodsCategory == null || goodsCategory.getCategoryLevel().intValue() != NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel()) {
return ServiceResultEnum.GOODS_CATEGORY_ERROR.getResult();
}
NewBeeMallGoods temp = goodsMapper.selectByPrimaryKey(goods.getGoodsId());
if (temp == null) {
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
NewBeeMallGoods temp2 = goodsMapper.selectByCategoryIdAndName(goods.getGoodsName(), goods.getGoodsCategoryId());
if (temp2 != null && !temp2.getGoodsId().equals(goods.getGoodsId())) {
//name和分类id相同且不同id 不能继续修改
return ServiceResultEnum.SAME_GOODS_EXIST.getResult();
}
goods.setUpdateTime(new Date());
if (goodsMapper.updateByPrimaryKeySelective(goods) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public NewBeeMallGoods getNewBeeMallGoodsById(Long id) {
NewBeeMallGoods newBeeMallGoods = goodsMapper.selectByPrimaryKey(id);
if (newBeeMallGoods == null) {
NewBeeMallException.fail(ServiceResultEnum.GOODS_NOT_EXIST.getResult());
}
return newBeeMallGoods;
}
@Override
public List getNewBeeMallGoodsByIds(List goodsIds) {
return goodsMapper.selectByPrimaryKeys(goodsIds);
}
@Override
public Boolean batchUpdateSellStatus(Long[] ids, int sellStatus) {
return goodsMapper.batchUpdateSellStatus(ids, sellStatus) > 0;
}
@Override
public PageResult searchNewBeeMallGoods(PageQueryUtil pageUtil) {
List goodsList = goodsMapper.findNewBeeMallGoodsListBySearch(pageUtil);
int total = goodsMapper.getTotalNewBeeMallGoodsBySearch(pageUtil);
List newBeeMallSearchGoodsVOS = new ArrayList<>();
if (!CollectionUtils.isEmpty(goodsList)) {
newBeeMallSearchGoodsVOS = BeanUtil.copyList(goodsList, NewBeeMallSearchGoodsVO.class);
for (NewBeeMallSearchGoodsVO newBeeMallSearchGoodsVO : newBeeMallSearchGoodsVOS) {
String goodsName = newBeeMallSearchGoodsVO.getGoodsName();
String goodsIntro = newBeeMallSearchGoodsVO.getGoodsIntro();
// 字符串过长导致文字超出的问题
if (goodsName.length() > 28) {
goodsName = goodsName.substring(0, 28) + "...";
newBeeMallSearchGoodsVO.setGoodsName(goodsName);
}
if (goodsIntro.length() > 30) {
goodsIntro = goodsIntro.substring(0, 30) + "...";
newBeeMallSearchGoodsVO.setGoodsIntro(goodsIntro);
}
}
}
PageResult pageResult = new PageResult(newBeeMallSearchGoodsVOS, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public Boolean updateStockNum(List stockNumDTOS) {
return goodsMapper.updateStockNum(stockNumDTOS) > 0;
}
}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/resources/application.properties
================================================
server.port=29010
# 服务名称
spring.application.name=newbee-mall-cloud-goods-service
# Nacos地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# Nacos登录用户名(默认为nacos,生产环境一定要修改)
spring.cloud.nacos.username=nacos
# Nacos登录密码(默认为nacos,生产环境一定要修改)
spring.cloud.nacos.password=nacos
# datasource config (MySQL)
spring.datasource.name=newbee-mall-cloud-goods-datasource
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/newbee_mall_cloud_goods_db?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=123456
# 指定数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# Druid 数据源设置
# 初始化时建立数据库连接的个数
spring.datasource.initialSize=10
# 最小连接池数量
spring.datasource.minIdle=5
# 最大连接池数量
spring.datasource.maxActive=30
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
# 用来检测连接是否有效的SQL语句
spring.datasource.validationQuery=SELECT 1
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# mybatis config
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
# openfeign config
feign.client.config.default.connectTimeout=2000
feign.client.config.default.readTimeout=5000
feign.compression.request.enabled=true
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=1024
feign.compression.response.enabled=true
# sentinel config
spring.cloud.sentinel.transport.port=8910
spring.cloud.sentinel.transport.clientIp=127.0.0.1
# 指定Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=127.0.0.1:9113
# 演示需要,开启OpenFeign和当前项目中的DEBUG级别日志
#logging.level.ltd.user.cloud.newbee.openfeign=debug
#logging.level.ltd.goods.cloud.newbee=debug
# Sleuth采样率,取值范围为[0.1,1.0],值越大收集越及时,但性能影响也越大
spring.sleuth.sampler.probability=1.0
# 每秒数据采集量,最多n条/秒Trace
spring.sleuth.sampler.rate=500
spring.zipkin.base-url=http://localhost:9411
seata.enabled=true
seata.application-id=goods-server
#事务分组配置
seata.tx-service-group=newbee_cloud_save_order_group
service.vgroupMapping.newbee_cloud_save_order_group=default
#连接Nacos服务中心的配置信息
seata.registry.type=nacos
seata.registry.nacos.application=seata-server
seata.registry.nacos.server-addr=127.0.0.1:8848
seata.registry.nacos.username=nacos
seata.registry.nacos.password=nacos
seata.registry.nacos.group=DEFAULT_GROUP
seata.registry.nacos.cluster=default
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/resources/logback.xml
================================================
${APP_NAME}
INFO
${CONSOLE_LOG_PATTERN}
utf8
192.168.110.57:4560
INFO
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/resources/mapper/GoodsCategoryMapper.xml
================================================
category_id, category_level, parent_id, category_name, category_rank, is_deleted,
create_time, create_user, update_time, update_user
update tb_newbee_mall_goods_category set is_deleted=1
where category_id = #{categoryId,jdbcType=BIGINT} and is_deleted=0
update tb_newbee_mall_goods_category
set is_deleted=1 where category_id in
#{id}
insert into tb_newbee_mall_goods_category (category_id, category_level, parent_id,
category_name, category_rank, is_deleted,
create_time, create_user, update_time,
update_user)
values (#{categoryId,jdbcType=BIGINT}, #{categoryLevel,jdbcType=TINYINT}, #{parentId,jdbcType=BIGINT},
#{categoryName,jdbcType=VARCHAR}, #{categoryRank,jdbcType=INTEGER}, #{isDeleted,jdbcType=TINYINT},
#{createTime,jdbcType=TIMESTAMP}, #{createUser,jdbcType=INTEGER}, #{updateTime,jdbcType=TIMESTAMP},
#{updateUser,jdbcType=INTEGER})
insert into tb_newbee_mall_goods_category
category_id,
category_level,
parent_id,
category_name,
category_rank,
is_deleted,
create_time,
create_user,
update_time,
update_user,
#{categoryId,jdbcType=BIGINT},
#{categoryLevel,jdbcType=TINYINT},
#{parentId,jdbcType=BIGINT},
#{categoryName,jdbcType=VARCHAR},
#{categoryRank,jdbcType=INTEGER},
#{isDeleted,jdbcType=TINYINT},
#{createTime,jdbcType=TIMESTAMP},
#{createUser,jdbcType=INTEGER},
#{updateTime,jdbcType=TIMESTAMP},
#{updateUser,jdbcType=INTEGER},
update tb_newbee_mall_goods_category
category_level = #{categoryLevel,jdbcType=TINYINT},
parent_id = #{parentId,jdbcType=BIGINT},
category_name = #{categoryName,jdbcType=VARCHAR},
category_rank = #{categoryRank,jdbcType=INTEGER},
is_deleted = #{isDeleted,jdbcType=TINYINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
create_user = #{createUser,jdbcType=INTEGER},
update_time = #{updateTime,jdbcType=TIMESTAMP},
update_user = #{updateUser,jdbcType=INTEGER},
where category_id = #{categoryId,jdbcType=BIGINT}
update tb_newbee_mall_goods_category
set category_level = #{categoryLevel,jdbcType=TINYINT},
parent_id = #{parentId,jdbcType=BIGINT},
category_name = #{categoryName,jdbcType=VARCHAR},
category_rank = #{categoryRank,jdbcType=INTEGER},
is_deleted = #{isDeleted,jdbcType=TINYINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
create_user = #{createUser,jdbcType=INTEGER},
update_time = #{updateTime,jdbcType=TIMESTAMP},
update_user = #{updateUser,jdbcType=INTEGER}
where category_id = #{categoryId,jdbcType=BIGINT}
================================================
FILE: newbee-mall-cloud-goods-service/newbee-mall-cloud-goods-web/src/main/resources/mapper/NewBeeMallGoodsMapper.xml
================================================
goods_id, goods_name, goods_intro,goods_category_id, goods_cover_img, goods_carousel, original_price,
selling_price, stock_num, tag, goods_sell_status, create_user, create_time, update_user,
update_time
goods_detail_content
INSERT INTO tb_newbee_mall_goods_info(goods_name, goods_intro, goods_category_id,goods_cover_img,
goods_carousel,
goods_detail_content,original_price,
selling_price, stock_num)
VALUES
(#{goods.goodsName},#{goods.goodsIntro},#{goods.goodsCategoryId},#{goods.goodsCoverImg},#{goods.goodsCarousel},#{goods.goodsDetailContent},#{goods.originalPrice},#{goods.sellingPrice},#{goods.stockNum})
update tb_newbee_mall_goods_info set stock_num = stock_num-#{stockNumDTO.goodsCount}
where goods_id = #{stockNumDTO.goodsId} and stock_num>=#{stockNumDTO.goodsCount} and goods_sell_status = 0;
update tb_newbee_mall_goods_info
set goods_sell_status=#{sellStatus},update_time=now() where goods_id in
#{id}
delete from tb_newbee_mall_goods_info
where goods_id = #{goodsId,jdbcType=BIGINT}
insert into tb_newbee_mall_goods_info (goods_id, goods_name, goods_intro,
goods_cover_img, goods_carousel, original_price,
selling_price, stock_num, tag,
goods_sell_status, create_user, create_time,
update_user, update_time, goods_detail_content
)
values (#{goodsId,jdbcType=BIGINT}, #{goodsName,jdbcType=VARCHAR}, #{goodsIntro,jdbcType=VARCHAR},
#{goodsCoverImg,jdbcType=VARCHAR}, #{goodsCarousel,jdbcType=VARCHAR}, #{originalPrice,jdbcType=INTEGER},
#{sellingPrice,jdbcType=INTEGER}, #{stockNum,jdbcType=INTEGER}, #{tag,jdbcType=VARCHAR},
#{goodsSellStatus,jdbcType=TINYINT}, #{createUser,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP},
#{updateUser,jdbcType=INTEGER}, #{updateTime,jdbcType=TIMESTAMP}, #{goodsDetailContent,jdbcType=LONGVARCHAR}
)
insert into tb_newbee_mall_goods_info
goods_id,
goods_name,
goods_intro,
goods_category_id,
goods_cover_img,
goods_carousel,
original_price,
selling_price,
stock_num,
tag,
goods_sell_status,
create_user,
create_time,
update_user,
update_time,
goods_detail_content,
#{goodsId,jdbcType=BIGINT},
#{goodsName,jdbcType=VARCHAR},
#{goodsIntro,jdbcType=VARCHAR},
#{goodsCategoryId,jdbcType=BIGINT},
#{goodsCoverImg,jdbcType=VARCHAR},
#{goodsCarousel,jdbcType=VARCHAR},
#{originalPrice,jdbcType=INTEGER},
#{sellingPrice,jdbcType=INTEGER},
#{stockNum,jdbcType=INTEGER},
#{tag,jdbcType=VARCHAR},
#{goodsSellStatus,jdbcType=TINYINT},
#{createUser,jdbcType=INTEGER},
#{createTime,jdbcType=TIMESTAMP},
#{updateUser,jdbcType=INTEGER},
#{updateTime,jdbcType=TIMESTAMP},
#{goodsDetailContent,jdbcType=LONGVARCHAR},
update tb_newbee_mall_goods_info
goods_name = #{goodsName,jdbcType=VARCHAR},
goods_intro = #{goodsIntro,jdbcType=VARCHAR},
goods_category_id = #{goodsCategoryId,jdbcType=BIGINT},
goods_cover_img = #{goodsCoverImg,jdbcType=VARCHAR},
goods_carousel = #{goodsCarousel,jdbcType=VARCHAR},
original_price = #{originalPrice,jdbcType=INTEGER},
selling_price = #{sellingPrice,jdbcType=INTEGER},
stock_num = #{stockNum,jdbcType=INTEGER},
tag = #{tag,jdbcType=VARCHAR},
goods_sell_status = #{goodsSellStatus,jdbcType=TINYINT},
create_user = #{createUser,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_user = #{updateUser,jdbcType=INTEGER},
update_time = #{updateTime,jdbcType=TIMESTAMP},
goods_detail_content = #{goodsDetailContent,jdbcType=LONGVARCHAR},
where goods_id = #{goodsId,jdbcType=BIGINT}
update tb_newbee_mall_goods_info
set goods_name = #{goodsName,jdbcType=VARCHAR},
goods_intro = #{goodsIntro,jdbcType=VARCHAR},
goods_cover_img = #{goodsCoverImg,jdbcType=VARCHAR},
goods_carousel = #{goodsCarousel,jdbcType=VARCHAR},
original_price = #{originalPrice,jdbcType=INTEGER},
selling_price = #{sellingPrice,jdbcType=INTEGER},
stock_num = #{stockNum,jdbcType=INTEGER},
tag = #{tag,jdbcType=VARCHAR},
goods_sell_status = #{goodsSellStatus,jdbcType=TINYINT},
create_user = #{createUser,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_user = #{updateUser,jdbcType=INTEGER},
update_time = #{updateTime,jdbcType=TIMESTAMP},
goods_detail_content = #{goodsDetailContent,jdbcType=LONGVARCHAR}
where goods_id = #{goodsId,jdbcType=BIGINT}
update tb_newbee_mall_goods_info
set goods_name = #{goodsName,jdbcType=VARCHAR},
goods_intro = #{goodsIntro,jdbcType=VARCHAR},
goods_cover_img = #{goodsCoverImg,jdbcType=VARCHAR},
goods_carousel = #{goodsCarousel,jdbcType=VARCHAR},
original_price = #{originalPrice,jdbcType=INTEGER},
selling_price = #{sellingPrice,jdbcType=INTEGER},
stock_num = #{stockNum,jdbcType=INTEGER},
tag = #{tag,jdbcType=VARCHAR},
goods_sell_status = #{goodsSellStatus,jdbcType=TINYINT},
create_user = #{createUser,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_user = #{updateUser,jdbcType=INTEGER},
update_time = #{updateTime,jdbcType=TIMESTAMP}
where goods_id = #{goodsId,jdbcType=BIGINT}
================================================
FILE: newbee-mall-cloud-goods-service/pom.xml
================================================
4.0.0
ltd.newbee.cloud
newbee-mall-cloud-goods-service
0.0.1-SNAPSHOT
pom
newbee-mall-cloud-goods-service
商品模块
ltd.newbee.cloud
newbee-mall-cloud
0.0.1-SNAPSHOT
1.8
newbee-mall-cloud-goods-web
newbee-mall-cloud-goods-api
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-api/pom.xml
================================================
4.0.0
ltd.order.newbee.cloud
newbee-mall-cloud-order-api
jar
0.0.1-SNAPSHOT
newbee-mall-cloud-order-api
订单服务openfeign
ltd.newbee.cloud
newbee-mall-cloud-order-service
0.0.1-SNAPSHOT
1.8
org.springframework.cloud
spring-cloud-starter-openfeign
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/pom.xml
================================================
4.0.0
ltd.order.newbee.cloud
newbee-mall-cloud-order-web
0.0.1-SNAPSHOT
newbee-mall-cloud-order-web
订单服务
ltd.newbee.cloud
newbee-mall-cloud-order-service
0.0.1-SNAPSHOT
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
org.springframework.boot
spring-boot-starter-validation
org.mybatis.spring.boot
mybatis-spring-boot-starter
com.alibaba.cloud
spring-cloud-starter-alibaba-seata
org.projectlombok
lombok
${lombok.version}
provided
io.springfox
springfox-boot-starter
mysql
mysql-connector-java
runtime
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
org.springframework.cloud
spring-cloud-starter-sleuth
org.springframework.cloud
spring-cloud-sleuth-zipkin
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
org.springframework.cloud
spring-cloud-starter-openfeign
org.springframework.cloud
spring-cloud-starter-loadbalancer
net.logstash.logback
logstash-logback-encoder
${logstash-logback-encoder.version}
ltd.user.newbee.cloud
newbee-mall-cloud-user-api
0.0.1-SNAPSHOT
ltd.goods.newbee.cloud
newbee-mall-cloud-goods-api
0.0.1-SNAPSHOT
ltd.shopcart.newbee.cloud
newbee-mall-cloud-shop-cart-api
0.0.1-SNAPSHOT
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/NewBeeMallCloudOrderServiceApplication.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee;
import ltd.goods.cloud.newbee.openfeign.NewBeeCloudGoodsServiceFeign;
import ltd.shopcart.cloud.newbee.openfeign.NewBeeCloudShopCartServiceFeign;
import ltd.user.cloud.newbee.openfeign.NewBeeCloudUserServiceFeign;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @author 程序员十三
* @qq交流群 791509631
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("ltd.order.cloud.newbee.dao")
@EnableFeignClients(basePackageClasses ={NewBeeCloudUserServiceFeign.class, NewBeeCloudGoodsServiceFeign.class, NewBeeCloudShopCartServiceFeign.class})
public class NewBeeMallCloudOrderServiceApplication {
public static void main(String[] args) {
System.setProperty("nacos.logging.default.config.enabled","false");
SpringApplication.run(NewBeeMallCloudOrderServiceApplication.class, args);
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/config/OpenFeignConfiguration.java
================================================
package ltd.order.cloud.newbee.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenFeignConfiguration {
@Bean
public Logger.Level openFeignLogLevel() {
// 设置OpenFeign日志级别
return Logger.Level.FULL;
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/config/OrderServiceExceptionHandler.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.config;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* 全局异常处理
*/
@RestControllerAdvice
public class OrderServiceExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(OrderServiceExceptionHandler.class);
@ExceptionHandler(BindException.class)
public Object bindException(BindException e) {
log.error("OrderServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(510);
BindingResult bindingResult = e.getBindingResult();
result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
return result;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object bindException(MethodArgumentNotValidException e) {
log.error("OrderServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(510);
BindingResult bindingResult = e.getBindingResult();
result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
return result;
}
@ExceptionHandler(Exception.class)
public Object handleException(Exception e, HttpServletRequest req) {
log.error("OrderServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(500);
//区分是否为自定义异常
if (e instanceof NewBeeMallException) {
result.setMessage(e.getMessage());
if (e.getMessage().equals(ServiceResultEnum.ADMIN_NOT_LOGIN_ERROR.getResult()) || e.getMessage().equals(ServiceResultEnum.ADMIN_TOKEN_EXPIRE_ERROR.getResult())) {
result.setResultCode(419);
}
if (e.getMessage().equals(ServiceResultEnum.NOT_LOGIN_ERROR.getResult()) || e.getMessage().equals(ServiceResultEnum.TOKEN_EXPIRE_ERROR.getResult())) {
result.setResultCode(416);
}
} else {
e.printStackTrace();
result.setMessage("未知异常,请查看控制台日志并检查配置文件。");
}
return result;
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/config/OrderServiceSwagger3Config.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.config;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import ltd.order.cloud.newbee.entity.LoginAdminUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableOpenApi
public class OrderServiceSwagger3Config {
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.ignoredParameterTypes(LoginAdminUser.class, MallUserToken.class)
.select()
.apis(RequestHandlerSelectors.basePackage("ltd.order.cloud.newbee.controller"))
.paths(PathSelectors.any())
.build()
.globalRequestParameters(getGlobalRequestParameters());
}
//生成全局通用参数
private List getGlobalRequestParameters() {
List parameters = new ArrayList<>();
parameters.add(new RequestParameterBuilder()
.name("token")
.description("登录认证token")
.required(false) // 非必传
.in(ParameterType.HEADER) //请求头中的参数,其它类型可以点进ParameterType类中查看
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.build());
return parameters;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("newbee-mall-cloud-order-service接口文档")
.description("swagger接口文档")
.version("2.0")
.build();
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/config/OrderServiceWebMvcConfigurer.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.config;
import com.alibaba.cloud.sentinel.SentinelProperties;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import ltd.order.cloud.newbee.config.handler.TokenToAdminUserMethodArgumentResolver;
import ltd.order.cloud.newbee.config.handler.TokenToMallUserMethodArgumentResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
import java.util.Optional;
@Configuration
public class OrderServiceWebMvcConfigurer extends WebMvcConfigurationSupport {
private static final Logger log = LoggerFactory.getLogger(OrderServiceWebMvcConfigurer.class);
@Autowired
private SentinelProperties sentinelProperties;
@Autowired
private Optional sentinelWebInterceptorOptional;
@Autowired
@Lazy
private TokenToAdminUserMethodArgumentResolver tokenToAdminUserMethodArgumentResolver;
@Autowired
@Lazy
private TokenToMallUserMethodArgumentResolver tokenToMallUserMethodArgumentResolver;
/**
* @param argumentResolvers
* @tip @TokenToAdminUser 注解处理方法
*/
public void addArgumentResolvers(List argumentResolvers) {
argumentResolvers.add(tokenToAdminUserMethodArgumentResolver);
argumentResolvers.add(tokenToMallUserMethodArgumentResolver);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.
addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
.resourceChain(false);
}
public void addInterceptors(InterceptorRegistry registry) {
if (this.sentinelWebInterceptorOptional.isPresent()) {
SentinelProperties.Filter filterConfig = this.sentinelProperties.getFilter();
registry.addInterceptor((HandlerInterceptor) this.sentinelWebInterceptorOptional.get()).order(filterConfig.getOrder()).addPathPatterns(filterConfig.getUrlPatterns());
log.info("[Sentinel Starter] register SentinelWebInterceptor with urlPatterns: {}.", filterConfig.getUrlPatterns());
}
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/config/SeataProxyConfiguration.java
================================================
package ltd.order.cloud.newbee.config;
import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
@Configuration
public class SeataProxyConfiguration {
//创建Druid数据源
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource() {
return new DruidDataSource();
}
//创建DataSource数据源代理
@Bean("dataSource")
@Primary
public DataSource dataSourceDelegation(DruidDataSource druidDataSource) {
return new DataSourceProxy(druidDataSource);
}
/*
* 解决druid 日志报错:discard long time none received connection:xxx
* */
@PostConstruct
public void setProperties(){
System.setProperty("druid.mysql.usePingMethod","false");
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/config/annotation/TokenToAdminUser.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.config.annotation;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TokenToAdminUser {
/**
* 当前用户在request中的名字
*
* @return
*/
String value() default "adminUser";
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/config/annotation/TokenToMallUser.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.config.annotation;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TokenToMallUser {
/**
* 当前用户在request中的名字
*
* @return
*/
String value() default "user";
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/config/handler/TokenToAdminUserMethodArgumentResolver.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.config.handler;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.order.cloud.newbee.config.annotation.TokenToAdminUser;
import ltd.order.cloud.newbee.entity.LoginAdminUser;
import ltd.user.cloud.newbee.openfeign.NewBeeCloudUserServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.LinkedHashMap;
@Component
public class TokenToAdminUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
private NewBeeCloudUserServiceFeign newBeeCloudUserService;
public TokenToAdminUserMethodArgumentResolver() {
}
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(TokenToAdminUser.class)) {
return true;
}
return false;
}
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
if (parameter.getParameterAnnotation(TokenToAdminUser.class) instanceof TokenToAdminUser) {
String token = webRequest.getHeader("token");
if (null != token && !"".equals(token) && token.length() == 32) {
// 通过用户中心获取用户信息
Result result = newBeeCloudUserService.getAdminUserByToken(token);
if (result == null || result.getResultCode() != 200 || result.getData() == null) {
NewBeeMallException.fail(ServiceResultEnum.ADMIN_NOT_LOGIN_ERROR.getResult());
}
LinkedHashMap resultData = (LinkedHashMap) result.getData();
// 将返回的字段封装到LoginAdminUser对象中
LoginAdminUser loginAdminUser = new LoginAdminUser();
loginAdminUser.setAdminUserId(Long.valueOf(resultData.get("adminUserId").toString()));
loginAdminUser.setLoginUserName((String) resultData.get("loginUserName"));
loginAdminUser.setNickName((String) resultData.get("nickName"));
loginAdminUser.setLocked(Byte.valueOf(resultData.get("locked").toString()));
return loginAdminUser;
} else {
NewBeeMallException.fail(ServiceResultEnum.ADMIN_NOT_LOGIN_ERROR.getResult());
}
}
return null;
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/config/handler/TokenToMallUserMethodArgumentResolver.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.config.handler;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import ltd.order.cloud.newbee.config.annotation.TokenToMallUser;
import ltd.user.cloud.newbee.dto.MallUserDTO;
import ltd.user.cloud.newbee.openfeign.NewBeeCloudUserServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@Component
public class TokenToMallUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
private NewBeeCloudUserServiceFeign newBeeCloudUserService;
public TokenToMallUserMethodArgumentResolver() {
}
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(TokenToMallUser.class)) {
return true;
}
return false;
}
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
if (parameter.getParameterAnnotation(TokenToMallUser.class) instanceof TokenToMallUser) {
String token = webRequest.getHeader("token");
if (null != token && !"".equals(token) && token.length() == 32) {
Result result = newBeeCloudUserService.getMallUserByToken(token);
if (result == null || result.getResultCode() != 200 || result.getData() == null) {
NewBeeMallException.fail(ServiceResultEnum.TOKEN_EXPIRE_ERROR.getResult());
}
MallUserToken mallUserToken = new MallUserToken();
mallUserToken.setToken(token);
mallUserToken.setUserId(result.getData().getUserId());
return mallUserToken;
} else {
NewBeeMallException.fail(ServiceResultEnum.NOT_LOGIN_ERROR.getResult());
}
}
return null;
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/NewBeeAdminOrderController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.order.cloud.newbee.config.annotation.TokenToAdminUser;
import ltd.order.cloud.newbee.controller.param.BatchIdParam;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallOrderDetailVO;
import ltd.order.cloud.newbee.entity.LoginAdminUser;
import ltd.order.cloud.newbee.service.NewBeeMallOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@RestController
@Api(value = "v1", tags = "后台管理系统订单模块接口")
@RequestMapping("/orders/admin")
public class NewBeeAdminOrderController {
private static final Logger logger = LoggerFactory.getLogger(NewBeeAdminOrderController.class);
@Resource
private NewBeeMallOrderService newBeeMallOrderService;
/**
* 列表
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ApiOperation(value = "订单列表", notes = "可根据订单号和订单状态筛选")
public Result list(@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
@RequestParam(required = false) @ApiParam(value = "每页条数") Integer pageSize,
@RequestParam(required = false) @ApiParam(value = "订单号") String orderNo,
@RequestParam(required = false) @ApiParam(value = "订单状态") Integer orderStatus, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (pageNumber == null || pageNumber < 1 || pageSize == null || pageSize < 10) {
return ResultGenerator.genFailResult("分页参数异常!");
}
Map params = new HashMap(8);
params.put("page", pageNumber);
params.put("limit", pageSize);
if (StringUtils.hasText(orderNo)) {
params.put("orderNo", orderNo);
}
if (orderStatus != null) {
params.put("orderStatus", orderStatus);
}
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallOrderService.getNewBeeMallOrdersPage(pageUtil));
}
@GetMapping("/detail/{orderId}")
@ApiOperation(value = "订单详情接口", notes = "传参为订单号")
public Result orderDetailPage(@ApiParam(value = "订单号") @PathVariable("orderId") Long orderId, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
return ResultGenerator.genSuccessResult(newBeeMallOrderService.getOrderDetailByOrderId(orderId));
}
/**
* 配货
*/
@RequestMapping(value = "/checkDone", method = RequestMethod.PUT)
@ApiOperation(value = "修改订单状态为配货成功", notes = "批量修改")
public Result checkDone(@RequestBody BatchIdParam batchIdParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (batchIdParam==null||batchIdParam.getIds().length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallOrderService.checkDone(batchIdParam.getIds());
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 出库
*/
@RequestMapping(value = "/checkOut", method = RequestMethod.PUT)
@ApiOperation(value = "修改订单状态为已出库", notes = "批量修改")
public Result checkOut(@RequestBody BatchIdParam batchIdParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (batchIdParam==null||batchIdParam.getIds().length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallOrderService.checkOut(batchIdParam.getIds());
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 关闭订单
*/
@RequestMapping(value = "/close", method = RequestMethod.PUT)
@ApiOperation(value = "修改订单状态为商家关闭", notes = "批量修改")
public Result closeOrder(@RequestBody BatchIdParam batchIdParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (batchIdParam==null||batchIdParam.getIds().length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallOrderService.closeOrder(batchIdParam.getIds());
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/NewBeeMallOrderController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import ltd.order.cloud.newbee.config.annotation.TokenToMallUser;
import ltd.order.cloud.newbee.controller.param.SaveOrderParam;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallOrderDetailVO;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallOrderListVO;
import ltd.order.cloud.newbee.entity.MallUserAddress;
import ltd.order.cloud.newbee.service.NewBeeMallOrderService;
import ltd.order.cloud.newbee.service.NewBeeMallUserAddressService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@Api(value = "v1", tags = "新蜂商城订单操作相关接口")
@RequestMapping("/orders/mall")
public class NewBeeMallOrderController {
@Resource
private NewBeeMallOrderService newBeeMallOrderService;
@Resource
private NewBeeMallUserAddressService newBeeMallUserAddressService;
@PostMapping("/saveOrder")
@ApiOperation(value = "生成订单接口", notes = "传参为地址id和待结算的购物项id数组")
public Result saveOrder(@ApiParam(value = "订单参数") @RequestBody SaveOrderParam saveOrderParam, @TokenToMallUser MallUserToken loginMallUserToken) {
if (saveOrderParam == null || saveOrderParam.getCartItemIds() == null || saveOrderParam.getAddressId() == null) {
NewBeeMallException.fail(ServiceResultEnum.PARAM_ERROR.getResult());
}
if (saveOrderParam.getCartItemIds().length < 1) {
NewBeeMallException.fail(ServiceResultEnum.PARAM_ERROR.getResult());
}
MallUserAddress address = newBeeMallUserAddressService.getMallUserAddressById(saveOrderParam.getAddressId());
if (!loginMallUserToken.getUserId().equals(address.getUserId())) {
return ResultGenerator.genFailResult(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
}
//保存订单并返回订单号
String saveOrderResult = newBeeMallOrderService.saveOrder(loginMallUserToken.getUserId(), address, Arrays.asList(saveOrderParam.getCartItemIds()));
Result result = ResultGenerator.genSuccessResult();
result.setData(saveOrderResult);
return result;
}
@GetMapping("/order/{orderNo}")
@ApiOperation(value = "订单详情接口", notes = "传参为订单号")
public Result orderDetailPage(@ApiParam(value = "订单号") @PathVariable("orderNo") String orderNo, @TokenToMallUser MallUserToken loginMallUserToken) {
return ResultGenerator.genSuccessResult(newBeeMallOrderService.getOrderDetailByOrderNo(orderNo, loginMallUserToken.getUserId()));
}
@GetMapping("/order")
@ApiOperation(value = "订单列表接口", notes = "传参为页码")
public Result>> orderList(@ApiParam(value = "页码") @RequestParam(required = false) Integer pageNumber,
@ApiParam(value = "订单状态:0.待支付 1.待确认 2.待发货 3:已发货 4.交易成功") @RequestParam(required = false) Integer status,
@TokenToMallUser MallUserToken loginMallUserToken) {
Map params = new HashMap(8);
if (pageNumber == null || pageNumber < 1) {
pageNumber = 1;
}
params.put("userId", loginMallUserToken.getUserId());
params.put("orderStatus", status);
params.put("page", pageNumber);
params.put("limit", 5);
//封装分页请求参数
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallOrderService.getMyOrders(pageUtil));
}
@PutMapping("/order/{orderNo}/cancel")
@ApiOperation(value = "订单取消接口", notes = "传参为订单号")
public Result cancelOrder(@ApiParam(value = "订单号") @PathVariable("orderNo") String orderNo, @TokenToMallUser MallUserToken loginMallUserToken) {
String cancelOrderResult = newBeeMallOrderService.cancelOrder(orderNo, loginMallUserToken.getUserId());
if (ServiceResultEnum.SUCCESS.getResult().equals(cancelOrderResult)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(cancelOrderResult);
}
}
@PutMapping("/order/{orderNo}/finish")
@ApiOperation(value = "确认收货接口", notes = "传参为订单号")
public Result finishOrder(@ApiParam(value = "订单号") @PathVariable("orderNo") String orderNo, @TokenToMallUser MallUserToken loginMallUserToken) {
String finishOrderResult = newBeeMallOrderService.finishOrder(orderNo, loginMallUserToken.getUserId());
if (ServiceResultEnum.SUCCESS.getResult().equals(finishOrderResult)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(finishOrderResult);
}
}
@GetMapping("/paySuccess")
@ApiOperation(value = "模拟支付成功回调的接口", notes = "传参为订单号和支付方式")
public Result paySuccess(@ApiParam(value = "订单号") @RequestParam("orderNo") String orderNo, @ApiParam(value = "支付方式") @RequestParam("payType") int payType) {
String payResult = newBeeMallOrderService.paySuccess(orderNo, payType);
if (ServiceResultEnum.SUCCESS.getResult().equals(payResult)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(payResult);
}
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/NewBeeMallUserAddressController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.order.cloud.newbee.config.annotation.TokenToMallUser;
import ltd.order.cloud.newbee.controller.param.SaveMallUserAddressParam;
import ltd.order.cloud.newbee.controller.param.UpdateMallUserAddressParam;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallUserAddressVO;
import ltd.order.cloud.newbee.entity.MallUserAddress;
import ltd.order.cloud.newbee.service.NewBeeMallUserAddressService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@Api(value = "v1", tags = "新蜂商城个人地址相关接口")
@RequestMapping("/mall")
public class NewBeeMallUserAddressController {
@Resource
private NewBeeMallUserAddressService mallUserAddressService;
@GetMapping("/address")
@ApiOperation(value = "我的收货地址列表", notes = "")
public Result> addressList(@TokenToMallUser MallUserToken loginMallUserToken) {
return ResultGenerator.genSuccessResult(mallUserAddressService.getMyAddresses(loginMallUserToken.getUserId()));
}
@PostMapping("/address")
@ApiOperation(value = "添加地址", notes = "")
public Result saveUserAddress(@RequestBody SaveMallUserAddressParam saveMallUserAddressParam,
@TokenToMallUser MallUserToken loginMallUserToken) {
MallUserAddress userAddress = new MallUserAddress();
BeanUtil.copyProperties(saveMallUserAddressParam, userAddress);
userAddress.setUserId(loginMallUserToken.getUserId());
Boolean saveResult = mallUserAddressService.saveUserAddress(userAddress);
//添加成功
if (saveResult) {
return ResultGenerator.genSuccessResult();
}
//添加失败
return ResultGenerator.genFailResult("添加失败");
}
@PutMapping("/address")
@ApiOperation(value = "修改地址", notes = "")
public Result updateMallUserAddress(@RequestBody UpdateMallUserAddressParam updateMallUserAddressParam,
@TokenToMallUser MallUserToken loginMallUserToken) {
MallUserAddress mallUserAddressById = mallUserAddressService.getMallUserAddressById(updateMallUserAddressParam.getAddressId());
if (!loginMallUserToken.getUserId().equals(mallUserAddressById.getUserId())) {
return ResultGenerator.genFailResult(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
}
MallUserAddress userAddress = new MallUserAddress();
BeanUtil.copyProperties(updateMallUserAddressParam, userAddress);
userAddress.setUserId(loginMallUserToken.getUserId());
Boolean updateResult = mallUserAddressService.updateMallUserAddress(userAddress);
//修改成功
if (updateResult) {
return ResultGenerator.genSuccessResult();
}
//修改失败
return ResultGenerator.genFailResult("修改失败");
}
@GetMapping("/address/{addressId}")
@ApiOperation(value = "获取收货地址详情", notes = "传参为地址id")
public Result getMallUserAddress(@PathVariable("addressId") Long addressId,
@TokenToMallUser MallUserToken loginMallUserToken) {
MallUserAddress mallUserAddressById = mallUserAddressService.getMallUserAddressById(addressId);
NewBeeMallUserAddressVO newBeeMallUserAddressVO = new NewBeeMallUserAddressVO();
BeanUtil.copyProperties(mallUserAddressById, newBeeMallUserAddressVO);
if (!loginMallUserToken.getUserId().equals(mallUserAddressById.getUserId())) {
return ResultGenerator.genFailResult(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
}
return ResultGenerator.genSuccessResult(newBeeMallUserAddressVO);
}
@GetMapping("/address/default")
@ApiOperation(value = "获取默认收货地址", notes = "无传参")
public Result getDefaultMallUserAddress(@TokenToMallUser MallUserToken loginMallUserToken) {
MallUserAddress mallUserAddressById = mallUserAddressService.getMyDefaultAddressByUserId(loginMallUserToken.getUserId());
return ResultGenerator.genSuccessResult(mallUserAddressById);
}
@DeleteMapping("/address/{addressId}")
@ApiOperation(value = "删除收货地址", notes = "传参为地址id")
public Result deleteAddress(@PathVariable("addressId") Long addressId,
@TokenToMallUser MallUserToken loginMallUserToken) {
MallUserAddress mallUserAddressById = mallUserAddressService.getMallUserAddressById(addressId);
if (!loginMallUserToken.getUserId().equals(mallUserAddressById.getUserId())) {
return ResultGenerator.genFailResult(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
}
Boolean deleteResult = mallUserAddressService.deleteById(addressId);
//删除成功
if (deleteResult) {
return ResultGenerator.genSuccessResult();
}
//删除失败
return ResultGenerator.genFailResult(ServiceResultEnum.OPERATE_ERROR.getResult());
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/param/BatchIdParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller.param;
import lombok.Data;
import java.io.Serializable;
@Data
public class BatchIdParam implements Serializable {
//id数组
Long[] ids;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/param/SaveMallUserAddressParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 添加收货地址param
*/
@Data
public class SaveMallUserAddressParam {
@ApiModelProperty("收件人名称")
private String userName;
@ApiModelProperty("收件人联系方式")
private String userPhone;
@ApiModelProperty("是否默认地址 0-不是 1-是")
private Byte defaultFlag;
@ApiModelProperty("省")
private String provinceName;
@ApiModelProperty("市")
private String cityName;
@ApiModelProperty("区/县")
private String regionName;
@ApiModelProperty("详细地址")
private String detailAddress;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/param/SaveOrderParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 保存订单param
*/
@Data
public class SaveOrderParam implements Serializable {
@ApiModelProperty("订单项id数组")
private Long[] cartItemIds;
@ApiModelProperty("地址id")
private Long addressId;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/param/UpdateMallUserAddressParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 修改收货地址param
*/
@Data
public class UpdateMallUserAddressParam {
@ApiModelProperty("地址id")
private Long addressId;
@ApiModelProperty("用户id")
private Long userId;
@ApiModelProperty("收件人名称")
private String userName;
@ApiModelProperty("收件人联系方式")
private String userPhone;
@ApiModelProperty("是否默认地址 0-不是 1-是")
private Byte defaultFlag;
@ApiModelProperty("省")
private String provinceName;
@ApiModelProperty("市")
private String cityName;
@ApiModelProperty("区/县")
private String regionName;
@ApiModelProperty("详细地址")
private String detailAddress;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/vo/NewBeeMallOrderDetailVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 订单详情页页面VO
*/
@Data
public class NewBeeMallOrderDetailVO implements Serializable {
@ApiModelProperty("订单号")
private String orderNo;
@ApiModelProperty("订单价格")
private Integer totalPrice;
@ApiModelProperty("订单支付状态码")
private Byte payStatus;
@ApiModelProperty("订单支付方式")
private Byte payType;
@ApiModelProperty("订单支付方式")
private String payTypeString;
@ApiModelProperty("订单支付时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date payTime;
@ApiModelProperty("订单状态码")
private Byte orderStatus;
@ApiModelProperty("订单状态")
private String orderStatusString;
@ApiModelProperty("创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@ApiModelProperty("订单项列表")
private List newBeeMallOrderItemVOS;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/vo/NewBeeMallOrderItemVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 订单详情页页面订单项VO
*/
@Data
public class NewBeeMallOrderItemVO implements Serializable {
@ApiModelProperty("商品id")
private Long goodsId;
@ApiModelProperty("商品数量")
private Integer goodsCount;
@ApiModelProperty("商品名称")
private String goodsName;
@ApiModelProperty("商品图片")
private String goodsCoverImg;
@ApiModelProperty("商品价格")
private Integer sellingPrice;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/vo/NewBeeMallOrderListVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 订单列表页面VO
*/
@Data
public class NewBeeMallOrderListVO implements Serializable {
private Long orderId;
@ApiModelProperty("订单号")
private String orderNo;
@ApiModelProperty("订单价格")
private Integer totalPrice;
@ApiModelProperty("订单支付方式")
private Byte payType;
@ApiModelProperty("订单状态码")
private Byte orderStatus;
@ApiModelProperty("订单状态")
private String orderStatusString;
@ApiModelProperty("创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@ApiModelProperty("订单项列表")
private List newBeeMallOrderItemVOS;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/controller/vo/NewBeeMallUserAddressVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 收货地址VO
*/
@Data
public class NewBeeMallUserAddressVO {
@ApiModelProperty("地址id")
private Long addressId;
@ApiModelProperty("用户id")
private Long userId;
@ApiModelProperty("收件人名称")
private String userName;
@ApiModelProperty("收件人联系方式")
private String userPhone;
@ApiModelProperty("是否默认地址 0-不是 1-是")
private Byte defaultFlag;
@ApiModelProperty("省")
private String provinceName;
@ApiModelProperty("市")
private String cityName;
@ApiModelProperty("区/县")
private String regionName;
@ApiModelProperty("详细地址")
private String detailAddress;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/dao/MallUserAddressMapper.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.dao;
import ltd.order.cloud.newbee.entity.MallUserAddress;
import java.util.List;
public interface MallUserAddressMapper {
int deleteByPrimaryKey(Long addressId);
int insert(MallUserAddress record);
int insertSelective(MallUserAddress record);
MallUserAddress selectByPrimaryKey(Long addressId);
MallUserAddress getMyDefaultAddress(Long userId);
List findMyAddressList(Long userId);
int updateByPrimaryKeySelective(MallUserAddress record);
int updateByPrimaryKey(MallUserAddress record);
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/dao/NewBeeMallOrderAddressMapper.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.dao;
import ltd.order.cloud.newbee.entity.NewBeeMallOrderAddress;
public interface NewBeeMallOrderAddressMapper {
int deleteByPrimaryKey(Long orderId);
int insert(NewBeeMallOrderAddress record);
int insertSelective(NewBeeMallOrderAddress record);
NewBeeMallOrderAddress selectByPrimaryKey(Long orderId);
int updateByPrimaryKeySelective(NewBeeMallOrderAddress record);
int updateByPrimaryKey(NewBeeMallOrderAddress record);
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/dao/NewBeeMallOrderItemMapper.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.dao;
import ltd.order.cloud.newbee.entity.NewBeeMallOrderItem;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface NewBeeMallOrderItemMapper {
int deleteByPrimaryKey(Long orderItemId);
int insert(NewBeeMallOrderItem record);
int insertSelective(NewBeeMallOrderItem record);
NewBeeMallOrderItem selectByPrimaryKey(Long orderItemId);
/**
* 根据订单id获取订单项列表
*
* @param orderId
* @return
*/
List selectByOrderId(Long orderId);
/**
* 根据订单ids获取订单项列表
*
* @param orderIds
* @return
*/
List selectByOrderIds(@Param("orderIds") List orderIds);
/**
* 批量insert订单项数据
*
* @param orderItems
* @return
*/
int insertBatch(@Param("orderItems") List orderItems);
int updateByPrimaryKeySelective(NewBeeMallOrderItem record);
int updateByPrimaryKey(NewBeeMallOrderItem record);
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/dao/NewBeeMallOrderMapper.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.dao;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.order.cloud.newbee.entity.NewBeeMallOrder;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface NewBeeMallOrderMapper {
int deleteByPrimaryKey(Long orderId);
int insert(NewBeeMallOrder record);
int insertSelective(NewBeeMallOrder record);
NewBeeMallOrder selectByPrimaryKey(Long orderId);
NewBeeMallOrder selectByOrderNo(String orderNo);
int updateByPrimaryKeySelective(NewBeeMallOrder record);
int updateByPrimaryKey(NewBeeMallOrder record);
List findNewBeeMallOrderList(PageQueryUtil pageUtil);
int getTotalNewBeeMallOrders(PageQueryUtil pageUtil);
List selectByPrimaryKeys(@Param("orderIds") List orderIds);
int checkOut(@Param("orderIds") List orderIds);
int closeOrder(@Param("orderIds") List orderIds, @Param("orderStatus") int orderStatus);
int checkDone(@Param("orderIds") List asList);
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/entity/LoginAdminUser.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.entity;
import lombok.Data;
@Data
public class LoginAdminUser {
private Long adminUserId;
private String loginUserName;
private String loginPassword;
private String nickName;
private Byte locked;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/entity/MallUserAddress.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.entity;
import lombok.Data;
import java.util.Date;
@Data
public class MallUserAddress {
private Long addressId;
private Long userId;
private String userName;
private String userPhone;
private Byte defaultFlag;
private String provinceName;
private String cityName;
private String regionName;
private String detailAddress;
private Byte isDeleted;
private Date createTime;
private Date updateTime;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/entity/NewBeeMallOrder.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class NewBeeMallOrder {
private Long orderId;
private String orderNo;
private Long userId;
private Integer totalPrice;
private Byte payStatus;
private Byte payType;
private Date payTime;
private Byte orderStatus;
private String extraInfo;
private Byte isDeleted;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/entity/NewBeeMallOrderAddress.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.entity;
import lombok.Data;
@Data
public class NewBeeMallOrderAddress {
private Long orderId;
private String userName;
private String userPhone;
private String provinceName;
private String cityName;
private String regionName;
private String detailAddress;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/entity/NewBeeMallOrderItem.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.entity;
import lombok.Data;
import java.util.Date;
@Data
public class NewBeeMallOrderItem {
private Long orderItemId;
private Long orderId;
private Long goodsId;
private String goodsName;
private String goodsCoverImg;
private Integer sellingPrice;
private Integer goodsCount;
private Date createTime;
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/service/NewBeeMallOrderService.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.service;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallOrderDetailVO;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallOrderItemVO;
import ltd.order.cloud.newbee.entity.MallUserAddress;
import ltd.order.cloud.newbee.entity.NewBeeMallOrder;
import java.util.List;
public interface NewBeeMallOrderService {
/**
* 获取订单详情
*
* @param orderId
* @return
*/
NewBeeMallOrderDetailVO getOrderDetailByOrderId(Long orderId);
/**
* 获取订单详情
*
* @param orderNo
* @param userId
* @return
*/
NewBeeMallOrderDetailVO getOrderDetailByOrderNo(String orderNo, Long userId);
/**
* 我的订单列表
*
* @param pageUtil
* @return
*/
PageResult getMyOrders(PageQueryUtil pageUtil);
/**
* 手动取消订单
*
* @param orderNo
* @param userId
* @return
*/
String cancelOrder(String orderNo, Long userId);
/**
* 确认收货
*
* @param orderNo
* @param userId
* @return
*/
String finishOrder(String orderNo, Long userId);
String paySuccess(String orderNo, int payType);
/**
* 生成订单
* @param mallUserId
* @param address
* @param cartItemIds
* @return
*/
String saveOrder(Long mallUserId, MallUserAddress address, List cartItemIds);
/**
* 后台分页
*
* @param pageUtil
* @return
*/
PageResult getNewBeeMallOrdersPage(PageQueryUtil pageUtil);
/**
* 订单信息修改
*
* @param newBeeMallOrder
* @return
*/
String updateOrderInfo(NewBeeMallOrder newBeeMallOrder);
/**
* 配货
*
* @param ids
* @return
*/
String checkDone(Long[] ids);
/**
* 出库
*
* @param ids
* @return
*/
String checkOut(Long[] ids);
/**
* 关闭订单
*
* @param ids
* @return
*/
String closeOrder(Long[] ids);
List getOrderItems(Long orderId);
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/service/NewBeeMallUserAddressService.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.service;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallUserAddressVO;
import ltd.order.cloud.newbee.entity.MallUserAddress;
import java.util.List;
public interface NewBeeMallUserAddressService {
/**
* 获取我的收货地址
*
* @param userId
* @return
*/
List getMyAddresses(Long userId);
/**
* 保存收货地址
*
* @param mallUserAddress
* @return
*/
Boolean saveUserAddress(MallUserAddress mallUserAddress);
/**
* 修改收货地址
*
* @param mallUserAddress
* @return
*/
Boolean updateMallUserAddress(MallUserAddress mallUserAddress);
/**
* 获取收货地址详情
*
* @param addressId
* @return
*/
MallUserAddress getMallUserAddressById(Long addressId);
/**
* 获取我的默认收货地址
*
* @param userId
* @return
*/
MallUserAddress getMyDefaultAddressByUserId(Long userId);
/**
* 删除收货地址
*
* @param addressId
* @return
*/
Boolean deleteById(Long addressId);
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/service/impl/NewBeeMallOrderServiceImpl.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.service.impl;
import io.seata.spring.annotation.GlobalTransactional;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.enums.NewBeeMallOrderStatusEnum;
import ltd.common.cloud.newbee.enums.PayStatusEnum;
import ltd.common.cloud.newbee.enums.PayTypeEnum;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.common.cloud.newbee.util.NumberUtil;
import ltd.goods.cloud.newbee.dto.NewBeeMallGoodsDTO;
import ltd.goods.cloud.newbee.dto.StockNumDTO;
import ltd.goods.cloud.newbee.dto.UpdateStockNumDTO;
import ltd.goods.cloud.newbee.openfeign.NewBeeCloudGoodsServiceFeign;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallOrderDetailVO;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallOrderItemVO;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallOrderListVO;
import ltd.order.cloud.newbee.dao.NewBeeMallOrderAddressMapper;
import ltd.order.cloud.newbee.dao.NewBeeMallOrderItemMapper;
import ltd.order.cloud.newbee.dao.NewBeeMallOrderMapper;
import ltd.order.cloud.newbee.entity.MallUserAddress;
import ltd.order.cloud.newbee.entity.NewBeeMallOrder;
import ltd.order.cloud.newbee.entity.NewBeeMallOrderAddress;
import ltd.order.cloud.newbee.entity.NewBeeMallOrderItem;
import ltd.order.cloud.newbee.service.NewBeeMallOrderService;
import ltd.shopcart.cloud.newbee.dto.NewBeeMallShoppingCartItemDTO;
import ltd.shopcart.cloud.newbee.openfeign.NewBeeCloudShopCartServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy;
@Service
public class NewBeeMallOrderServiceImpl implements NewBeeMallOrderService {
@Autowired
private NewBeeMallOrderMapper newBeeMallOrderMapper;
@Autowired
private NewBeeMallOrderItemMapper newBeeMallOrderItemMapper;
@Autowired
private NewBeeMallOrderAddressMapper newBeeMallOrderAddressMapper;
@Autowired
private NewBeeCloudGoodsServiceFeign goodsService;
@Autowired
private NewBeeCloudShopCartServiceFeign shopCartService;
@Override
public NewBeeMallOrderDetailVO getOrderDetailByOrderId(Long orderId) {
NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByPrimaryKey(orderId);
if (newBeeMallOrder == null) {
NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
}
List orderItems = newBeeMallOrderItemMapper.selectByOrderId(newBeeMallOrder.getOrderId());
//获取订单项数据
if (!CollectionUtils.isEmpty(orderItems)) {
List newBeeMallOrderItemVOS = BeanUtil.copyList(orderItems, NewBeeMallOrderItemVO.class);
NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = new NewBeeMallOrderDetailVO();
BeanUtil.copyProperties(newBeeMallOrder, newBeeMallOrderDetailVO);
newBeeMallOrderDetailVO.setOrderStatusString(NewBeeMallOrderStatusEnum.getNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderDetailVO.getOrderStatus()).getName());
newBeeMallOrderDetailVO.setPayTypeString(PayTypeEnum.getPayTypeEnumByType(newBeeMallOrderDetailVO.getPayType()).getName());
newBeeMallOrderDetailVO.setNewBeeMallOrderItemVOS(newBeeMallOrderItemVOS);
return newBeeMallOrderDetailVO;
} else {
NewBeeMallException.fail(ServiceResultEnum.ORDER_ITEM_NULL_ERROR.getResult());
return null;
}
}
@Override
public NewBeeMallOrderDetailVO getOrderDetailByOrderNo(String orderNo, Long userId) {
NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(orderNo);
if (newBeeMallOrder == null) {
NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
}
if (!userId.equals(newBeeMallOrder.getUserId())) {
NewBeeMallException.fail(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
}
List orderItems = newBeeMallOrderItemMapper.selectByOrderId(newBeeMallOrder.getOrderId());
//获取订单项数据
if (CollectionUtils.isEmpty(orderItems)) {
NewBeeMallException.fail(ServiceResultEnum.ORDER_ITEM_NOT_EXIST_ERROR.getResult());
}
List newBeeMallOrderItemVOS = BeanUtil.copyList(orderItems, NewBeeMallOrderItemVO.class);
NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = new NewBeeMallOrderDetailVO();
BeanUtil.copyProperties(newBeeMallOrder, newBeeMallOrderDetailVO);
newBeeMallOrderDetailVO.setOrderStatusString(NewBeeMallOrderStatusEnum.getNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderDetailVO.getOrderStatus()).getName());
newBeeMallOrderDetailVO.setPayTypeString(PayTypeEnum.getPayTypeEnumByType(newBeeMallOrderDetailVO.getPayType()).getName());
newBeeMallOrderDetailVO.setNewBeeMallOrderItemVOS(newBeeMallOrderItemVOS);
return newBeeMallOrderDetailVO;
}
@Override
public PageResult getMyOrders(PageQueryUtil pageUtil) {
int total = newBeeMallOrderMapper.getTotalNewBeeMallOrders(pageUtil);
List newBeeMallOrders = newBeeMallOrderMapper.findNewBeeMallOrderList(pageUtil);
List orderListVOS = new ArrayList<>();
if (total > 0) {
//数据转换 将实体类转成vo
orderListVOS = BeanUtil.copyList(newBeeMallOrders, NewBeeMallOrderListVO.class);
//设置订单状态中文显示值
for (NewBeeMallOrderListVO newBeeMallOrderListVO : orderListVOS) {
newBeeMallOrderListVO.setOrderStatusString(NewBeeMallOrderStatusEnum.getNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderListVO.getOrderStatus()).getName());
}
List orderIds = newBeeMallOrders.stream().map(NewBeeMallOrder::getOrderId).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(orderIds)) {
List orderItems = newBeeMallOrderItemMapper.selectByOrderIds(orderIds);
Map> itemByOrderIdMap = orderItems.stream().collect(groupingBy(NewBeeMallOrderItem::getOrderId));
for (NewBeeMallOrderListVO newBeeMallOrderListVO : orderListVOS) {
//封装每个订单列表对象的订单项数据
if (itemByOrderIdMap.containsKey(newBeeMallOrderListVO.getOrderId())) {
List orderItemListTemp = itemByOrderIdMap.get(newBeeMallOrderListVO.getOrderId());
//将NewBeeMallOrderItem对象列表转换成NewBeeMallOrderItemVO对象列表
List newBeeMallOrderItemVOS = BeanUtil.copyList(orderItemListTemp, NewBeeMallOrderItemVO.class);
newBeeMallOrderListVO.setNewBeeMallOrderItemVOS(newBeeMallOrderItemVOS);
}
}
}
}
PageResult pageResult = new PageResult(orderListVOS, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public String cancelOrder(String orderNo, Long userId) {
NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(orderNo);
if (newBeeMallOrder != null) {
//验证是否是当前userId下的订单,否则报错
if (!userId.equals(newBeeMallOrder.getUserId())) {
NewBeeMallException.fail(ServiceResultEnum.NO_PERMISSION_ERROR.getResult());
}
//订单状态判断
if (newBeeMallOrder.getOrderStatus().intValue() == NewBeeMallOrderStatusEnum.ORDER_SUCCESS.getOrderStatus()
|| newBeeMallOrder.getOrderStatus().intValue() == NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_MALLUSER.getOrderStatus()
|| newBeeMallOrder.getOrderStatus().intValue() == NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_EXPIRED.getOrderStatus()
|| newBeeMallOrder.getOrderStatus().intValue() == NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_JUDGE.getOrderStatus()) {
return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
}
if (newBeeMallOrderMapper.closeOrder(Collections.singletonList(newBeeMallOrder.getOrderId()), NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_MALLUSER.getOrderStatus()) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
} else {
return ServiceResultEnum.DB_ERROR.getResult();
}
}
return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
}
@Override
public String finishOrder(String orderNo, Long userId) {
NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(orderNo);
if (newBeeMallOrder != null) {
//验证是否是当前userId下的订单,否则报错
if (!userId.equals(newBeeMallOrder.getUserId())) {
return ServiceResultEnum.NO_PERMISSION_ERROR.getResult();
}
//订单状态判断 非出库状态下不进行修改操作
if (newBeeMallOrder.getOrderStatus().intValue() != NewBeeMallOrderStatusEnum.ORDER_EXPRESS.getOrderStatus()) {
return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
}
newBeeMallOrder.setOrderStatus((byte) NewBeeMallOrderStatusEnum.ORDER_SUCCESS.getOrderStatus());
newBeeMallOrder.setUpdateTime(new Date());
if (newBeeMallOrderMapper.updateByPrimaryKeySelective(newBeeMallOrder) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
} else {
return ServiceResultEnum.DB_ERROR.getResult();
}
}
return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
}
@Override
public String paySuccess(String orderNo, int payType) {
NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(orderNo);
if (newBeeMallOrder != null) {
//订单状态判断 非待支付状态下不进行修改操作
if (newBeeMallOrder.getOrderStatus().intValue() != NewBeeMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()) {
return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
}
newBeeMallOrder.setOrderStatus((byte) NewBeeMallOrderStatusEnum.ORDER_PAID.getOrderStatus());
newBeeMallOrder.setPayType((byte) payType);
newBeeMallOrder.setPayStatus((byte) PayStatusEnum.PAY_SUCCESS.getPayStatus());
newBeeMallOrder.setPayTime(new Date());
newBeeMallOrder.setUpdateTime(new Date());
if (newBeeMallOrderMapper.updateByPrimaryKeySelective(newBeeMallOrder) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
} else {
return ServiceResultEnum.DB_ERROR.getResult();
}
}
return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
}
@Override
@Transactional
@GlobalTransactional
public String saveOrder(Long mallUserId, MallUserAddress address, List cartItemIds) {
//调用购物车服务feign获取数据
Result> cartItemDTOListResult = shopCartService.listByCartItemIds(cartItemIds);
if (cartItemDTOListResult == null || cartItemDTOListResult.getResultCode() != 200) {
NewBeeMallException.fail("参数异常");
}
List itemsForSave = cartItemDTOListResult.getData();
if (CollectionUtils.isEmpty(itemsForSave)) {
//无数据
NewBeeMallException.fail("参数异常");
}
List itemIdList = itemsForSave.stream().map(NewBeeMallShoppingCartItemDTO::getCartItemId).collect(Collectors.toList());
List goodsIds = itemsForSave.stream().map(NewBeeMallShoppingCartItemDTO::getGoodsId).collect(Collectors.toList());
//调用商品服务feign获取数据
Result> goodsDTOListResult = goodsService.listByGoodsIds(goodsIds);
if (goodsDTOListResult == null || goodsDTOListResult.getResultCode() != 200) {
NewBeeMallException.fail("参数异常");
}
List newBeeMallGoods = goodsDTOListResult.getData();
//检查是否包含已下架商品
List goodsListNotSelling = newBeeMallGoods.stream()
.filter(newBeeMallGoodsTemp -> newBeeMallGoodsTemp.getGoodsSellStatus() != 0)
.collect(Collectors.toList());
if (!CollectionUtils.isEmpty(goodsListNotSelling)) {
//goodsListNotSelling 对象非空则表示有下架商品
NewBeeMallException.fail(goodsListNotSelling.get(0).getGoodsName() + "已下架,无法生成订单");
}
Map newBeeMallGoodsMap = newBeeMallGoods.stream().collect(Collectors.toMap(NewBeeMallGoodsDTO::getGoodsId, Function.identity(), (entity1, entity2) -> entity1));
//判断商品库存
for (NewBeeMallShoppingCartItemDTO cartItemDTO : itemsForSave) {
//查出的商品中不存在购物车中的这条关联商品数据,直接返回错误提醒
if (!newBeeMallGoodsMap.containsKey(cartItemDTO.getGoodsId())) {
NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
}
//存在数量大于库存的情况,直接返回错误提醒
if (cartItemDTO.getGoodsCount() > newBeeMallGoodsMap.get(cartItemDTO.getGoodsId()).getStockNum()) {
NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_COUNT_ERROR.getResult());
}
}
//删除购物项
if (!CollectionUtils.isEmpty(itemIdList) && !CollectionUtils.isEmpty(goodsIds) && !CollectionUtils.isEmpty(newBeeMallGoods)) {
//调用购物车服务feign删除数据
Result deleteByCartItemIdsResult = shopCartService.deleteByCartItemIds(itemIdList);
if (deleteByCartItemIdsResult != null && deleteByCartItemIdsResult.getResultCode() == 200) {
List stockNumDTOS = BeanUtil.copyList(itemsForSave, StockNumDTO.class);
UpdateStockNumDTO updateStockNumDTO = new UpdateStockNumDTO();
updateStockNumDTO.setStockNumDTOS(stockNumDTOS);
//调用商品服务feign修改库存数据
Result updateStockResult = goodsService.updateStock(updateStockNumDTO);
if (updateStockResult == null || updateStockResult.getResultCode() != 200) {
NewBeeMallException.fail(ServiceResultEnum.PARAM_ERROR.getResult());
}
if (!updateStockResult.getData()) {
NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_COUNT_ERROR.getResult());
}
//生成订单号
String orderNo = NumberUtil.genOrderNo();
int priceTotal = 0;
//保存订单
NewBeeMallOrder newBeeMallOrder = new NewBeeMallOrder();
newBeeMallOrder.setOrderNo(orderNo);
newBeeMallOrder.setUserId(mallUserId);
//总价
for (NewBeeMallShoppingCartItemDTO cartItemDTO : itemsForSave) {
priceTotal += cartItemDTO.getGoodsCount() * newBeeMallGoodsMap.get(cartItemDTO.getGoodsId()).getSellingPrice();
}
if (priceTotal < 1) {
NewBeeMallException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getResult());
}
newBeeMallOrder.setTotalPrice(priceTotal);
String extraInfo = "";
newBeeMallOrder.setExtraInfo(extraInfo);
//生成订单项并保存订单项纪录
if (newBeeMallOrderMapper.insertSelective(newBeeMallOrder) > 0) {
//生成订单收货地址快照,并保存至数据库
NewBeeMallOrderAddress newBeeMallOrderAddress = new NewBeeMallOrderAddress();
BeanUtil.copyProperties(address, newBeeMallOrderAddress);
newBeeMallOrderAddress.setOrderId(newBeeMallOrder.getOrderId());
//生成所有的订单项快照,并保存至数据库
List newBeeMallOrderItems = new ArrayList<>();
for (NewBeeMallShoppingCartItemDTO cartItemDTO : itemsForSave) {
NewBeeMallOrderItem newBeeMallOrderItem = new NewBeeMallOrderItem();
//使用BeanUtil工具类将cartItemDTO中的属性复制到newBeeMallOrderItem对象中
BeanUtil.copyProperties(cartItemDTO, newBeeMallOrderItem);
newBeeMallOrderItem.setGoodsCoverImg(newBeeMallGoodsMap.get(cartItemDTO.getGoodsId()).getGoodsCoverImg());
newBeeMallOrderItem.setGoodsName(newBeeMallGoodsMap.get(cartItemDTO.getGoodsId()).getGoodsName());
newBeeMallOrderItem.setSellingPrice(newBeeMallGoodsMap.get(cartItemDTO.getGoodsId()).getSellingPrice());
//NewBeeMallOrderMapper文件insert()方法中使用了useGeneratedKeys因此orderId可以获取到
newBeeMallOrderItem.setOrderId(newBeeMallOrder.getOrderId());
newBeeMallOrderItems.add(newBeeMallOrderItem);
}
//保存至数据库
if (newBeeMallOrderItemMapper.insertBatch(newBeeMallOrderItems) > 0 && newBeeMallOrderAddressMapper.insertSelective(newBeeMallOrderAddress) > 0) {
//所有操作成功后,将订单号返回,以供Controller方法跳转到订单详情
return orderNo;
}
NewBeeMallException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getResult());
}
NewBeeMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
}
NewBeeMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
}
NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
return ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult();
}
@Override
public PageResult getNewBeeMallOrdersPage(PageQueryUtil pageUtil) {
List newBeeMallOrders = newBeeMallOrderMapper.findNewBeeMallOrderList(pageUtil);
int total = newBeeMallOrderMapper.getTotalNewBeeMallOrders(pageUtil);
PageResult pageResult = new PageResult(newBeeMallOrders, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
@Transactional
public String updateOrderInfo(NewBeeMallOrder newBeeMallOrder) {
NewBeeMallOrder temp = newBeeMallOrderMapper.selectByPrimaryKey(newBeeMallOrder.getOrderId());
//不为空且orderStatus>=0且状态为出库之前可以修改部分信息
if (temp != null && temp.getOrderStatus() >= 0 && temp.getOrderStatus() < 3) {
temp.setTotalPrice(newBeeMallOrder.getTotalPrice());
temp.setUpdateTime(new Date());
if (newBeeMallOrderMapper.updateByPrimaryKeySelective(temp) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
@Override
@Transactional
public String checkDone(Long[] ids) {
//查询所有的订单 判断状态 修改状态和更新时间
List orders = newBeeMallOrderMapper.selectByPrimaryKeys(Arrays.asList(ids));
String errorOrderNos = "";
if (!CollectionUtils.isEmpty(orders)) {
for (NewBeeMallOrder newBeeMallOrder : orders) {
if (newBeeMallOrder.getIsDeleted() == 1) {
errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
continue;
}
if (newBeeMallOrder.getOrderStatus() != 1) {
errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
}
}
if (!StringUtils.hasText(errorOrderNos)) {
//订单状态正常 可以执行配货完成操作 修改订单状态和更新时间
if (newBeeMallOrderMapper.checkDone(Arrays.asList(ids)) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
} else {
return ServiceResultEnum.DB_ERROR.getResult();
}
} else {
//订单此时不可执行出库操作
if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
return errorOrderNos + "订单的状态不是支付成功无法执行出库操作";
} else {
return "你选择了太多状态不是支付成功的订单,无法执行配货完成操作";
}
}
}
//未查询到数据 返回错误提示
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
@Override
@Transactional
public String checkOut(Long[] ids) {
//查询所有的订单 判断状态 修改状态和更新时间
List orders = newBeeMallOrderMapper.selectByPrimaryKeys(Arrays.asList(ids));
String errorOrderNos = "";
if (!CollectionUtils.isEmpty(orders)) {
for (NewBeeMallOrder newBeeMallOrder : orders) {
if (newBeeMallOrder.getIsDeleted() == 1) {
errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
continue;
}
if (newBeeMallOrder.getOrderStatus() != 1 && newBeeMallOrder.getOrderStatus() != 2) {
errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
}
}
if (!StringUtils.hasText(errorOrderNos)) {
//订单状态正常 可以执行出库操作 修改订单状态和更新时间
if (newBeeMallOrderMapper.checkOut(Arrays.asList(ids)) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
} else {
return ServiceResultEnum.DB_ERROR.getResult();
}
} else {
//订单此时不可执行出库操作
if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
return errorOrderNos + "订单的状态不是支付成功或配货完成无法执行出库操作";
} else {
return "你选择了太多状态不是支付成功或配货完成的订单,无法执行出库操作";
}
}
}
//未查询到数据 返回错误提示
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
@Override
@Transactional
public String closeOrder(Long[] ids) {
//查询所有的订单 判断状态 修改状态和更新时间
List orders = newBeeMallOrderMapper.selectByPrimaryKeys(Arrays.asList(ids));
String errorOrderNos = "";
if (!CollectionUtils.isEmpty(orders)) {
for (NewBeeMallOrder newBeeMallOrder : orders) {
// isDeleted=1 一定为已关闭订单
if (newBeeMallOrder.getIsDeleted() == 1) {
errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
continue;
}
//已关闭或者已完成无法关闭订单
if (newBeeMallOrder.getOrderStatus() == 4 || newBeeMallOrder.getOrderStatus() < 0) {
errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
}
}
if (!StringUtils.hasText(errorOrderNos)) {
//订单状态正常 可以执行关闭操作 修改订单状态和更新时间
if (newBeeMallOrderMapper.closeOrder(Arrays.asList(ids), NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_JUDGE.getOrderStatus()) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
} else {
return ServiceResultEnum.DB_ERROR.getResult();
}
} else {
//订单此时不可执行关闭操作
if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
return errorOrderNos + "订单不能执行关闭操作";
} else {
return "你选择的订单不能执行关闭操作";
}
}
}
//未查询到数据 返回错误提示
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
@Override
public List getOrderItems(Long orderId) {
NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByPrimaryKey(orderId);
if (newBeeMallOrder != null) {
List orderItems = newBeeMallOrderItemMapper.selectByOrderId(newBeeMallOrder.getOrderId());
//获取订单项数据
if (!CollectionUtils.isEmpty(orderItems)) {
List newBeeMallOrderItemVOS = BeanUtil.copyList(orderItems, NewBeeMallOrderItemVO.class);
return newBeeMallOrderItemVOS;
}
}
return null;
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/java/ltd/order/cloud/newbee/service/impl/NewBeeMallUserAddressServiceImpl.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.order.cloud.newbee.service.impl;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.order.cloud.newbee.controller.vo.NewBeeMallUserAddressVO;
import ltd.order.cloud.newbee.dao.MallUserAddressMapper;
import ltd.order.cloud.newbee.entity.MallUserAddress;
import ltd.order.cloud.newbee.service.NewBeeMallUserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@Service
public class NewBeeMallUserAddressServiceImpl implements NewBeeMallUserAddressService {
@Autowired
private MallUserAddressMapper userAddressMapper;
@Override
public List getMyAddresses(Long userId) {
List myAddressList = userAddressMapper.findMyAddressList(userId);
List newBeeMallUserAddressVOS = BeanUtil.copyList(myAddressList, NewBeeMallUserAddressVO.class);
return newBeeMallUserAddressVOS;
}
@Override
@Transactional
public Boolean saveUserAddress(MallUserAddress mallUserAddress) {
Date now = new Date();
if (mallUserAddress.getDefaultFlag().intValue() == 1) {
//添加默认地址,需要将原有的默认地址修改掉
MallUserAddress defaultAddress = userAddressMapper.getMyDefaultAddress(mallUserAddress.getUserId());
if (defaultAddress != null) {
defaultAddress.setDefaultFlag((byte) 0);
defaultAddress.setUpdateTime(now);
int updateResult = userAddressMapper.updateByPrimaryKeySelective(defaultAddress);
if (updateResult < 1) {
//未更新成功
NewBeeMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
}
}
}
return userAddressMapper.insertSelective(mallUserAddress) > 0;
}
@Override
public Boolean updateMallUserAddress(MallUserAddress mallUserAddress) {
MallUserAddress tempAddress = getMallUserAddressById(mallUserAddress.getAddressId());
Date now = new Date();
if (mallUserAddress.getDefaultFlag().intValue() == 1) {
//修改为默认地址,需要将原有的默认地址修改掉
MallUserAddress defaultAddress = userAddressMapper.getMyDefaultAddress(mallUserAddress.getUserId());
if (defaultAddress != null && !defaultAddress.getAddressId().equals(tempAddress)) {
//存在默认地址且默认地址并不是当前修改的地址
defaultAddress.setDefaultFlag((byte) 0);
defaultAddress.setUpdateTime(now);
int updateResult = userAddressMapper.updateByPrimaryKeySelective(defaultAddress);
if (updateResult < 1) {
//未更新成功
NewBeeMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
}
}
}
mallUserAddress.setUpdateTime(now);
return userAddressMapper.updateByPrimaryKeySelective(mallUserAddress) > 0;
}
@Override
public MallUserAddress getMallUserAddressById(Long addressId) {
MallUserAddress mallUserAddress = userAddressMapper.selectByPrimaryKey(addressId);
if (mallUserAddress == null) {
NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
}
return mallUserAddress;
}
@Override
public MallUserAddress getMyDefaultAddressByUserId(Long userId) {
return userAddressMapper.getMyDefaultAddress(userId);
}
@Override
public Boolean deleteById(Long addressId) {
return userAddressMapper.deleteByPrimaryKey(addressId) > 0;
}
}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/resources/application.properties
================================================
server.port=29040
# 服务名称
spring.application.name=newbee-mall-cloud-order-service
# Nacos地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# Nacos登录用户名(默认为nacos,生产环境一定要修改)
spring.cloud.nacos.username=nacos
# Nacos登录密码(默认为nacos,生产环境一定要修改)
spring.cloud.nacos.password=nacos
# datasource config (MySQL)
spring.datasource.name=newbee-mall-cloud-order-datasource
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/newbee_mall_cloud_order_db?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf8&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
# 指定数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# Druid 数据源设置
# 初始化时建立数据库连接的个数
spring.datasource.initialSize=10
# 最小连接池数量
spring.datasource.minIdle=5
# 最大连接池数量
spring.datasource.maxActive=30
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
# 用来检测连接是否有效的SQL语句
spring.datasource.validationQuery=SELECT 1
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# mybatis config
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
# sentinel config
spring.cloud.sentinel.transport.port=8940
spring.cloud.sentinel.transport.clientIp=127.0.0.1
# 指定Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=127.0.0.1:9113
# openfeign config
feign.client.config.default.connectTimeout=2000
feign.client.config.default.readTimeout=5000
feign.compression.request.enabled=true
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=1024
feign.compression.response.enabled=true
# 演示需要,开启OpenFeign和当前项目中的DEBUG级别日志
#logging.level.ltd.user.cloud.newbee.openfeign=debug
#logging.level.ltd.goods.cloud.newbee.openfeign=debug
#logging.level.ltd.shopcart.cloud.newbee.openfeign=debug
#logging.level.ltd.order.cloud.newbee=debug
# Sleuth采样率,取值范围为[0.1,1.0],值越大收集越及时,但性能影响也越大
spring.sleuth.sampler.probability=1.0
# 每秒数据采集量,最多n条/秒Trace
spring.sleuth.sampler.rate=500
spring.zipkin.base-url=http://localhost:9411
seata.enabled=true
seata.application-id=order-server
#事务分组配置
seata.tx-service-group=newbee_cloud_save_order_group
service.vgroupMapping.newbee_cloud_save_order_group=default
#连接Nacos服务中心的配置信息
seata.registry.type=nacos
seata.registry.nacos.application=seata-server
seata.registry.nacos.server-addr=127.0.0.1:8848
seata.registry.nacos.username=nacos
seata.registry.nacos.password=nacos
seata.registry.nacos.group=DEFAULT_GROUP
seata.registry.nacos.cluster=default
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/resources/logback.xml
================================================
${APP_NAME}
INFO
${CONSOLE_LOG_PATTERN}
utf8
192.168.110.57:4560
INFO
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/resources/mapper/MallUserAddressMapper.xml
================================================
address_id, user_id, user_name, user_phone, default_flag, province_name, city_name,
region_name, detail_address, is_deleted, create_time, update_time
update tb_newbee_mall_user_address set is_deleted = 1
where address_id = #{addressId,jdbcType=BIGINT}
insert into tb_newbee_mall_user_address (address_id, user_id, user_name,
user_phone, default_flag, province_name,
city_name, region_name, detail_address,
is_deleted, create_time, update_time
)
values (#{addressId,jdbcType=BIGINT}, #{userId,jdbcType=BIGINT}, #{userName,jdbcType=VARCHAR},
#{userPhone,jdbcType=VARCHAR}, #{defaultFlag,jdbcType=TINYINT}, #{provinceName,jdbcType=VARCHAR},
#{cityName,jdbcType=VARCHAR}, #{regionName,jdbcType=VARCHAR}, #{detailAddress,jdbcType=VARCHAR},
#{isDeleted,jdbcType=TINYINT}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}
)
insert into tb_newbee_mall_user_address
address_id,
user_id,
user_name,
user_phone,
default_flag,
province_name,
city_name,
region_name,
detail_address,
is_deleted,
create_time,
update_time,
#{addressId,jdbcType=BIGINT},
#{userId,jdbcType=BIGINT},
#{userName,jdbcType=VARCHAR},
#{userPhone,jdbcType=VARCHAR},
#{defaultFlag,jdbcType=TINYINT},
#{provinceName,jdbcType=VARCHAR},
#{cityName,jdbcType=VARCHAR},
#{regionName,jdbcType=VARCHAR},
#{detailAddress,jdbcType=VARCHAR},
#{isDeleted,jdbcType=TINYINT},
#{createTime,jdbcType=TIMESTAMP},
#{updateTime,jdbcType=TIMESTAMP},
update tb_newbee_mall_user_address
user_id = #{userId,jdbcType=BIGINT},
user_name = #{userName,jdbcType=VARCHAR},
user_phone = #{userPhone,jdbcType=VARCHAR},
default_flag = #{defaultFlag,jdbcType=TINYINT},
province_name = #{provinceName,jdbcType=VARCHAR},
city_name = #{cityName,jdbcType=VARCHAR},
region_name = #{regionName,jdbcType=VARCHAR},
detail_address = #{detailAddress,jdbcType=VARCHAR},
is_deleted = #{isDeleted,jdbcType=TINYINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP},
where address_id = #{addressId,jdbcType=BIGINT}
update tb_newbee_mall_user_address
set user_id = #{userId,jdbcType=BIGINT},
user_name = #{userName,jdbcType=VARCHAR},
user_phone = #{userPhone,jdbcType=VARCHAR},
default_flag = #{defaultFlag,jdbcType=TINYINT},
province_name = #{provinceName,jdbcType=VARCHAR},
city_name = #{cityName,jdbcType=VARCHAR},
region_name = #{regionName,jdbcType=VARCHAR},
detail_address = #{detailAddress,jdbcType=VARCHAR},
is_deleted = #{isDeleted,jdbcType=TINYINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP}
where address_id = #{addressId,jdbcType=BIGINT}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/resources/mapper/NewBeeMallOrderAddressMapper.xml
================================================
order_id, user_name, user_phone, province_name, city_name, region_name, detail_address
delete from tb_newbee_mall_order_address
where order_id = #{orderId,jdbcType=BIGINT}
insert into tb_newbee_mall_order_address (order_id, user_name, user_phone,
province_name, city_name, region_name,
detail_address)
values (#{orderId,jdbcType=BIGINT}, #{userName,jdbcType=VARCHAR}, #{userPhone,jdbcType=VARCHAR},
#{provinceName,jdbcType=VARCHAR}, #{cityName,jdbcType=VARCHAR}, #{regionName,jdbcType=VARCHAR},
#{detailAddress,jdbcType=VARCHAR})
insert into tb_newbee_mall_order_address
order_id,
user_name,
user_phone,
province_name,
city_name,
region_name,
detail_address,
#{orderId,jdbcType=BIGINT},
#{userName,jdbcType=VARCHAR},
#{userPhone,jdbcType=VARCHAR},
#{provinceName,jdbcType=VARCHAR},
#{cityName,jdbcType=VARCHAR},
#{regionName,jdbcType=VARCHAR},
#{detailAddress,jdbcType=VARCHAR},
update tb_newbee_mall_order_address
user_name = #{userName,jdbcType=VARCHAR},
user_phone = #{userPhone,jdbcType=VARCHAR},
province_name = #{provinceName,jdbcType=VARCHAR},
city_name = #{cityName,jdbcType=VARCHAR},
region_name = #{regionName,jdbcType=VARCHAR},
detail_address = #{detailAddress,jdbcType=VARCHAR},
where order_id = #{orderId,jdbcType=BIGINT}
update tb_newbee_mall_order_address
set user_name = #{userName,jdbcType=VARCHAR},
user_phone = #{userPhone,jdbcType=VARCHAR},
province_name = #{provinceName,jdbcType=VARCHAR},
city_name = #{cityName,jdbcType=VARCHAR},
region_name = #{regionName,jdbcType=VARCHAR},
detail_address = #{detailAddress,jdbcType=VARCHAR}
where order_id = #{orderId,jdbcType=BIGINT}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/resources/mapper/NewBeeMallOrderItemMapper.xml
================================================
order_item_id, order_id, goods_id, goods_name, goods_cover_img, selling_price, goods_count,
create_time
delete from tb_newbee_mall_order_item
where order_item_id = #{orderItemId,jdbcType=BIGINT}
insert into tb_newbee_mall_order_item (order_id, goods_id,
goods_name, goods_cover_img, selling_price,
goods_count)
values
(#{orderItem.orderId,jdbcType=BIGINT}, #{orderItem.goodsId,jdbcType=BIGINT},
#{orderItem.goodsName,jdbcType=VARCHAR}, #{orderItem.goodsCoverImg,jdbcType=VARCHAR},
#{orderItem.sellingPrice,jdbcType=INTEGER},
#{orderItem.goodsCount,jdbcType=INTEGER})
insert into tb_newbee_mall_order_item (order_item_id, order_id, goods_id,
goods_name, goods_cover_img, selling_price,
goods_count, create_time)
values (#{orderItemId,jdbcType=BIGINT}, #{orderId,jdbcType=BIGINT}, #{goodsId,jdbcType=BIGINT},
#{goodsName,jdbcType=VARCHAR}, #{goodsCoverImg,jdbcType=VARCHAR}, #{sellingPrice,jdbcType=INTEGER},
#{goodsCount,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP})
insert into tb_newbee_mall_order_item
order_item_id,
order_id,
goods_id,
goods_name,
goods_cover_img,
selling_price,
goods_count,
create_time,
#{orderItemId,jdbcType=BIGINT},
#{orderId,jdbcType=BIGINT},
#{goodsId,jdbcType=BIGINT},
#{goodsName,jdbcType=VARCHAR},
#{goodsCoverImg,jdbcType=VARCHAR},
#{sellingPrice,jdbcType=INTEGER},
#{goodsCount,jdbcType=INTEGER},
#{createTime,jdbcType=TIMESTAMP},
update tb_newbee_mall_order_item
order_id = #{orderId,jdbcType=BIGINT},
goods_id = #{goodsId,jdbcType=BIGINT},
goods_name = #{goodsName,jdbcType=VARCHAR},
goods_cover_img = #{goodsCoverImg,jdbcType=VARCHAR},
selling_price = #{sellingPrice,jdbcType=INTEGER},
goods_count = #{goodsCount,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP},
where order_item_id = #{orderItemId,jdbcType=BIGINT}
update tb_newbee_mall_order_item
set order_id = #{orderId,jdbcType=BIGINT},
goods_id = #{goodsId,jdbcType=BIGINT},
goods_name = #{goodsName,jdbcType=VARCHAR},
goods_cover_img = #{goodsCoverImg,jdbcType=VARCHAR},
selling_price = #{sellingPrice,jdbcType=INTEGER},
goods_count = #{goodsCount,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP}
where order_item_id = #{orderItemId,jdbcType=BIGINT}
================================================
FILE: newbee-mall-cloud-order-service/newbee-mall-cloud-order-web/src/main/resources/mapper/NewBeeMallOrderMapper.xml
================================================
order_id, order_no, user_id, total_price, pay_status, pay_type, pay_time, order_status,
extra_info, is_deleted, create_time, update_time
update tb_newbee_mall_order set is_deleted=1
where order_id = #{orderId,jdbcType=BIGINT} and is_deleted=0
insert into tb_newbee_mall_order (order_id, order_no, user_id,
total_price, pay_status, pay_type,
pay_time, order_status, extra_info,
is_deleted, create_time, update_time
)
values (#{orderId,jdbcType=BIGINT}, #{orderNo,jdbcType=VARCHAR}, #{userId,jdbcType=BIGINT},
#{totalPrice,jdbcType=INTEGER}, #{payStatus,jdbcType=TINYINT}, #{payType,jdbcType=TINYINT},
#{payTime,jdbcType=TIMESTAMP}, #{orderStatus,jdbcType=TINYINT}, #{extraInfo,jdbcType=VARCHAR},
#{isDeleted,jdbcType=TINYINT}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}
)
insert into tb_newbee_mall_order
order_id,
order_no,
user_id,
total_price,
pay_status,
pay_type,
pay_time,
order_status,
extra_info,
is_deleted,
create_time,
update_time,
#{orderId,jdbcType=BIGINT},
#{orderNo,jdbcType=VARCHAR},
#{userId,jdbcType=BIGINT},
#{totalPrice,jdbcType=INTEGER},
#{payStatus,jdbcType=TINYINT},
#{payType,jdbcType=TINYINT},
#{payTime,jdbcType=TIMESTAMP},
#{orderStatus,jdbcType=TINYINT},
#{extraInfo,jdbcType=VARCHAR},
#{isDeleted,jdbcType=TINYINT},
#{createTime,jdbcType=TIMESTAMP},
#{updateTime,jdbcType=TIMESTAMP},
update tb_newbee_mall_order
set order_status = 2,update_time = now()
where order_id in
#{item}
update tb_newbee_mall_order
set order_status = 3,update_time = now()
where order_id in
#{item}
update tb_newbee_mall_order
set order_status = #{orderStatus},update_time = now()
where order_id in
#{item}
update tb_newbee_mall_order
order_no = #{orderNo,jdbcType=VARCHAR},
user_id = #{userId,jdbcType=BIGINT},
total_price = #{totalPrice,jdbcType=INTEGER},
pay_status = #{payStatus,jdbcType=TINYINT},
pay_type = #{payType,jdbcType=TINYINT},
pay_time = #{payTime,jdbcType=TIMESTAMP},
order_status = #{orderStatus,jdbcType=TINYINT},
extra_info = #{extraInfo,jdbcType=VARCHAR},
is_deleted = #{isDeleted,jdbcType=TINYINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP},
where order_id = #{orderId,jdbcType=BIGINT}
update tb_newbee_mall_order
set order_no = #{orderNo,jdbcType=VARCHAR},
user_id = #{userId,jdbcType=BIGINT},
total_price = #{totalPrice,jdbcType=INTEGER},
pay_status = #{payStatus,jdbcType=TINYINT},
pay_type = #{payType,jdbcType=TINYINT},
pay_time = #{payTime,jdbcType=TIMESTAMP},
order_status = #{orderStatus,jdbcType=TINYINT},
extra_info = #{extraInfo,jdbcType=VARCHAR},
is_deleted = #{isDeleted,jdbcType=TINYINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP}
where order_id = #{orderId,jdbcType=BIGINT}
================================================
FILE: newbee-mall-cloud-order-service/pom.xml
================================================
4.0.0
ltd.newbee.cloud
newbee-mall-cloud-order-service
0.0.1-SNAPSHOT
pom
newbee-mall-cloud-order-service
订单模块
ltd.newbee.cloud
newbee-mall-cloud
0.0.1-SNAPSHOT
1.8
newbee-mall-cloud-order-web
newbee-mall-cloud-order-api
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-api/pom.xml
================================================
4.0.0
ltd.recommend.newbee.cloud
newbee-mall-cloud-recommend-api
jar
0.0.1-SNAPSHOT
newbee-mall-cloud-recommend-api
推荐服务openfeign
ltd.newbee.cloud
newbee-mall-cloud-recommend-service
0.0.1-SNAPSHOT
1.8
org.springframework.cloud
spring-cloud-starter-openfeign
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/pom.xml
================================================
4.0.0
ltd.recommend.newbee.cloud
newbee-mall-cloud-recommend-web
0.0.1-SNAPSHOT
newbee-mall-cloud-recommend-web
推荐服务
ltd.newbee.cloud
newbee-mall-cloud-recommend-service
0.0.1-SNAPSHOT
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
org.springframework.boot
spring-boot-starter-validation
org.mybatis.spring.boot
mybatis-spring-boot-starter
org.projectlombok
lombok
${lombok.version}
provided
io.springfox
springfox-boot-starter
mysql
mysql-connector-java
runtime
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
org.springframework.cloud
spring-cloud-starter-openfeign
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
org.springframework.cloud
spring-cloud-starter-sleuth
org.springframework.cloud
spring-cloud-sleuth-zipkin
org.springframework.cloud
spring-cloud-starter-loadbalancer
net.logstash.logback
logstash-logback-encoder
${logstash-logback-encoder.version}
ltd.user.newbee.cloud
newbee-mall-cloud-user-api
0.0.1-SNAPSHOT
ltd.goods.newbee.cloud
newbee-mall-cloud-goods-api
0.0.1-SNAPSHOT
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/NewBeeMallCloudRecommendServiceApplication.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee;
import ltd.user.cloud.newbee.openfeign.NewBeeCloudUserServiceFeign;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @author 程序员十三
* @qq交流群 791509631
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("ltd.recommend.cloud.newbee.dao")
@EnableFeignClients(basePackageClasses =
{NewBeeCloudUserServiceFeign.class,
ltd.goods.cloud.newbee.openfeign.NewBeeCloudGoodsServiceFeign.class})
public class NewBeeMallCloudRecommendServiceApplication {
public static void main(String[] args) {
System.setProperty("nacos.logging.default.config.enabled","false");
SpringApplication.run(NewBeeMallCloudRecommendServiceApplication.class, args);
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/config/OpenFeignConfiguration.java
================================================
package ltd.recommend.cloud.newbee.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenFeignConfiguration {
@Bean
public Logger.Level openFeignLogLevel() {
// 设置OpenFeign日志级别
return Logger.Level.FULL;
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/config/RecommendServiceExceptionHandler.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.config;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* 全局异常处理
*/
@RestControllerAdvice
public class RecommendServiceExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(RecommendServiceExceptionHandler.class);
@ExceptionHandler(BindException.class)
public Object bindException(BindException e) {
log.error("RecommendServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(510);
BindingResult bindingResult = e.getBindingResult();
result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
return result;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object bindException(MethodArgumentNotValidException e) {
log.error("RecommendServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(510);
BindingResult bindingResult = e.getBindingResult();
result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
return result;
}
@ExceptionHandler(Exception.class)
public Object handleException(Exception e, HttpServletRequest req) {
log.error("RecommendServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(500);
//区分是否为自定义异常
if (e instanceof NewBeeMallException) {
result.setMessage(e.getMessage());
if (e.getMessage().equals(ServiceResultEnum.ADMIN_NOT_LOGIN_ERROR.getResult()) || e.getMessage().equals(ServiceResultEnum.ADMIN_TOKEN_EXPIRE_ERROR.getResult())) {
result.setResultCode(419);
}
} else {
e.printStackTrace();
result.setMessage("未知异常,请查看控制台日志并检查配置文件。");
}
return result;
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/config/RecommendServiceSwagger3Config.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.config;
import ltd.common.cloud.newbee.pojo.AdminUserToken;
import ltd.recommend.cloud.newbee.entity.LoginAdminUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableOpenApi
public class RecommendServiceSwagger3Config{
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.ignoredParameterTypes(AdminUserToken.class, LoginAdminUser.class)
.select()
.apis(RequestHandlerSelectors.basePackage("ltd.recommend.cloud.newbee.controller"))
.paths(PathSelectors.any())
.build()
.globalRequestParameters(getGlobalRequestParameters());
}
//生成全局通用参数
private List getGlobalRequestParameters() {
List parameters = new ArrayList<>();
parameters.add(new RequestParameterBuilder()
.name("token")
.description("登录认证token")
.required(false) // 非必传
.in(ParameterType.HEADER) //请求头中的参数,其它类型可以点进ParameterType类中查看
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.build());
return parameters;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("newbee-mall-cloud-recommend-service接口文档")
.description("swagger接口文档")
.version("2.0")
.build();
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/config/RecommendServiceWebMvcConfigurer.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.config;
import com.alibaba.cloud.sentinel.SentinelProperties;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import ltd.recommend.cloud.newbee.config.handler.TokenToAdminUserMethodArgumentResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
import java.util.Optional;
@Configuration
public class RecommendServiceWebMvcConfigurer extends WebMvcConfigurationSupport {
private static final Logger log = LoggerFactory.getLogger(RecommendServiceWebMvcConfigurer.class);
@Autowired
private SentinelProperties sentinelProperties;
@Autowired
private Optional sentinelWebInterceptorOptional;
@Autowired
@Lazy
private TokenToAdminUserMethodArgumentResolver tokenToAdminUserMethodArgumentResolver;
/**
* @param argumentResolvers
* @tip @TokenToAdminUser 注解处理方法
*/
public void addArgumentResolvers(List argumentResolvers) {
argumentResolvers.add(tokenToAdminUserMethodArgumentResolver);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.
addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
.resourceChain(false);
}
public void addInterceptors(InterceptorRegistry registry) {
if (this.sentinelWebInterceptorOptional.isPresent()) {
SentinelProperties.Filter filterConfig = this.sentinelProperties.getFilter();
registry.addInterceptor((HandlerInterceptor) this.sentinelWebInterceptorOptional.get()).order(filterConfig.getOrder()).addPathPatterns(filterConfig.getUrlPatterns());
log.info("[Sentinel Starter] register SentinelWebInterceptor with urlPatterns: {}.", filterConfig.getUrlPatterns());
}
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/config/annotation/TokenToAdminUser.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.config.annotation;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TokenToAdminUser {
/**
* 当前用户在request中的名字
*
* @return
*/
String value() default "adminUser";
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/config/handler/TokenToAdminUserMethodArgumentResolver.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.config.handler;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.recommend.cloud.newbee.config.annotation.TokenToAdminUser;
import ltd.recommend.cloud.newbee.entity.LoginAdminUser;
import ltd.user.cloud.newbee.openfeign.NewBeeCloudUserServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.LinkedHashMap;
@Component
public class TokenToAdminUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
private NewBeeCloudUserServiceFeign newBeeCloudUserService;
public TokenToAdminUserMethodArgumentResolver() {
}
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(TokenToAdminUser.class)) {
return true;
}
return false;
}
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
if (parameter.getParameterAnnotation(TokenToAdminUser.class) instanceof TokenToAdminUser) {
String token = webRequest.getHeader("token");
if (null != token && !"".equals(token) && token.length() == 32) {
// 通过用户中心获取用户信息
Result result = newBeeCloudUserService.getAdminUserByToken(token);
if (result == null || result.getResultCode() != 200 || result.getData() == null) {
NewBeeMallException.fail(ServiceResultEnum.ADMIN_NOT_LOGIN_ERROR.getResult());
}
LinkedHashMap resultData = (LinkedHashMap) result.getData();
// 将返回的字段封装到LoginAdminUser对象中
LoginAdminUser loginAdminUser = new LoginAdminUser();
loginAdminUser.setAdminUserId(Long.valueOf(resultData.get("adminUserId").toString()));
loginAdminUser.setLoginUserName((String) resultData.get("loginUserName"));
loginAdminUser.setNickName((String) resultData.get("nickName"));
loginAdminUser.setLocked(Byte.valueOf(resultData.get("locked").toString()));
return loginAdminUser;
} else {
NewBeeMallException.fail(ServiceResultEnum.ADMIN_NOT_LOGIN_ERROR.getResult());
}
}
return null;
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/NewBeeAdminCarouselController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.recommend.cloud.newbee.config.annotation.TokenToAdminUser;
import ltd.recommend.cloud.newbee.controller.param.BatchIdParam;
import ltd.recommend.cloud.newbee.controller.param.CarouselAddParam;
import ltd.recommend.cloud.newbee.controller.param.CarouselEditParam;
import ltd.recommend.cloud.newbee.entity.Carousel;
import ltd.recommend.cloud.newbee.entity.LoginAdminUser;
import ltd.recommend.cloud.newbee.service.NewBeeMallCarouselService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@RestController
@Api(value = "v1", tags = "后台管理系统轮播图模块接口")
@RequestMapping("/carousels/admin")
public class NewBeeAdminCarouselController {
private static final Logger logger = LoggerFactory.getLogger(NewBeeAdminCarouselController.class);
@Resource
NewBeeMallCarouselService newBeeMallCarouselService;
/**
* 列表
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ApiOperation(value = "轮播图列表", notes = "轮播图列表")
public Result list(@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
@RequestParam(required = false) @ApiParam(value = "每页条数") Integer pageSize, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (pageNumber == null || pageNumber < 1 || pageSize == null || pageSize < 10) {
return ResultGenerator.genFailResult("分页参数异常!");
}
Map params = new HashMap(4);
params.put("page", pageNumber);
params.put("limit", pageSize);
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallCarouselService.getCarouselPage(pageUtil));
}
/**
* 添加
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ApiOperation(value = "新增轮播图", notes = "新增轮播图")
public Result save(@RequestBody @Valid CarouselAddParam carouselAddParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
Carousel carousel = new Carousel();
BeanUtil.copyProperties(carouselAddParam, carousel);
String result = newBeeMallCarouselService.saveCarousel(carousel);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 修改
*/
@RequestMapping(value = "/update", method = RequestMethod.PUT)
@ApiOperation(value = "修改轮播图信息", notes = "修改轮播图信息")
public Result update(@RequestBody CarouselEditParam carouselEditParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
Carousel carousel = new Carousel();
BeanUtil.copyProperties(carouselEditParam, carousel);
String result = newBeeMallCarouselService.updateCarousel(carousel);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 详情
*/
@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
@ApiOperation(value = "获取单条轮播图信息", notes = "根据id查询")
public Result info(@PathVariable("id") Integer id, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
Carousel carousel = newBeeMallCarouselService.getCarouselById(id);
if (carousel == null) {
return ResultGenerator.genFailResult(ServiceResultEnum.DATA_NOT_EXIST.getResult());
}
return ResultGenerator.genSuccessResult(carousel);
}
/**
* 删除
*/
@RequestMapping(value = "/batchDelete", method = RequestMethod.DELETE)
@ApiOperation(value = "批量删除轮播图信息", notes = "批量删除轮播图信息")
public Result delete(@RequestBody BatchIdParam batchIdParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (batchIdParam == null || batchIdParam.getIds().length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
if (newBeeMallCarouselService.deleteBatch(batchIdParam.getIds())) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/NewBeeAdminIndexConfigController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.enums.IndexConfigTypeEnum;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.recommend.cloud.newbee.config.annotation.TokenToAdminUser;
import ltd.recommend.cloud.newbee.controller.param.BatchIdParam;
import ltd.recommend.cloud.newbee.controller.param.IndexConfigAddParam;
import ltd.recommend.cloud.newbee.controller.param.IndexConfigEditParam;
import ltd.recommend.cloud.newbee.entity.IndexConfig;
import ltd.recommend.cloud.newbee.entity.LoginAdminUser;
import ltd.recommend.cloud.newbee.service.NewBeeMallIndexConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
/**
* @author 13
* @qq交流群 796794009
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@RestController
@Api(value = "v1", tags = "后台管理系统首页配置模块接口")
@RequestMapping("/indexConfigs/admin")
public class NewBeeAdminIndexConfigController {
private static final Logger logger = LoggerFactory.getLogger(NewBeeAdminIndexConfigController.class);
@Resource
private NewBeeMallIndexConfigService newBeeMallIndexConfigService;
/**
* 列表
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ApiOperation(value = "首页配置列表", notes = "首页配置列表")
public Result list(@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
@RequestParam(required = false) @ApiParam(value = "每页条数") Integer pageSize,
@RequestParam(required = false) @ApiParam(value = "1-搜索框热搜 2-搜索下拉框热搜 3-(首页)热销商品 4-(首页)新品上线 5-(首页)为你推荐") Integer configType, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (pageNumber == null || pageNumber < 1 || pageSize == null || pageSize < 10) {
return ResultGenerator.genFailResult("分页参数异常!");
}
IndexConfigTypeEnum indexConfigTypeEnum = IndexConfigTypeEnum.getIndexConfigTypeEnumByType(configType);
if (indexConfigTypeEnum.equals(IndexConfigTypeEnum.DEFAULT)) {
return ResultGenerator.genFailResult("非法参数!");
}
Map params = new HashMap(8);
params.put("page", pageNumber);
params.put("limit", pageSize);
params.put("configType", configType);
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallIndexConfigService.getConfigsPage(pageUtil));
}
/**
* 添加
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ApiOperation(value = "新增首页配置项", notes = "新增首页配置项")
public Result save(@RequestBody @Valid IndexConfigAddParam indexConfigAddParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
IndexConfig indexConfig = new IndexConfig();
BeanUtil.copyProperties(indexConfigAddParam, indexConfig);
String result = newBeeMallIndexConfigService.saveIndexConfig(indexConfig);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 修改
*/
@RequestMapping(value = "/update", method = RequestMethod.PUT)
@ApiOperation(value = "修改首页配置项", notes = "修改首页配置项")
public Result update(@RequestBody @Valid IndexConfigEditParam indexConfigEditParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
IndexConfig indexConfig = new IndexConfig();
BeanUtil.copyProperties(indexConfigEditParam, indexConfig);
String result = newBeeMallIndexConfigService.updateIndexConfig(indexConfig);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 详情
*/
@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
@ApiOperation(value = "获取单条首页配置项信息", notes = "根据id查询")
public Result info(@PathVariable("id") Long id, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
IndexConfig config = newBeeMallIndexConfigService.getIndexConfigById(id);
if (config == null) {
return ResultGenerator.genFailResult("未查询到数据");
}
return ResultGenerator.genSuccessResult(config);
}
/**
* 删除
*/
@RequestMapping(value = "/batchDelete", method = RequestMethod.DELETE)
@ApiOperation(value = "批量删除首页配置项信息", notes = "批量删除首页配置项信息")
public Result delete(@RequestBody BatchIdParam batchIdParam, @TokenToAdminUser LoginAdminUser adminUser) {
logger.info("adminUser:{}", adminUser.toString());
if (batchIdParam == null || batchIdParam.getIds().length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
if (newBeeMallIndexConfigService.deleteBatch(batchIdParam.getIds())) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/NewBeeMallIndexController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.enums.IndexConfigTypeEnum;
import ltd.recommend.cloud.newbee.controller.vo.IndexInfoVO;
import ltd.recommend.cloud.newbee.controller.vo.NewBeeMallIndexCarouselVO;
import ltd.recommend.cloud.newbee.controller.vo.NewBeeMallIndexConfigGoodsVO;
import ltd.recommend.cloud.newbee.service.NewBeeMallCarouselService;
import ltd.recommend.cloud.newbee.service.NewBeeMallIndexConfigService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
@Api(value = "v1", tags = "新蜂商城首页接口")
@RequestMapping("/mall/index")
public class NewBeeMallIndexController {
@Resource
private NewBeeMallCarouselService newBeeMallCarouselService;
@Resource
private NewBeeMallIndexConfigService newBeeMallIndexConfigService;
@GetMapping("/recommondInfos")
@ApiOperation(value = "获取首页数据", notes = "轮播图、新品、推荐等")
public Result indexInfo() {
IndexInfoVO indexInfoVO = new IndexInfoVO();
List carousels = newBeeMallCarouselService.getCarouselsForIndex(5);
List hotGoodses = newBeeMallIndexConfigService.getConfigGoodsesForIndex(IndexConfigTypeEnum.INDEX_GOODS_HOT.getType(), 4);
List newGoodses = newBeeMallIndexConfigService.getConfigGoodsesForIndex(IndexConfigTypeEnum.INDEX_GOODS_NEW.getType(), 6);
List recommendGoodses = newBeeMallIndexConfigService.getConfigGoodsesForIndex(IndexConfigTypeEnum.INDEX_GOODS_RECOMMOND.getType(), 10);
indexInfoVO.setCarousels(carousels);
indexInfoVO.setHotGoodses(hotGoodses);
indexInfoVO.setNewGoodses(newGoodses);
indexInfoVO.setRecommendGoodses(recommendGoodses);
return ResultGenerator.genSuccessResult(indexInfoVO);
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/param/BatchIdParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.param;
import lombok.Data;
import java.io.Serializable;
@Data
public class BatchIdParam implements Serializable {
//id数组
Long[] ids;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/param/CarouselAddParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
public class CarouselAddParam {
@ApiModelProperty("轮播图URL地址")
@NotEmpty(message = "轮播图URL不能为空")
private String carouselUrl;
@ApiModelProperty("轮播图跳转地址")
@NotEmpty(message = "轮播图跳转地址不能为空")
private String redirectUrl;
@ApiModelProperty("排序值")
@Min(value = 1, message = "carouselRank最低为1")
@Max(value = 200, message = "carouselRank最高为200")
@NotNull(message = "carouselRank不能为空")
private Integer carouselRank;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/param/CarouselEditParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
public class CarouselEditParam {
@ApiModelProperty("待修改轮播图id")
@NotNull(message = "轮播图id不能为空")
@Min(1)
private Integer carouselId;
@ApiModelProperty("轮播图URL地址")
@NotEmpty(message = "轮播图URL不能为空")
private String carouselUrl;
@ApiModelProperty("轮播图跳转地址")
@NotEmpty(message = "轮播图跳转地址不能为空")
private String redirectUrl;
@ApiModelProperty("排序值")
@Min(value = 1, message = "carouselRank最低为1")
@Max(value = 200, message = "carouselRank最高为200")
@NotNull(message = "carouselRank不能为空")
private Integer carouselRank;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/param/IndexConfigAddParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
public class IndexConfigAddParam {
@ApiModelProperty("配置项名称")
@NotEmpty(message = "configName不能为空")
private String configName;
@ApiModelProperty("配置类别")
@NotNull(message = "configType不能为空")
@Min(value = 1, message = "configType最小为1")
@Max(value = 5, message = "configType最大为5")
private Byte configType;
@ApiModelProperty("商品id")
@NotNull(message = "商品id不能为空")
@Min(value = 1, message = "商品id不能为空")
private Long goodsId;
@ApiModelProperty("排序值")
@Min(value = 1, message = "configRank最低为1")
@Max(value = 200, message = "configRank最高为200")
@NotNull(message = "configRank不能为空")
private Integer configRank;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/param/IndexConfigEditParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
public class IndexConfigEditParam {
@ApiModelProperty("待修改配置id")
@NotNull(message = "configId不能为空")
@Min(value = 1, message = "configId不能为空")
private Long configId;
@ApiModelProperty("配置的名称")
@NotEmpty(message = "configName不能为空")
private String configName;
@ApiModelProperty("配置类别")
@NotNull(message = "configType不能为空")
@Min(value = 1, message = "configType最小为1")
@Max(value = 5, message = "configType最大为5")
private Byte configType;
@ApiModelProperty("商品id")
@NotNull(message = "商品id不能为空")
@Min(value = 1, message = "商品id不能为空")
private Long goodsId;
@ApiModelProperty("排序值")
@Min(value = 1, message = "configRank最低为1")
@Max(value = 200, message = "configRank最高为200")
@NotNull(message = "configRank不能为空")
private Integer configRank;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/vo/IndexInfoVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class IndexInfoVO implements Serializable {
@ApiModelProperty("轮播图(列表)")
private List carousels;
@ApiModelProperty("首页热销商品(列表)")
private List hotGoodses;
@ApiModelProperty("首页新品推荐(列表)")
private List newGoodses;
@ApiModelProperty("首页推荐商品(列表)")
private List recommendGoodses;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/vo/NewBeeMallIndexCarouselVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 首页轮播图VO
*/
@Data
public class NewBeeMallIndexCarouselVO implements Serializable {
@ApiModelProperty("轮播图图片地址")
private String carouselUrl;
@ApiModelProperty("轮播图点击后的跳转路径")
private String redirectUrl;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/vo/NewBeeMallIndexCategoryVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 首页分类数据VO
*/
@Data
public class NewBeeMallIndexCategoryVO implements Serializable {
@ApiModelProperty("当前一级分类id")
private Long categoryId;
@ApiModelProperty("当前分类级别")
private Byte categoryLevel;
@ApiModelProperty("当前一级分类名称")
private String categoryName;
@ApiModelProperty("二级分类列表")
private List secondLevelCategoryVOS;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/vo/NewBeeMallIndexConfigGoodsVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 首页配置商品VO
*/
@Data
public class NewBeeMallIndexConfigGoodsVO implements Serializable {
@ApiModelProperty("商品id")
private Long goodsId;
@ApiModelProperty("商品名称")
private String goodsName;
@ApiModelProperty("商品简介")
private String goodsIntro;
@ApiModelProperty("商品图片地址")
private String goodsCoverImg;
@ApiModelProperty("商品价格")
private Integer sellingPrice;
@ApiModelProperty("商品标签")
private String tag;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/vo/SecondLevelCategoryVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 首页分类数据VO(第二级)
*/
@Data
public class SecondLevelCategoryVO implements Serializable {
@ApiModelProperty("当前二级分类id")
private Long categoryId;
@ApiModelProperty("父级分类id")
private Long parentId;
@ApiModelProperty("当前分类级别")
private Byte categoryLevel;
@ApiModelProperty("当前二级分类名称")
private String categoryName;
@ApiModelProperty("三级分类列表")
private List thirdLevelCategoryVOS;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/controller/vo/ThirdLevelCategoryVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 首页分类数据VO(第三级)
*/
@Data
public class ThirdLevelCategoryVO implements Serializable {
@ApiModelProperty("当前三级分类id")
private Long categoryId;
@ApiModelProperty("当前分类级别")
private Byte categoryLevel;
@ApiModelProperty("当前三级分类名称")
private String categoryName;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/dao/CarouselMapper.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.dao;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.recommend.cloud.newbee.entity.Carousel;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface CarouselMapper {
int deleteByPrimaryKey(Integer carouselId);
int insert(Carousel record);
int insertSelective(Carousel record);
Carousel selectByPrimaryKey(Integer carouselId);
int updateByPrimaryKeySelective(Carousel record);
int updateByPrimaryKey(Carousel record);
List findCarouselList(PageQueryUtil pageUtil);
int getTotalCarousels(PageQueryUtil pageUtil);
int deleteBatch(Long[] ids);
List findCarouselsByNum(@Param("number") int number);
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/dao/IndexConfigMapper.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.dao;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.recommend.cloud.newbee.entity.IndexConfig;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface IndexConfigMapper {
int deleteByPrimaryKey(Long configId);
int insert(IndexConfig record);
int insertSelective(IndexConfig record);
IndexConfig selectByPrimaryKey(Long configId);
IndexConfig selectByTypeAndGoodsId(@Param("configType") int configType, @Param("goodsId") Long goodsId);
int updateByPrimaryKeySelective(IndexConfig record);
int updateByPrimaryKey(IndexConfig record);
List findIndexConfigList(PageQueryUtil pageUtil);
int getTotalIndexConfigs(PageQueryUtil pageUtil);
int deleteBatch(Long[] ids);
List findIndexConfigsByTypeAndNum(@Param("configType") int configType, @Param("number") int number);
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/entity/Carousel.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class Carousel {
private Integer carouselId;
private String carouselUrl;
private String redirectUrl;
private Integer carouselRank;
private Byte isDeleted;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
private Integer createUser;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
private Integer updateUser;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/entity/IndexConfig.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class IndexConfig {
private Long configId;
private String configName;
private Byte configType;
private Long goodsId;
private String redirectUrl;
private Integer configRank;
private Byte isDeleted;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
private Integer createUser;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
private Integer updateUser;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/entity/LoginAdminUser.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.entity;
import lombok.Data;
@Data
public class LoginAdminUser {
private Long adminUserId;
private String loginUserName;
private String loginPassword;
private String nickName;
private Byte locked;
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/service/NewBeeMallCarouselService.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.service;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.recommend.cloud.newbee.controller.vo.NewBeeMallIndexCarouselVO;
import ltd.recommend.cloud.newbee.entity.Carousel;
import java.util.List;
public interface NewBeeMallCarouselService {
/**
* 后台分页
*
* @param pageUtil
* @return
*/
PageResult getCarouselPage(PageQueryUtil pageUtil);
String saveCarousel(Carousel carousel);
String updateCarousel(Carousel carousel);
Carousel getCarouselById(Integer id);
Boolean deleteBatch(Long[] ids);
/**
* 返回固定数量的轮播图对象(首页调用)
*
* @param number
* @return
*/
List getCarouselsForIndex(int number);
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/service/NewBeeMallIndexConfigService.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.service;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.recommend.cloud.newbee.controller.vo.NewBeeMallIndexConfigGoodsVO;
import ltd.recommend.cloud.newbee.entity.IndexConfig;
import java.util.List;
public interface NewBeeMallIndexConfigService {
/**
* 后台分页
*
* @param pageUtil
* @return
*/
PageResult getConfigsPage(PageQueryUtil pageUtil);
String saveIndexConfig(IndexConfig indexConfig);
String updateIndexConfig(IndexConfig indexConfig);
IndexConfig getIndexConfigById(Long id);
Boolean deleteBatch(Long[] ids);
/**
* 返回固定数量的首页配置商品对象(首页调用)
*
* @param number
* @return
*/
List getConfigGoodsesForIndex(int configType, int number);
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/service/impl/NewBeeMallCarouselServiceImpl.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.service.impl;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.recommend.cloud.newbee.controller.vo.NewBeeMallIndexCarouselVO;
import ltd.recommend.cloud.newbee.dao.CarouselMapper;
import ltd.recommend.cloud.newbee.entity.Carousel;
import ltd.recommend.cloud.newbee.service.NewBeeMallCarouselService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class NewBeeMallCarouselServiceImpl implements NewBeeMallCarouselService {
@Autowired
private CarouselMapper carouselMapper;
@Override
public PageResult getCarouselPage(PageQueryUtil pageUtil) {
List carousels = carouselMapper.findCarouselList(pageUtil);
int total = carouselMapper.getTotalCarousels(pageUtil);
PageResult pageResult = new PageResult(carousels, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public String saveCarousel(Carousel carousel) {
if (carouselMapper.insertSelective(carousel) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public String updateCarousel(Carousel carousel) {
Carousel temp = carouselMapper.selectByPrimaryKey(carousel.getCarouselId());
if (temp == null) {
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
temp.setCarouselRank(carousel.getCarouselRank());
temp.setRedirectUrl(carousel.getRedirectUrl());
temp.setCarouselUrl(carousel.getCarouselUrl());
temp.setUpdateTime(new Date());
if (carouselMapper.updateByPrimaryKeySelective(temp) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public Carousel getCarouselById(Integer id) {
return carouselMapper.selectByPrimaryKey(id);
}
@Override
public Boolean deleteBatch(Long[] ids) {
if (ids.length < 1) {
return false;
}
//删除数据
return carouselMapper.deleteBatch(ids) > 0;
}
@Override
public List getCarouselsForIndex(int number) {
List newBeeMallIndexCarouselVOS = new ArrayList<>(number);
List carousels = carouselMapper.findCarouselsByNum(number);
if (!CollectionUtils.isEmpty(carousels)) {
newBeeMallIndexCarouselVOS = BeanUtil.copyList(carousels, NewBeeMallIndexCarouselVO.class);
}
return newBeeMallIndexCarouselVOS;
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/java/ltd/recommend/cloud/newbee/service/impl/NewBeeMallIndexConfigServiceImpl.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.recommend.cloud.newbee.service.impl;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.goods.cloud.newbee.dto.NewBeeMallGoodsDTO;
import ltd.goods.cloud.newbee.openfeign.NewBeeCloudGoodsServiceFeign;
import ltd.recommend.cloud.newbee.controller.vo.NewBeeMallIndexConfigGoodsVO;
import ltd.recommend.cloud.newbee.dao.IndexConfigMapper;
import ltd.recommend.cloud.newbee.entity.IndexConfig;
import ltd.recommend.cloud.newbee.service.NewBeeMallIndexConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class NewBeeMallIndexConfigServiceImpl implements NewBeeMallIndexConfigService {
@Autowired
private IndexConfigMapper indexConfigMapper;
@Autowired
private NewBeeCloudGoodsServiceFeign goodsService;
@Override
public PageResult getConfigsPage(PageQueryUtil pageUtil) {
List indexConfigs = indexConfigMapper.findIndexConfigList(pageUtil);
int total = indexConfigMapper.getTotalIndexConfigs(pageUtil);
PageResult pageResult = new PageResult(indexConfigs, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public String saveIndexConfig(IndexConfig indexConfig) {
Result goodsDetailResult = goodsService.getGoodsDetail(indexConfig.getGoodsId());
if (goodsDetailResult == null || goodsDetailResult.getResultCode() != 200) {
return ServiceResultEnum.GOODS_NOT_EXIST.getResult();
}
if (indexConfigMapper.selectByTypeAndGoodsId(indexConfig.getConfigType(), indexConfig.getGoodsId()) != null) {
return ServiceResultEnum.SAME_INDEX_CONFIG_EXIST.getResult();
}
if (indexConfigMapper.insertSelective(indexConfig) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public String updateIndexConfig(IndexConfig indexConfig) {
Result goodsDetailResult = goodsService.getGoodsDetail(indexConfig.getGoodsId());
if (goodsDetailResult == null || goodsDetailResult.getResultCode() != 200) {
return ServiceResultEnum.GOODS_NOT_EXIST.getResult();
}
IndexConfig temp = indexConfigMapper.selectByPrimaryKey(indexConfig.getConfigId());
if (temp == null) {
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
IndexConfig temp2 = indexConfigMapper.selectByTypeAndGoodsId(indexConfig.getConfigType(), indexConfig.getGoodsId());
if (temp2 != null && !temp2.getConfigId().equals(indexConfig.getConfigId())) {
//goodsId相同且不同id 不能继续修改
return ServiceResultEnum.SAME_INDEX_CONFIG_EXIST.getResult();
}
indexConfig.setUpdateTime(new Date());
if (indexConfigMapper.updateByPrimaryKeySelective(indexConfig) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public IndexConfig getIndexConfigById(Long id) {
return indexConfigMapper.selectByPrimaryKey(id);
}
@Override
public Boolean deleteBatch(Long[] ids) {
if (ids.length < 1) {
return false;
}
//删除数据
return indexConfigMapper.deleteBatch(ids) > 0;
}
@Override
public List getConfigGoodsesForIndex(int configType, int number) {
List newBeeMallIndexConfigGoodsVOS = new ArrayList<>(number);
List indexConfigs = indexConfigMapper.findIndexConfigsByTypeAndNum(configType, number);
if (!CollectionUtils.isEmpty(indexConfigs)) {
//取出所有的goodsId
List goodsIds = indexConfigs.stream().map(IndexConfig::getGoodsId).collect(Collectors.toList());
Result> newBeeMallGoodsDTOResult = goodsService.listByGoodsIds(goodsIds);
newBeeMallIndexConfigGoodsVOS = BeanUtil.copyList(newBeeMallGoodsDTOResult.getData(), NewBeeMallIndexConfigGoodsVO.class);
for (NewBeeMallIndexConfigGoodsVO newBeeMallIndexConfigGoodsVO : newBeeMallIndexConfigGoodsVOS) {
String goodsName = newBeeMallIndexConfigGoodsVO.getGoodsName();
String goodsIntro = newBeeMallIndexConfigGoodsVO.getGoodsIntro();
// 字符串过长导致文字超出的问题
if (goodsName.length() > 30) {
goodsName = goodsName.substring(0, 30) + "...";
newBeeMallIndexConfigGoodsVO.setGoodsName(goodsName);
}
if (goodsIntro.length() > 22) {
goodsIntro = goodsIntro.substring(0, 22) + "...";
newBeeMallIndexConfigGoodsVO.setGoodsIntro(goodsIntro);
}
}
}
return newBeeMallIndexConfigGoodsVOS;
}
}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/resources/application.properties
================================================
server.port=29020
# 服务名称
spring.application.name=newbee-mall-cloud-recommend-service
# Nacos地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
# Nacos登录用户名(默认为nacos,生产环境一定要修改)
spring.cloud.nacos.username=nacos
# Nacos登录密码(默认为nacos,生产环境一定要修改)
spring.cloud.nacos.password=nacos
# datasource config (MySQL)
spring.datasource.name=newbee-mall-cloud-recommend-datasource
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/newbee_mall_cloud_recommend_db?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf8&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=60000
spring.datasource.hikari.pool-name=hikariCP
spring.datasource.hikari.max-lifetime=600000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1
# mybatis config
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
# openfeign config
feign.client.config.default.connectTimeout=2000
feign.client.config.default.readTimeout=5000
feign.compression.request.enabled=true
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=1024
feign.compression.response.enabled=true
# 演示需要,开启OpenFeign和当前项目中的DEBUG级别日志
#logging.level.ltd.user.cloud.newbee.openfeign=debug
#logging.level.ltd.goods.cloud.newbee.openfeign=debug
#logging.level.ltd.recommend.cloud.newbee=debug
# sentinel config
spring.cloud.sentinel.transport.port=8920
spring.cloud.sentinel.transport.clientIp=127.0.0.1
# 指定Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=127.0.0.1:9113
# Sleuth采样率,取值范围为[0.1,1.0],值越大收集越及时,但性能影响也越大
spring.sleuth.sampler.probability=1.0
# 每秒数据采集量,最多n条/秒Trace
spring.sleuth.sampler.rate=500
spring.zipkin.base-url=http://localhost:9411
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/resources/logback.xml
================================================
${APP_NAME}
INFO
${CONSOLE_LOG_PATTERN}
utf8
192.168.110.57:4560
INFO
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/resources/mapper/CarouselMapper.xml
================================================
carousel_id, carousel_url, redirect_url, carousel_rank, is_deleted, create_time,
create_user, update_time, update_user
delete from tb_newbee_mall_carousel
where carousel_id = #{carouselId,jdbcType=INTEGER}
insert into tb_newbee_mall_carousel (carousel_id, carousel_url, redirect_url,
carousel_rank, is_deleted, create_time,
create_user, update_time, update_user
)
values (#{carouselId,jdbcType=INTEGER}, #{carouselUrl,jdbcType=VARCHAR}, #{redirectUrl,jdbcType=VARCHAR},
#{carouselRank,jdbcType=INTEGER}, #{isDeleted,jdbcType=TINYINT}, #{createTime,jdbcType=TIMESTAMP},
#{createUser,jdbcType=INTEGER}, #{updateTime,jdbcType=TIMESTAMP}, #{updateUser,jdbcType=INTEGER}
)
insert into tb_newbee_mall_carousel
carousel_id,
carousel_url,
redirect_url,
carousel_rank,
is_deleted,
create_time,
create_user,
update_time,
update_user,
#{carouselId,jdbcType=INTEGER},
#{carouselUrl,jdbcType=VARCHAR},
#{redirectUrl,jdbcType=VARCHAR},
#{carouselRank,jdbcType=INTEGER},
#{isDeleted,jdbcType=TINYINT},
#{createTime,jdbcType=TIMESTAMP},
#{createUser,jdbcType=INTEGER},
#{updateTime,jdbcType=TIMESTAMP},
#{updateUser,jdbcType=INTEGER},
update tb_newbee_mall_carousel
carousel_url = #{carouselUrl,jdbcType=VARCHAR},
redirect_url = #{redirectUrl,jdbcType=VARCHAR},
carousel_rank = #{carouselRank,jdbcType=INTEGER},
is_deleted = #{isDeleted,jdbcType=TINYINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
create_user = #{createUser,jdbcType=INTEGER},
update_time = #{updateTime,jdbcType=TIMESTAMP},
update_user = #{updateUser,jdbcType=INTEGER},
where carousel_id = #{carouselId,jdbcType=INTEGER}
update tb_newbee_mall_carousel
set carousel_url = #{carouselUrl,jdbcType=VARCHAR},
redirect_url = #{redirectUrl,jdbcType=VARCHAR},
carousel_rank = #{carouselRank,jdbcType=INTEGER},
is_deleted = #{isDeleted,jdbcType=TINYINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
create_user = #{createUser,jdbcType=INTEGER},
update_time = #{updateTime,jdbcType=TIMESTAMP},
update_user = #{updateUser,jdbcType=INTEGER}
where carousel_id = #{carouselId,jdbcType=INTEGER}
update tb_newbee_mall_carousel
set is_deleted=1,update_time=now() where carousel_id in
#{id}
================================================
FILE: newbee-mall-cloud-recommend-service/newbee-mall-cloud-recommend-web/src/main/resources/mapper/IndexConfigMapper.xml
================================================
config_id, config_name, config_type, goods_id, redirect_url, config_rank, is_deleted,
create_time, create_user, update_time, update_user
update tb_newbee_mall_index_config set is_deleted=1
where config_id = #{configId,jdbcType=BIGINT} and is_deleted=0
update tb_newbee_mall_index_config
set is_deleted=1,update_time=now() where is_deleted=0 and config_id in
#{id}
insert into tb_newbee_mall_index_config (config_id, config_name, config_type,
goods_id, redirect_url, config_rank,
is_deleted, create_time, create_user,
update_time, update_user)
values (#{configId,jdbcType=BIGINT}, #{configName,jdbcType=VARCHAR}, #{configType,jdbcType=TINYINT},
#{goodsId,jdbcType=BIGINT}, #{redirectUrl,jdbcType=VARCHAR}, #{configRank,jdbcType=INTEGER},
#{isDeleted,jdbcType=TINYINT}, #{createTime,jdbcType=TIMESTAMP}, #{createUser,jdbcType=INTEGER},
#{updateTime,jdbcType=TIMESTAMP}, #{updateUser,jdbcType=INTEGER})
insert into tb_newbee_mall_index_config
config_id,
config_name,
config_type,
goods_id,
redirect_url,
config_rank,
is_deleted,
create_time,
create_user,
update_time,
update_user,
#{configId,jdbcType=BIGINT},
#{configName,jdbcType=VARCHAR},
#{configType,jdbcType=TINYINT},
#{goodsId,jdbcType=BIGINT},
#{redirectUrl,jdbcType=VARCHAR},
#{configRank,jdbcType=INTEGER},
#{isDeleted,jdbcType=TINYINT},
#{createTime,jdbcType=TIMESTAMP},
#{createUser,jdbcType=INTEGER},
#{updateTime,jdbcType=TIMESTAMP},
#{updateUser,jdbcType=INTEGER},
update tb_newbee_mall_index_config
config_name = #{configName,jdbcType=VARCHAR},
config_type = #{configType,jdbcType=TINYINT},
goods_id = #{goodsId,jdbcType=BIGINT},
redirect_url = #{redirectUrl,jdbcType=VARCHAR},
config_rank = #{configRank,jdbcType=INTEGER},
is_deleted = #{isDeleted,jdbcType=TINYINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
create_user = #{createUser,jdbcType=INTEGER},
update_time = #{updateTime,jdbcType=TIMESTAMP},
update_user = #{updateUser,jdbcType=INTEGER},
where config_id = #{configId,jdbcType=BIGINT}
update tb_newbee_mall_index_config
set config_name = #{configName,jdbcType=VARCHAR},
config_type = #{configType,jdbcType=TINYINT},
goods_id = #{goodsId,jdbcType=BIGINT},
redirect_url = #{redirectUrl,jdbcType=VARCHAR},
config_rank = #{configRank,jdbcType=INTEGER},
is_deleted = #{isDeleted,jdbcType=TINYINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
create_user = #{createUser,jdbcType=INTEGER},
update_time = #{updateTime,jdbcType=TIMESTAMP},
update_user = #{updateUser,jdbcType=INTEGER}
where config_id = #{configId,jdbcType=BIGINT}
================================================
FILE: newbee-mall-cloud-recommend-service/pom.xml
================================================
4.0.0
ltd.newbee.cloud
newbee-mall-cloud-recommend-service
0.0.1-SNAPSHOT
pom
newbee-mall-cloud-recommend-service
推荐模块
ltd.newbee.cloud
newbee-mall-cloud
0.0.1-SNAPSHOT
1.8
newbee-mall-cloud-recommend-web
newbee-mall-cloud-recommend-api
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-api/pom.xml
================================================
4.0.0
ltd.shopcart.newbee.cloud
newbee-mall-cloud-shop-cart-api
jar
0.0.1-SNAPSHOT
newbee-mall-cloud-shop-cart-api
购物车服务openfeign
ltd.newbee.cloud
newbee-mall-cloud-shop-cart-service
0.0.1-SNAPSHOT
1.8
org.springframework.cloud
spring-cloud-starter-openfeign
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-api/src/main/java/ltd/shopcart/cloud/newbee/dto/NewBeeMallShoppingCartItemDTO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.dto;
import java.io.Serializable;
public class NewBeeMallShoppingCartItemDTO implements Serializable {
private Long cartItemId;
private Long userId;
private Long goodsId;
private Integer goodsCount;
public Long getCartItemId() {
return cartItemId;
}
public void setCartItemId(Long cartItemId) {
this.cartItemId = cartItemId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getGoodsId() {
return goodsId;
}
public void setGoodsId(Long goodsId) {
this.goodsId = goodsId;
}
public Integer getGoodsCount() {
return goodsCount;
}
public void setGoodsCount(Integer goodsCount) {
this.goodsCount = goodsCount;
}
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-api/src/main/java/ltd/shopcart/cloud/newbee/openfeign/NewBeeCloudShopCartServiceFeign.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.openfeign;
import ltd.common.cloud.newbee.dto.Result;
import ltd.shopcart.cloud.newbee.dto.NewBeeMallShoppingCartItemDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@FeignClient(value = "newbee-mall-cloud-shop-cart-service", path = "/shop-cart")
public interface NewBeeCloudShopCartServiceFeign {
@GetMapping(value = "/listByCartItemIds")
Result> listByCartItemIds(@RequestParam(value = "cartItemIds") List cartItemIds);
@DeleteMapping(value = "/deleteByCartItemIds")
Result deleteByCartItemIds(@RequestParam(value = "cartItemIds") List cartItemIds);
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/pom.xml
================================================
4.0.0
ltd.shopcart.newbee.cloud
newbee-mall-cloud-shop-cart-web
0.0.1-SNAPSHOT
newbee-mall-cloud-shop-cart-web
购物车服务
ltd.newbee.cloud
newbee-mall-cloud-shop-cart-service
0.0.1-SNAPSHOT
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
org.springframework.boot
spring-boot-starter-validation
org.mybatis.spring.boot
mybatis-spring-boot-starter
com.alibaba.cloud
spring-cloud-starter-alibaba-seata
org.projectlombok
lombok
${lombok.version}
provided
io.springfox
springfox-boot-starter
mysql
mysql-connector-java
runtime
ltd.newbee.cloud
newbee-mall-cloud-common
0.0.1-SNAPSHOT
org.springframework.cloud
spring-cloud-starter-openfeign
org.springframework.cloud
spring-cloud-starter-loadbalancer
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
org.springframework.cloud
spring-cloud-starter-sleuth
org.springframework.cloud
spring-cloud-sleuth-zipkin
net.logstash.logback
logstash-logback-encoder
${logstash-logback-encoder.version}
ltd.user.newbee.cloud
newbee-mall-cloud-user-api
0.0.1-SNAPSHOT
ltd.goods.newbee.cloud
newbee-mall-cloud-goods-api
0.0.1-SNAPSHOT
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/NewBeeMallCloudShopCartServiceApplication.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本系统已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee;
import ltd.goods.cloud.newbee.openfeign.NewBeeCloudGoodsServiceFeign;
import ltd.user.cloud.newbee.openfeign.NewBeeCloudUserServiceFeign;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @author 程序员十三
* @qq交流群 791509631
* @email 2449207463@qq.com
* @link https://github.com/newbee-ltd
*/
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("ltd.shopcart.cloud.newbee.dao")
@EnableFeignClients(basePackageClasses ={NewBeeCloudUserServiceFeign.class, NewBeeCloudGoodsServiceFeign.class})
public class NewBeeMallCloudShopCartServiceApplication {
public static void main(String[] args) {
System.setProperty("nacos.logging.default.config.enabled","false");
SpringApplication.run(NewBeeMallCloudShopCartServiceApplication.class, args);
}
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/config/OpenFeignConfiguration.java
================================================
package ltd.shopcart.cloud.newbee.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenFeignConfiguration {
@Bean
public Logger.Level openFeignLogLevel() {
// 设置OpenFeign日志级别
return Logger.Level.FULL;
}
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/config/SeataProxyConfiguration.java
================================================
package ltd.shopcart.cloud.newbee.config;
import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
@Configuration
public class SeataProxyConfiguration {
//创建Druid数据源
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource() {
return new DruidDataSource();
}
//创建DataSource数据源代理
@Bean("dataSource")
@Primary
public DataSource dataSourceDelegation(DruidDataSource druidDataSource) {
return new DataSourceProxy(druidDataSource);
}
/*
* 解决druid 日志报错:discard long time none received connection:xxx
* */
@PostConstruct
public void setProperties(){
System.setProperty("druid.mysql.usePingMethod","false");
}
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/config/ShopCartServiceExceptionHandler.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.config;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* 全局异常处理
*/
@RestControllerAdvice
public class ShopCartServiceExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(ShopCartServiceExceptionHandler.class);
@ExceptionHandler(BindException.class)
public Object bindException(BindException e) {
log.error("ShopCartServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(510);
BindingResult bindingResult = e.getBindingResult();
result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
return result;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object bindException(MethodArgumentNotValidException e) {
log.error("ShopCartServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(510);
BindingResult bindingResult = e.getBindingResult();
result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
return result;
}
@ExceptionHandler(Exception.class)
public Object handleException(Exception e, HttpServletRequest req) {
log.error("ShopCartServiceExceptionHandler:",e);
Result result = new Result();
result.setResultCode(500);
//区分是否为自定义异常
if (e instanceof NewBeeMallException) {
result.setMessage(e.getMessage());
if (e.getMessage().equals(ServiceResultEnum.NOT_LOGIN_ERROR.getResult()) || e.getMessage().equals(ServiceResultEnum.TOKEN_EXPIRE_ERROR.getResult())) {
result.setResultCode(416);
}
} else {
e.printStackTrace();
result.setMessage("未知异常,请查看控制台日志并检查配置文件。");
}
return result;
}
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/config/ShopCartServiceSwagger3Config.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.config;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableOpenApi
public class ShopCartServiceSwagger3Config{
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.ignoredParameterTypes(MallUserToken.class)
.select()
.apis(RequestHandlerSelectors.basePackage("ltd.shopcart.cloud.newbee.controller"))
.paths(PathSelectors.any())
.build()
.globalRequestParameters(getGlobalRequestParameters());
}
//生成全局通用参数
private List getGlobalRequestParameters() {
List parameters = new ArrayList<>();
parameters.add(new RequestParameterBuilder()
.name("token")
.description("登录认证token")
.required(false) // 非必传
.in(ParameterType.HEADER) //请求头中的参数,其它类型可以点进ParameterType类中查看
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.build());
return parameters;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("newbee-mall-cloud-shop-cart-service接口文档")
.description("swagger接口文档")
.version("2.0")
.build();
}
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/config/ShopCartServiceWebMvcConfigurer.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.config;
import com.alibaba.cloud.seata.web.SeataHandlerInterceptor;
import com.alibaba.cloud.sentinel.SentinelProperties;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import ltd.shopcart.cloud.newbee.config.handler.TokenToMallUserMethodArgumentResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
import java.util.Optional;
@Configuration
public class ShopCartServiceWebMvcConfigurer extends WebMvcConfigurationSupport {
private static final Logger log = LoggerFactory.getLogger(ShopCartServiceWebMvcConfigurer.class);
@Autowired
private SentinelProperties sentinelProperties;
@Autowired
private Optional sentinelWebInterceptorOptional;
@Autowired
@Lazy
private TokenToMallUserMethodArgumentResolver tokenToMallUserMethodArgumentResolver;
/**
* @param argumentResolvers
* @tip @TokenToMallUser 注解处理方法
*/
public void addArgumentResolvers(List argumentResolvers) {
argumentResolvers.add(tokenToMallUserMethodArgumentResolver);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.
addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
.resourceChain(false);
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SeataHandlerInterceptor()).addPathPatterns("/**");
if (this.sentinelWebInterceptorOptional.isPresent()) {
SentinelProperties.Filter filterConfig = this.sentinelProperties.getFilter();
registry.addInterceptor((HandlerInterceptor) this.sentinelWebInterceptorOptional.get()).order(filterConfig.getOrder()).addPathPatterns(filterConfig.getUrlPatterns());
log.info("[Sentinel Starter] register SentinelWebInterceptor with urlPatterns: {}.", filterConfig.getUrlPatterns());
}
}
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/config/annotation/TokenToMallUser.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.config.annotation;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TokenToMallUser {
/**
* 当前用户在request中的名字
*
* @return
*/
String value() default "user";
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/config/handler/TokenToMallUserMethodArgumentResolver.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.config.handler;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import ltd.shopcart.cloud.newbee.config.annotation.TokenToMallUser;
import ltd.user.cloud.newbee.dto.MallUserDTO;
import ltd.user.cloud.newbee.openfeign.NewBeeCloudUserServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@Component
public class TokenToMallUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
private NewBeeCloudUserServiceFeign newBeeCloudUserService;
public TokenToMallUserMethodArgumentResolver() {
}
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(TokenToMallUser.class)) {
return true;
}
return false;
}
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
if (parameter.getParameterAnnotation(TokenToMallUser.class) instanceof TokenToMallUser) {
String token = webRequest.getHeader("token");
if (null != token && !"".equals(token) && token.length() == 32) {
Result result = newBeeCloudUserService.getMallUserByToken(token);
if (result == null || result.getResultCode() != 200 || result.getData() == null) {
NewBeeMallException.fail(ServiceResultEnum.TOKEN_EXPIRE_ERROR.getResult());
}
MallUserToken mallUserToken = new MallUserToken();
mallUserToken.setToken(token);
mallUserToken.setUserId(result.getData().getUserId());
return mallUserToken;
} else {
NewBeeMallException.fail(ServiceResultEnum.NOT_LOGIN_ERROR.getResult());
}
}
return null;
}
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/controller/NewBeeMallShoppingCartController.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.controller;
import io.seata.core.context.RootContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.dto.ResultGenerator;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.common.cloud.newbee.pojo.MallUserToken;
import ltd.shopcart.cloud.newbee.config.annotation.TokenToMallUser;
import ltd.shopcart.cloud.newbee.controller.param.SaveCartItemParam;
import ltd.shopcart.cloud.newbee.controller.param.UpdateCartItemParam;
import ltd.shopcart.cloud.newbee.controller.vo.NewBeeMallShoppingCartItemVO;
import ltd.shopcart.cloud.newbee.entity.NewBeeMallShoppingCartItem;
import ltd.shopcart.cloud.newbee.service.NewBeeMallShoppingCartService;
import org.springframework.http.HttpRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@Api(value = "v1", tags = "新蜂商城购物车相关接口")
public class NewBeeMallShoppingCartController {
@Resource
private NewBeeMallShoppingCartService newBeeMallShoppingCartService;
@GetMapping("/shop-cart/page")
@ApiOperation(value = "购物车列表(每页默认5条)", notes = "传参为页码")
public Result>> cartItemPageList(Integer pageNumber, @TokenToMallUser MallUserToken loginMallUserToken) {
Map params = new HashMap(8);
if (pageNumber == null || pageNumber < 1) {
pageNumber = 1;
}
params.put("userId", loginMallUserToken.getUserId());
params.put("page", pageNumber);
params.put("limit", 5);
//封装分页请求参数
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallShoppingCartService.getMyShoppingCartItems(pageUtil));
}
@GetMapping("/shop-cart")
@ApiOperation(value = "购物车列表(网页移动端不分页)", notes = "")
public Result> cartItemList(@TokenToMallUser MallUserToken loginMallUserToken) {
return ResultGenerator.genSuccessResult(newBeeMallShoppingCartService.getMyShoppingCartItems(loginMallUserToken.getUserId()));
}
@PostMapping("/shop-cart")
@ApiOperation(value = "添加商品到购物车接口", notes = "传参为商品id、数量")
public Result saveNewBeeMallShoppingCartItem(@RequestBody SaveCartItemParam saveCartItemParam,
@TokenToMallUser MallUserToken loginMallUserToken) {
String saveResult = newBeeMallShoppingCartService.saveNewBeeMallCartItem(saveCartItemParam, loginMallUserToken.getUserId());
//添加成功
if (ServiceResultEnum.SUCCESS.getResult().equals(saveResult)) {
return ResultGenerator.genSuccessResult();
}
//添加失败
return ResultGenerator.genFailResult(saveResult);
}
@PutMapping("/shop-cart")
@ApiOperation(value = "修改购物项数据", notes = "传参为购物项id、数量")
public Result updateNewBeeMallShoppingCartItem(@RequestBody UpdateCartItemParam updateCartItemParam,
@TokenToMallUser MallUserToken loginMallUserToken) {
String updateResult = newBeeMallShoppingCartService.updateNewBeeMallCartItem(updateCartItemParam, loginMallUserToken.getUserId());
//修改成功
if (ServiceResultEnum.SUCCESS.getResult().equals(updateResult)) {
return ResultGenerator.genSuccessResult();
}
//修改失败
return ResultGenerator.genFailResult(updateResult);
}
@DeleteMapping("/shop-cart/{newBeeMallShoppingCartItemId}")
@ApiOperation(value = "删除购物项", notes = "传参为购物项id")
public Result updateNewBeeMallShoppingCartItem(@PathVariable("newBeeMallShoppingCartItemId") Long newBeeMallShoppingCartItemId,
@TokenToMallUser MallUserToken loginMallUserToken) {
NewBeeMallShoppingCartItem newBeeMallCartItemById = newBeeMallShoppingCartService.getNewBeeMallCartItemById(newBeeMallShoppingCartItemId);
if (!loginMallUserToken.getUserId().equals(newBeeMallCartItemById.getUserId())) {
return ResultGenerator.genFailResult(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
}
Boolean deleteResult = newBeeMallShoppingCartService.deleteById(newBeeMallShoppingCartItemId, loginMallUserToken.getUserId());
//删除成功
if (deleteResult) {
return ResultGenerator.genSuccessResult();
}
//删除失败
return ResultGenerator.genFailResult(ServiceResultEnum.OPERATE_ERROR.getResult());
}
@GetMapping("/shop-cart/settle")
@ApiOperation(value = "根据购物项id数组查询购物项明细", notes = "确认订单页面使用")
public Result> toSettle(Long[] cartItemIds, @TokenToMallUser MallUserToken loginMallUserToken) {
if (cartItemIds.length < 1) {
NewBeeMallException.fail("参数异常");
}
int priceTotal = 0;
List itemsForSettle = newBeeMallShoppingCartService.getCartItemsForSettle(Arrays.asList(cartItemIds), loginMallUserToken.getUserId());
if (CollectionUtils.isEmpty(itemsForSettle)) {
//无数据则抛出异常
NewBeeMallException.fail("参数异常");
} else {
//总价
for (NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO : itemsForSettle) {
priceTotal += newBeeMallShoppingCartItemVO.getGoodsCount() * newBeeMallShoppingCartItemVO.getSellingPrice();
}
if (priceTotal < 1) {
NewBeeMallException.fail("价格异常");
}
}
return ResultGenerator.genSuccessResult(itemsForSettle);
}
@GetMapping("/shop-cart/listByCartItemIds")
@ApiOperation(value = "购物车列表", notes = "")
public Result> cartItemListByIds(@RequestParam("cartItemIds") List cartItemIds) {
if (CollectionUtils.isEmpty(cartItemIds)) {
return ResultGenerator.genFailResult("error param");
}
return ResultGenerator.genSuccessResult(newBeeMallShoppingCartService.getCartItemsByCartIds(cartItemIds));
}
@DeleteMapping("/shop-cart/deleteByCartItemIds")
@ApiOperation(value = "批量删除购物项", notes = "")
public Result deleteByCartItemIds(@RequestParam("cartItemIds") List cartItemIds, HttpServletRequest request) {
System.out.println("RootContext.getXID()="+ RootContext.getXID());
if (CollectionUtils.isEmpty(cartItemIds)) {
return ResultGenerator.genFailResult("error param");
}
return ResultGenerator.genSuccessResult(newBeeMallShoppingCartService.deleteCartItemsByCartIds(cartItemIds) > 0);
}
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/controller/param/SaveCartItemParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 添加购物项param
*/
@Data
public class SaveCartItemParam implements Serializable {
@ApiModelProperty("商品数量")
private Integer goodsCount;
@ApiModelProperty("商品id")
private Long goodsId;
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/controller/param/UpdateCartItemParam.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.controller.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 修改购物项param
*/
@Data
public class UpdateCartItemParam implements Serializable {
@ApiModelProperty("购物项id")
private Long cartItemId;
@ApiModelProperty("商品数量")
private Integer goodsCount;
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/controller/vo/NewBeeMallShoppingCartItemVO.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.controller.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 购物车页面购物项VO
*/
@Data
public class NewBeeMallShoppingCartItemVO implements Serializable {
@ApiModelProperty("购物项id")
private Long cartItemId;
@ApiModelProperty("商品id")
private Long goodsId;
@ApiModelProperty("商品数量")
private Integer goodsCount;
@ApiModelProperty("商品名称")
private String goodsName;
@ApiModelProperty("商品图片")
private String goodsCoverImg;
@ApiModelProperty("商品价格")
private Integer sellingPrice;
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/dao/NewBeeMallShoppingCartItemMapper.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.dao;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.shopcart.cloud.newbee.entity.NewBeeMallShoppingCartItem;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface NewBeeMallShoppingCartItemMapper {
int deleteByPrimaryKey(Long cartItemId);
int insert(NewBeeMallShoppingCartItem record);
int insertSelective(NewBeeMallShoppingCartItem record);
NewBeeMallShoppingCartItem selectByPrimaryKey(Long cartItemId);
NewBeeMallShoppingCartItem selectByUserIdAndGoodsId(@Param("newBeeMallUserId") Long newBeeMallUserId, @Param("goodsId") Long goodsId);
List selectByUserId(@Param("newBeeMallUserId") Long newBeeMallUserId, @Param("number") int number);
List selectByUserIdAndCartItemIds(@Param("newBeeMallUserId") Long newBeeMallUserId, @Param("cartItemIds") List cartItemIds);
List selectByCartItemIds(@Param("cartItemIds") List cartItemIds);
int selectCountByUserId(Long newBeeMallUserId);
int updateByPrimaryKeySelective(NewBeeMallShoppingCartItem record);
int updateByPrimaryKey(NewBeeMallShoppingCartItem record);
int deleteBatch(List ids);
List findMyNewBeeMallCartItems(PageQueryUtil pageUtil);
int getTotalMyNewBeeMallCartItems(PageQueryUtil pageUtil);
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/entity/NewBeeMallShoppingCartItem.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.entity;
import lombok.Data;
import java.util.Date;
@Data
public class NewBeeMallShoppingCartItem {
private Long cartItemId;
private Long userId;
private Long goodsId;
private Integer goodsCount;
private Byte isDeleted;
private Date createTime;
private Date updateTime;
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/service/NewBeeMallShoppingCartService.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.service;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.shopcart.cloud.newbee.controller.param.SaveCartItemParam;
import ltd.shopcart.cloud.newbee.controller.param.UpdateCartItemParam;
import ltd.shopcart.cloud.newbee.controller.vo.NewBeeMallShoppingCartItemVO;
import ltd.shopcart.cloud.newbee.entity.NewBeeMallShoppingCartItem;
import java.util.List;
public interface NewBeeMallShoppingCartService {
/**
* 保存商品至购物车中
*
* @param saveCartItemParam
* @param userId
* @return
*/
String saveNewBeeMallCartItem(SaveCartItemParam saveCartItemParam, Long userId);
/**
* 修改购物车中的属性
*
* @param updateCartItemParam
* @param userId
* @return
*/
String updateNewBeeMallCartItem(UpdateCartItemParam updateCartItemParam, Long userId);
/**
* 获取购物项详情
*
* @param newBeeMallShoppingCartItemId
* @return
*/
NewBeeMallShoppingCartItem getNewBeeMallCartItemById(Long newBeeMallShoppingCartItemId);
/**
* 删除购物车中的商品
*
* @param shoppingCartItemId
* @param userId
* @return
*/
Boolean deleteById(Long shoppingCartItemId, Long userId);
/**
* 获取我的购物车中的列表数据
*
* @param newBeeMallUserId
* @return
*/
List getMyShoppingCartItems(Long newBeeMallUserId);
/**
* 根据userId和cartItemIds获取对应的购物项记录
*
* @param cartItemIds
* @param newBeeMallUserId
* @return
*/
List getCartItemsForSettle(List cartItemIds, Long newBeeMallUserId);
/**
* 根据cartItemIds获取对应的购物项记录
*
* @param cartItemIds
* @return
*/
List getCartItemsByCartIds(List cartItemIds);
/**
* 批量删除购物项记录
*
* @param cartItemIds
* @return
*/
int deleteCartItemsByCartIds(List cartItemIds);
/**
* 我的购物车(分页数据)
*
* @param pageUtil
* @return
*/
PageResult getMyShoppingCartItems(PageQueryUtil pageUtil);
}
================================================
FILE: newbee-mall-cloud-shop-cart-service/newbee-mall-cloud-shop-cart-web/src/main/java/ltd/shopcart/cloud/newbee/service/impl/NewBeeMallShoppingCartServiceImpl.java
================================================
/**
* 严肃声明:
* 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究!
* 本软件已申请软件著作权,受国家版权局知识产权以及国家计算机软件著作权保护!
* 可正常分享和学习源码,不得用于违法犯罪活动,违者必究!
* Copyright (c) 2022 程序员十三 all rights reserved.
* 版权所有,侵权必究!
*/
package ltd.shopcart.cloud.newbee.service.impl;
import ltd.common.cloud.newbee.enums.ServiceResultEnum;
import ltd.common.cloud.newbee.dto.PageQueryUtil;
import ltd.common.cloud.newbee.dto.PageResult;
import ltd.common.cloud.newbee.dto.Result;
import ltd.common.cloud.newbee.exception.NewBeeMallException;
import ltd.common.cloud.newbee.util.BeanUtil;
import ltd.goods.cloud.newbee.dto.NewBeeMallGoodsDTO;
import ltd.goods.cloud.newbee.openfeign.NewBeeCloudGoodsServiceFeign;
import ltd.shopcart.cloud.newbee.controller.param.SaveCartItemParam;
import ltd.shopcart.cloud.newbee.controller.param.UpdateCartItemParam;
import ltd.shopcart.cloud.newbee.controller.vo.NewBeeMallShoppingCartItemVO;
import ltd.shopcart.cloud.newbee.dao.NewBeeMallShoppingCartItemMapper;
import ltd.shopcart.cloud.newbee.entity.NewBeeMallShoppingCartItem;
import ltd.shopcart.cloud.newbee.service.NewBeeMallShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class NewBeeMallShoppingCartServiceImpl implements NewBeeMallShoppingCartService {
@Autowired
private NewBeeMallShoppingCartItemMapper newBeeMallShoppingCartItemMapper;
@Autowired
private NewBeeCloudGoodsServiceFeign goodsService;
@Override
public String saveNewBeeMallCartItem(SaveCartItemParam saveCartItemParam, Long userId) {
NewBeeMallShoppingCartItem temp = newBeeMallShoppingCartItemMapper.selectByUserIdAndGoodsId(userId, saveCartItemParam.getGoodsId());
if (temp != null) {
//已存在则修改该记录
NewBeeMallException.fail(ServiceResultEnum.SHOPPING_CART_ITEM_EXIST_ERROR.getResult());
}
Result goodsDetailResult = goodsService.getGoodsDetail(saveCartItemParam.getGoodsId());
//商品为空
if (goodsDetailResult == null || goodsDetailResult.getResultCode() != 200) {
return ServiceResultEnum.GOODS_NOT_EXIST.getResult();
}
int totalItem = newBeeMallShoppingCartItemMapper.selectCountByUserId(userId);
//超出单个商品的最大数量
if (saveCartItemParam.getGoodsCount() < 1) {
return ServiceResultEnum.SHOPPING_CART_ITEM_NUMBER_ERROR.getResult();
}
//超出单个商品的最大数量
if (saveCartItemParam.getGoodsCount() > 5) {
return ServiceResultEnum.SHOPPING_CART_ITEM_LIMIT_NUMBER_ERROR.getResult();
}
//超出最大数量
if (totalItem > 20) {
return ServiceResultEnum.SHOPPING_CART_ITEM_TOTAL_NUMBER_ERROR.getResult();
}
NewBeeMallShoppingCartItem newBeeMallShoppingCartItem = new NewBeeMallShoppingCartItem();
BeanUtil.copyProperties(saveCartItemParam, newBeeMallShoppingCartItem);
newBeeMallShoppingCartItem.setUserId(userId);
//保存记录
if (newBeeMallShoppingCartItemMapper.insertSelective(newBeeMallShoppingCartItem) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public String updateNewBeeMallCartItem(UpdateCartItemParam updateCartItemParam, Long userId) {
NewBeeMallShoppingCartItem newBeeMallShoppingCartItemUpdate = newBeeMallShoppingCartItemMapper.selectByPrimaryKey(updateCartItemParam.getCartItemId());
if (newBeeMallShoppingCartItemUpdate == null) {
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
if (!newBeeMallShoppingCartItemUpdate.getUserId().equals(userId)) {
NewBeeMallException.fail(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
}
//超出单个商品的最大数量
if (updateCartItemParam.getGoodsCount() > 5) {
return ServiceResultEnum.SHOPPING_CART_ITEM_LIMIT_NUMBER_ERROR.getResult();
}
//当前登录账号的userId与待修改的cartItem中userId不同,返回错误
if (!newBeeMallShoppingCartItemUpdate.getUserId().equals(userId)) {
return ServiceResultEnum.NO_PERMISSION_ERROR.getResult();
}
//数值相同,则不执行数据操作
if (updateCartItemParam.getGoodsCount().equals(newBeeMallShoppingCartItemUpdate.getGoodsCount())) {
return ServiceResultEnum.SUCCESS.getResult();
}
newBeeMallShoppingCartItemUpdate.setGoodsCount(updateCartItemParam.getGoodsCount());
newBeeMallShoppingCartItemUpdate.setUpdateTime(new Date());
//修改记录
if (newBeeMallShoppingCartItemMapper.updateByPrimaryKeySelective(newBeeMallShoppingCartItemUpdate) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public NewBeeMallShoppingCartItem getNewBeeMallCartItemById(Long newBeeMallShoppingCartItemId) {
NewBeeMallShoppingCartItem newBeeMallShoppingCartItem = newBeeMallShoppingCartItemMapper.selectByPrimaryKey(newBeeMallShoppingCartItemId);
if (newBeeMallShoppingCartItem == null) {
NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
}
return newBeeMallShoppingCartItem;
}
@Override
public Boolean deleteById(Long shoppingCartItemId, Long userId) {
NewBeeMallShoppingCartItem newBeeMallShoppingCartItem = newBeeMallShoppingCartItemMapper.selectByPrimaryKey(shoppingCartItemId);
if (newBeeMallShoppingCartItem == null) {
return false;
}
//userId不同不能删除
if (!userId.equals(newBeeMallShoppingCartItem.getUserId())) {
return false;
}
return newBeeMallShoppingCartItemMapper.deleteByPrimaryKey(shoppingCartItemId) > 0;
}
@Override
public List getMyShoppingCartItems(Long newBeeMallUserId) {
List newBeeMallShoppingCartItemVOS = new ArrayList<>();
List newBeeMallShoppingCartItems = newBeeMallShoppingCartItemMapper.selectByUserId(newBeeMallUserId, 20);
return getNewBeeMallShoppingCartItemVOS(newBeeMallShoppingCartItemVOS, newBeeMallShoppingCartItems);
}
@Override
public List getCartItemsForSettle(List cartItemIds, Long newBeeMallUserId) {
List newBeeMallShoppingCartItemVOS = new ArrayList<>();
if (CollectionUtils.isEmpty(cartItemIds)) {
NewBeeMallException.fail("购物项不能为空");
}
List newBeeMallShoppingCartItems = newBeeMallShoppingCartItemMapper.selectByUserIdAndCartItemIds(newBeeMallUserId, cartItemIds);
if (CollectionUtils.isEmpty(newBeeMallShoppingCartItems)) {
NewBeeMallException.fail("购物项不能为空");
}
if (newBeeMallShoppingCartItems.size() != cartItemIds.size()) {
NewBeeMallException.fail("参数异常");
}
return getNewBeeMallShoppingCartItemVOS(newBeeMallShoppingCartItemVOS, newBeeMallShoppingCartItems);
}
@Override
public List