投稿時間:2022-12-12 23:24:10 RSSフィード2022-12-12 23:00 分まとめ(28件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 冬の困りごと、2位「朝起きたときに室内が寒い」 1位は? https://www.itmedia.co.jp/business/articles/2212/12/news183.html itmedia 2022-12-12 22:40:00
python Pythonタグが付けられた新着投稿 - Qiita Pythonで問題を解いてみる https://qiita.com/Hiiro_Tanio/items/a9805db5a04c3a680f91 atcoder 2022-12-12 22:42:09
python Pythonタグが付けられた新着投稿 - Qiita HandyRLの使い方 https://qiita.com/ikedasan/items/f5882e43930d073be649 handyrl 2022-12-12 22:15:49
python Pythonタグが付けられた新着投稿 - Qiita 【個人開発】料理の盛り付けレベルを判定してくれる機械学習を作成しました【暇つぶしWEBアプリ】 https://qiita.com/bluenouni/items/cdcec500d22c077bf7f8 暇つぶし 2022-12-12 22:10:53
js JavaScriptタグが付けられた新着投稿 - Qiita async/awaitを使った非同期処理を使ってみた。 https://qiita.com/sawakishuto/items/f41d6f79e0d6a164098f asyncawait 2022-12-12 22:10:12
Ruby Rubyタグが付けられた新着投稿 - Qiita 2つの文字列の末尾に対して一致・不一致を判断するプログラムの実装 https://qiita.com/nktyn_frtn0906/items/36093a8827aed8277629 endother 2022-12-12 22:25:26
Ruby Rubyタグが付けられた新着投稿 - Qiita 【Ruby】Gemのインストール先を確認する方法 https://qiita.com/P-man_Brown/items/6298a584c3bf5a293b18 vironmentgemdirusrlocalb 2022-12-12 22:00:43
技術ブログ Mercari Engineering Blog メルカリにおけるA/Bテスト分析自動化の取り組み https://engineering.mercari.com/blog/entry/20221212-dc31d8e3d8/ hellip 2022-12-12 14:00:43
技術ブログ Developers.IO [セッションレポート]規模に応じたウォーター・スチュワードシップと再生可能エネルギー (SUS211) #reInvent https://dev.classmethod.jp/articles/reinvent2020-session-sus211/ andrenewableenergyatscale 2022-12-12 13:39:55
海外TECH Ars Technica The 2023 Mitsubishi Outlander PHEV is a much-improved hybrid SUV https://arstechnica.com/?p=1903600 mitsubishi 2022-12-12 13:00:50
海外TECH MakeUseOf 5 Sites for Free Christmas Carols, Karaoke, and Festive Songs https://www.makeuseof.com/tag/free-christmas-carols-karaoke-festive-songs/ Sites for Free Christmas Carols Karaoke and Festive SongsIt s Christmas time Embrace the season with Christmas carols karaoke and festive songs Here are few of the top sites for Christmas music 2022-12-12 13:30:16
海外TECH DEV Community B2B Commerce w. Medusa: Set up a Next.js storefront (2/2) https://dev.to/medusajs/b2b-commerce-w-medusa-set-up-a-nextjs-storefront-22-2jbi BB Commerce w Medusa Set up a Next js storefront In part of the BB series you learned how to set up your Medusa server for a BB ecommerce use case You set up a BB Sales Channel Customer Groups and Price List You also added an endpoint that checks whether a customer is a BB customer or not In this part of the series you ll customize Medusa s Next js storefront to add a Wholesaler login screen and a different way of displaying products for BB customers You ll also explore how the checkout flow works for BB customers You can find the full code for this tutorial series in this GitHub repository Install Next js StorefrontIn your terminal run the following command to install the Next js Storefront npx create next app e bb storefrontThis installs the Next js storefront in a newly created directory bb storefront Then change to the bb storefront directory and rename the env template file cd bb storefrontmv env template env local Install DependenciesTo ensure you re using the latest version of Medusa dependencies run the following command to update Medusa dependencies npm install medusajs medusa latest medusajs medusa js latest medusa react latestIn addition install axios to send requests to the custom endpoint you created in the previous tutorial npm install axios Add Sales Channel Environment VariableYou ll be using the Sales Channel you created in the first part to retrieve BB products for BB customers and to set the correct Sales Channel for BB customers carts So you need to set the ID of the sales channel in an environment variable If you re unsure what the ID of the sales channel is you can send a request to the List Sales Channel admin endpoint You should find a Sales Channel with the name “BB Copy the ID of that Sales Channel Then add the following environment variable in env local NEXT PUBLIC SALES CHANNEL ID lt YOUR SALES CHANNEL ID gt Where lt YOUR SALES CHANNEL ID gt is the ID of the BB Sales Channel Create a Wholesale Login PageIn this section you ll add a login page specific to BB customers This requires adding some new pages and files but also customizing existing logic Change AccountContextThe Next js storefront defines an AccountContext that allows you to get access to customer related data and functionalities across your storefront You need to make changes to it to add a new variable to the context is bb This variable will allow you to check whether the customer is a BB customer or not throughout the storefront In src lib context account context tsx add the is bb attribute to the AccountContext interface interface AccountContext is bb boolean Then at the beginning of the AccountProvider function add a new state variable is bb export const AccountProvider children AccountProviderProps gt const is bb setIsBb useState false Next add a new callback function checkBb inside the AccountProvider function import axios from axios import useRouter from next router import MEDUSA BACKEND URL medusaClient from lib config export const AccountProvider children AccountProviderProps gt const checkBb useCallback async gt if customer check if the customer is a bb customer const data await axios get MEDUSA BACKEND URL store customers is bb withCredentials true setIsBb data is bb else setIsBb false customer useEffect gt checkBb checkBb This function sends a request to the store customers is bb endpoint that you created in part It then changes the value of the is bb state variable based on the response received You also run this callback function in useEffect which triggers the function whenever there s a change in the callback In other words whenever the customer is changed You also need to set the value of is bb back to false when the customer logs out You can add that in the handleLogout function in AccountProvider const handleLogout gt useDeleteSession mutate undefined onSuccess gt setIsBb false Lastly pass is bb in the value prop of AccountContext Provider return lt AccountContext Provider value is bb gt children lt AccountContext Provider gt These are all the changes necessary to enable checking whether the customer is a BB customer or not throughout the storefront There s also one last change to make that enhances the customer experience Change the checkSession function in AccountProvider to the following const checkSession useCallback gt if customer amp amp retrievingCustomer router push router pathname includes wholesale wholesale account login account login customer retrievingCustomer router Previously the function redirects the customer to account login if they were trying to access account pages To ensure that a guest customer gets redirected to the wholesaler login page when they try to access a wholesale page you add a condition that determines where the guest customer should be redirected Change StoreContextThe Next js storefront also defines a StoreContext that manages the store s regions cart and more In this section you ll make changes to the StoreContext to ensure the correct sales channel is assigned to BB customers carts In src lib context store context tsx change the createNewCart function in the StoreProvider function to the following import MEDUSA BACKEND URL medusaClient from lib config import axios from axios import React createContext useCallback useContext useEffect useState from react export const StoreProvider children StoreProps gt const createNewCart async regionId string gt const cartData region id string sales channel id string region id regionId if process env NEXT PUBLIC SALES CHANNEL ID check if customer is bb const data await axios get MEDUSA BACKEND URL store customers is bb withCredentials true if data is bb cartData sales channel id process env NEXT PUBLIC SALES CHANNEL ID await createCart mutateAsync cartData onSuccess cart gt setCart cart storeCart cart id ensureRegion cart region onError error gt if process env NODE ENV development console error error Previously this function only passed the region ID to the createCart mutation By making the above change you check first if the customer is a BB customer and add the sales channel id field to the data to be passed to the createCart mutation Next change the resetCart function in the StoreProvider function to the following export const StoreProvider children StoreProps gt const resetCart async gt deleteCart const savedRegion getRegion const cartData region id string sales channel id string region id savedRegion regionId if process env NEXT PUBLIC SALES CHANNEL ID check if customer is bb const data await axios get MEDUSA BACKEND URL store customers is bb withCredentials true if data is bb cartData sales channel id process env NEXT PUBLIC SALES CHANNEL ID createCart mutate cartData onSuccess cart gt setCart cart storeCart cart id ensureRegion cart region onError error gt if process env NODE ENV development console error error This change is similar to the previous change It ensures that the correct sales channel ID is assigned to the cart when it s reset Finally change the ensureCart function inside useEffect to the following useEffect gt const ensureCart async gt const cartId getCart const region getRegion if cartId const cartRes await medusaClient carts retrieve cartId then async cart gt if process env NEXT PUBLIC SALES CHANNEL ID amp amp cart sales channel id process env NEXT PUBLIC SALES CHANNEL ID check if bb customer const data await axios get MEDUSA BACKEND URL store customers is bb withCredentials true if data is bb update cart s sales channel const response await medusaClient carts update cart id sales channel id process env NEXT PUBLIC SALES CHANNEL ID return response cart return cart catch async gt return null if cartRes cartRes completed at deleteCart await createNewCart region regionId return setCart cartRes ensureRegion cartRes region else await createNewCart region regionId if IS SERVER amp amp cart id ensureCart eslint disable next line react hooks exhaustive deps Similar to the previous changes this ensures that when the storefront is opened and the cart is retrieved the correct sales channel is assigned to the cart Change the Nav ComponentTo ensure customers can access the wholesale login page you ll add a new link to the navigation bar In src modules layout templates nav index tsx add the following in the returned JSX above the Account link lt Link href wholesale account gt lt a gt Wholesale Account lt a gt lt Link gt lt Link href account gt lt a gt Account lt a gt lt Link gt Add Login Form ComponentThe login page should display a login form for the customer To create the login form create the file src modules wholesale components login index tsx with the following content import FieldValues useForm from react hook form import MEDUSA BACKEND URL medusaClient from lib config import Button from modules common components button import Input from modules common components input import axios from axios import useAccount from lib context account context import useCart from medusa react import useRouter from next router import useState from react interface SignInCredentials extends FieldValues email string password string const Login gt const refetchCustomer is bb useAccount const authError setAuthError useState lt string undefined gt undefined const router useRouter const cart updateCart useCart const handleError e Error gt setAuthError Invalid email or password const register handleSubmit formState errors useForm lt SignInCredentials gt const onSubmit handleSubmit async credentials gt medusaClient auth authenticate credentials then async gt refetchCustomer if process env NEXT PUBLIC SALES CHANNEL ID amp amp cart sales channel id process env NEXT PUBLIC SALES CHANNEL ID const data await axios get MEDUSA BACKEND URL store customers is bb withCredentials true if data is bb updateCart mutate sales channel id process env NEXT PUBLIC SALES CHANNEL ID router push is bb wholesale account account catch handleError return lt div className max w sm w full flex flex col items center gt lt h className text large semi uppercase mb gt Welcome back lt h gt lt p className text center text base regular text gray mb gt Sign in to your wholesale account lt p gt lt form className w full onSubmit onSubmit gt lt div className flex flex col w full gap y gt lt Input label Email register email required Email is required autoComplete email errors errors gt lt Input label Password register password required Password is required type password autoComplete current password errors errors gt lt div gt authError amp amp lt div gt lt span className text rose w full text small regular gt These credentials do not match our records lt span gt lt div gt lt Button className mt gt Enter lt Button gt lt form gt lt div gt export default LoginThis login form shows the customer the fields email and password When the customer submits the form and they re authenticated successfully you check if the customer is a BB customer and accordingly update the cart s sales channel ID This is important as products can only be added to a cart that belongs to the same sales channel Add Login Template ComponentThe login template component will be displayed on the Login page Create the file src modules wholesale templates login template tsx with the following content import Login from components login import useAccount from lib context account context import useEffect from react import useRouter from next router const WholesaleLoginTemplate gt const customer retrievingCustomer is bb useAccount const router useRouter useEffect gt if retrievingCustomer amp amp customer router push is bb wholesale account account customer retrievingCustomer router is bb return lt div className w full flex justify center py gt lt Login gt lt div gt export default WholesaleLoginTemplateIn this template you first check if the customer is already logged in and redirect them to their account page based on whether they re a BB customer or not If the customer is not logged in you show the Login form component Add Login PageCreate the file src pages wholesale account login tsx with the following content import Head from modules common components head import Layout from modules layout templates import LoginTemplate from modules wholesale templates login template import NextPageWithLayout from types global const Login NextPageWithLayout gt return lt gt lt Head title Sign in description Sign in to your Wholesale account gt lt LoginTemplate gt lt gt Login getLayout page gt return lt Layout gt page lt Layout gt export default LoginThis is the login page that the customer sees when they access the wholesale account login path It shows the LoginTemplate component Add Wholesale Account PageThe last part you ll add to finish the Wholesale login functionality is the account page for wholesalers This page is shown when the BB customer is logged in Create the file src pages wholesale account index tsx with the following content import AccountLayout from modules account templates account layout import Head from modules common components head import Layout from modules layout templates import NextPageWithLayout from types global import OverviewTemplate from modules account templates overview template import ReactElement from react import useAccount from lib context account context import useRouter from next router const Account NextPageWithLayout gt const customer is bb useAccount const router useRouter if customer amp amp is bb router push account return lt gt lt Head title Wholesale Account description Overview of your account activity gt lt OverviewTemplate gt lt gt Account getLayout page ReactElement gt return lt Layout gt lt AccountLayout gt page lt AccountLayout gt lt Layout gt export default AccountIn this page you first check whether the customer is logged in but they re not a BB customer In that case you redirect them to the account page which is used by other types of customers On this page you show the same OverviewTemplate that is shown by default for customers This is for the simplicity of the tutorial If you want to display other information to BB customers you can make the changes on this page Test Wholesale LoginMake sure the Medusa server you created in part is running Then run the following command to run the Next js storefront npm run devOpen the storefront at localhost and click on the Wholesale Account link in the navigation bar This will open the login page you created In part you created a customer in a BB customer group Use the email and password of that customer to log in Once you re logged in you ll be redirected to the wholesale account page Create BB Products PageIn this section you ll customize the current product page available on the page store to show products as a list of variants in a table This makes it easier for BB customers to view available products and their variants and add big quantities of them to the cart Change ProductContextAnother context that the Next js storefront defines is the ProductContext which manages a product s options price variants and more You ll be customizing this context to expose in the context the setQuantity function that allows setting the quantity to be added to the cart In src lib context product context tsx add in the ProductContext interface the setQuantity function interface ProductContext setQuantity quantity number gt void Then add the function to the object passed to the ProductActionContext Provider s value prop return lt ProductActionContext Provider value setQuantity gt children lt ProductActionContext Provider gt Please note that the function is already defined in the context with the quantity state variable Create ProductActions ComponentThe ProductActions component is a component that displays a button and a quantity input and handles the add to cart functionality It ll be displayed for each variant in the products table Create the file src modules wholesale components product actions index tsx with the following content import Product Variant from types medusa import React useEffect useMemo useState from react import Button from modules common components button import isEqual from lodash import useProductActions from lib context product context type ProductActionsProps product Product selectedVariant Variant const ProductActions React FC lt ProductActionsProps gt product selectedVariant gt const updateOptions addToCart inStock options quantity setQuantity useProductActions useEffect gt const tempOptions Record lt string string gt for const option of selectedVariant options tempOptions option option id option value if isEqual tempOptions options updateOptions tempOptions selectedVariant options options return lt div className flex flex col gap y gt lt input type number min max selectedVariant inventory quantity value quantity disabled inStock onChange e gt setQuantity parseInt e target value className border p w max mt gt lt Button onClick addToCart className w max my gt inStock Out of stock Add to cart lt Button gt lt div gt export default ProductActionsThis component uses the useProductActions hook which exposes the values in the ProductContext In useEffect it preselects the options in the current variant It displays a quantity input and an add to cart button Both the value of the quantity input and the add to cart handler are managed by ProductContext Create ProductPrice ComponentThe ProductPrice component handles showing the correct variant price to the customer It ll be used to show the price of variants in the products table Create the file src modules wholesale components product price index tsx with the following content import Product from medusajs medusa import Variant from types medusa import clsx from clsx import useMemo from react import useProductPrice from lib hooks use product price type ProductPriceProps product Product variant Variant const ProductPrice React FC lt ProductPriceProps gt product variant gt const price useProductPrice id product id variantId variant id const selectedPrice useMemo gt const variantPrice cheapestPrice price return variantPrice cheapestPrice null price return lt div className mb gt selectedPrice lt div className flex flex col text gray gt lt span gt selectedPrice calculated price lt span gt lt div gt lt div gt lt div gt lt div gt export default ProductPriceThis component uses the useProductPrice hook which makes it easier to manage the price of a variant then display the price to the customer Create Products ComponentThe Products component is the products table that will be shown to the BB customer Create the file src modules wholesale components products index tsx with the following content import ProductProvider useProductActions from lib context product context import useCart useProducts from medusa react import useMemo useState from react import Button from modules common components button import Link from next link import ProductActions from product actions import ProductPrice from product price import StoreGetProductsParams from medusajs medusa type GetProductParams StoreGetProductsParams amp sales channel id string type ProductsType params GetProductParams const Products params ProductsType gt const cart useCart const offset setOffset useState const currentPage setCurrentPage useState const queryParams useMemo gt const p GetProductParams if cart id p cart id cart id p is giftcard false p offset offset return p params cart id params offset const products isLoading count limit useProducts queryParams enabled cart function previousPage if limit count return const newOffset Math max offset limit setOffset newOffset setCurrentPage currentPage function nextPage if limit count return const newOffset Math min count offset limit setOffset newOffset setCurrentPage currentPage return lt div className flex content container gt isLoading amp amp products amp amp lt gt lt table className table auto w full border collapse border gt lt thead gt lt tr className text left border collapse border gt lt th className p gt Product Title lt th gt lt th gt Variant Title lt th gt lt th gt SKU lt th gt lt th gt Options lt th gt lt th gt Available Quantity lt th gt lt th gt Price lt th gt lt th gt Actions lt th gt lt tr gt lt thead gt lt tbody gt products map product gt lt gt lt tr gt lt td className p rowSpan product variants length gt lt Link href products product handle passHref true gt lt a className underline gt product title lt a gt lt Link gt lt td gt lt tr gt product variants map variant gt lt ProductProvider product product key variant id gt lt tr className border collapse border gt lt td gt variant title lt td gt lt td gt variant sku lt td gt lt td gt lt ul gt variant options map option gt lt li key option id gt product options find op gt op id option option id title option value lt li gt lt ul gt lt td gt lt td gt variant inventory quantity lt td gt lt td gt lt ProductPrice product product variant variant gt lt td gt lt td gt lt ProductActions product product selectedVariant variant gt lt td gt lt tr gt lt ProductProvider gt lt gt lt tbody gt lt table gt lt div className my flex justify center items center gt lt Button onClick previousPage disabled currentPage lt className w max inline flex gt Prev lt Button gt lt span className mx gt currentPage lt span gt lt Button onClick nextPage disabled count undefined amp amp limit undefined amp amp count offset limit lt className w max inline flex gt Next lt Button gt lt div gt lt gt lt div gt export default ProductsThis component retrieves the products in the BB Sales Channel and displays them in a table It also shows pagination controls to move between different pages For each product you loop over its variants and display them one by one in different rows For each variant you use the ProductActions and the ProductPrice components you created to show the quantity input the add to cart button and the variant s price Change Store PageCurrently the store page displays products in an infinite scroll mode for all customers You ll change it to display the Products table for BB customers and the infinite scroll mode for other customers Change the content of src pages store tsx to the following import Head from modules common components head import InfiniteProducts from modules products components infinite products import Layout from modules layout templates import NextPageWithLayout from types global import Products from modules wholesale components products import RefinementList from modules store components refinement list import StoreGetProductsParams from medusajs medusa import useAccount from lib context account context import useState from react const Store NextPageWithLayout gt const params setParams useState lt StoreGetProductsParams gt const is bb useAccount return lt gt is bb amp amp lt gt lt Head title Store description Explore all of our products gt lt div className flex flex col small flex row small items start py gt lt RefinementList refinementList params setRefinementList setParams gt lt InfiniteProducts params params gt lt div gt lt gt is bb amp amp lt gt lt Head title Wholesale Products description Explore all of our products gt lt div className flex flex col small flex row small items start py gt lt Products params params sales channel id process env NEXT PUBLIC SALES CHANNEL ID gt lt div gt lt gt lt gt Store getLayout page gt lt Layout gt page lt Layout gt export default StoreYou first retrieve is bb from useAccount Then if is bb is false you display the InfiniteProducts component Otherwise for BB customers you display the Products component that you created Change Store DropdownWhen you hover over the Store link in the navigation bar it currently shows a dropdown with some products and collections As this is distracting for BB customers you ll remove it for them In src modules layout components dropdown menu index tsx retrieve the is bb variable from the AccountContext import useAccount from lib context account context const DropdownMenu gt const is bb useAccount And change the returned JSX to the following const DropdownMenu gt return lt gt is bb amp amp lt div className h full flex gt lt Link href store passHref gt lt a className relative flex h full gt lt span className relative h full flex items center transition all ease out duration gt Store lt span gt lt a gt lt Link gt lt div gt is bb amp amp lt div onMouseEnter gt setOpen true onMouseLeave gt setOpen false className h full gt lt div className flex items center h full gt lt Popover className h full flex gt lt gt lt Link href shop passHref gt lt a className relative flex h full gt lt Popover Button className clsx relative h full flex items center transition all ease out duration onClick gt push store gt Store lt Popover Button gt lt a gt lt Link gt lt Transition show open as React Fragment enter transition ease out duration enterFrom opacity enterTo opacity leave transition ease in duration leaveFrom opacity leaveTo opacity gt lt Popover Panel static className absolute top full inset x text sm text gray z border y border gray gt lt div className relative bg white py gt lt div className flex items start content container gt lt div className flex flex col flex max w gt lt h className text base semi text gray mb gt Collections lt h gt lt div className flex items start gt collections amp amp chunk collections map chunk index gt return lt ul key index className min w px max w px pr gt chunk map collection gt return lt div key collection id className pb gt lt Link href collections collection id gt lt a onClick gt setOpen false gt collection title lt a gt lt Link gt lt div gt lt ul gt loadingCollections amp amp repeat map index gt lt div key index className w h bg gray animate pulse gt lt div gt lt div gt lt div className flex gt lt div className grid grid cols gap gt products slice map product gt lt ProductPreview product key product id gt loadingProducts amp amp repeat map index gt lt SkeletonProductPreview key index gt lt div gt lt div gt lt div gt lt div gt lt Popover Panel gt lt Transition gt lt gt lt Popover gt lt div gt lt div gt lt gt If is bb is true the dropdown is hidden Otherwise is bb is shown Test Products PageMake sure your Medusa server is still running and restart your Next js storefront Then open the Next js storefront and after logging in as a BB customer click on the Store link in the navigation bar at the top left You ll see your list of product variants in a table Notice how the prices of the variants are different than those shown to other customers These prices are the prices you defined in the BB Price List You can also test the prices with quantity based conditions you added to the Price List For example if the condition was that product Medusa Hoodie s variant S should have a different price if its quantity in the cart is more than try changing the quantity to or more and clicking Add to Cart You ll see a different price for that variant in the cart Test Checkout FlowThe checkout flow is pretty similar to those of regular customers Add a couple of items to the cart from the table Click on the My Bag link at the top right of the navigation bar Click on Go to Checkout Fill out the Shipping Address information and choose a Fulfillment method Choose a payment method Since in this tutorial you didn t add any payment methods you ll use the manual payment method However you can integrate many other payment methods with Medusa such as Stripe or PayPal or create your own Click on the Checkout button This places the order on the Medusa server Please note that Medusa does not capture the payment when an order is placed it only authorizes it You ll need to capture it from the Medusa admin View Order Details on Medusa AdminRun both the Medusa server and Medusa admin you created in part Then access the Medusa admin on localhost After logging in you should see the list of orders in your store In the list you can see the payment status of the order the sales channel and more You should find the order you just created in the list Click on the order to view its details On the order details page you can see all the details of the order such as the items ordered the payment and fulfillment details the customer s details and more Capture PaymentTo capture the payment of the order Scroll to the Payment section Click on the Capture Payment If you chose the Test payment provider during checkout this will not actually do anything other than change the payment status of the order If you re using other payment providers such as Stripe this is when the payment will actually be captured ConclusionBy following this two part tutorial series you should have the basis of a BB ecommerce store built with Medusa You can read more about how Medusa supports BB and compares to other OS BB platforms on our webpage Likewise you can perform much more customizations and add additional features to your store including Add a payment provider As mentioned you can add payment providers like Stripe and PayPal or create your own Create a Fulfillment Provider Integrate search engines such as Algolia or MeiliSearch Should you have any issues or questions related to Medusa then feel free to reach out to the Medusa team via Discord 2022-12-12 13:27:41
海外TECH DEV Community B2B Commerce w. Medusa: Set up a headless Node.js backend (1/2) https://dev.to/medusajs/b2b-commerce-w-medusa-set-up-a-headless-nodejs-backend-12-2n7m BB Commerce w Medusa Set up a headless Node js backend This tutorial series covers how you can use Medusa and its different components and features to implement a BB commerce store The series is split in two parts This article Part one Covers how to prepare your backend to handle BB shopping experiencesPart two Covers how to customize our Next js storefront to create a BB storefront You can check out the full code for this tutorial series in this GitHub repository Why use open source for BB commerce BB commerce has seen rapid growth in recent years and is now among the top revenue generating channels for BB businesses according to a recent McKinsey study Yet many businesses struggle to get their BB setup right Mostly challenges come from a need to build more custom logic and integration to handle the higher complexity of BB sales Some examples of BB complexities Unique customers Special purchasing agreements require the possibility to create custom logic for individual BB customer groupsSpecial pricing The commerce engine needs to be able to differentiate pricing and discounts based on customer groupsOmnichannel need Selling to BB is often not a one channel effort and the commerce engine needs to be able to handle multiple channels Why use MedusaMedusa is an open source composable commerce engine Unlike existing proprietary platforms its value proposition comes from the flexible and open architecture that equips tech teams with a unique possibility to build bespoke commerce setups This is even more important in the context of complex BB businessesMedusa provides the foundational commerce infrastructure for businesses to take full ownership of their tech stack and avoid compromising on business needs Custom logic can be injected natively instead of through hacky workarounds Our developer first approach is a central element in this promise of customization and composability That is why we want to give developers the essential features we find necessary for building a BB commerce setup In this guide we ll take you through how you combine these to achieve a scaleable BB setup Medusa s Recipe for a BB Commerce StoreMedusa provides many essential commerce features For the BB case in particular you ll be using the following features in Medusa to create a BB commerce store Sales Channels Sales Channels allow you to segment your product catalog across the channels you sell through For BB commerce stores Sales Channels can be used to specify which products are available for BB customers Customer Groups Customer Groups allow you to combine customers with similar attributes For BB commerce stores they can be used to combine customers that belong to an organization that purchases products from your store Price Lists Price Lists can be used to override products prices based on different conditions For BB commerce stores they can be used to set the prices negotiated with BB customers Prerequisites Node jsMedusa is a Node js commerce platform So you must have at least version of Node js installed on your machine PostgreSQLAlthough Medusa works with an SQLite database it is highly recommended to use PostgreSQL instead You can follow our documentation to learn how to install it Make sure to also create an empty PostgreSQL database Medusa CLI ToolYou ll need Medusa s CLI tool to install a Medusa server You can install the CLI tool with the following command npm install medusajs medusa cli gIf you face any error with this installation please check out the troubleshooting guide Install the Medusa ServerIn your terminal run the following command to install the Medusa server medusa new bb serverThis will install a Medusa server under a newly created bb server directory Once the command is done executing change to that directory cd bb server Configure Medusa Server Enable Sales ChannelsSales Channels is a feature in Medusa that allows you to separate between the different sales channels you sell your products in and ensure different products are available for each sales channel For example you can have a Sales Channel for mobile stores another for website storefronts and so on In the case of BB stores you can create a BB Sales Channel that groups all wholesale products that should only be available to BB customers Sales Channels is currently in beta mode so you have to enable it manually to use it In the env file of your Medusa server add the following environment variable MEDUSA FF SALES CHANNELS trueThis will enable sales channels on your Medusa server Add Database ConfigurationBy default Medusa runs with an SQLite database This is great for development purposes but for an optimal experience it s recommended to use a PostgreSQL database instead In env add the following environment variable DATABASE URL lt DATABASE URL gt Where lt DATABASE URL gt is the URL of your database If you re unsure of what your URL is check out PostgreSQL s documentation to see its format Then in medusa config js you ll find an exported object similar to this module exports projectConfig redis url REDIS URL For more production like environment install PostgresQL database url DATABASE URL database type postgres database database medusa db sql database type sqlite store cors STORE CORS admin cors ADMIN CORS plugins Remove the SQLite database configuration and un comment the PostgreSQL configurations as such module exports projectConfig redis url REDIS URL database url DATABASE URL database type postgres store cors STORE CORS admin cors ADMIN CORS plugins Run MigrationsThe Medusa server has migrations defined for all its entities so that you can smoothly prepare your database schema for your commerce store Run the following command in the root directory of your Medusa server to migrate entities into your database schema medusa migrations run Seed DatabaseThis step is optional but recommended for the sake of the tutorial You can seed your database with demo data such as an admin user and products Run the following command in the root directory of the Medusa server to seed your database npm run seed Install a File Service PluginFile service plugins in Medusa are used to store files such as product images Although this step is optional for this tutorial if you want to add products with images in your store you must install a file service plugin Medusa provides three official file service plugins MinIO Spaces and S You can follow along with the documentation of the file service plugin of your choice to learn how to install it Test Medusa ServerIn the root directory of your Medusa server run the following command to run your Medusa server npm startThis runs your Medusa server on port You can test it out by opening localhost store products in your browser If you seeded the database earlier you should see many products in the response Otherwise you can see an empty array of products in the response It s recommended to keep the Medusa server running throughout the tutorial as you ll need it for all the steps Install Medusa AdminMedusa provides an admin panel that allows you to manage the different settings and data of your Medusa server including products sales channels customers and much more In a different directory than the Medusa server run the following command to clone the Admin panel from GitHub git clone bb adminThis creates a new directory bb admin and clones the codebase of the Medusa admin into it Change into the new directory and install the dependencies with NPM cd bb admin amp amp npm install Test Medusa AdminOnce the NPM installation is done make sure that the Medusa server is running then run the following command in the bb admin directory npm startThis runs the Medusa admin on localhost by default If you open it in your browser you should see a login screen If you seeded the database earlier you can log in with the email admin medusa test com and password supersecret If not you can create a user using the Medusa CLI tool Add Wholesale ProductsAfter you log in to the admin go to the Products page from the sidebar If you ve seeded the database you should find some products already added To add new products Go to the Products page Click on the New Product button at the top right Enter details related to general information variants prices and more Once you re done click on the Publish Products button You can add as many products as you want Create BB Sales ChannelAs mentioned earlier you ll create a BB Sales Channel to add Wholesale Products These products will then only be available in that sales channel To create a BB Sales Channel Go to Settings →Sales ChannelsIn the Sales Channels section on the left click on the plus icon next to the title of the section The form to create a new sales channel will open Enter a name and description for the sales channel You can set the name to “BB Once you re done click on the Publish Channel button Add Products to the Sales ChannelNow you can add products to your BB sales channel To do that Go to Settings →Sales ChannelsIn the sales channels list on the left choose the BB sales channel At the top right of the right section click on the three dots icon Choose from the dropdown list “Add products Select the products you want to add to the sales channel Once you re done click on the Save button Create BB Customer GroupsCustomer groups allow you to group together customers that have common criteria You can then use this group to apply special pricing for these customers In the BB case in this tutorial you ll create a customer group for every organization that will be a BB customer To differentiate every BB customer group from other customer groups you ll also add in the metadata field of the customer group an is bb flag To create a BB customer group in the admin Go to the Customers page Choose the Groups headline Click on the New Group button In the new window that opens Enter the name of the organization in the Title field Click on the Add Metadata button This shows additional Key and Value fields Enter in the Key field is bb and in the Value field true Once you re done click on the Publish Group button Do these steps for every organization you want to add Create CustomersBefore you can add customers to the customer group you need to create the customers You ll need to use the API Endpoints to do that You can use a tool like Postman to send requests or you can use cURL Start by logging in using the User Login endpoint Send a POST request to localhost admin auth with the following request body email admin medusa test com password supersecret You can replace the email and password with your own if you re using different ones When you log the Session ID is set in the cookies In tools like Postman you can go ahead and send the rest of the requests and it appends that Session ID to the cookies of those requests If you re using cURL you can learn how to set the Cookie Session ID in our documentation Next you ll create a customer using the Create a Customer endpoint Send a POST request to localhost admin customers with the following request body email customer acme com first name Acme last name Customer password supersecret You can change the values of any of the fields as necessary You can add as many customers as you want Once you re done if you go back to the Medusa admin you can see the new customer on the Customers page Add Customers to Customer GroupIn this section you ll add the customers you created to the customer group of their organization To add customers to a customer group Go to each of the BB customer group s details page Click on the “Edit customers button at the top right of the Customers section Check the box next to every customer you want to add to the group Click on the Save button Create BB Price ListPrice lists in Medusa are a list of prices that are applied on specific products under defined conditions For example you can set different prices for different customer groups You can also specify prices based on the quantity of the product in the cart In this section you ll create a BB Price List that applies to all the BB customer groups you created in the previous sections You ll then set different prices for each of the wholesale products To create a price list Go to the Pricing page Click on the “Add price list button at the top right In the new form that opens Choose Override under the Price list type Expand the General collapsible section Enter a name for the price list for example BB and a description Expand the Configuration collapsible section Then toggle the Customer availability field and choose all the BB customer groups you created You can add prices manually at this point you can add them manually after creating the price list or you can import prices from a CSV file after creation To add prices manually now Expand the Prices collapsible section Click on the Add Products Manually button Check all the products you want to add then click the Save button For all of the products you added click on the icon This will expand the list of variants for that product You can specify the same prices for all variants remove some of the variants from the price list and specify different prices for all variants To specify prices Click on the three dots icon next to each of the variants and choose Edit prices In the new window either select Apply overrides on selected variants or Apply on all variants and add the price for every currency in your store Once you re done click Save and Close Once you re done click on the Publish price list button at the top right Importing PricesAs mentioned earlier you can import prices from a CSV file This will replace any prices you ve added before To import prices from a CSV file Go to the BB price list s details page In the Prices section click on the three dots icon and click on “Import price list from the dropdown In the new window If you re unsure of what the CSV file s format must be like you can download a template CSV file by clicking the download icon To upload the CSV file you want to import prices from either Drag and drop the file into the dashed box Or click on the dashed box and choose the file you want to import the prices from After you upload the CSV file you can check the number of prices to be added above the uploaded file s name Once you re done choosing a file to import prices from click on the Import List button Adding Prices Using the APIsYou can also add prices using the API endpoints These provide you with even more options than what is currently available in the admin such as prices based on quantity in the cart To add prices to a price list send a POST request to BACKEND URL admin price lists price list id prices batch replacing price list id with the ID of the price list with the following request body prices amount variant id variant id currency code eur min quantity amount variant id variant id currency code eur max quantity Each object in the prices array is an object that contains the amount the ID of the variant to apply the price to the currency code and other conditions such as min quantity and max quantity You can check all the conditions you can pass by referring to the API Reference Add Endpoint to Check Customer GroupThe last step is to create an endpoint on the Medusa server to allow you to check whether a customer belongs to a BB customer group or not This is helpful when you start customizing the storefront as you need to figure out what type of customer is logged in To create an endpoint create the file bb server src api index ts with the following content import CustomerService from medusajs medusa import Router from express import authenticate from medusajs medusa dist api middlewares authenticate customer import cors from cors import projectConfig from medusa config export default gt const router Router const corsOptions origin projectConfig store cors split credentials true router options store customers is bb cors corsOptions router get store customers is bb cors corsOptions authenticate async req res gt if req user return res json is bb false const customerService CustomerService req scope resolve customerService const customer await customerService retrieve req user customer id relations groups const is bb customer groups some group gt group metadata is bb true return res json is bb return router In this file you add a new storefront endpoint store customers is bb This endpoint checks if the currently logged in customer belongs to a BB customer group Looking back at when you created each customer group you set in its metadata field is bb to true In this endpoint you retrieve the customer along with their customer groups then check if any of its customer groups has the is bb field set to true Test EndpointTo test the endpoint first run the following command to transpile the TypeScript file into the dist directory npm run buildThen start the Medusa server npm startUsing a tool like Postman try to first login with a BB customer then send a request to localhost store customers is bb You should see that it returns is bb with the value true If you try sending that same request when the customer is logged out or when the customer does not belong to a BB customer group is bb in the response should be set to false Next StepsThis concludes preparing your Medusa backend to be used for a BB shopping experience In the next part of the tutorial you ll learn how you can customize the Next js storefront to implement the entire BB flow for the customers You can read more about how Medusa supports BB and compares to other OS BB platforms on our webpage You can also check out the following resources in our documentation to learn more about the different components used in this tutorial Sales Channels and how to use them Customer Groups and how to use them Price Lists and how to use them Should you have any issues or questions related to Medusa then feel free to reach out to the Medusa team via Discord 2022-12-12 13:17:34
Apple AppleInsider - Frontpage News How to keep your Mac optimized -- the ultimate guide https://appleinsider.com/articles/22/12/12/how-to-keep-your-mac-optimized----the-ultimate-guide?utm_medium=rss How to keep your Mac optimized the ultimate guideWhen we get a new Mac it s easy to be mesmerized by how clean and blazing fast everything feels You can get this back with some regular maintenance Here s how CleanMyMac X by MacPawWith that new Mac apps open instantly and there s plenty of storage for all types of files As time goes by the new Mac will look less and less like this Folders will start to accumulate on the hard drive apps will seem slower and the battery won t last nearly as long Read more 2022-12-12 13:30:58
Apple AppleInsider - Frontpage News Keep your car or truck safe with the 70mai Omni Dash Cam https://appleinsider.com/articles/22/12/10/keep-your-car-or-truck-safe-with-the-70mai-omni-dash-cam?utm_medium=rss Keep your car or truck safe with the mai Omni Dash CamIf you re passionate about your car or truck here s how you can keep it safe when parked or on the move using the mai Dash Cam Omni The all new mai Dash Cam OmniOne of the hazards of car ownership is that other people use the roads With crashes and other road incidents being a problem dash cams have become a must need accessory for multiple reasons Read more 2022-12-12 13:57:59
海外TECH Engadget Google's Pixel and Nest smart home devices are back at Black Friday prices https://www.engadget.com/google-pixel-buds-and-smart-home-devices-low-prices-134748438.html?src=rss Google x s Pixel and Nest smart home devices are back at Black Friday pricesIf you have any regrets about pass on Google Pixel smartphone deals during this year s Black Friday sales worry not Nearly all of the same devices discounted last month are back on sale at the same prices with up to percent off the Pixel a Pixel Pixel Watch and Pixel Buds A Series along with home products like the Nest Thermostat Nest Security Cam and Nest Doorbell Shop Google Pixel and Nest products on AmazonFor smartphone shoppers on a budget Google s Pixel a is on sale for just percent off the regular price matching the Black Friday deal It has top notch performance while giving you the purest Android experience possible At the same time you get excellent camera quality thanks to the two megapixel rear cameras and MP front sensor delivering bright colorful pictures and video It also comes with a distinctive design sharp inch OLED screen covered with Gorilla Glass long lasting battery IP water dust protection and more Google s latest phones are also on sale The Google Pixel GB G unlocked is available for just instead of percent off while the top end Pixel Pro G unlocked is priced at or off the regular price Both models have the new Tensor G chip excellent cameras and new software and features like Direct My Call and Photo Unblur ーhelping them both achieve high scores in our Engadget review The main differences between the two are in the display with the Pixel Pro being better for mobile gaming thanks to the Hz display compared to Hz on the Pixel EngadgetThough it only recently came out Google s sleek Pixel Watch is on sale for or percent off the regular price It s easily one of the prettiest Wear OS watches out there offers excellent health and fitness tracking and useful new faces Meanwhile Google s Pixel Buds A Series are discounted by percent bringing the regular price down to We called them Google s best earbuds yet thanks to the solid ANC performance punchy bass and reliable touch controls Finally multiple Google Nest products are available at some of the lowest prices we ve seen You can grab the Google Nest Thermostat for a savings of percent off the regular price The Google Nest Security Cam wired has been reduced by percent to and if it s a Google Nest Doorbell you re after that item is on sale for for a savings of percent All of these will make great Christmas gifts but it s best to act soon before the sale ends Follow EngadgetDeals on Twitter and subscribe to the Engadget Deals newsletter for the latest tech deals and buying advice 2022-12-12 13:47:48
金融 RSS FILE - 日本証券業協会 公社債発行額・償還額等 https://www.jsda.or.jp/shiryoshitsu/toukei/hakkou/index.html 発行 2022-12-12 15:00:00
金融 RSS FILE - 日本証券業協会 公社債発行銘柄一覧 https://www.jsda.or.jp/shiryoshitsu/toukei/saiken_hakkou/youkou/ichiran.html 銘柄 2022-12-12 15:00:00
ニュース BBC News - Home Solihull: Three children die in icy lake tragedy https://www.bbc.co.uk/news/uk-england-63944005?at_medium=RSS&at_campaign=KARANGA emergency 2022-12-12 13:45:43
ニュース BBC News - Home Harry and Meghan on Netflix: Duke speaks of 'lies' in new trailer https://www.bbc.co.uk/news/uk-63945810?at_medium=RSS&at_campaign=KARANGA duties 2022-12-12 13:17:12
ニュース BBC News - Home EU corruption charges 'very very worrisome', says foreign policy chief https://www.bbc.co.uk/news/world-europe-63941509?at_medium=RSS&at_campaign=KARANGA european 2022-12-12 13:50:58
ニュース BBC News - Home Ministers to hold emergency meeting as strikes loom https://www.bbc.co.uk/news/uk-63939396?at_medium=RSS&at_campaign=KARANGA border 2022-12-12 13:39:31
ニュース BBC News - Home Queensland shooting: Two police officers, and member of public, killed at remote property https://www.bbc.co.uk/news/world-australia-63943292?at_medium=RSS&at_campaign=KARANGA brisbane 2022-12-12 13:34:30
ニュース BBC News - Home China to de-activate national Covid tracking app https://www.bbc.co.uk/news/world-asia-china-63941512?at_medium=RSS&at_campaign=KARANGA covid 2022-12-12 13:30:47
ニュース BBC News - Home Yan Bingtao: Former Masters champion suspended as part of a match-fixing investigation https://www.bbc.co.uk/sport/snooker/63945840?at_medium=RSS&at_campaign=KARANGA Yan Bingtao Former Masters champion suspended as part of a match fixing investigationFormer Masters champion Yan Bingtao is suspended from the World Snooker Tour as part of an ongoing investigation into match fixing 2022-12-12 13:31:55
ニュース BBC News - Home England's Rugby World Cup performance review not to be made public https://www.bbc.co.uk/sport/rugby-union/63942309?at_medium=RSS&at_campaign=KARANGA football 2022-12-12 13:33:35
ニュース BBC News - Home UK weather: How long will the cold snap last? https://www.bbc.co.uk/news/uk-63893192?at_medium=RSS&at_campaign=KARANGA december 2022-12-12 13:10:46
仮想通貨 BITPRESS(ビットプレス) コインチェック、1/13まで「Coincheckつみたて キャッシュバックキャンペーン」実施 https://bitpress.jp/count2/3_14_13492 coincheck 2022-12-12 22:27:07

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)