├── .github
├── ISSUE_TEMPLATE
│ └── bug_report.md
└── workflows
│ ├── documentation.yaml
│ └── publish.yaml
├── .gitignore
├── .prettierrc.json
├── .vscode
└── settings.json
├── CODE-OF-CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── __test__
├── cli.test.js
└── mock
│ └── mock-const.js
├── assets
└── cli_logo.png
├── babel.config.cjs
├── bin
└── ablestar-cli.js
├── docs
├── .vscode
│ └── settings.json
├── Makefile
├── make.bat
└── source
│ ├── basic_usage.rst
│ ├── conf.py
│ ├── creating_shopify_api_credentials.rst
│ ├── images
│ ├── access-token.png
│ ├── api-access-scopes.png
│ ├── app-settings-menu.png
│ ├── create-a-custom-app.png
│ ├── custom-app-name.png
│ ├── custom-app-settings.png
│ ├── custom-apps-warning.png
│ ├── install-app.png
│ └── shopify-order-export.png
│ ├── index.rst
│ └── installation.rst
├── package-lock.json
├── package.json
├── src
├── cli.js
├── help.js
├── import.js
├── init.js
├── main.js
├── treePrompt.js
├── verify.js
└── version-check.js
└── utils
├── actions.js
├── fields.js
├── import.js
├── index.js
├── shopify.js
└── style.js
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Additional context**
32 | Add any other context about the problem here.
33 |
--------------------------------------------------------------------------------
/.github/workflows/documentation.yaml:
--------------------------------------------------------------------------------
1 | name: Docs
2 |
3 | # Controls when the workflow will run
4 | on:
5 | push:
6 | branches:
7 | - main
8 |
9 | jobs:
10 | build_docs_job:
11 | runs-on: ubuntu-latest
12 | env:
13 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
14 |
15 | steps:
16 | - name: Checkout
17 | uses: actions/checkout@v2.3.4
18 |
19 | - name: Set up Python
20 | uses: actions/setup-python@v2.2.1
21 | with:
22 | python-version: 3.9
23 |
24 | - name: Install dependencies
25 | run: |
26 | python -m pip install -U sphinx
27 | python -m pip install sphinx-rtd-theme
28 |
29 | - name: make the sphinx docs
30 | run: |
31 | make -C docs clean
32 | make -C docs html
33 |
34 | - name: Init new repo in dist folder and commit
35 | run: |
36 | git config --global --add safe.directory /github/workspace
37 | git config --global init.defaultBranch main
38 | cd docs/build/html/
39 | git init
40 | touch .nojekyll
41 | echo 'cli.ablestar.com' > CNAME
42 | git add -A
43 | git config --local user.email "action@github.com"
44 | git config --local user.name "GitHub Action"
45 | ls -al .
46 | git commit -m 'deploy'
47 | - name: Force push to destination branch
48 | uses: ad-m/github-push-action@v0.6.0
49 | with:
50 | github_token: ${{ secrets.GITHUB_TOKEN }}
51 | branch: gh-pages
52 | force: true
53 | directory: ./docs/build/html
54 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yaml:
--------------------------------------------------------------------------------
1 | name: Build and Publish NPM Package
2 |
3 | on:
4 | release:
5 | types: [created]
6 |
7 | jobs:
8 | build-and-publish:
9 | runs-on: ubuntu-latest
10 | env:
11 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
12 | steps:
13 | - name: Checkout Code
14 | uses: actions/checkout@v3
15 |
16 | - name: Set up Node.js
17 | uses: actions/setup-node@v3
18 | with:
19 | node-version: 14
20 |
21 | - name: Install Dependencies
22 | run: npm ci
23 |
24 | - name: Build
25 | run: npm build
26 |
27 | - name: Publish to NPM
28 | run: |
29 | echo "@ablestar:registry=https://registry.npmjs.org/" > ~/.npmrc
30 | echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/.npmrc
31 | npm publish --access public
32 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # NPM #
2 | node_modules/
3 | /node_modules/
4 |
5 | # Logs and databases #
6 | ######################
7 | *.log
8 | *.sql
9 | *.env
10 |
11 | # config file.
12 | ######################
13 | config.ini
14 | cli.ini
15 |
16 | #####################
17 | *.csv
18 | *.xlsx
19 |
20 | #####################
21 | *.tgz
22 |
23 |
24 | # Docs
25 | docs/build
26 | .DS_Store
27 |
28 | # Ignore test-related files
29 | /coverage.data
30 | /coverage/
31 |
--------------------------------------------------------------------------------
/.prettierrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "trailingComma": "all",
3 | "arrowParens": "avoid",
4 | "singleQuote": true,
5 | "printWidth": 100,
6 | "useTabs": true,
7 | "tabWidth": 4,
8 | "semi": true
9 | }
10 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "esbonio.sphinx.confDir": "",
3 | "workbench.colorCustomizations": {
4 | "activityBar.background": "#253114",
5 | "titleBar.activeBackground": "#34451C",
6 | "titleBar.activeForeground": "#F8FBF4"
7 | }
8 | }
--------------------------------------------------------------------------------
/CODE-OF-CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Ablestar CLI Code of Conduct
2 |
3 | ## Introduction
4 |
5 | As contributors and maintainers of Ablestar CLI, we are committed to providing a welcoming and inclusive environment for everyone, regardless of their background, identity, or personal preferences. We believe that everyone should be treated with respect and dignity, and we expect everyone in the Ablestar CLI community to abide by this principle.
6 |
7 | ## Our Standards
8 |
9 | We expect everyone in the Ablestar CLI community to:
10 |
11 | - Be respectful and considerate towards others.
12 | - Use welcoming and inclusive language.
13 | - Do not engage in harmful, abusive, or discriminatory behavior.
14 | - Do not harass or bully others.
15 | - Be open to constructive feedback and criticism.
16 | - Show empathy and kindness towards others.
17 | - Respect the privacy and boundaries of others.
18 | - Avoid any behavior that could be construed as sexual harassment.
19 |
20 | ## Enforcement
21 |
22 | If someone violates this Code of Conduct, the Ablestar CLI maintainers may take action to address the issue. This could include, but is not limited to:
23 |
24 | - Asking the individual to stop their behavior.
25 | - Asking the individual to leave the project or community temporarily or permanently.
26 | - Reporting the behavior to appropriate authorities.
27 |
28 | The Ablestar CLI maintainers have the right and responsibility to remove, edit, or reject contributions that are not aligned with this Code of Conduct.
29 |
30 | ## Reporting
31 |
32 | If you witness or experience behavior that violates this Code of Conduct, please report it to the Ablestar CLI maintainers by emailing [maintainers email address]. All reports will be kept confidential, and we will work to resolve the issue as quickly as possible.
33 |
34 | ## Conclusion
35 |
36 | By participating in the Ablestar CLI community, you agree to abide by this Code of Conduct. We believe that this Code of Conduct will help us create a safe, inclusive, and welcoming environment for everyone in the Ablestar CLI community.
37 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Ablestar CLI
2 |
3 | Thank you for your interest in contributing to Ablestar CLI! This document outlines different ways in which you can contribute to the project.
4 |
5 | ## Code Contributions
6 |
7 | If you have a code contribution, please submit it as a Github pull request. Here's how to do it:
8 |
9 | 1. Fork the repository to your Github account.
10 | 2. Clone the repository to your local machine.
11 | 3. Create a new branch from the `main` branch.
12 | 4. Make your changes on that branch.
13 | 5. Test your changes locally.
14 | 6. Commit your changes with a clear and descriptive commit message.
15 | 7. Push your branch to your Github repository.
16 | 8. Create a pull request to the `main` branch of the Ablestar CLI repository.
17 |
18 | When submitting the pull request, please ensure that you:
19 |
20 | - Follow existing code styles and conventions.
21 | - Reference any relevant Github issues that the code addresses.
22 |
23 | We will review your pull request as soon as possible. Please be patient while we review it and address any feedback we may have.
24 |
25 | ## Bug Reports
26 |
27 | If you have found a bug, please report it as a Github issue. Before you do so, please:
28 |
29 | - Make sure that you are using the latest version of Ablestar CLI.
30 | - Check the existing issues list on Github to see if the bug has already been reported.
31 |
32 | If the bug has not been reported, please create a new issue. Make sure to include:
33 |
34 | - The version of Ablestar CLI you are using.
35 | - The operating system you are using.
36 | - Any additional information, such as error messages, that can help us reproduce the issue.
37 |
38 | Note: Please make sure that any logs or screenshots you include do not contain sensitive information such as Shopify Access Tokens.
39 |
40 | ## Feature Suggestions
41 |
42 | If you have a feature suggestion, please suggest it as a Github issue. Before you do so, please:
43 |
44 | - Check the existing issues list on Github to see if the feature has already been suggested.
45 |
46 | If the feature has not been suggested, please create a new issue. Make sure to include:
47 |
48 | - A clear and descriptive title for the issue.
49 | - An explanation of why the feature would be useful.
50 | - A step-by-step description of the suggested feature in as much detail as possible.
51 |
52 | ## Code of Conduct
53 |
54 | Please note that by contributing to Ablestar CLI, you agree to abide by our [Code of Conduct](https://github.com/ablestar/ablestar-cli/blob/main/CODE-OF-CONDUCT.md). Please take a moment to read it before contributing.
55 |
56 | Thank you for contributing to Ablestar CLI!
57 |
58 |
59 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | # ablestar-cli
5 |
6 |
7 |
8 | `ablestar-cli` is a command tool for importing and exporting data from your Shopify store. Once you configure your store you can upload and download spreadsheets of your products, customers, orders and more.
9 |
10 | ## Quick Start
11 |
12 |
13 | ```
14 | # Install the tool locally
15 | npm i -g @ablestar/ablestar-cli
16 |
17 | # Configure your API keys
18 | ablestar-cli init
19 |
20 | # Run the tool to export your data
21 | ablestar-cli
22 | ```
23 |
24 | ## Documentation
25 |
26 | The [Ablestar CLI documentation website](https://cli.ablestar.com/) contains setup and usage instructions for `ablestar-cli`.
27 |
28 | ## Demo
29 |
30 | This short recording shows how to configure `ablestar-cli` and export Shopify orders to a file in the Matrixify format:
31 |
32 | [](https://asciinema.org/a/589699)
33 |
34 | The output file will look like this:
35 |
36 |
37 |
38 | ## Supported Objects
39 |
40 | We're slowly adding support for additional Shopify record types. If you would like to see one added please submit an issue or PR.
41 |
42 | | Object | Export | Import/Update |
43 | |-------------|:--------:|:--------:|
44 | | Products | ✅ | ❌ |
45 | | Orders | ✅ | ❌ |
46 | | Pages | ✅ | ✅ |
47 | | Blog Posts | ✅ | ✅ |
48 | | Smart & Manual Collections | ✅ | ✅ |
49 | | Metaobject Entries | ✅ | ❌ |
50 | | Discount Codes | ✅ | ❌ |
51 |
52 | ## Contributing
53 |
54 | All contributions are welcome, when opening a PR please follow our [contribution guide](https://github.com/ablestar/ablestar-cli/blob/main/CONTRIBUTING.md)
55 |
56 | ## About Ablestar
57 |
58 | Ablestar is a trusted Shopify app developer, specializing in creating highly-rated apps since 2016. With tens of thousands of stores using their apps, Ablestar is known for their top-ranked [Bulk Product Editor](https://apps.shopify.com/bulk-product-editor?utm_source=ablestar-cli&utm_medium=readme&utm_campaign=ablestar-cli) app and their commitment to helping businesses save time, streamline operations, and increase sales.
59 |
60 | Other Ablestar projects include:
61 |
62 | - [AppNavigator](https://appnavigator.io/) - Historical data and review analysis for the Shopify App store
63 | - [Spreadsheet Toolkit](https://spreadsheettoolkit.com) - Free tool for performing common tasks on spreadsheets
64 |
65 | You can keep yourself informed on updates to ablestar-cli through our [mailing list](https://confirmsubscription.com/h/y/5C2D5BEBF1A3998F).
--------------------------------------------------------------------------------
/__test__/cli.test.js:
--------------------------------------------------------------------------------
1 | import { initMethod, promptForMissingOptions } from '../src/cli.js';
2 | import { addFields, addPrefix, addValues, defaultFields, isMain } from '../utils/fields.js';
3 | import { getHeader, jsonToSheet } from '../utils/index.js';
4 | import { testJson } from './mock/mock-const.js';
5 |
6 | describe('cli init', () => {
7 | it('should return correct method', async () => {
8 | const options = await initMethod({ method: 'init' });
9 | expect(options.method).toEqual('init');
10 | });
11 |
12 | });
13 |
14 | describe('export', () => {
15 | it('should return correct method', async () => {
16 | const options = await initMethod({ method: 'export' });
17 | expect(options.method).toEqual('export');
18 | });
19 |
20 | it('should return correct options', async () => {
21 | const options = await promptForMissingOptions({
22 | type: 'products',
23 | url: 'test',
24 | format: 'csv',
25 | fileName: 'test_file_name',
26 | fields: ['id'],
27 | });
28 | expect(options.fileName).toEqual('test_file_name');
29 | expect(options.type).toEqual('products');
30 | expect(options.format).toEqual('csv');
31 | expect(options.fields).toHaveLength(1);
32 | });
33 |
34 | it('should add default fields', () => {
35 | const fields = defaultFields('products');
36 | expect(fields).toEqual(['id', 'handle']);
37 | });
38 |
39 | it('should define main field', () => {
40 | const is_main = isMain('products', 'variants');
41 | expect(is_main).toEqual(true);
42 | });
43 |
44 | it('should add prefix to the object keys', () => {
45 | const result = addPrefix({ id: 'test_id', value: 'test_value' }, 'variants');
46 | expect(Object.keys(result)).toEqual(['variants__id', 'variants__value']);
47 | });
48 |
49 | it('should add additional fields depends on format', () => {
50 | const result = addFields('Matrixify', 'products', [
51 | 'tags-basic',
52 | 'id-basic',
53 | 'handle-basic',
54 | 'id-variants',
55 | 'src-images',
56 | ]);
57 | expect(result).toEqual([
58 | 'command-basic',
59 | 'row_number_command-basic',
60 | 'top_row_command-basic',
61 | 'tags_command-basic',
62 | 'variant_command-variants',
63 | 'image_command-images',
64 | ]);
65 | });
66 |
67 | it('should add additional values depends on format', () => {
68 | const result = addValues(
69 | 'Matrixify',
70 | 'products',
71 | { variants__id: 1, images__src: 'src' },
72 | 0,
73 | );
74 | expect(result).toMatchObject({
75 | command: 'MERGE',
76 | tags_command: 'REPLACE',
77 | row_number_command: 1,
78 | variants__variant_command: 'MERGE',
79 | images__image_command: 'MERGE',
80 | });
81 | });
82 |
83 | it('should return correct keys and headers', () => {
84 | const fields = ['id-basic', 'handle-basic', 'title-basic'];
85 | const { keys, header } = getHeader(testJson, 'products', fields);
86 | expect(keys).toEqual(['id', 'handle', 'title']);
87 | expect(header).toEqual(['ID', 'Handle', 'Title']);
88 | });
89 |
90 | it('should return correct worksheet', () => {
91 | const keys = ['id', 'handle', 'title'];
92 | const header = ['ID', 'Handle', 'Title'];
93 | let testsheet;
94 |
95 | const data = jsonToSheet(testJson, 0, testsheet, 'products', keys, header);
96 |
97 | expect(Object.keys(data).length).toBe(43);
98 | expect(data['A2'].v).toBe(6796247957694);
99 | expect(data['F5'].v).toBe('TRUE');
100 | expect(data['!ref']).toBe('A1:F7');
101 | });
102 | });
103 |
--------------------------------------------------------------------------------
/__test__/mock/mock-const.js:
--------------------------------------------------------------------------------
1 | export const testJson = [
2 | {
3 | id: 6796247957694,
4 | title: 'Woodwork Carpenter Pencil Sharpener',
5 | handle: 'woodwork-carpenter-pencil-sharpener-cutter-shaver-narrow-sharpening-tool-for-woodworking-hand-tools-pencil-sharpener-knife',
6 | domain: 'example.myshopify.com',
7 | top_row_command: 'TRUE',
8 | client_details__top_row_command: 'TRUE'
9 | },
10 | {
11 | id: 6796248088766,
12 | title: 'Brutfuner Professional Oil Colored Pencil',
13 | handle: 'brutfuner-48-72-120-160-180-professional-oil-colored-pencil-wooden-soft-watercolor-colour-pencil-school-draw-sketch-art-supplies',
14 | domain: 'example.myshopify.com',
15 | top_row_command: 'TRUE',
16 | client_details__top_row_command: 'TRUE'
17 | },
18 | {
19 | id: 6796248121534,
20 | title: '14 pcs/set Professional Sketch Drawing',
21 | handle: '14-pcs-set-professional-sketch-drawing-pencil-set-hb-2b-6h-4h-2h-3b-4b-5b-6b-10b-12b-1b-painting-pencils-stationery-supplies',
22 | domain: 'example.myshopify.com',
23 | top_row_command: 'TRUE',
24 | client_details__top_row_command: 'TRUE'
25 | },
26 | {
27 | id: 6796248187070,
28 | title: 'Andstal Professional Oil Color Pencil Set',
29 | handle: 'andstal-48-72-120-160-180-professional-oil-color-pencil-set-watercolor-drawing-colored-pencils-wood-colour-coloured-pencils-kids',
30 | domain: 'example.myshopify.com',
31 | top_row_command: 'TRUE',
32 | client_details__top_row_command: 'TRUE'
33 | },
34 | {
35 | id: 7294754455742,
36 | title: 'New pencil',
37 | handle: 'new-pencil',
38 | domain: 'example.myshopify.com',
39 | top_row_command: 'TRUE',
40 | client_details__top_row_command: 'TRUE'
41 | },
42 | {
43 | id: 7301916033214,
44 | title: 'GC1',
45 | handle: 'gc1',
46 | domain: 'example.myshopify.com',
47 | top_row_command: 'TRUE',
48 | client_details__top_row_command: 'TRUE'
49 | }
50 | ];
51 |
--------------------------------------------------------------------------------
/assets/cli_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ablestar/ablestar-cli/7d8a8729b5d41cdf976fad6c0b0325f6c97299a7/assets/cli_logo.png
--------------------------------------------------------------------------------
/babel.config.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | env: {
3 | test: {
4 | presets: [
5 | [
6 | '@babel/preset-env',
7 | {
8 | modules: 'commonjs',
9 | debug: false
10 | }
11 | ],
12 | ],
13 | plugins: [
14 | '@babel/plugin-syntax-dynamic-import',
15 | '@babel/plugin-proposal-class-properties',
16 | ["babel-plugin-transform-import-meta", { "module": "ES6" }]
17 | ]
18 | },
19 | }
20 | };
--------------------------------------------------------------------------------
/bin/ablestar-cli.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | import cli from '../src/cli.js';
4 | cli(process.argv);
5 |
--------------------------------------------------------------------------------
/docs/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "esbonio.sphinx.confDir": ""
3 | }
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line, and also
5 | # from the environment for the first two.
6 | SPHINXOPTS ?=
7 | SPHINXBUILD ?= sphinx-build
8 | SOURCEDIR = source
9 | BUILDDIR = build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
21 |
--------------------------------------------------------------------------------
/docs/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | pushd %~dp0
4 |
5 | REM Command file for Sphinx documentation
6 |
7 | if "%SPHINXBUILD%" == "" (
8 | set SPHINXBUILD=sphinx-build
9 | )
10 | set SOURCEDIR=source
11 | set BUILDDIR=build
12 |
13 | if "%1" == "" goto help
14 |
15 | %SPHINXBUILD% >NUL 2>NUL
16 | if errorlevel 9009 (
17 | echo.
18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
19 | echo.installed, then set the SPHINXBUILD environment variable to point
20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you
21 | echo.may add the Sphinx directory to PATH.
22 | echo.
23 | echo.If you don't have Sphinx installed, grab it from
24 | echo.http://sphinx-doc.org/
25 | exit /b 1
26 | )
27 |
28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
29 | goto end
30 |
31 | :help
32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
33 |
34 | :end
35 | popd
36 |
--------------------------------------------------------------------------------
/docs/source/basic_usage.rst:
--------------------------------------------------------------------------------
1 | Basic Usage
2 | ===========
3 |
4 | Once you've configured ``ablestar-cli`` with the API credentials for your store you can run the command without any arguments to enter interactive mode: ::
5 |
6 | $ ablestar-cli
7 |
8 | This will take you through a wizard where you can select the store, objects (products, orders, customers, etc..) that you want to export. After you go through the wizard it will also give you a command-line equivalent so you can quickly re-run the task.
9 |
10 | You can also use the arguments to tell the tool what you want to do. For example: ::
11 |
12 | ablestar-cli export
13 |
14 | ablestar-cli export products
15 |
16 | ablestar-cli export products example.myshopify.com
17 |
18 | ablestar-cli export products example.myshopify.com --format=CSV
19 |
20 | ablestar-cli export products example.myshopify.com --format=CSV --fields=products --fields=variants
21 |
22 |
--------------------------------------------------------------------------------
/docs/source/conf.py:
--------------------------------------------------------------------------------
1 | # Configuration file for the Sphinx documentation builder.
2 |
3 | # -- Project information
4 |
5 | project = "ablestar-cli"
6 | copyright = "2023, Ablestar LLC"
7 | author = "Ablestar LLC"
8 |
9 | release = "1.0"
10 | version = "0.0.4"
11 |
12 | # -- General configuration
13 |
14 | extensions = [
15 | "sphinx.ext.duration",
16 | "sphinx.ext.doctest",
17 | "sphinx.ext.autodoc",
18 | "sphinx.ext.autosummary",
19 | "sphinx.ext.intersphinx",
20 | ]
21 |
22 | intersphinx_mapping = {
23 | "python": ("https://docs.python.org/3/", None),
24 | "sphinx": ("https://www.sphinx-doc.org/en/master/", None),
25 | }
26 | intersphinx_disabled_domains = ["std"]
27 |
28 | templates_path = ["_templates"]
29 |
30 | # -- Options for HTML output
31 |
32 | html_theme = "sphinx_rtd_theme"
33 |
34 | # -- Options for EPUB output
35 | epub_show_urls = "footnote"
36 |
37 | html_show_sphinx = False
38 |
--------------------------------------------------------------------------------
/docs/source/creating_shopify_api_credentials.rst:
--------------------------------------------------------------------------------
1 | Creating API Keys in the Shopify Admin
2 | ======================================
3 |
4 | ``ablestar-cli`` communictes with Shopify through the REST and GraphQL APIs. In order to access these API we need to generate API keys through the Shopify admin by creating a custom app. This document will show you how to do that.
5 |
6 | .. note::
7 |
8 | The steps here might be different as Shopify is constantly upgrading the admin section. If you notice a discrepancy let us know and we'll update the instructions.
9 |
10 | Open up App Developer in the Shopify admin
11 | ------------------------------------------
12 |
13 | 1. Go to the Shopify admin and click on **Apps >** on the left-hand menu. In the popup that opens up click on **App and sales channel settings**:
14 |
15 | .. image:: images/app-settings-menu.png
16 | :width: 741
17 |
18 | 2. Near the top of the page click on the **Develop Apps** link.
19 |
20 | This will take you to the section of the admin where you can manage your custom apps and API keys.
21 |
22 | Allow custom app development
23 | ----------------------------
24 |
25 | If this is the first time you've created a custom app on this Shopify store you'll need to enable custom app development. If you've already done this you can skip to the next section.
26 |
27 | 1. On the "Develop Apps" page you'll see a message explaining that you need to enable development. We'll click on the **Allow custom app development** button.
28 |
29 | .. image:: images/custom-apps-warning.png
30 | :width: 890
31 |
32 | 2. Shopify will ask us again to confirm that we want to enable custom apps. Click on the **Allow custom app development** button once more.
33 |
34 | Now you should see the page where you can create a new custom app:
35 |
36 | .. image:: images/create-a-custom-app.png
37 | :width: 890
38 |
39 | Creating a new custom app
40 | -------------------------
41 |
42 | From the "App development" page in settings click on the **Create an app** button.
43 |
44 | 1. In the popup enter a name for the app and click on **Create app**:
45 |
46 | .. image:: images/custom-app-name.png
47 | :width: 646
48 |
49 | 2. You will be redirected to the main configuration page for your custom app.
50 |
51 | .. image:: images/custom-app-settings.png
52 |
53 | 3. Now we need to grant API permissions to the application. Click on the **Configure Admin API scopes** button.
54 |
55 | 4. You should see section where you can choose which permissions to grant the application.
56 |
57 | .. image:: images/api-access-scopes.png
58 |
59 |
60 | As a best practice, we recommend that you choose the minimum permissions necessary for your use case. If you want to export and import products, customers and orders you can select the following:
61 |
62 | - read_products
63 | - write_products
64 | - read_orders
65 | - write_orders
66 | - read_customers
67 | - write_customers
68 |
69 | Once you've selected the scopes you need, click on the **Save** button.
70 |
71 | 5. Now the app is configured, we just need to copy the API credentials so we can use them with ``ablestar-cli``. To get these credentials click on the **API credentials** tab at the top of the page.
72 |
73 | .. image:: images/install-app.png
74 |
75 | 6. Click on the **Install app** button. A confirmation dialog will appear and click on the **Install** to continue. Now Shopify will provide you with an access token. This token will only be displayed once so make sure to copy it to a safe place.
76 |
77 | .. image:: images/access-token.png
78 |
79 | 7. We also need to store the API key for the app. This is shown beneath the access token in the 'API key and secret key' section. Copy the API key to a safe place.
80 |
81 |
82 | Next steps
83 | ----------
84 |
85 | Now you have the access token and API key for the custom app you just created. With this information you can run ``ablestar-cli`` to set up the credentials for your store:
86 |
87 | .. code-block:: console
88 |
89 | $ ablestar-cli init
--------------------------------------------------------------------------------
/docs/source/images/access-token.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ablestar/ablestar-cli/7d8a8729b5d41cdf976fad6c0b0325f6c97299a7/docs/source/images/access-token.png
--------------------------------------------------------------------------------
/docs/source/images/api-access-scopes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ablestar/ablestar-cli/7d8a8729b5d41cdf976fad6c0b0325f6c97299a7/docs/source/images/api-access-scopes.png
--------------------------------------------------------------------------------
/docs/source/images/app-settings-menu.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ablestar/ablestar-cli/7d8a8729b5d41cdf976fad6c0b0325f6c97299a7/docs/source/images/app-settings-menu.png
--------------------------------------------------------------------------------
/docs/source/images/create-a-custom-app.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ablestar/ablestar-cli/7d8a8729b5d41cdf976fad6c0b0325f6c97299a7/docs/source/images/create-a-custom-app.png
--------------------------------------------------------------------------------
/docs/source/images/custom-app-name.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ablestar/ablestar-cli/7d8a8729b5d41cdf976fad6c0b0325f6c97299a7/docs/source/images/custom-app-name.png
--------------------------------------------------------------------------------
/docs/source/images/custom-app-settings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ablestar/ablestar-cli/7d8a8729b5d41cdf976fad6c0b0325f6c97299a7/docs/source/images/custom-app-settings.png
--------------------------------------------------------------------------------
/docs/source/images/custom-apps-warning.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ablestar/ablestar-cli/7d8a8729b5d41cdf976fad6c0b0325f6c97299a7/docs/source/images/custom-apps-warning.png
--------------------------------------------------------------------------------
/docs/source/images/install-app.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ablestar/ablestar-cli/7d8a8729b5d41cdf976fad6c0b0325f6c97299a7/docs/source/images/install-app.png
--------------------------------------------------------------------------------
/docs/source/images/shopify-order-export.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ablestar/ablestar-cli/7d8a8729b5d41cdf976fad6c0b0325f6c97299a7/docs/source/images/shopify-order-export.png
--------------------------------------------------------------------------------
/docs/source/index.rst:
--------------------------------------------------------------------------------
1 | Documentation for ablestar-cli
2 | ==============================
3 |
4 | **ablestar-cli** is a command-line tool written in Node that lets you quickly import and export data from your Shopify store. To exports and imports can either be configured with options from the command line or you can use the interactive wizard to configure your job.
5 |
6 | To get started you will need to:
7 |
8 | - Generate API credentials in the Shopify admin
9 | - Configure ``ablestar-cli`` with your credentials
10 |
11 | Contents
12 | --------
13 |
14 | .. toctree::
15 | installation
16 | creating_shopify_api_credentials
17 | basic_usage
18 |
19 | Demo
20 | ----
21 |
22 | .. raw:: html
23 |
24 |
25 |
26 | This will produce an Excel file that looks like this:
27 |
28 | .. image:: images/shopify-order-export.png
29 | :width: 1258
30 |
31 | Source Code
32 | -----------
33 |
34 | The source code for **ablestar-cli** is available on Github at https://github.com/ablestar/ablestar-cli.
35 |
36 | About Ablestar
37 | --------------
38 |
39 | Ablestar is a trusted Shopify app developer, specializing in creating highly-rated apps since 2016. With tens of thousands of stores using their apps, Ablestar is known for their top-ranked `Bulk Product Editor `_ app and their commitment to helping businesses save time, streamline operations, and increase sales.
40 |
41 | You can keep yourself informed on updates to ablestar-cli through our `mailing list `_
--------------------------------------------------------------------------------
/docs/source/installation.rst:
--------------------------------------------------------------------------------
1 | Installation
2 | ============
3 |
4 | From npm
5 | ---------
6 |
7 | You can install ``ablestar-cli`` on your local system by running: ::
8 |
9 | npm i -g @ablestar/ablestar-cli
10 |
11 | From Source
12 | -----------
13 |
14 | If you want to install the source code from source you can download the code from Github and install it that way. The steps are:
15 |
16 | - Clone the project to a local folder
17 | - Enter the folder and run ``npm install``
18 | - Run ``npm link`` so that you can run the ``ablestar-cli`` command globally.
19 |
20 | The shell commands to do this are: ::
21 |
22 | git clone https://github.com/ablestar/ablestar-cli.git
23 | cd ablestar-cli
24 | npm install
25 | npm link
26 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@ablestar/ablestar-cli",
3 | "version": "0.1.2",
4 | "description": "Ablestar command-line interface for Shopify.",
5 | "main": "src/cli.js",
6 | "bin": {
7 | "@ablestar/ablestar-cli": "bin/ablestar-cli.js",
8 | "ablestar-cli": "bin/ablestar-cli.js"
9 | },
10 | "publishConfig": {
11 | "access": "public"
12 | },
13 | "scripts": {
14 | "format": "prettier --write \"./**/*.{js,json}\"",
15 | "test": "jest"
16 | },
17 | "keywords": [
18 | "cli",
19 | "ablestar-cli"
20 | ],
21 | "author": "",
22 | "license": "AGPL",
23 | "dependencies": {
24 | "app-root-path": "^3.1.0",
25 | "arg": "^5.0.2",
26 | "axios": "^1.1.3",
27 | "chalk": "^5.1.2",
28 | "cli-handle-unhandled": "^1.1.1",
29 | "cli-progress": "^3.11.2",
30 | "cli-welcome": "^2.2.2",
31 | "exceljs": "^4.3.0",
32 | "ini": "^3.0.1",
33 | "inquirer": "^9.1.4",
34 | "inquirer-autocomplete-prompt": "^3.0.0",
35 | "inquirer-fuzzy-path": "^2.3.0",
36 | "inquirer-tree-prompt": "^1.1.2",
37 | "ora": "^6.1.2",
38 | "package-json": "^8.1.0",
39 | "semver": "^7.3.8",
40 | "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.0/xlsx-0.20.0.tgz"
41 | },
42 | "dependenciesComments": {
43 | "xlsx": "refer the version from https://docs.sheetjs.com/docs/getting-started/installation/nodejs/"
44 | },
45 | "devDependencies": {
46 | "@babel/preset-env": "^7.20.2",
47 | "babel-jest": "^29.4.2",
48 | "babel-plugin-transform-import-meta": "^2.2.0",
49 | "jest": "^29.4.2",
50 | "prettier": "^2.7.1",
51 | "ts-jest": "^29.0.5"
52 | },
53 | "type": "module",
54 | "files": [
55 | "bin/",
56 | "src/",
57 | "utils/"
58 | ],
59 | "jest": {
60 | "testEnvironment": "node",
61 | "transform": {
62 | "^.+\\.(js|jsx)$": "babel-jest",
63 | "node_modules/inquirer/.+\\.(j|t)sx?$": "babel-jest",
64 | "node_modules/chalk/.+\\.(j|t)sx?$": "babel-jest"
65 | },
66 | "transformIgnorePatterns": []
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/cli.js:
--------------------------------------------------------------------------------
1 | import arg from 'arg';
2 | import inquirer from 'inquirer';
3 | import showHelp from './help.js';
4 | import chalk from 'chalk';
5 | import { generateFileName, jsonToSheet, sheetToCsv, validateApiKey, validateFileName, validateURL } from '../utils/index.js';
6 | import { verifyApiKey } from './verify.js';
7 | import ora from 'ora';
8 | import { run } from './main.js';
9 | import TreePrompt from './treePrompt.js';
10 | import {
11 | automatedCollectionFields,
12 | blogsFields,
13 | customCollectionFields,
14 | customerFields,
15 | discountFields,
16 | getGroup,
17 | metaobjectEntriesFields,
18 | orderFields,
19 | pagesFields,
20 | productFields,
21 | } from '../utils/fields.js';
22 | import fs from 'fs';
23 | import ini from 'ini';
24 | // import appRootPath from 'app-root-path';
25 | import versionCheck from './version-check.js';
26 | import { analyzeFile, getHeaderColumn } from '../utils/import.js';
27 | import { actionTree } from '../utils/actions.js';
28 |
29 | import inquirerPrompt from 'inquirer-autocomplete-prompt';
30 | import fuzzyPath from 'inquirer-fuzzy-path';
31 | import { runImport, runImportArticles, runImportCustomCollection, runImportPages, runImportSmartCollection } from './import.js';
32 | import os from 'os';
33 |
34 | const appRootPath = { path: os.homedir() };
35 |
36 | inquirer.registerPrompt('tree', TreePrompt);
37 | inquirer.registerPrompt('autocomplete', inquirerPrompt);
38 | inquirer.registerPrompt('fuzzypath', fuzzyPath);
39 |
40 | /**
41 | * Convert the raw arguments input to options object.
42 | *
43 | * @param {string} rawArgs raw args user inputed.
44 | * @return {object} option value (object).
45 | */
46 | function parseArgumentsIntoOptions(rawArgs) {
47 | const args = arg(
48 | {
49 | '--help': Boolean,
50 | '-h': '--help',
51 | '--version': Boolean,
52 | '-v': '--version',
53 |
54 | '--type': String,
55 | '--url': String,
56 | '--format': String,
57 | '--fields': [String],
58 | '--group': [String],
59 |
60 | '--fileName': String,
61 |
62 | '-t': '--type',
63 | '-u': '--url',
64 | '-f': '--format',
65 | '-i': '--fields',
66 | '-g': '--group',
67 |
68 | '--apiKey': String,
69 | '--apiPass': String,
70 |
71 | '--idColumn': String,
72 | '--actionColumn': String,
73 | '--action': String,
74 | },
75 | {
76 | argv: rawArgs.slice(2),
77 | },
78 | );
79 | return {
80 | help: args['--help'] || false,
81 | version: args['--version'] || false,
82 |
83 | method: args._[0],
84 | type: args['--type'] || args._[1] || '',
85 | url: args['--url'] || args._[2] || '',
86 | format: args['--format'] || args._[3] || '',
87 | fields: args['--fields'] || [],
88 | group: args['--group'] || [],
89 | apiKey: args['--apiKey'] || '',
90 | apiPass: args['--apiPass'] || '',
91 |
92 | fileName: args['--fileName'] || args._[4] || '',
93 |
94 | idColumn: args['--idColumn'] || '',
95 | action: args['--action'] || '',
96 | actionColumn: args['--actionColumn'] || '',
97 | };
98 | }
99 |
100 | /**
101 | * Initialize the method to one of ["init", "export", "import"]
102 | *
103 | * @param {object} options options object.
104 | * @return {object} options object that has method.
105 | */
106 | export async function initMethod(options) {
107 | const defaultTemplate = 'export';
108 | if (options.method && !['export', 'import', 'init'].includes(options.method)) {
109 | throw 'error';
110 | }
111 | const questions = [];
112 | if (!options.method) {
113 | questions.push({
114 | type: 'list',
115 | name: 'method',
116 | message: 'Please choose what you will do',
117 | choices: ['init', 'export', 'import'],
118 | default: defaultTemplate,
119 | });
120 | }
121 | const answers = await inquirer.prompt(questions);
122 | return {
123 | ...options,
124 | method: options.method || answers.method,
125 | };
126 | }
127 |
128 | /**
129 | * Fulfill the missing options.
130 | *
131 | * @param {object} options options object.
132 | * @return {object} options object that has all options (type, url, format, fields).
133 | */
134 | export async function promptForMissingOptions(options) {
135 | const defaultType = 'products';
136 |
137 | const questions = [
138 | {
139 | type: 'list',
140 | name: 'type',
141 | message: `Please choose what you try to ${options.method}`,
142 | choices: [
143 | { name: 'Products', value: 'products' },
144 | { name: 'Orders', value: 'orders' },
145 | { name: 'Customers', value: 'customers' },
146 | { name: 'Manual Collection', value: 'custom_collections' },
147 | { name: 'Automated Collection', value: 'smart_collections' },
148 | { name: 'Metaobject Definitions', value: 'metaobject_definitions' },
149 | { name: 'Metaobject Entries', value: 'metaobject_entries' },
150 | { name: 'Discounts', value: 'price_rules' },
151 | { name: 'Pages', value: 'pages' },
152 | { name: 'Blog Posts', value: 'blogs' },
153 | ],
154 | default: defaultType,
155 | when: () => !options.type,
156 | },
157 | {
158 | type: 'list',
159 | name: 'url',
160 | message: () => {
161 | let config = {};
162 | if (fs.existsSync(appRootPath.path + '/.ablestar/cli.ini')) {
163 | config = ini.parse(fs.readFileSync(appRootPath.path + '/.ablestar/cli.ini', 'utf-8'));
164 | }
165 |
166 | return Object.keys(config).filter(key => key !== 'core').length
167 | ? 'Please choose store'
168 | : "We couldn't find any initialized store, please initialize the store first";
169 | },
170 | choices: () => {
171 | let config = {};
172 | if (fs.existsSync(appRootPath.path + '/.ablestar/cli.ini')) {
173 | config = ini.parse(fs.readFileSync(appRootPath.path + '/.ablestar/cli.ini', 'utf-8'));
174 | }
175 | return Object.keys(config).filter(key => key !== 'core');
176 | },
177 | when: () => !options.url,
178 | },
179 | {
180 | type: 'list',
181 | name: 'format',
182 | message: `Please choose which format file you will ${options.method}.`,
183 | choices: ['CSV', 'Excel', 'Matrixify'],
184 | default: 'CSV',
185 | when: () => !options.format,
186 | },
187 | {
188 | type: 'input',
189 | name: 'fileName',
190 | message: `Please input file name.`,
191 | default: answers => {
192 | return generateFileName(answers.type || options.type);
193 | },
194 | when: () => !options.fileName,
195 | },
196 | {
197 | type: 'tree',
198 | name: 'fields',
199 | message: `Please choose fields you'd ${options.method}`,
200 | pageSize: 20,
201 | tree: answers => {
202 | if (answers.type === 'products' || options.type === 'products')
203 | return productFields;
204 | if (answers.type === 'orders' || options.type === 'orders') return orderFields;
205 | if (answers.type === 'customers' || options.type === 'customers')
206 | return customerFields;
207 | if (answers.type === 'custom_collections' || options.type === 'custom_collections')
208 | return customCollectionFields;
209 | if (answers.type === 'smart_collections' || options.type === 'smart_collections')
210 | return automatedCollectionFields;
211 | if (answers.type === 'metaobject_entries' || options.type === 'metaobject_entries')
212 | return metaobjectEntriesFields;
213 | if (answers.type === 'price_rules' || options.type === 'price_rules')
214 | return discountFields;
215 | if (answers.type === 'pages' || options.type === 'pages') return pagesFields;
216 | if (answers.type === 'blogs' || options.type === 'blogs') return blogsFields;
217 | },
218 | multiple: true,
219 | when: (answers) => !options.fields?.length && !options.group?.length && (!answers.type?.includes('metaobject_definitions') && !options.type?.includes('metaobject_definitions')),
220 | },
221 | ];
222 |
223 | const answers = await inquirer.prompt(questions);
224 | return {
225 | ...options,
226 | type: options.type || answers.type,
227 | url: options.url || answers.url,
228 | format: options.format || answers.format,
229 | fileName: options.fileName || answers.fileName,
230 | fields: options.fields.length ? options.fields : answers.fields,
231 | };
232 | }
233 |
234 | /**
235 | * Fulfill the url option when init the store.
236 | *
237 | * @param {object} options options object.
238 | * @return {object} options object that has url option.
239 | */
240 | async function initStore(options) {
241 | const questions = [];
242 | if (!options.url) {
243 | questions.push({
244 | type: 'input',
245 | name: 'url',
246 | message: 'Please enter the myshopify.com domain for your store',
247 | validate: validateURL,
248 | });
249 | }
250 | const answers = await inquirer.prompt(questions);
251 | return {
252 | ...options,
253 | url: options.url || answers.url,
254 | };
255 | }
256 |
257 | /**
258 | * Fulfill the apiKey and apiPass options when init the store.
259 | *
260 | * @param {object} options options object.
261 | * @return {object} options object that has apiKey and apiPass options.
262 | */
263 | async function initApi(options) {
264 | const questions = [];
265 | if (!options.apiKey) {
266 | questions.push({
267 | type: 'input',
268 | name: 'apiKey',
269 | message: 'API Key:',
270 | validate: validateApiKey,
271 | });
272 | }
273 | questions.push({
274 | type: 'password',
275 | name: 'apiPass',
276 | message: 'Password:',
277 | });
278 | const answers = await inquirer.prompt(questions);
279 | return {
280 | ...options,
281 | apiKey: options.apiKey || answers.apiKey,
282 | apiPass: answers.apiPass,
283 | };
284 | }
285 |
286 | async function importFile(options) {
287 | const questions = [
288 | {
289 | type: 'fuzzypath',
290 | name: 'fileName',
291 | message: 'Please enter file path/name: ',
292 | validate: validateFileName,
293 | when: () => !options.fileName,
294 |
295 | excludePath: nodePath =>
296 | nodePath.startsWith('node_modules') ||
297 | nodePath.includes('git'),
298 | // excludePath :: (String) -> Bool
299 | // excludePath to exclude some paths from the file-system scan
300 | excludeFilter: nodePath => nodePath == '.',
301 | // excludeFilter :: (String) -> Bool
302 | // excludeFilter to exclude some paths from the final list, e.g. '.'
303 | itemType: 'file',
304 | // itemType :: 'any' | 'directory' | 'file'
305 | // specify the type of nodes to display
306 | // default value: 'any'
307 | // example: itemType: 'file' - hides directories from the item list
308 | rootPath: './',
309 | // rootPath :: String
310 | // Root search directory
311 | suggestOnly: true,
312 | // suggestOnly :: Bool
313 | // Restrict prompt answer to available choices or use them as suggestions
314 | depthLimit: 2,
315 | },
316 | ];
317 | const answers = await inquirer.prompt(questions);
318 | return {
319 | ...options,
320 | fileName: options.fileName || answers.fileName,
321 | };
322 | }
323 |
324 | async function importOptions(options, fileData) {
325 | const defaultType = 'customers';
326 |
327 | const questions = [
328 | {
329 | type: 'list',
330 | name: 'type',
331 | message: `Please choose which field you try to import/update: `,
332 | choices: [
333 | { name: 'Products', value: 'products' },
334 | { name: 'Orders', value: 'orders' },
335 | { name: 'Customers', value: 'customers' },
336 | { name: 'Manual Collection', value: 'custom_collections' },
337 | { name: 'Automated Collection', value: 'smart_collections' },
338 | { name: 'Pages', value: 'pages' },
339 | { name: 'Blog Posts', value: 'articles' },
340 | ],
341 | default: defaultType,
342 | when: () => !options.type,
343 | },
344 | {
345 | type: 'list',
346 | name: 'url',
347 | message: () => {
348 | let config = {};
349 | if (fs.existsSync(appRootPath.path + '/.ablestar/cli.ini')) {
350 | config = ini.parse(fs.readFileSync(appRootPath.path + '/.ablestar/cli.ini', 'utf-8'));
351 | }
352 |
353 | return Object.keys(config).filter(key => key !== 'core').length
354 | ? 'Please choose store'
355 | : "We couldn't find any initialized store, please initialize the store first";
356 | },
357 | choices: () => {
358 | let config = {};
359 | if (fs.existsSync(appRootPath.path + '/.ablestar/cli.ini')) {
360 | config = ini.parse(fs.readFileSync(appRootPath.path + '/.ablestar/cli.ini', 'utf-8'));
361 | }
362 | return Object.keys(config).filter(key => key !== 'core');
363 | },
364 | when: () => !options.url,
365 | },
366 | {
367 | type: 'list',
368 | name: 'format',
369 | message: `Please choose which format file you will ${options.method}.`,
370 | choices: ['CSV', 'Excel', 'Matrixify'],
371 | default: 'CSV',
372 | when: () => !options.format,
373 | },
374 | {
375 | type: 'list',
376 | name: 'idColumn',
377 | message: 'Which column do you want to use as Identify column?',
378 | choices: () => {
379 | return Object.keys(fileData[0]);
380 | },
381 | when: (answers) => !options.idColumn && (options.format !== 'Matrixify' && answers.format !== 'Matrixify'),
382 | },
383 | {
384 | type: 'list',
385 | name: 'action',
386 | message: `Please choose action you'd like to do: `,
387 | choices: answers => {
388 | return actionTree(answers.type || options.type);
389 | },
390 | when: (answers) => !options.action && (options.format !== 'Matrixify' && answers.format !== 'Matrixify'),
391 | },
392 | {
393 | type: 'list',
394 | name: 'actionColumn',
395 | message: 'Which column do you want to use as action column?',
396 | choices: () => {
397 | return Object.keys(fileData[0]);
398 | },
399 | when: (answers) => !options.actionColumn && (options.format !== 'Matrixify' && answers.format !== 'Matrixify'),
400 | },
401 | ];
402 |
403 | const answers = await inquirer.prompt(questions);
404 | return {
405 | ...options,
406 | type: options.type || answers.type,
407 | url: options.url || answers.url,
408 | format: options.format || answers.format,
409 | idColumn: options.idColumn || answers.idColumn,
410 | actionColumn: options.actionColumn || answers.actionColumn,
411 | action: options.action || answers.action,
412 | };
413 | }
414 |
415 | /**
416 | * Main function run by ablestar-cli command.
417 | *
418 | * @param {string} args raw args user inputed.
419 | */
420 | async function cli(args) {
421 | versionCheck();
422 | try {
423 | let options = parseArgumentsIntoOptions(args);
424 | if (options.version) {
425 | return;
426 | }
427 | if (options.help) {
428 | showHelp();
429 | return;
430 | }
431 | options = await initMethod(options);
432 | if (options.method === 'init') {
433 | options = await initStore(options);
434 | console.log();
435 | console.log(
436 | `Go to https://${options.url}/admin/settings/apps/development and create a new private app`,
437 | );
438 | console.log();
439 | options = await initApi(options);
440 | const spinner = ora('Testing credentials').start();
441 | await verifyApiKey(options);
442 | spinner.stop();
443 | console.log();
444 | } else if (options.method === 'export') {
445 | options = await promptForMissingOptions(options);
446 | options.fields = options.fields || [];
447 | await run(options);
448 |
449 | console.log(chalk.bgCyan.black(' == Alternative Command == '));
450 | console.log(
451 | chalk.cyan(
452 | `ablestar-cli ${options.method} ${options.type} ${options.url} --format=${options.format
453 | } --fileName=${options.fileName}${getGroup(options.type, options.fields)}`,
454 | ),
455 | );
456 | } else if (options.method === 'import') {
457 | options = await importFile(options);
458 | const fileData = await analyzeFile(options.fileName);
459 | options = await importOptions(options, fileData);
460 |
461 | if (options.format === 'Matrixify') {
462 | let outputData = {};
463 | if (options.type === 'custom_collections') outputData = await runImportCustomCollection(options, fileData);
464 | if (options.type === 'smart_collections') outputData = await runImportSmartCollection(options, fileData);
465 | if (options.type === 'pages') outputData = await runImportPages(options, fileData);
466 | if (options.type === 'articles') outputData = await runImportArticles(options, fileData);
467 |
468 | const outputJson = fileData.map((item, itemIndex) => {
469 | const { itemKey, ...rest } = Object.values(outputData).find(i => i.itemKey === item.ID || i.itemKey === item.Handle || i.itemKey === itemIndex);
470 |
471 | return { ...item, ...rest }
472 | })
473 |
474 | const outputHeader = [await getHeaderColumn(options.fileName), ['ID (ref)', 'Handle (ref)', 'Import Result', 'Import Comment']].flat();
475 |
476 | let worksheet;
477 | const outputSheet = jsonToSheet(outputJson, 0, worksheet, 'output', outputHeader, outputHeader);
478 | sheetToCsv(outputSheet, `${options.fileName}_Results.csv`);
479 |
480 | console.log("Result Saved to ", chalk.greenBright(`${options.fileName}_Results.csv \n`));
481 | }
482 |
483 | else await runImport(options, fileData);
484 |
485 | console.log(chalk.bgCyan.black(' == Alternative Command == '));
486 | console.log(
487 | chalk.cyan(
488 | `ablestar-cli ${options.method} ${options.type} ${options.url} --fileName=${options.fileName} --format=${options.format} ${options.type === 'customers' ? `--idColumn=${options.idColumn} --action=${options.action} --actionColumn=${options.actionColumn}` : ``}`,
489 | ),
490 | );
491 | }
492 | } catch (error) {
493 | console.log(error);
494 | console.log(chalk.bgRed.black(' Error '), 'Incorrect use of command, please check help');
495 |
496 | // showHelp();
497 | }
498 |
499 | return 'run successfully';
500 | }
501 |
502 | export default cli;
503 |
--------------------------------------------------------------------------------
/src/help.js:
--------------------------------------------------------------------------------
1 | import chalk from 'chalk';
2 |
3 | export default function showHelp() {
4 | console.log(`
5 | ${chalk.bgGreenBright.black(' USAGE ')}
6 |
7 | $ ${chalk.greenBright('ablestar-cli')} ${chalk.cyan('')} ${chalk.yellowBright('[options]')}
8 |
9 | ${chalk.bgCyan.black(' COMMANDS ')}
10 |
11 | ${chalk.cyan('init')} Initialize the store
12 |
13 | ${chalk.cyan('export')} Export products from Shopify
14 | ${chalk.cyan('import')} Import products to Shopify
15 |
16 | ${chalk.bgYellowBright.black(' OPTIONS ')}
17 |
18 | ${chalk.yellowBright('-t, --type')} Type of products to export/import (${chalk.yellowBright(
19 | 'products',
20 | )}/${chalk.yellowBright('variants')})
21 | ${chalk.yellowBright('-u, --url')} URL of store (${chalk.yellowBright('*.myshopify.com')})
22 | ${chalk.yellowBright(
23 | '-f, --format',
24 | )} File format that be uses to export/import (${chalk.yellowBright(
25 | 'CSV',
26 | )}/${chalk.yellowBright('Excel')})
27 | ${chalk.yellowBright('-i, --fields')} Fields that be exported/imported (${chalk.yellowBright(
28 | 'products',
29 | )}/${chalk.yellowBright('variants')})
30 |
31 | ${chalk.yellowBright('-v, --version')} Print CLI version
32 | ${chalk.yellowBright('-h, --help')} Print CLI help
33 | `);
34 | }
35 |
--------------------------------------------------------------------------------
/src/import.js:
--------------------------------------------------------------------------------
1 | import { articlesQuery, customCollectionQuery, groupSmartCollection, pagesQuery, runMatrixify, smartCollectionQuery } from '../utils/import.js';
2 | import { shopifyRESTApi, shopifyRESTApiSingle } from '../utils/shopify.js';
3 | import cliProgress from 'cli-progress';
4 |
5 | export async function runImport(options, fileData) {
6 | const bar1 = new cliProgress.SingleBar(
7 | {
8 | format: `[{bar}] {percentage}% | DUR: {duration}s | ETA: {eta}s | {value}/{total}`,
9 | },
10 | cliProgress.Presets.shades_classic,
11 | );
12 | try {
13 | console.log();
14 | bar1.start(fileData.length, 0);
15 | if (
16 | options.type === 'customers' &&
17 | ['add-tags', 'set-tags', 'remove-tags'].includes(options.action)
18 | ) {
19 | let since_id = 0;
20 | const limit = 250;
21 | let result = [];
22 | while (true) {
23 | const query = {
24 | params: {
25 | fields: ['id', 'email', 'tags'],
26 | since_id,
27 | limit,
28 | },
29 | };
30 |
31 | const data = await shopifyRESTApi(options.url, options.type, 'get', query);
32 |
33 | if (data[options.type].length === 0) break;
34 |
35 | result = [...result, ...data[options.type]];
36 |
37 | if (data[options.type].length !== limit) break;
38 | since_id = data[options.type][data[options.type].length - 1].id;
39 | }
40 |
41 | const filterCol = options.idColumn === 'email' ? 'email' : 'id';
42 | const ids = fileData.map(item => ({
43 | ...item,
44 | id: result.find(i => i[filterCol] === item[options.idColumn])?.id || null,
45 | }));
46 | const updateResult = await Promise.all(
47 | ids.map(async item => {
48 | if (!item.id) return null;
49 | const tags =
50 | options.action === 'set-tags'
51 | ? item[options.actionColumn]
52 | : options.action === 'add-tags'
53 | ? `${result.find(i => i.id === item.id)?.tags || ''}, ${
54 | item[options.actionColumn]
55 | }`
56 | : result
57 | .find(i => i.id === item.id)
58 | ?.tags.split(', ')
59 | .filter(
60 | el => !item[options.actionColumn].split(', ').includes(el),
61 | );
62 | const response = await shopifyRESTApiSingle(
63 | options.url,
64 | options.type,
65 | item.id,
66 | 'put',
67 | { customer: { id: item.id, tags } },
68 | );
69 | bar1.increment(1);
70 | return response.customer;
71 | }),
72 | );
73 | bar1.stop();
74 | console.log(updateResult);
75 | }
76 | } catch (error) {
77 | bar1.stop();
78 | throw error;
79 | }
80 | }
81 |
82 | export async function runImportCustomCollection(options, fileData) {
83 | const output = await runMatrixify(options, fileData, customCollectionQuery);
84 | return output;
85 | }
86 |
87 | export async function runImportSmartCollection(options, fileData) {
88 | const groupData = groupSmartCollection(fileData);
89 | const output = await runMatrixify(options, groupData, smartCollectionQuery);
90 | return output;
91 | }
92 |
93 | export async function runImportPages(options, fileData) {
94 | const output = await runMatrixify(options, fileData, pagesQuery);
95 | return output;
96 | }
97 |
98 | export async function runImportArticles(options, fileData) {
99 | const output = await runMatrixify(options, fileData, articlesQuery, true);
100 | return output;
101 | }
102 |
--------------------------------------------------------------------------------
/src/init.js:
--------------------------------------------------------------------------------
1 | import welcome from 'cli-welcome';
2 | import unhandled from 'cli-handle-unhandled';
3 | import { require } from '../utils/index.js';
4 | const pkg = require('./../package.json');
5 |
6 | export default () => {
7 | unhandled();
8 | welcome({
9 | title: `ablestar-cli`,
10 | tagLine: ``,
11 | description: pkg.description,
12 | version: pkg.version,
13 | bgColor: '#36BB09',
14 | color: '#000000',
15 | bold: true,
16 | clear: false,
17 | });
18 | };
19 |
--------------------------------------------------------------------------------
/src/main.js:
--------------------------------------------------------------------------------
1 | import chalk from 'chalk';
2 | import {
3 | shopifyGraphMetaobject,
4 | shopifyGraphMetaobjectEntries,
5 | shopifyItemRESTApi,
6 | shopifyRESTApi,
7 | shopifyRESTApiCollectionProducts,
8 | shopifyRESTApiCount,
9 | shopifyRESTApiDomain,
10 | shopifyRESTApiProductMetafield,
11 | shopifyRESTApiSubList,
12 | shopifyRESTApiVariantMetafield,
13 | } from '../utils/shopify.js';
14 | import {
15 | getHeader,
16 | jsonToSheet,
17 | numFromID,
18 | orderMultiFields,
19 | sheetToCsv,
20 | writeExcel,
21 | writeMatrixify,
22 | } from '../utils/index.js';
23 | import cliProgress from 'cli-progress';
24 | import _ from 'lodash';
25 | import {
26 | addFields,
27 | addPrefix,
28 | addValues,
29 | capitalize,
30 | convertion,
31 | defaultFields,
32 | getFieldsFromGroup,
33 | isMain,
34 | isMulti,
35 | } from '../utils/fields.js';
36 |
37 | export async function run(options) {
38 | try {
39 | let since_id = 0;
40 | const limit = 250;
41 |
42 | let worksheet;
43 |
44 | console.log();
45 | // create a new progress bar instance and use shades_classic theme
46 | const bar1 = new cliProgress.SingleBar(
47 | {
48 | format: `[{bar}] {percentage}% | DUR: {duration}s | ETA: {eta}s | {value}/{total}`,
49 | },
50 | cliProgress.Presets.shades_classic,
51 | );
52 |
53 | let result = [];
54 | let filters = {}; // save non-basic fields
55 | let fields = defaultFields(options.type);
56 |
57 | const start_at = new Date();
58 |
59 | // Graphql api
60 | if (options.type.includes('metaobject')) {
61 | let endCursor = '';
62 | bar1.start(0, 0);
63 |
64 | while (true) {
65 | const data = await shopifyGraphMetaobject({store: options.url, endCursor});
66 |
67 | if (!data) {
68 | bar1.stop();
69 |
70 | console.log('\n No result \n');
71 |
72 | return;
73 | }
74 | bar1.setTotal( result.length + data.nodes.length );
75 |
76 | if (options.type === 'metaobject_definitions') {
77 |
78 | result = [...result, ...data.nodes.map(item => (item.fieldDefinitions.map(itemField => ({
79 | id: item.id,
80 | name: item.name,
81 | type: item.type,
82 | metaobjectsCount: item.metaobjectsCount,
83 | fieldDefinitionKey: itemField.key,
84 | fieldDefinitionName: itemField.name,
85 | fieldDefinitionType: itemField.type.name,
86 | fieldDefinitionRequired: itemField.required,
87 | fieldDefinitionDescription: itemField.description,
88 | })))).flat()];
89 |
90 | bar1.increment( data.nodes.length );
91 | } else if (options.type === 'metaobject_entries') {
92 | const entryData = await Promise.all(
93 | data.nodes.map(async (definition) => {
94 | let entryEndCursor = '';
95 | const entries = await shopifyGraphMetaobjectEntries({ store: options.url, type: definition.type, entryEndCursor});
96 | bar1.increment(1);
97 | if (options.fields.includes('fieldValue-field') || options.fields.includes('fieldKey-field'))
98 | result = [...result, ...entries ? entries.nodes.map(item => (item.fields.map((itemField, index) => ({
99 | id: numFromID(item.id),
100 |
101 | top_row_command : index === 0 ? 'TRUE' : null,
102 | definitionHandle: definition.type,
103 | definitionName: definition.name,
104 | status: 'Active',
105 |
106 | displayName: item.displayName,
107 | handle: item.handle,
108 | type: item.type,
109 | updatedAt: item.updatedAt,
110 |
111 | field__fieldKey: itemField.key,
112 | field__fieldValue: itemField.value,
113 | })))).flat() : [] ];
114 | else
115 | result = [...result, ...entries ? entries.nodes.map(item => ({
116 | id: numFromID(item.id),
117 |
118 | top_row_command : 'TRUE',
119 | definitionHandle: definition.type,
120 | definitionName: definition.name,
121 | status: 'Active',
122 |
123 | displayName: item.displayName,
124 | handle: item.handle,
125 | type: item.type,
126 | updatedAt: item.updatedAt,
127 | })).flat() : [] ];
128 | })
129 | )
130 | }
131 |
132 |
133 |
134 | if (!data.pageInfo.hasNextPage) break;
135 | endCursor = data.pageInfo.endCursor;
136 | }
137 |
138 | }
139 |
140 | else {
141 | // Get total items count
142 | const data = await shopifyRESTApiCount(options.url, options.type, 'get');
143 |
144 | if (!data) {
145 | console.log(`No ${chalk.greenBright(`${options.type}`)} exist on store`)
146 | console.log();
147 | return;
148 | }
149 | bar1.start(data.count, 0);
150 |
151 | const domainData = await shopifyRESTApiDomain(options.url, 'get');
152 |
153 | let functions = {}; // save the headers of sheet
154 |
155 | options.fields = getFieldsFromGroup(options);
156 |
157 | if (options.type === 'smart_collections') fields.push('disjunctive');
158 |
159 | for (const field of options.fields) {
160 | const split = field.split('-');
161 |
162 | if (split[1] === 'basic' || split[1] === 'metafields' || !split[1]) {
163 | const funcs = split[0].split('___');
164 | if (!funcs[1]) fields.push(funcs[0]);
165 | else {
166 | fields = [...fields, ...funcs[1].split('__')];
167 | functions['basic'] = functions['basic'] || [];
168 | functions['basic'].push(funcs[0]);
169 | }
170 | } else {
171 | fields.push(split[1]);
172 |
173 | filters[split[1]] = filters[split[1]] || [];
174 |
175 | const funcs = split[0].split('___');
176 | if (!funcs[1]) filters[split[1]].push(funcs[0]);
177 | else {
178 | filters[split[1]] = [...filters[split[1]], ...funcs[1].split('__')];
179 | functions[split[1]] = functions[split[1]] || [];
180 | functions[split[1]].push(funcs[0]);
181 | }
182 | }
183 | }
184 |
185 | for (const filter in filters) {
186 | filters[filter] = filters[filter].filter(function (item, pos, self) {
187 | return self.indexOf(item) === pos;
188 | });
189 | }
190 | // Sort filters array, format like {key:[value1, value2]}
191 | filters = Object.entries(filters)
192 | .sort(([a], [b]) =>
193 | isMain(options.type, a) || isMulti(options.type, a)
194 | ? 1
195 | : isMain(options.type, b) || isMulti(options.type, b)
196 | ? -1
197 | : 0,
198 | )
199 | .sort(([a], [b]) => (a == 'variants' ? -1 : b == 'variants' ? 1 : 0))
200 | .reduce((r, [k, v]) => ({ ...r, [k]: v }), {});
201 |
202 | if (options.type === 'price_rules') {
203 | filters['entitled_collection_ids'] = [];
204 | filters['entitled_product_ids'] = [];
205 | filters['entitled_variant_ids'] = [];
206 |
207 | filters['prerequisite_collection_ids'] = [];
208 | filters['prerequisite_product_ids'] = [];
209 | filters['prerequisite_variant_ids'] = [];
210 | filters['prerequisite_customer_ids'] = [];
211 | }
212 | // Loop till result length === 0
213 | while (true) {
214 | const query = {
215 | params: {
216 | fields: fields
217 | // remove the duplicated values
218 | .filter(function (item, pos, self) {
219 | return self.indexOf(item) === pos;
220 | })
221 | .join(','),
222 | since_id,
223 | limit,
224 | },
225 | };
226 |
227 | const data = await shopifyRESTApi(options.url, options.type, 'get', query);
228 | let filteredData = [];
229 | // If type is custom_collection and user selects products export, then should fetch collection products for every collection.
230 | if ((options.type === 'custom_collections' && filters.products?.length) || options.type === 'price_rules' || options.type === 'blogs') {
231 | filteredData = await Promise.all(
232 | data[options.type].map(async item => {
233 | let products_data = {};
234 | if (options.type === 'custom_collections' && filters.products?.length) {
235 | products_data = await shopifyRESTApiCollectionProducts(
236 | options.url,
237 | item.id,
238 | { fields: ['id'] },
239 | );
240 | }
241 |
242 | if (options.type === 'price_rules' && filters.discount_codes?.length) {
243 | const value = await shopifyRESTApiSubList(
244 | options.url,
245 | 'price_rules',
246 | item.id,
247 | 'discount_codes'
248 | );
249 |
250 | products_data = { discount_codes: value?.discount_codes || [] };
251 | }
252 | if (options.type === 'blogs' && filters.articles?.length) {
253 | const value = await shopifyRESTApiSubList(
254 | options.url,
255 | 'blogs',
256 | item.id,
257 | 'articles'
258 | );
259 |
260 | products_data = { articles: value?.articles || [] };
261 | }
262 | let temp = { ...item, ...products_data, domain: domainData.shop.domain };
263 | bar1.increment(1);
264 |
265 | for (const filter in filters) {
266 | if (temp[filter]?.length || item[filter]?.length) {
267 | if (isMain(options.type, filter)) {
268 | if (!Array.isArray(temp))
269 | temp = temp[filter].map((subItem, item_index) => {
270 | return {
271 | ..._.omit(temp, [filter]),
272 | ...addPrefix(
273 | {
274 | ..._.pick(subItem, filters[filter]),
275 | item_index,
276 | },
277 | filter,
278 | ),
279 | };
280 | });
281 | else {
282 | const maxLength = Math.max(
283 | temp.length,
284 | item[filter].length,
285 | );
286 | for (let i = 0; i < maxLength; i++) {
287 | let itemHandle = null;
288 | let customerEmail = null;
289 | if (options.type === "price_rules" && ["string", "number"].includes(typeof item[filter][i]) && filter.includes("ids")) {
290 | if (filter.includes("product_ids")) {
291 | const itemValue = await shopifyItemRESTApi(options.url, 'products', item[filter][i], 'get');
292 | itemHandle = itemValue?.product?.handle;
293 | } else if (filter.includes("collection_ids")) {
294 | const itemValue = await shopifyItemRESTApi(options.url, 'collections', item[filter][i], 'get');
295 | itemHandle = itemValue?.collection?.handle;
296 | } else if (filter.includes("variant_ids")) {
297 | const itemValue = await shopifyItemRESTApi(options.url, 'variants', item[filter][i], 'get');
298 | itemHandle = itemValue?.variant?.handle;
299 | } else if (filter.includes("customer_ids")) {
300 | const itemValue = await shopifyItemRESTApi(options.url, 'customers', item[filter][i], 'get');
301 | customerEmail = itemValue?.customer?.email;
302 | }
303 | }
304 | temp[i] = {
305 | ...(temp[i]
306 | ? { ..._.omit(temp[i], [filter]) }
307 | : {
308 | ..._.omit(
309 | item,
310 | Object.keys(filters).filter(key =>
311 | isMain(options.type, key),
312 | ),
313 | ),
314 | }),
315 | ...addPrefix(
316 | (["string", "number"].includes(typeof item[filter][i])) ? { itemVal: itemHandle ?? item[filter][i], ...(customerEmail ? { customerEmail } : {}) } : _.pick(item[filter][i], filters[filter]) || {},
317 | filter,
318 | ),
319 | };
320 | }
321 | }
322 |
323 | if (functions[filter]?.length) {
324 | for (const func of functions[filter]) {
325 | const funcName = func.split('__')[0];
326 | const param = func.split('__')[1];
327 |
328 | if (param) {
329 | temp = temp.map(item =>
330 | convertion[options.type][filter][funcName](
331 | item,
332 | param,
333 | ),
334 | );
335 | } else {
336 | temp = temp.map(item =>
337 | convertion[options.type][filter][funcName](
338 | item,
339 | ),
340 | );
341 | }
342 | }
343 | }
344 | } else {
345 | temp = {
346 | ..._.omit(temp, [filter]),
347 | [filter]: Array.isArray(temp[filter])
348 | ? JSON.stringify(
349 | temp[filter].map(i =>
350 | _.pick(i, filters[filter]),
351 | ),
352 | )
353 | : JSON.stringify(_.pick(temp[filter], filters[filter])),
354 | };
355 | }
356 | }
357 | }
358 |
359 | if (temp.length) {
360 | temp[0].top_row_command = 'TRUE';
361 | for (let i = 0; i < temp.length; i++) {
362 | if (functions.basic?.length) {
363 | for (const func of functions.basic) {
364 | const funcName = func.split('__')[0];
365 | const param = func.split('__')[1];
366 |
367 | if (param) {
368 | temp[i] = convertion[options.type]['basic'][funcName](
369 | temp[i],
370 | param,
371 | );
372 | } else {
373 | temp[i] = convertion[options.type]['basic'][funcName](
374 | temp[i],
375 | );
376 | }
377 | }
378 | }
379 | }
380 | } else {
381 | temp.top_row_command = 'TRUE';
382 | if (functions.basic?.length) {
383 | for (const func of functions.basic) {
384 | const funcName = func.split('__')[0];
385 | const param = func.split('__')[1];
386 |
387 | if (param) {
388 | temp = convertion[options.type]['basic'][funcName](
389 | temp,
390 | param,
391 | );
392 | } else {
393 | temp = convertion[options.type]['basic'][funcName](temp);
394 | }
395 | }
396 | }
397 | }
398 |
399 | return temp;
400 | }),
401 | );
402 | } else {
403 | filteredData = await Promise.all(
404 | data[options.type].map(async item => {
405 | let metafields = {};
406 | if (options.type === 'products' && fields.includes('metafields')) {
407 | const value = await shopifyRESTApiProductMetafield(
408 | options.url,
409 | item.id,
410 | );
411 |
412 | metafields = { metafields: value?.metafields || [] };
413 | }
414 |
415 | let temp = { ...item, ...metafields, domain: domainData.shop.domain };
416 | if (fields.includes('variant_metafields')) {
417 | temp.variants = await Promise.all(
418 | (temp.variants || []).map(async subItem => {
419 | const response = await shopifyRESTApiVariantMetafield(
420 | options.url,
421 | subItem.id,
422 | );
423 | let adds = {};
424 | for (const meta in response?.metafields) {
425 | if (
426 | !filters.variants.includes(
427 | `h_variant__${response.metafields[meta]?.key}`,
428 | )
429 | )
430 | filters.variants.push(
431 | `h_variant__${response.metafields[meta]?.key}`,
432 | );
433 | adds = {
434 | ...adds,
435 | [`h_variant__${response.metafields[meta]?.key}`]:
436 | response.metafields[meta]?.value,
437 | };
438 | }
439 | filters.variants.push('variant_metafields');
440 | return {
441 | ...subItem,
442 | ...adds,
443 | variant_metafields: response?.metafields || [],
444 | };
445 | }),
446 | );
447 | }
448 |
449 | if (functions.basic?.length) {
450 | for (const func of functions.basic) {
451 | const funcName = func.split('__')[0];
452 | const param = func.split('__')[1];
453 |
454 | if (param) {
455 | temp = convertion[options.type]['basic'][funcName](temp, param);
456 | } else {
457 | temp = convertion[options.type]['basic'][funcName](temp);
458 | }
459 | }
460 | }
461 |
462 | const itemWithFunc = { ...temp };
463 |
464 | for (const filter in filters) {
465 | if (
466 | item[filter]?.length ||
467 | (options.type === 'orders' && orderMultiFields().includes(filter))
468 | ) {
469 | item[filter] = item[filter] || [];
470 |
471 | if (isMain(options.type, filter)) {
472 | // should use temp to pick for variant metafield
473 | if (!Array.isArray(temp))
474 | temp = temp[filter].map(subItem => {
475 | return {
476 | ..._.omit(temp, [filter]),
477 | ...addPrefix(
478 | _.pick(subItem, filters[filter]),
479 | filter,
480 | ),
481 | };
482 | });
483 | else {
484 | const maxLength = Math.max(
485 | temp.length,
486 | item[filter].length,
487 | );
488 | for (let i = 0; i < maxLength; i++) {
489 | temp[i] = {
490 | ...(temp[i]
491 | ? { ..._.omit(temp[i], [filter]) }
492 | : {
493 | ..._.omit(
494 | itemWithFunc,
495 | Object.keys(filters).filter(key =>
496 | isMain(options.type, key),
497 | ),
498 | ),
499 | }),
500 | ...addPrefix(
501 | _.pick(item[filter][i], filters[filter]) || {},
502 | filter,
503 | ),
504 | };
505 | }
506 | }
507 |
508 | if (functions[filter]?.length) {
509 | for (const func of functions[filter]) {
510 | const funcName = func.split('__')[0];
511 | const param = func.split('__')[1];
512 |
513 | if (param) {
514 | temp = temp.map(item =>
515 | convertion[options.type][filter][funcName](
516 | item,
517 | param,
518 | ),
519 | );
520 | } else {
521 | temp = temp.map(item =>
522 | convertion[options.type][filter][funcName](
523 | item,
524 | ),
525 | );
526 | }
527 | }
528 | }
529 | } else if (isMulti(options.type, filter)) {
530 | if (!Array.isArray(temp))
531 | temp = item[filter].map(subItem => {
532 | return {
533 | client_details__line_type_command: capitalize(
534 | filter,
535 | ).slice(0, -1),
536 | line_items__line_command: 'DEFAULT',
537 | line_items__force_gift_card: 'No',
538 | ..._.omit(temp, [filter]),
539 | ...addPrefix(
540 | _.pick(subItem, filters[filter]),
541 | filter,
542 | ),
543 | };
544 | });
545 | else {
546 | let tempLength = item[filter].length;
547 | if (item[filter].length > 0)
548 | for (let i = 0; i < tempLength; i++) {
549 | temp.push({
550 | client_details__line_type_command: capitalize(
551 | filter,
552 | ).slice(0, -1),
553 | line_items__line_command: 'DEFAULT',
554 | line_items__force_gift_card: 'No',
555 | ..._.omit(
556 | itemWithFunc,
557 | Object.keys(filters).filter(key =>
558 | isMulti(options.type, key),
559 | ),
560 | ),
561 | ...addPrefix(
562 | _.pick(item[filter][i], filters[filter]) ||
563 | {},
564 | filter,
565 | ),
566 | });
567 | }
568 | }
569 |
570 | if (functions[filter]?.length) {
571 | for (const func of functions[filter]) {
572 | const funcName = func.split('__')[0];
573 | const param = func.split('__')[1];
574 | if (param) {
575 | temp = temp.map(item =>
576 | convertion[options.type][filter][funcName](
577 | item,
578 | param,
579 | ),
580 | );
581 | } else {
582 | temp = temp.map(item =>
583 | convertion[options.type][filter][funcName](
584 | item,
585 | ),
586 | );
587 | }
588 | }
589 | }
590 | } else {
591 | temp = {
592 | ..._.omit(temp, [filter]),
593 | [filter]: Array.isArray(item[filter])
594 | ? JSON.stringify(
595 | item[filter].map(i =>
596 | _.pick(i, filters[filter]),
597 | ),
598 | )
599 | : JSON.stringify(_.pick(item[filter], filters[filter])),
600 | };
601 | }
602 | } else if (!Array.isArray(item[filter])) {
603 | temp = {
604 | ..._.omit(temp, [filter]),
605 | ...addPrefix(_.pick(item[filter], filters[filter]), filter),
606 | };
607 |
608 | if (functions[filter]?.length) {
609 | for (const func of functions[filter]) {
610 | const funcName = func.split('__')[0];
611 | const param = func.split('__')[1];
612 |
613 | if (param) {
614 | temp = convertion[options.type][filter][funcName](
615 | temp,
616 | param,
617 | );
618 | } else {
619 | temp = convertion[options.type][filter][funcName](temp);
620 | }
621 | }
622 | }
623 | }
624 | }
625 |
626 | if (temp.length) {
627 | temp[0].top_row_command = 'TRUE';
628 | temp[0].client_details__top_row_command = 'TRUE';
629 | for (let i = 0; i < temp.length; i++) {
630 | if (options.type === 'products' && i !== 0) temp[i].body_html = '';
631 | if (options.type === 'products' && fields.includes('metafields') && i !== 0) {
632 | for (const key of Object.keys(temp[i])) {
633 | if (key.includes('h_product__')) temp[i][key] = '';
634 | }
635 | }
636 | }
637 | } else {
638 | temp.top_row_command = 'TRUE';
639 | temp.client_details__top_row_command = 'TRUE';
640 | }
641 |
642 | bar1.increment(1);
643 | return temp;
644 | }),
645 | );
646 | }
647 | // Flat the filteredData because it might be nested array.
648 | const flatData = filteredData.flat();
649 |
650 | if (data[options.type].length === 0) break;
651 |
652 | result = [...result, ...flatData];
653 |
654 | if (data[options.type].length !== limit) break;
655 | since_id = data[options.type][data[options.type].length - 1].id;
656 | }
657 | }
658 | const finish_at = new Date();
659 |
660 | const { keys, header } = getHeader(result, options.type, [
661 | ...options.fields,
662 | ...addFields(options.format, options.type, options.fields),
663 | ]);
664 |
665 | result = result.map((item, index) =>
666 | _.pick(
667 | {
668 | ...item,
669 | ...addValues(options.format, options.type, item, index),
670 | },
671 | keys,
672 | ),
673 | );
674 | worksheet = jsonToSheet(result, 0, worksheet, options.type, keys, header);
675 |
676 | if (options.format === 'Excel') {
677 | writeExcel(worksheet, `${options.type}`, `${options.fileName}.xlsx`);
678 | } else if (options.format === 'CSV') {
679 | sheetToCsv(worksheet, `${options.fileName}.csv`);
680 | } else if (options.format === 'Matrixify') {
681 | writeMatrixify(
682 | worksheet,
683 | capitalize(options.type),
684 | `${options.fileName}.xlsx`,
685 | header,
686 | {
687 | items: capitalize(options.type),
688 | start_at,
689 | finish_at,
690 | duration: new Date(finish_at - start_at).toISOString().substring(11, 19),
691 | per_seconds: ((finish_at - start_at) / result.length / 1000).toFixed(3),
692 | exported: result.length,
693 | details: [
694 | 'base',
695 | ...Object.keys(filters),
696 | ...(options.type === 'products' && fields.includes('metafields')
697 | ? ['Metafields']
698 | : []),
699 | ...(fields.includes('variant_metafields') ? ['Variant Metafields'] : []),
700 | ]
701 | .map(capitalize)
702 | .toString(),
703 | filter: '',
704 | columns: [
705 | ...header.filter(h => !h.includes('Metafield')),
706 | ...(options.type === 'products' && fields.includes('metafields')
707 | ? ['Metafield ...']
708 | : []),
709 | ...(fields.includes('variant_metafields') ? ['Variant Metafield ...'] : []),
710 | ].toString(),
711 | },
712 | );
713 | }
714 | bar1.stop();
715 | console.log();
716 | console.log('%s Operation Succeeded.', chalk.green.bold('DONE'));
717 |
718 | console.log();
719 | } catch (error) {
720 | console.log(error);
721 | console.error('%s Operation Failed.', chalk.red.bold('ERROR'));
722 | }
723 | }
724 |
--------------------------------------------------------------------------------
/src/treePrompt.js:
--------------------------------------------------------------------------------
1 | // custom tree prompt for inquirer
2 |
3 | import { require } from '../utils/index.js';
4 | const _ = {
5 | cloneDeep: require('lodash/cloneDeep'),
6 | };
7 | import chalk from 'chalk';
8 | import figures from 'figures';
9 | import cliCursor from 'cli-cursor';
10 | const { fromEvent } = require('rxjs');
11 | const { filter, share, flatMap, map, take, takeUntil } = require('rxjs/operators');
12 | import BasePrompt from 'inquirer/lib/prompts/base.js';
13 | import observe from 'inquirer/lib/utils/events.js';
14 | import Paginator from 'inquirer/lib/utils/paginator.js';
15 | import util from 'util';
16 |
17 | class TreePrompt extends BasePrompt {
18 | constructor(questions, rl, answers) {
19 | super(questions, rl, answers);
20 |
21 | this.done = () => {};
22 |
23 | this.firstRender = true;
24 |
25 | const tree =
26 | typeof this.opt.tree === 'function'
27 | ? _.cloneDeep(this.opt.tree(answers))
28 | : _.cloneDeep(this.opt.tree);
29 |
30 | this.tree = { children: tree };
31 |
32 | this.shownList = [];
33 |
34 | this.opt = {
35 | pageSize: 10,
36 | multiple: false,
37 | ...this.opt,
38 | };
39 |
40 | // Make sure no default is set (so it won't be printed)
41 | this.opt.default = null;
42 |
43 | this.paginator = new Paginator(this.screen, { isInfinite: this.opt.loop !== false });
44 |
45 | this.selectedList = [];
46 | }
47 |
48 | /**
49 | * @protected
50 | */
51 | async _run(done) {
52 | this.done = done;
53 |
54 | this._installKeyHandlers();
55 |
56 | cliCursor.hide();
57 |
58 | await this.prepareChildrenAndRender(this.tree);
59 |
60 | // TODO: exit early somehow if no items
61 | // TODO: what about if there are no valid items?
62 |
63 | return this;
64 | }
65 |
66 | _installKeyHandlers() {
67 | const events = observe(this.rl);
68 |
69 | const validation = this.handleSubmitEvents(
70 | events.line.pipe(
71 | map(() => this.valueFor(this.opt.multiple ? this.selectedList[0] : this.active)),
72 | ),
73 | );
74 | validation.success.forEach(this.onSubmit.bind(this));
75 | validation.error.forEach(this.onError.bind(this));
76 |
77 | events.normalizedUpKey.pipe(takeUntil(validation.success)).forEach(this.onUpKey.bind(this));
78 |
79 | events.normalizedDownKey
80 | .pipe(takeUntil(validation.success))
81 | .forEach(this.onDownKey.bind(this));
82 |
83 | events.keypress
84 | .pipe(
85 | filter(({ key }) => key.name === 'right'),
86 | share(),
87 | )
88 | .pipe(takeUntil(validation.success))
89 | .forEach(this.onRightKey.bind(this));
90 |
91 | events.keypress
92 | .pipe(
93 | filter(({ key }) => key.name === 'left'),
94 | share(),
95 | )
96 | .pipe(takeUntil(validation.success))
97 | .forEach(this.onLeftKey.bind(this));
98 |
99 | events.spaceKey.pipe(takeUntil(validation.success)).forEach(this.onSpaceKey.bind(this));
100 |
101 | function normalizeKeypressEvents(value, key) {
102 | return { value: value, key: key || {} };
103 | }
104 | fromEvent(this.rl.input, 'keypress', normalizeKeypressEvents)
105 | .pipe(
106 | filter(({ key }) => key && key.name === 'tab'),
107 | share(),
108 | )
109 | .pipe(takeUntil(validation.success))
110 | .forEach(this.onTabKey.bind(this));
111 | }
112 |
113 | async prepareChildrenAndRender(node) {
114 | await this.prepareChildren(node);
115 |
116 | this.render();
117 | }
118 |
119 | async prepareChildren(node) {
120 | if (node.prepared) {
121 | return;
122 | }
123 | node.prepared = true;
124 |
125 | await this.runChildrenFunctionIfRequired(node);
126 |
127 | if (!node.children) {
128 | return;
129 | }
130 |
131 | this.cloneAndNormaliseChildren(node);
132 |
133 | await this.validateAndFilterDescendants(node);
134 | }
135 |
136 | async runChildrenFunctionIfRequired(node) {
137 | if (typeof node.children === 'function') {
138 | try {
139 | const nodeOrChildren = await node.children();
140 | if (nodeOrChildren) {
141 | let children;
142 | if (Array.isArray(nodeOrChildren)) {
143 | children = nodeOrChildren;
144 | } else {
145 | children = nodeOrChildren.children;
146 | ['name', 'value', 'short'].forEach(property => {
147 | node[property] = nodeOrChildren[property];
148 | });
149 | node.isValid = undefined;
150 |
151 | await this.addValidity(node);
152 |
153 | /*
154 | * Don't filter based on validity; children can be handled by the
155 | * callback itself if desired, and filtering out the node itself
156 | * would be a poor experience in this scenario.
157 | */
158 | }
159 |
160 | node.children = _.cloneDeep(children);
161 | }
162 | } catch (e) {
163 | /*
164 | * if something goes wrong gathering the children, ignore it;
165 | * it could be something like permission denied for a single
166 | * directory in a file hierarchy
167 | */
168 |
169 | node.children = null;
170 | }
171 | }
172 | }
173 |
174 | cloneAndNormaliseChildren(node) {
175 | node.children = node.children.map(item => {
176 | if (typeof item !== 'object') {
177 | return {
178 | value: item,
179 | };
180 | }
181 |
182 | return item;
183 | });
184 | }
185 |
186 | async validateAndFilterDescendants(node) {
187 | for (let index = node.children.length - 1; index >= 0; index--) {
188 | const child = node.children[index];
189 |
190 | child.parent = node;
191 |
192 | await this.addValidity(child);
193 |
194 | if (this.opt.hideChildrenOfValid && child.isValid === true) {
195 | child.children = null;
196 | }
197 |
198 | if (this.opt.onlyShowValid && child.isValid !== true && !child.children) {
199 | node.children.splice(index, 1);
200 | }
201 |
202 | await this.prepareChildren(child);
203 | }
204 | }
205 |
206 | async addValidity(node) {
207 | if (typeof node.isValid === 'undefined') {
208 | if (this.opt.validate) {
209 | node.isValid = await this.opt.validate(this.valueFor(node), this.answers);
210 | } else {
211 | node.isValid = true;
212 | }
213 | }
214 | }
215 |
216 | render(error) {
217 | let message = this.getQuestion();
218 |
219 | if (this.firstRender) {
220 | let hint = 'Use arrow keys,';
221 | if (this.opt.multiple) {
222 | hint += ' space to select,';
223 | }
224 | hint += ' enter to confirm.';
225 |
226 | message += chalk.dim(`(${hint})`);
227 | }
228 |
229 | if (this.status === 'answered') {
230 | let answer = '\n ';
231 | if (this.opt.multiple) {
232 | // group the values to output
233 | const groupBy = this.selectedList.reduce(function (r, a) {
234 | if (!!a.children) return r;
235 | r[a.parent.name] = r[a.parent.name] || [];
236 | r[a.parent.name].push(a);
237 | return r;
238 | }, {});
239 |
240 | for (const groupName in groupBy) {
241 | if (groupName !== 'undefined') {
242 | answer += `${groupName}[`;
243 | answer +=
244 | groupBy[groupName].map(item => this.shortFor(item, true)).join(', ') +
245 | '] \n ';
246 | } else {
247 | answer += groupBy[groupName].map(item => this.shortFor(item, true)).join(', ')
248 | }
249 | }
250 | } else {
251 | answer = this.shortFor(this.active, true);
252 | }
253 |
254 | message += chalk.cyan(answer);
255 | } else {
256 | this.shownList = [];
257 | let treeContent = this.createTreeContent();
258 | if (this.opt.loop !== false) {
259 | treeContent += '----------------';
260 | }
261 | message +=
262 | '\n' +
263 | this.paginator.paginate(
264 | treeContent,
265 | this.shownList.indexOf(this.active),
266 | this.opt.pageSize,
267 | );
268 | }
269 |
270 | let bottomContent;
271 |
272 | if (error) {
273 | bottomContent = '\n' + chalk.red('>> ') + error;
274 | }
275 |
276 | this.firstRender = false;
277 |
278 | this.screen.render(message, bottomContent);
279 | }
280 |
281 | createTreeContent(node = this.tree, indent = 2) {
282 | const children = node.children || [];
283 | let output = '';
284 | const isFinal = this.status === 'answered';
285 |
286 | children.forEach(child => {
287 | this.shownList.push(child);
288 | if (!this.active) {
289 | this.active = child;
290 | }
291 |
292 | let prefix = child.children
293 | ? child.open
294 | ? figures.arrowDown + ' '
295 | : figures.arrowRight + ' '
296 | : child === this.active
297 | ? figures.pointer + ' '
298 | : ' ';
299 |
300 | if (this.opt.multiple) {
301 | prefix += this.selectedList.includes(child) ? figures.radioOn : figures.radioOff;
302 | prefix += ' ';
303 | }
304 |
305 | const showValue = ' '.repeat(indent) + prefix + this.nameFor(child, isFinal) + '\n';
306 |
307 | if (child === this.active) {
308 | if (child.isValid === true) {
309 | output += chalk.cyan(showValue);
310 | } else {
311 | output += chalk.red(showValue);
312 | }
313 | } else {
314 | output += showValue;
315 | }
316 |
317 | if (child.open) {
318 | output += this.createTreeContent(child, indent + 2);
319 | }
320 | });
321 |
322 | return output;
323 | }
324 |
325 | shortFor(node, isFinal = false) {
326 | return typeof node.short !== 'undefined' ? node.short : this.nameFor(node, isFinal);
327 | }
328 |
329 | nameFor(node, isFinal = false) {
330 | if (typeof node.name !== 'undefined') {
331 | return node.name;
332 | }
333 |
334 | if (this.opt.transformer) {
335 | return this.opt.transformer(node.value, this.answers, { isFinal });
336 | }
337 |
338 | return node.value;
339 | }
340 |
341 | valueFor(node) {
342 | return typeof node?.value !== 'undefined' ? node.value : node?.name || '';
343 | }
344 |
345 | onError(state) {
346 | this.render(state.isValid);
347 | }
348 |
349 | onSubmit(state) {
350 | if (this.opt.multiple && !this.selectedList.length) throw 'error';
351 | this.status = 'answered';
352 |
353 | this.render();
354 |
355 | this.screen.done();
356 | cliCursor.show();
357 |
358 | this.done(
359 | this.opt.multiple
360 | ? this.selectedList
361 | .map(item => {
362 | if (!item.children && this.valueFor(item.parent))
363 | return `${this.valueFor(item)}-${this.valueFor(item.parent)}`;
364 | else if (!item.children && !this.valueFor(item.parent))
365 | return `${this.valueFor(item)}-metafields`;
366 | })
367 | .filter(item => !!item)
368 | : state.value,
369 | );
370 | }
371 |
372 | onUpKey() {
373 | this.moveActive(-1);
374 | }
375 |
376 | onDownKey() {
377 | this.moveActive(1);
378 | }
379 |
380 | onLeftKey() {
381 | if (this.active.children && this.active.open) {
382 | this.active.open = false;
383 | } else {
384 | if (this.active.parent !== this.tree) {
385 | this.active = this.active.parent;
386 | }
387 | }
388 |
389 | this.render();
390 | }
391 |
392 | onRightKey() {
393 | if (this.active.children) {
394 | if (!this.active.open) {
395 | this.active.open = true;
396 |
397 | this.prepareChildrenAndRender(this.active);
398 | } else if (this.active.children.length) {
399 | this.moveActive(1);
400 | }
401 | }
402 | }
403 |
404 | moveActive(distance = 0) {
405 | const currentIndex = this.shownList.indexOf(this.active);
406 | let index = currentIndex + distance;
407 |
408 | if (index >= this.shownList.length) {
409 | if (this.opt.loop === false) {
410 | return;
411 | }
412 | index = 0;
413 | } else if (index < 0) {
414 | if (this.opt.loop === false) {
415 | return;
416 | }
417 | index = this.shownList.length - 1;
418 | }
419 |
420 | this.active = this.shownList[index];
421 |
422 | this.render();
423 | }
424 |
425 | onTabKey() {
426 | this.toggleOpen();
427 | }
428 |
429 | onSpaceKey() {
430 | if (this.opt.multiple) {
431 | this.toggleSelection();
432 | } else {
433 | this.toggleOpen();
434 | }
435 | }
436 |
437 | toggleSelection() {
438 | if (this.active.isValid !== true) {
439 | return;
440 | }
441 | const selectedIndex = this.selectedList.indexOf(this.active);
442 | if (selectedIndex === -1) {
443 | this.selectedList.push(this.active);
444 | this.toggleAll(this.active, true);
445 | this.checkParent(this.active, true);
446 | } else {
447 | this.selectedList.splice(selectedIndex, 1);
448 | this.toggleAll(this.active, false);
449 | this.checkParent(this.active, false);
450 | }
451 |
452 | this.render();
453 | }
454 |
455 | toggleAll(parent, value) {
456 | if (parent.children) {
457 | parent.children.map(child => {
458 | if (value) {
459 | if (this.selectedList.indexOf(child) === -1) this.selectedList.push(child);
460 | this.toggleAll(child, true);
461 | } else {
462 | this.selectedList.splice(this.selectedList.indexOf(child), 1);
463 | this.toggleAll(child, false);
464 | }
465 | });
466 | }
467 | return;
468 | }
469 |
470 | checkParent(item, value) {
471 | if (!item.parent.value) return;
472 | if (!value) {
473 | if (this.selectedList.indexOf(item.parent) !== -1)
474 | this.selectedList.splice(this.selectedList.indexOf(item.parent), 1);
475 | this.checkParent(item.parent, false);
476 | } else {
477 | if (item.parent.children.map(i => this.selectedList.indexOf(i)).includes(-1)) {
478 | if (this.selectedList.indexOf(item.parent) !== -1)
479 | this.selectedList.splice(this.selectedList.indexOf(item.parent), 1);
480 | this.checkParent(item.parent, false);
481 | } else {
482 | this.selectedList.push(item.parent);
483 | this.checkParent(item.parent, true);
484 | }
485 | }
486 | }
487 |
488 | toggleOpen() {
489 | if (!this.active.children) {
490 | return;
491 | }
492 |
493 | this.active.open = !this.active.open;
494 |
495 | this.render();
496 | }
497 | }
498 |
499 | export default TreePrompt;
500 |
--------------------------------------------------------------------------------
/src/verify.js:
--------------------------------------------------------------------------------
1 | import { writeIni } from '../utils/index.js';
2 | import { verifyToken } from '../utils/shopify.js';
3 |
4 | export async function verifyApiKey(options) {
5 | try {
6 | const response = await verifyToken(options);
7 |
8 | if (response.status === 200) writeIni(options);
9 | else throw `Error code ${response.status}`;
10 |
11 | console.log();
12 | console.log('Success! You can now export data with the following command:');
13 | console.log(
14 | 'ablestar-cli export products example.myshopify.com --format=CSV --fields=products',
15 | );
16 | } catch (error) {
17 | console.log(error);
18 | console.log('Error! Please check API Key and Password again.');
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/version-check.js:
--------------------------------------------------------------------------------
1 | // const packageJson = require("package-json");
2 | // const semver = require("semver");
3 | import packageJson from 'package-json';
4 | import semver from 'semver';
5 | import chalk from 'chalk';
6 | import fs from 'fs';
7 | // import appRootPath from 'app-root-path';
8 | import ini from 'ini';
9 |
10 | import { require } from '../utils/index.js';
11 | import init from './init.js';
12 | const thisPackage = require('../package.json');
13 | import os from 'os';
14 |
15 | const appRootPath = { path: os.homedir() };
16 |
17 | const shouldCheck = () => {
18 | let config = {};
19 | if (fs.existsSync(appRootPath.path + '/.ablestar/cli.ini')) {
20 | config = ini.parse(fs.readFileSync(appRootPath.path + '/.ablestar/cli.ini', 'utf-8'));
21 |
22 | if (
23 | config?.core?.disable_version_check === '1' ||
24 | config?.core?.disable_version_check === 'true'
25 | )
26 | return false;
27 | else return true;
28 | } else {
29 | return false; // set false if there is no config file.
30 | }
31 | };
32 |
33 | const versionCheck = async () => {
34 | const check = shouldCheck();
35 |
36 | if (!check) return;
37 |
38 | let config = ini.parse(fs.readFileSync(appRootPath.path + '/.ablestar/cli.ini', 'utf-8'));
39 |
40 | const current = getCurrentVersion();
41 | const latest = config.core?.latest_version || '0.0.0';
42 |
43 | if (newVersionAvailable(current, latest)) {
44 | renderUpdateBanner(current, latest);
45 | } else {
46 | init();
47 | }
48 | config.core.latest_version = await getLatestVersion();
49 |
50 | fs.writeFileSync(appRootPath.path + '/.ablestar/cli.ini', ini.stringify(config));
51 | };
52 |
53 | const getCurrentVersion = () => thisPackage.version;
54 |
55 | const getLatestVersion = async () => {
56 | try {
57 | const name = thisPackage.name;
58 | const publishedPackage = await packageJson(name, {
59 | allVersions: true,
60 | registryUrl: `https://npmjs-proxy.ablestar.workers.dev`,
61 | });
62 | return publishedPackage.version;
63 | } catch (e) {
64 | // Something failed. Return 0.0.0 to avoid the update message
65 | return '0.0.0';
66 | }
67 | };
68 |
69 | const newVersionAvailable = (current, latest) => semver.compare(current, latest) < 0;
70 |
71 | const renderUpdateBanner = (current, latest) => {
72 | console.log(`
73 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
74 | ${chalk.hex('#FFA500')(' Update available! ')} ${chalk.yellowBright(
75 | current,
76 | )} → ${chalk.greenBright(latest)}
77 | Run ${chalk.cyan('npm install -g @ablestar/ablestar-cli')} to update
78 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
79 | `);
80 | };
81 |
82 | export default versionCheck;
83 |
--------------------------------------------------------------------------------
/utils/actions.js:
--------------------------------------------------------------------------------
1 | export const actions = {
2 | customers: {
3 | tags: ['set-tags', 'add-tags', 'remove-tags'],
4 | },
5 | };
6 |
7 | export const actionTree = type => {
8 | return Object.keys(actions[type])
9 | .map(item =>
10 | actions[type][item].map(action => ({
11 | value: action,
12 | name: `${item} - ${action}`,
13 | })),
14 | )
15 | .flat();
16 | };
17 |
--------------------------------------------------------------------------------
/utils/import.js:
--------------------------------------------------------------------------------
1 | import fs from 'fs';
2 | import XLSX from 'xlsx';
3 | import cliProgress from 'cli-progress';
4 | import {
5 | shopifyItemRESTApi,
6 | shopifyRESTApi,
7 | shopifyRESTApiSubItem,
8 | shopifyRESTApiSubList,
9 | } from './shopify.js';
10 | import { Readable } from 'stream';
11 | import * as cpexcel from 'xlsx/dist/cpexcel.full.mjs';
12 | XLSX.set_fs(fs);
13 | XLSX.stream.set_readable(Readable);
14 | XLSX.set_cptable(cpexcel);
15 |
16 | export async function analyzeFile(fileName) {
17 | let fileContent;
18 | if (await fs.existsSync(fileName)) {
19 | const workbook = XLSX.readFile(fileName);
20 | const sheet_name_list = workbook.SheetNames;
21 | const xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
22 |
23 | return xlData;
24 | } else {
25 | console.log();
26 | console.log('Please correct file path/name');
27 | throw 'Error';
28 | }
29 | }
30 |
31 | export async function getHeaderColumn(fileName) {
32 | if (await fs.existsSync(fileName)) {
33 | const workbook = XLSX.readFile(fileName);
34 | const sheet_name_list = workbook.SheetNames;
35 | const columnsArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]], {
36 | header: 1,
37 | })[0];
38 |
39 | return columnsArray;
40 | } else {
41 | console.log();
42 | console.log('Please correct file path/name');
43 | throw 'Error';
44 | }
45 | }
46 |
47 | export const itemIDForMatrixify = (item, result) => {
48 | return item.ID && result.map(i => i.id).includes(item.ID)
49 | ? item.ID
50 | : result.find(i => i.handle === item.Handle)?.id;
51 | };
52 |
53 | export const handleOrIDCheck = (item, result) => {
54 | return (
55 | (item.ID && result.map(i => i.id).includes(item.ID)) ||
56 | (item.Handle && result.map(i => i.handle).includes(item.Handle))
57 | );
58 | };
59 |
60 | export const customCollectionQuery = (item, result, showId = false) => {
61 | return {
62 | custom_collection: {
63 | ...(showId
64 | ? {
65 | id: itemIDForMatrixify(item, result),
66 | }
67 | : {}),
68 | handle: item.Handle,
69 | title: item.Title,
70 | body_html: item['Body HTML'],
71 | sort_order: item['Sort Order']?.toLowerCase(),
72 | published: item.Published,
73 | published_scope: item['Published Scope'],
74 | template_suffix: item['Template Suffix'],
75 | image: {
76 | src: item['Image Src'],
77 | alt: item['Image Alt Text'],
78 | },
79 | },
80 | };
81 | };
82 |
83 | export const pagesQuery = (item, result, showId = false) => {
84 | return {
85 | page: {
86 | ...(showId
87 | ? {
88 | id: itemIDForMatrixify(item, result),
89 | }
90 | : {}),
91 | handle: item.Handle,
92 | title: item.Title,
93 | body_html: item['Body HTML'],
94 | published: item.Published,
95 | template_suffix: item['Template Suffix'],
96 | },
97 | };
98 | };
99 |
100 | export const articlesQuery = (item, result, showId = false) => {
101 | return {
102 | article: {
103 | ...(showId
104 | ? {
105 | id: itemIDForMatrixify(item, result),
106 | }
107 | : {}),
108 | blog_id: item['Blog: ID'],
109 | handle: item.Handle,
110 | title: item.Title,
111 | body_html: item['Body HTML'],
112 | summary_html: item['Summary HTML'],
113 | published: item.Published,
114 | published_at: item['Published At'],
115 | template_suffix: item['Template Suffix'],
116 | image: {
117 | src: item['Image Src'],
118 | alt: item['Image Alt Text'],
119 | },
120 | tags: item.Tags,
121 | },
122 | };
123 | };
124 |
125 | export const groupSmartCollection = inputJson => {
126 | if (!inputJson || !inputJson.length) return [];
127 |
128 | const firstKey = Object.keys(inputJson[0])[0];
129 |
130 | const output = [];
131 | const items = {};
132 |
133 | for (const row of inputJson) {
134 | const itemObj = items[row[firstKey]] || {
135 | ID: row['ID'],
136 | Handle: row['Handle'],
137 | Command: row.Command,
138 | title: row['Title'],
139 | body_html: row['Body HTML'],
140 | sort_order: row['Sort Order']?.toLowerCase()?.replace(' ', '-'),
141 | template_suffix: row['Template Suffix'],
142 | disjunctive: row['Must Match'] === 'any condition',
143 | published: row['Published'],
144 | published_scope: row['Published Scope'],
145 | image: {
146 | alt: row['Image Alt Text'],
147 | src: row['Image Src'],
148 | },
149 | rules: [],
150 | };
151 | itemObj.rules.push({
152 | column: row['Rule: Product Column']?.toLowerCase()?.replace(' ', '_'),
153 | relation: row['Rule: Relation']?.toLowerCase()?.replace(' ', '_'),
154 | condition: row['Rule: Condition'],
155 | });
156 | if (!items[row[firstKey]]) {
157 | items[row[firstKey]] = itemObj;
158 | output.push(itemObj);
159 | }
160 | }
161 |
162 | return output;
163 | };
164 |
165 | export const smartCollectionQuery = (item, result, showId = false) => {
166 | const { ID, Handle, Command, ...newItem } = item;
167 | return {
168 | smart_collection: showId
169 | ? {
170 | ...newItem,
171 | id: itemIDForMatrixify(item, result),
172 | handle: Handle,
173 | }
174 | : {
175 | ...newItem,
176 | handle: Handle,
177 | },
178 | };
179 | };
180 |
181 | export const runMatrixify = async (
182 | options,
183 | fileData,
184 | queryBuilder = customCollectionQuery,
185 | isSubType = false,
186 | ) => {
187 | const bar1 = new cliProgress.SingleBar(
188 | {
189 | format: `[{bar}] {percentage}% | DUR: {duration}s | ETA: {eta}s | {value}/{total}`,
190 | },
191 | cliProgress.Presets.shades_classic,
192 | );
193 | try {
194 | console.log();
195 | bar1.start(fileData.length, 0);
196 |
197 | let since_id = 0;
198 | const limit = 250;
199 | let result = [];
200 |
201 | let failed = 0,
202 | skip = 0,
203 | success = 0;
204 |
205 | // result output array
206 | let output = {};
207 |
208 | while (true) {
209 | const query = {
210 | params: {
211 | fields: ['id', 'handle'].join(','),
212 | since_id,
213 | limit,
214 | },
215 | };
216 |
217 | const data = await shopifyRESTApi(options.url, options.type, 'get', query);
218 |
219 | if (data[options.type].length === 0) break;
220 |
221 | result = [...result, ...data[options.type]];
222 |
223 | if (data[options.type].length !== limit) break;
224 | since_id = data[options.type][data[options.type].length - 1].id;
225 | }
226 |
227 | for (const [itemIndex, item] of fileData.entries()) {
228 | // values for isSubType = true;
229 | let mainId = null;
230 | let subId = null;
231 | let mainType = null;
232 | let subType = null;
233 |
234 | if (isSubType) {
235 | if (options.type === 'articles') {
236 | mainId = item['Blog: ID'];
237 | subId = itemIDForMatrixify(item, result);
238 | mainType = 'blogs';
239 | subType = 'articles';
240 | }
241 | }
242 |
243 | // key for result output
244 | const itemKey = item.ID || item.Handle || itemIndex;
245 | output[itemKey] = {
246 | itemKey,
247 | 'ID (ref)': itemIDForMatrixify(item, result),
248 | 'Handle (ref)': item.Handle,
249 | 'Import Result': 'OK',
250 | 'Import Comment': '',
251 | };
252 |
253 | switch (item.Command) {
254 | case 'NEW':
255 | output[itemKey]['Import Comment'] = 'New';
256 |
257 | if (handleOrIDCheck(item, result)) {
258 | output[itemKey]['Import Result'] = 'Failed';
259 | output[itemKey]['Import Comment'] = 'ID or Handle is already exist.';
260 | failed += 1;
261 | break;
262 | }
263 |
264 | const query = queryBuilder(item, result);
265 |
266 | try {
267 | if (isSubType)
268 | await shopifyRESTApiSubList(
269 | options.url,
270 | mainType,
271 | mainId,
272 | subType,
273 | 'post',
274 | query,
275 | );
276 | else await shopifyRESTApi(options.url, options.type, 'post', query);
277 | output[itemKey]['Import Result'] = 'OK';
278 | success += 1;
279 | } catch (error) {
280 | output[itemKey]['Import Result'] = 'Failed';
281 | output[itemKey]['Import Comment'] = 'Error when tring to create new item.';
282 | failed += 1;
283 | }
284 |
285 | break;
286 |
287 | case 'MERGE':
288 | if (handleOrIDCheck(item, result)) {
289 | if (!item.ID && !item.Handle) {
290 | output[itemKey]['Import Result'] = 'Failed';
291 | output[itemKey]['Import Comment'] =
292 | 'Should had ID or Handle to update item.';
293 | failed += 1;
294 | break;
295 | }
296 | const query1 = queryBuilder(item, result, true);
297 | try {
298 | if (isSubType)
299 | await shopifyRESTApiSubItem(
300 | options.url,
301 | mainType,
302 | mainId,
303 | subType,
304 | subId,
305 | 'put',
306 | query1,
307 | );
308 | else
309 | await shopifyItemRESTApi(
310 | options.url,
311 | options.type,
312 | itemIDForMatrixify(item, result),
313 | 'put',
314 | query1,
315 | );
316 | output[itemKey]['Import Result'] = 'OK';
317 | success += 1;
318 | } catch (error) {
319 | output[itemKey]['Import Result'] = 'Failed';
320 | output[itemKey]['Import Comment'] = 'Error when tring to update item.';
321 | failed += 1;
322 | }
323 | break;
324 | }
325 |
326 | const query1 = queryBuilder(item, result);
327 | try {
328 | if (isSubType)
329 | await shopifyRESTApiSubList(
330 | options.url,
331 | mainType,
332 | mainId,
333 | subType,
334 | 'post',
335 | query1,
336 | );
337 | else await shopifyRESTApi(options.url, options.type, 'post', query1);
338 | output[itemKey]['Import Result'] = 'OK';
339 | success += 1;
340 | } catch (error) {
341 | output[itemKey]['Import Result'] = 'Failed';
342 | output[itemKey]['Import Comment'] = 'Error when tring to create new item.';
343 | failed += 1;
344 | }
345 |
346 | break;
347 |
348 | case 'UPDATE':
349 | if (handleOrIDCheck(item, result)) {
350 | if (!item.ID && !item.Handle) {
351 | output[itemKey]['Import Result'] = 'Failed';
352 | output[itemKey]['Import Comment'] =
353 | 'Should had ID or Handle to update item.';
354 | failed += 1;
355 | break;
356 | }
357 | const query1 = queryBuilder(item, result, true);
358 | try {
359 | if (isSubType)
360 | await shopifyRESTApiSubItem(
361 | options.url,
362 | mainType,
363 | mainId,
364 | subType,
365 | subId,
366 | 'put',
367 | query1,
368 | );
369 | else
370 | await shopifyItemRESTApi(
371 | options.url,
372 | options.type,
373 | itemIDForMatrixify(item, result),
374 | 'put',
375 | query1,
376 | );
377 | output[itemKey]['Import Result'] = 'OK';
378 | success += 1;
379 | } catch (error) {
380 | output[itemKey]['Import Result'] = 'Failed';
381 | output[itemKey]['Import Comment'] = 'Error when tring to update item.';
382 | failed += 1;
383 | }
384 | break;
385 | }
386 | output[itemKey]['Import Result'] = 'Failed';
387 | output[itemKey]['Import Comment'] = 'Cannot find the ID or Handle matched.';
388 | failed += 1;
389 | break;
390 |
391 | case 'REPLACE':
392 | if (handleOrIDCheck(item, result)) {
393 | if (!item.ID && !item.Handle) {
394 | output[itemKey]['Import Result'] = 'Failed';
395 | output[itemKey]['Import Comment'] =
396 | 'Should had ID or Handle to update item.';
397 | failed += 1;
398 | break;
399 | }
400 | try {
401 | if (isSubType)
402 | await shopifyRESTApiSubItem(
403 | options.url,
404 | mainType,
405 | mainId,
406 | subType,
407 | subId,
408 | 'delete',
409 | );
410 | else
411 | await shopifyItemRESTApi(
412 | options.url,
413 | options.type,
414 | itemIDForMatrixify(item, result),
415 | 'delete',
416 | );
417 | } catch (error) {
418 | output[itemKey]['Import Result'] = 'Failed';
419 | output[itemKey]['Import Comment'] = 'Error when tring to delete item.';
420 | failed += 1;
421 | break;
422 | }
423 | }
424 |
425 | const query2 = queryBuilder(item, result);
426 | try {
427 | if (isSubType)
428 | await shopifyRESTApiSubList(
429 | options.url,
430 | mainType,
431 | mainId,
432 | subType,
433 | 'post',
434 | query2,
435 | );
436 | else await shopifyRESTApi(options.url, options.type, 'post', query2);
437 | output[itemKey]['Import Result'] = 'OK';
438 | success += 1;
439 | } catch (error) {
440 | output[itemKey]['Import Result'] = 'Failed';
441 | output[itemKey]['Import Comment'] = 'Error when tring to update item.';
442 | failed += 1;
443 | }
444 |
445 | break;
446 |
447 | case 'DELETE':
448 | if (handleOrIDCheck(item, result)) {
449 | if (!item.ID && !item.Handle) {
450 | output[itemKey]['Import Result'] = 'Failed';
451 | output[itemKey]['Import Comment'] =
452 | 'Should had ID or Handle to update item.';
453 | failed += 1;
454 | break;
455 | }
456 | try {
457 | if (isSubType)
458 | await shopifyRESTApiSubItem(
459 | options.url,
460 | mainType,
461 | mainId,
462 | subType,
463 | subId,
464 | 'delete',
465 | );
466 | else
467 | await shopifyItemRESTApi(
468 | options.url,
469 | options.type,
470 | itemIDForMatrixify(item, result),
471 | 'delete',
472 | );
473 | output[itemKey]['Import Result'] = 'OK';
474 | success += 1;
475 | break;
476 | } catch (error) {
477 | output[itemKey]['Import Result'] = 'Failed';
478 | output[itemKey]['Import Comment'] = 'Error when tring to delete item.';
479 | failed += 1;
480 | break;
481 | }
482 | }
483 | output[itemKey]['Import Result'] = 'Failed';
484 | output[itemKey]['Import Comment'] = 'Cannot find the ID or Handle matched.';
485 | failed += 1;
486 | break;
487 |
488 | case 'IGNORE':
489 | skip += 1;
490 | output[itemKey]['Import Result'] = 'Ignored';
491 | output[itemKey]['Import Comment'] = '';
492 | break;
493 |
494 | default:
495 | output[itemKey]['Import Result'] = 'Failed';
496 | output[itemKey]['Import Comment'] = 'No matched commands find.';
497 | failed += 1;
498 | break;
499 | }
500 | bar1.increment(1);
501 | }
502 |
503 | bar1.stop();
504 | console.log();
505 | console.log(`${success} items success, ${skip} items skip, and ${failed} items failed`);
506 | console.log();
507 | console.log();
508 | return output;
509 | } catch (error) {
510 | bar1.stop();
511 | throw error;
512 | }
513 | };
514 |
--------------------------------------------------------------------------------
/utils/index.js:
--------------------------------------------------------------------------------
1 | import { createRequire } from 'module';
2 | export const require = createRequire(import.meta.url);
3 | import fs from 'fs';
4 | import ini from 'ini';
5 | import chalk from 'chalk';
6 | // import appRootPath from 'app-root-path';
7 | import XLSX from 'xlsx';
8 | import { capitalize, fieldNames } from './fields.js';
9 | import { matrixifyStyles, summaryHeader } from './style.js';
10 | import Excel from 'exceljs';
11 | import os from 'os';
12 | import { Readable } from 'stream';
13 | import * as cpexcel from 'xlsx/dist/cpexcel.full.mjs';
14 | XLSX.set_fs(fs);
15 | XLSX.stream.set_readable(Readable);
16 | XLSX.set_cptable(cpexcel);
17 |
18 | const appRootPath = { path: os.homedir() };
19 |
20 | /**
21 | * Validate the store URL format(***.myshopify.com)
22 | *
23 | * @param {string} input string user inputed.
24 | * @return {boolean || string} validation result
25 | */
26 | export function validateURL(input) {
27 | if (!input) {
28 | return 'Please input store URL';
29 | }
30 | const splites = input.split('.');
31 | if (splites[0].length && splites[1] === 'myshopify' && splites[2] === 'com') return true;
32 | return 'Please input correct URL';
33 | }
34 |
35 | export function validateApiKey(input) {
36 | // TODO: apikey validation
37 | return !!input;
38 | }
39 |
40 | export function validateFileName(input) {
41 | // TODO: file path/name validation
42 | return !!input;
43 | }
44 |
45 | /**
46 | * Create or Update the config.ini file for new store.
47 | *
48 | * @param {object} options options for new store.
49 | */
50 | export function writeIni(options) {
51 | let config = {};
52 | if (fs.existsSync(appRootPath.path + '/.ablestar/cli.ini')) {
53 | config = ini.parse(fs.readFileSync(appRootPath.path + '/.ablestar/cli.ini', 'utf-8'));
54 | } else {
55 | if (!fs.existsSync(appRootPath.path + '/.ablestar')) {
56 | fs.mkdirSync(appRootPath.path + '/.ablestar');
57 | }
58 | config.core = config.core || {};
59 | config.core.default_format = 'CSV';
60 | }
61 |
62 | config[options.url] = config[options.url] || {};
63 | config[options.url].shopify_domain = options.url;
64 | config[options.url].api_key = options.apiKey;
65 | config[options.url].api_password = options.apiPass;
66 |
67 | fs.writeFileSync(appRootPath.path + '/.ablestar/cli.ini', ini.stringify(config));
68 | }
69 |
70 | /**
71 | * Get api password from store url (saved in config.ini)
72 | *
73 | * @param {string} url store url.
74 | * @return {string} api password.
75 | */
76 | export async function getToken(url) {
77 | let config = {};
78 | if (await fs.existsSync(appRootPath.path + '/.ablestar/cli.ini')) {
79 | config = await ini.parse(fs.readFileSync(appRootPath.path + '/.ablestar/cli.ini', 'utf-8'));
80 | } else {
81 | console.log();
82 | console.log('Please init the store by %s', chalk.cyan('ablestar-cli init'));
83 | throw 'Error';
84 | }
85 |
86 | if (config[url]?.api_password) {
87 | return config[url]?.api_password;
88 | } else {
89 | console.log();
90 | console.log('Please init the store by %s', chalk.cyan('ablestar-cli init'));
91 | throw 'Error';
92 | }
93 | }
94 |
95 | /**
96 | * Get api key and password from store url (saved in config.ini)
97 | *
98 | * @param {string} url store url.
99 | * @return {object} api key and password.
100 | */
101 | export async function getKeyToken(url) {
102 | let config = {};
103 | if (await fs.existsSync(appRootPath.path + '/.ablestar/cli.ini')) {
104 | config = await ini.parse(fs.readFileSync(appRootPath.path + '/.ablestar/cli.ini', 'utf-8'));
105 | } else {
106 | console.log();
107 | console.log('Please init the store by %s', chalk.cyan('ablestar-cli init'));
108 | throw 'Error';
109 | }
110 |
111 | if (config[url]?.api_password && config[url]?.api_key) {
112 | return { apikey: config[url]?.api_key, token: config[url]?.api_password };
113 | } else {
114 | console.log();
115 | console.log('Please init the store by %s', chalk.cyan('ablestar-cli init'));
116 | throw 'Error';
117 | }
118 | }
119 |
120 | /**
121 | * Get keys and header arrays from user input to make the sheet header.
122 | *
123 | * @param {object} json item object.
124 | * @param {string} type export type (products, ordes, ...)
125 | * @param {array} fields fields user inputed to export.
126 | * @return {object} keys and headers
127 | */
128 | export function getHeader(json, type, fields) {
129 | let keys = [],
130 | header = [];
131 |
132 | if (type.includes('metaobject_definitions')) {
133 | return {keys: Object.keys(json[0]), header: Object.keys(json[0])}
134 | }
135 |
136 | for (const key in fieldNames[type]) {
137 | for (const field in fieldNames[type][key]) {
138 | if (fields.includes(`${field}-${key}`) || (key === 'basic' && fields.includes(field))) {
139 | if (!field.includes('___')) {
140 | keys.push(`${key === 'basic' ? '' : `${key}__`}${field}`);
141 | header.push(`${fieldNames[type][key][field]}`);
142 | } else {
143 | const funcName = field.split('___')[0];
144 | if (
145 | !funcName.startsWith('n_') &&
146 | !funcName.startsWith('o_') &&
147 | !funcName.startsWith('h_')
148 | ) {
149 | keys.push(`${field}`);
150 | header.push(`${fieldNames[type][key][field]}`);
151 | } else if (funcName.startsWith('n_')) {
152 | let maxLength = Math.max(
153 | ...json.map(
154 | el =>
155 | el[
156 | `${key === 'basic' ? '' : `${key}__`}${
157 | field.split('___')[1]
158 | }`
159 | ]?.length || 0,
160 | ),
161 | );
162 | const arr = fields.filter(
163 | i => i.split('___')[0].split('__')[0] === funcName.split('__')[0],
164 | );
165 |
166 | for (let i = 0; i < maxLength; i++) {
167 | arr.map(item => {
168 | const keyName = item.split('___')[0].slice(2);
169 |
170 | if (keys.indexOf(`${keyName}__${i}`) === -1)
171 | keys.push(`${keyName}__${i}`);
172 | if (
173 | header.indexOf(
174 | `${fieldNames[type][key][item.split('-')[0]]}`.replace(
175 | '{n}',
176 | i + 1,
177 | ),
178 | ) === -1
179 | )
180 | header.push(
181 | `${fieldNames[type][key][item.split('-')[0]]}`.replace(
182 | '{n}',
183 | i + 1,
184 | ),
185 | );
186 | });
187 | }
188 | } else if (funcName.startsWith('o_')) {
189 | json.map(el =>
190 | el[`${key === 'basic' ? '' : `${key}__`}${field.split('___')[1]}`].map(
191 | item => {
192 | if (!keys.includes(item.name)) {
193 | keys.push(item.name);
194 | header.push(item.name);
195 | }
196 | },
197 | ),
198 | );
199 | } else if (funcName.startsWith('h_')) {
200 | const prefix = funcName === 'h_product' ? '' : 'variants__';
201 |
202 | json.map(el =>
203 | el[`${prefix}${field.split('___')[1]}`]?.map(item => {
204 | if (!keys.includes(`${prefix}${field.split('___')[0]}__${item.key}`)) {
205 | keys.push(`${prefix}${field.split('___')[0]}__${item.key}`);
206 | header.push(
207 | `${fieldNames[type]['metafields'][field]}: ${item.key} [${item.type}]`,
208 | );
209 | }
210 | }),
211 | );
212 | }
213 | }
214 | }
215 | }
216 | }
217 |
218 | if (type === "price_rules") {
219 | keys = ArrayMove(keys, keys.findIndex(i => i === 'discount_codes__code'), header.findIndex(i => i === 'Command') + 1);
220 | header = ArrayMove(header, header.findIndex(i => i === 'Code'), header.findIndex(i => i === 'Command') + 1);
221 |
222 | keys = ArrayMove(keys, keys.findIndex(i => i === 'discount_codes__usage_count'), header.findIndex(i => i === 'Command') + 2);
223 | header = ArrayMove(header, header.findIndex(i => i === 'Used Count'), header.findIndex(i => i === 'Command') + 2);
224 | }
225 |
226 | return { keys, header };
227 | }
228 |
229 | /**
230 | * Create or Update worksheet from JSON object.
231 | *
232 | * @param {object} json item object.
233 | * @param {number} since_id since_id of shopify api. If since_id is 0, then create new worksheet.
234 | * @param {XLSX.WorkSheet} worksheet worksheet to update.
235 | * @param {string} type export type (products, ordes, ...)
236 | * @param {array} keys keys for sheet.
237 | * @param {array} header header array for sheet.
238 | * @return {XLSX.WorkSheet}
239 | */
240 | export function jsonToSheet(json, since_id, worksheet, type, keys, header) {
241 | if (since_id === 0) {
242 | const ws = XLSX.utils.json_to_sheet(json, {
243 | header: keys,
244 | });
245 |
246 | XLSX.utils.sheet_add_aoa(ws, [header], { origin: 'A1' });
247 |
248 | return ws;
249 | } else {
250 | let ws = worksheet;
251 | XLSX.utils.sheet_add_json(ws, json, { skipHeader: true, origin: -1 });
252 | return ws;
253 | }
254 | }
255 |
256 | /**
257 | * Write excel file from sheet.
258 | *
259 | * @param {XLSX.WorkSheet} sheet worksheet.
260 | * @param {string} sheetName worksheet name on excel file.
261 | * @param {string} fileName excel file name.
262 | */
263 | export async function writeExcel(sheet, sheetName = 'Products', fileName = 'file.xlsx') {
264 | if (fs.existsSync(fileName)) {
265 | const workbook = XLSX.readFile(fileName);
266 | XLSX.utils.book_append_sheet(workbook, sheet, sheetName, true);
267 | const newName = workbook.SheetNames[workbook.SheetNames.length - 1];
268 | workbook.SheetNames = workbook.SheetNames.sort(function (x, y) {
269 | return x == newName ? -1 : y == newName ? 1 : 0;
270 | });
271 | XLSX.writeFile(workbook, fileName);
272 | } else {
273 | const workbook = XLSX.utils.book_new();
274 | XLSX.utils.book_append_sheet(workbook, sheet, sheetName);
275 | XLSX.writeFile(workbook, fileName);
276 | }
277 |
278 | // compress the file
279 | const workbook = new Excel.Workbook();
280 | await workbook.xlsx.readFile(fileName);
281 | await workbook.xlsx.writeFile(fileName);
282 | }
283 |
284 | /**
285 | * Write matrixify excel file from sheet.
286 | *
287 | * @param {XLSX.WorkSheet} sheet worksheet.
288 | * @param {string} sheetName worksheet name on excel file.
289 | * @param {string} fileName excel file name.
290 | * @param {array} header header array.
291 | * @param {object} summaryData summary data for summary sheet.
292 | */
293 | export async function writeMatrixify(
294 | sheet,
295 | sheetName = 'Products',
296 | fileName = 'matrixify.xlsx',
297 | header,
298 | summaryData,
299 | ) {
300 | const workbook1 = XLSX.utils.book_new();
301 | XLSX.utils.book_append_sheet(workbook1, sheet, sheetName);
302 | XLSX.writeFile(workbook1, fileName);
303 |
304 | const workbook = new Excel.Workbook();
305 | await workbook.xlsx.readFile(fileName);
306 |
307 | const worksheet = workbook.getWorksheet(sheetName);
308 | const xSpliteValue = header.findIndex(i => i === 'ID') < 0 ? 1 : 2;
309 | worksheet.views = [
310 | { state: 'frozen', xSplit: xSpliteValue, ySplit: 1, topLeftCell: 'C2', activeCell: 'A1' },
311 | ];
312 | worksheet.properties.defaultRowHeight = 16;
313 |
314 | header.map((item, index) => {
315 | worksheet.getColumn(index + 1).width = matrixifyStyles[sheetName]?.[item]?.width || 20;
316 | if (item.includes('Metafield')) worksheet.getColumn(index + 1).width = 40;
317 | worksheet.getColumn(index + 1).font = { name: 'Arial', size: 11, bold: false };
318 | worksheet.getColumn(index + 1).numFmt =
319 | matrixifyStyles[sheetName]?.[item]?.numFmt || undefined;
320 | });
321 |
322 | worksheet.getRow(1).eachCell(function (cell) {
323 | cell.font = { name: 'Arial', size: 11, bold: true };
324 | cell.fill = {
325 | type: 'pattern',
326 | pattern: 'solid',
327 | fgColor: { argb: matrixifyStyles[sheetName]?.[cell.value]?.fill || 'eeeeee' },
328 | };
329 | if (cell.value.includes('Metafield'))
330 | cell.fill = {
331 | type: 'pattern',
332 | pattern: 'solid',
333 | fgColor: { argb: 'b4c6e7' },
334 | };
335 | });
336 |
337 | const summarySheet = workbook.addWorksheet('Export Summary', {
338 | views: [{ state: 'frozen', xSplit: undefined, ySplit: 1 }],
339 | });
340 | summarySheet.columns = summaryHeader;
341 | summarySheet.getRow(1).eachCell(function (cell) {
342 | cell.style = summaryHeader.find(i => i.header === cell.value).style_1;
343 | });
344 | summarySheet.addRow(summaryData);
345 |
346 | await workbook.xlsx.writeFile(fileName);
347 | }
348 |
349 | /**
350 | * Convert worksheet to csv file.
351 | *
352 | * @param {XLSX.WorkSheet} sheet worksheet.
353 | */
354 | export function sheetToCsv(sheet, fileName) {
355 | const output_file_name = fileName;
356 | const stream = XLSX.stream.to_csv(sheet, { rawNumbers: true });
357 | stream.pipe(fs.createWriteStream(output_file_name));
358 | }
359 |
360 | export function sleep(ms) {
361 | return new Promise(resolve => setTimeout(resolve, ms));
362 | }
363 |
364 | export function orderMultiFields() {
365 | return ['line_items', 'refunds', 'transactions', 'risks', 'fulfillments'];
366 | }
367 |
368 | export function generateFileName(type) {
369 | const date = new Date();
370 |
371 | return `${capitalize(type)}_${date.getFullYear()}-${minTwoDigits(
372 | date.getMonth() + 1,
373 | )}-${minTwoDigits(date.getDate())}_${minTwoDigits(date.getHours())}-${minTwoDigits(
374 | date.getMinutes(),
375 | )}-${minTwoDigits(date.getSeconds())}`;
376 | }
377 |
378 | export function minTwoDigits(n) {
379 | return (n < 10 ? '0' : '') + n;
380 | }
381 |
382 | export function numFromID (str) {
383 | const match = str.match(/\d+$/);
384 | return match ? match[0] : null;
385 | }
386 |
387 | function ArrayMove(arr, old_index, new_index) {
388 | if (new_index >= arr.length) {
389 | var k = new_index - arr.length + 1;
390 | while (k--) {
391 | arr.push(undefined);
392 | }
393 | }
394 | arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
395 | return arr;
396 | };
397 |
--------------------------------------------------------------------------------
/utils/shopify.js:
--------------------------------------------------------------------------------
1 | // Shopify related functions.
2 | import { getKeyToken, getToken, sleep } from './index.js';
3 | import ax from 'axios';
4 |
5 | let axios = ax.create({});
6 |
7 | axios.interceptors.response.use(
8 | response => {
9 | return response;
10 | },
11 | error => {
12 | // send 429 as error so recall the api after sleep.
13 | if (error.response?.status === 429) {
14 | return Promise.reject(429);
15 | }
16 |
17 | if (error.code === 'ETIMEDOUT' && error.port === 443) {
18 | return Promise.reject(443);
19 | }
20 |
21 | if (error.code === 'ECONNRESET' || error.response?.status === 502|| error.response?.status === 504) {
22 | return Promise.reject(4077);
23 | }
24 |
25 | // console.log(error)
26 |
27 | return Promise.reject(error.message);
28 | },
29 | );
30 |
31 | const TEST_GRAPHQL_QUERY = `
32 | {
33 | shop {
34 | name
35 | }
36 | }`;
37 |
38 | const apiVersion = "2023-04";
39 |
40 | export async function verifyToken({ url, apiPass }) {
41 | const response = await axios.post(
42 | `https://${url}/admin/api/${apiVersion}/graphql.json`,
43 | TEST_GRAPHQL_QUERY,
44 | {
45 | headers: {
46 | 'Content-Type': 'application/graphql',
47 | 'X-Shopify-Access-Token': apiPass,
48 | },
49 | },
50 | );
51 | return response;
52 | }
53 |
54 | export async function shopifyApi(url, query) {
55 | const token = await getToken(url);
56 | const response = await axios.post(`https://${url}/admin/api/graphql.json`, query, {
57 | headers: {
58 | 'Content-Type': 'application/graphql',
59 | 'X-Shopify-Access-Token': token,
60 | },
61 | });
62 | return response.data?.data;
63 | }
64 |
65 | export async function shopifyRESTApi(store, resource, method, query) {
66 | const { apikey, token } = await getKeyToken(store);
67 | try {
68 | const response = await axios[method](
69 | `https://${apikey}:${token}@${store}/admin/api/${apiVersion}/${resource}.json`,
70 | query,
71 | );
72 | return response.data;
73 | } catch (error) {
74 | if (error === 429) {
75 | sleep(2000);
76 | return await shopifyRESTApi(store, resource, method, query);
77 | }
78 | if (error === 443) {
79 | sleep(5000);
80 | return await shopifyRESTApi(store, resource, method, query);
81 | }
82 | if (error === 4077) {
83 | sleep(10000);
84 | return await shopifyRESTApi(store, resource, method, query);
85 | }
86 | throw error;
87 | }
88 |
89 | }
90 |
91 | export async function shopifyItemRESTApi(store, resource, itemId, method, query) {
92 | const { apikey, token } = await getKeyToken(store);
93 | try {
94 | const response = await axios[method](
95 | `https://${apikey}:${token}@${store}/admin/api/${apiVersion}/${resource}/${itemId}.json`,
96 | query,
97 | );
98 |
99 | return response.data;
100 | } catch (error) {
101 | if (error === 429) {
102 | sleep(2000);
103 | return await shopifyItemRESTApi(store, resource, itemId, method, query);
104 | }
105 | if (error === 443) {
106 | sleep(5000);
107 | return await shopifyItemRESTApi(store, resource, itemId, method, query);
108 | }
109 | if (error === 4077) {
110 | sleep(10000);
111 | return await shopifyItemRESTApi(store, resource, itemId, method, query);
112 | }
113 |
114 | console.log(error);
115 | throw error;
116 | }
117 | }
118 |
119 | export async function shopifyRESTApiCount(store, resource, method, query) {
120 | const { apikey, token } = await getKeyToken(store);
121 | try {
122 | const response = await axios[method](
123 | `https://${apikey}:${token}@${store}/admin/api/${apiVersion}/${resource}/count.json`,
124 | query,
125 | );
126 | return response.data;
127 | } catch (error) {
128 | if (error === 429) {
129 | sleep(2000);
130 | return await shopifyRESTApiCount(store, resource, method, query);
131 | }
132 | if (error === 443) {
133 | sleep(5000);
134 | return await shopifyRESTApiCount(store, resource, method, query);
135 | }
136 | if (error === 4077) {
137 | sleep(10000);
138 | return await shopifyRESTApiCount(store, resource, method, query);
139 | }
140 | }
141 |
142 | }
143 |
144 | export async function shopifyRESTApiDomain(store, method, query) {
145 | const { apikey, token } = await getKeyToken(store);
146 | try {
147 | const response = await axios[method](
148 | `https://${apikey}:${token}@${store}/admin/api/${apiVersion}/shop.json`,
149 | query,
150 | );
151 | return response.data;
152 | } catch (error) {
153 | if (error === 429) {
154 | sleep(2000);
155 | return await shopifyRESTApiDomain(store, method, query);
156 | }
157 | if (error === 443) {
158 | sleep(5000);
159 | return await shopifyRESTApiDomain(store, method, query);
160 | }
161 | if (error === 4077) {
162 | sleep(10000);
163 | return await shopifyRESTApiDomain(store, method, query);
164 | }
165 | }
166 |
167 | }
168 |
169 | export async function shopifyRESTApiCollectionProducts(store, collectionId) {
170 | const { apikey, token } = await getKeyToken(store);
171 | try {
172 | const response = await axios['get'](
173 | `https://${apikey}:${token}@${store}/admin/api/${apiVersion}/collections/${collectionId}/products.json`,
174 | );
175 |
176 | return response.data;
177 | } catch (error) {
178 | if (error === 429) {
179 | sleep(2000);
180 | return await shopifyRESTApiCollectionProducts(store, collectionId);
181 | }
182 | if (error === 443) {
183 | sleep(5000);
184 | return await shopifyRESTApiCollectionProducts(store, collectionId);
185 | }
186 | if (error === 4077) {
187 | sleep(10000);
188 | return await shopifyRESTApiCollectionProducts(store, collectionId);
189 | }
190 | }
191 | }
192 |
193 | export async function shopifyRESTApiSubList(store, type, mainId, subtype, method = 'get', query = {}) {
194 | const { apikey, token } = await getKeyToken(store);
195 | try {
196 | const response = await axios[method](
197 | `https://${apikey}:${token}@${store}/admin/api/${apiVersion}/${type}/${mainId}/${subtype}.json`,
198 | query,
199 | );
200 |
201 | return response.data;
202 | } catch (error) {
203 | if (error === 429) {
204 | sleep(2000);
205 | return await shopifyRESTApiSubList(store, type, mainId, subtype, method, query);
206 | }
207 | if (error === 443) {
208 | sleep(5000);
209 | return await shopifyRESTApiSubList(store, type, mainId, subtype, method, query);
210 | }
211 | if (error === 4077) {
212 | sleep(10000);
213 | return await shopifyRESTApiSubList(store, type, mainId, subtype, method, query);
214 | }
215 |
216 | throw error;
217 | }
218 | }
219 |
220 | export async function shopifyRESTApiSubItem(store, type, mainId, subtype, subId, method = 'get', query = {}) {
221 | const { apikey, token } = await getKeyToken(store);
222 | try {
223 | const response = await axios[method](
224 | `https://${apikey}:${token}@${store}/admin/api/${apiVersion}/${type}/${mainId}/${subtype}/${subId}.json`,
225 | query,
226 | );
227 |
228 | return response.data;
229 | } catch (error) {
230 | if (error === 429) {
231 | sleep(2000);
232 | return await shopifyRESTApiSubItem(store, type, mainId, subtype, subId, method, query);
233 | }
234 | if (error === 443) {
235 | sleep(5000);
236 | return await shopifyRESTApiSubItem(store, type, mainId, subtype, subId, method, query);
237 | }
238 | if (error === 4077) {
239 | sleep(10000);
240 | return await shopifyRESTApiSubItem(store, type, mainId, subtype, subId, method, query);
241 | }
242 |
243 | throw error;
244 | }
245 | }
246 |
247 | export async function shopifyRESTApiProductMetafield(store, productId) {
248 | const { apikey, token } = await getKeyToken(store);
249 | try {
250 | const response = await axios['get'](
251 | `https://${apikey}:${token}@${store}/admin/api/${apiVersion}/products/${productId}/metafields.json`,
252 | );
253 |
254 | return response.data;
255 | } catch (error) {
256 | if (error === 429) {
257 | sleep(2000);
258 | return await shopifyRESTApiProductMetafield(store, productId);
259 | }
260 | if (error === 443) {
261 | sleep(5000);
262 | return await shopifyRESTApiProductMetafield(store, productId);
263 | }
264 | if (error === 4077) {
265 | sleep(10000);
266 | return await shopifyRESTApiProductMetafield(store, productId);
267 | }
268 | }
269 | }
270 |
271 |
272 | export async function shopifyRESTApiVariantMetafield(store, variantId) {
273 | const { apikey, token } = await getKeyToken(store);
274 | try {
275 | const response = await axios['get'](
276 | `https://${apikey}:${token}@${store}/admin/api/${apiVersion}/variants/${variantId}/metafields.json`,
277 | );
278 |
279 | return response.data;
280 | } catch (error) {
281 | if (error === 429) {
282 | sleep(2000);
283 | return await shopifyRESTApiVariantMetafield(store, variantId);
284 | }
285 | if (error === 443) {
286 | sleep(5000);
287 | return await shopifyRESTApiVariantMetafield(store, variantId);
288 | }
289 | if (error === 4077) {
290 | sleep(10000);
291 | return await shopifyRESTApiVariantMetafield(store, variantId);
292 | }
293 | }
294 | }
295 |
296 | export async function shopifyRESTApiSingle(store, resource, id, method, query) {
297 | const { apikey, token } = await getKeyToken(store);
298 | const response = await axios[method](
299 | `https://${apikey}:${token}@${store}/admin/api/${apiVersion}/${resource}/${id}.json`,
300 | query,
301 | );
302 | return response.data;
303 | }
304 |
305 | const META_QUERY = (cursor) => `{
306 | metaobjectDefinitions(first: 250 ${cursor ? `, after: "${cursor}"` : ''}) {
307 | nodes {
308 | id
309 | name
310 | type
311 | metaobjectsCount
312 | fieldDefinitions {
313 | key
314 | name
315 | description
316 | required
317 | type {
318 | name
319 | }
320 | }
321 | }
322 | pageInfo {
323 | hasNextPage
324 | endCursor
325 | }
326 | }
327 | }`
328 |
329 | export async function shopifyGraphMetaobject({ store, endCursor }) {
330 | const { token } = await getKeyToken(store);
331 | const QUERY = META_QUERY(endCursor);
332 |
333 | const response = await axios.post(
334 | `https://${store}/admin/api/${apiVersion}/graphql.json`,
335 | QUERY,
336 | {
337 | headers: {
338 | 'Content-Type': 'application/graphql',
339 | 'X-Shopify-Access-Token': token,
340 | },
341 | },
342 | );
343 | return response.data.data?.metaobjectDefinitions;
344 | }
345 |
346 | const ENTRY_QUERY = (cursor, type) => `{
347 | metaobjects (first: 250 ${cursor ? `, after: "${cursor}"` : ''}, type: "${type}") {
348 | nodes {
349 | id
350 | displayName
351 | handle
352 | type
353 | updatedAt
354 | fields {
355 | key
356 | value
357 | }
358 | }
359 | pageInfo {
360 | hasNextPage
361 | endCursor
362 | }
363 | }
364 | }`
365 |
366 | export async function shopifyGraphMetaobjectEntries({ store, type, endCursor }) {
367 | const { token } = await getKeyToken(store);
368 | const QUERY = ENTRY_QUERY(endCursor, type);
369 |
370 | const response = await axios.post(
371 | `https://${store}/admin/api/${apiVersion}/graphql.json`,
372 | QUERY,
373 | {
374 | headers: {
375 | 'Content-Type': 'application/graphql',
376 | 'X-Shopify-Access-Token': token,
377 | },
378 | },
379 | );
380 |
381 | if (response.data.errors?.[0].message === 'Throttled') {
382 | sleep(2000);
383 | return await shopifyGraphMetaobjectEntries({ store, type, endCursor });
384 | }
385 |
386 | return response.data.data?.metaobjects;
387 | }
388 |
--------------------------------------------------------------------------------
/utils/style.js:
--------------------------------------------------------------------------------
1 | // Matrixify sheet header style objects.
2 |
3 | export const matrixifyStyles = {
4 | Products: {
5 | ID: {
6 | width: 19.17,
7 | fill: 'e2efda',
8 | numFmt: '#',
9 | },
10 | Handle: {
11 | width: 29.17,
12 | fill: 'e2efda',
13 | },
14 | Command: {
15 | width: 11.17,
16 | fill: 'cbcbcb',
17 | },
18 | Title: {
19 | width: 29.17,
20 | fill: 'e2efda',
21 | },
22 | Description: {
23 | width: 29.17,
24 | fill: 'e2efda',
25 | },
26 | Vendor: {
27 | width: 19.17,
28 | fill: 'e2efda',
29 | },
30 | 'Product Type': {
31 | width: 19.17,
32 | fill: 'e2efda',
33 | },
34 | Status: {
35 | width: 12.17,
36 | fill: 'e2efda',
37 | },
38 | Tags: {
39 | width: 29.17,
40 | fill: 'e2efda',
41 | },
42 | 'Tags Command': {
43 | width: 18.17,
44 | fill: 'cbcbcb',
45 | },
46 | 'Variant ID': {
47 | width: 18.17,
48 | fill: 'a9d08f',
49 | numFmt: '#',
50 | },
51 | 'Variant Price': {
52 | width: 14.17,
53 | fill: 'a9d08f',
54 | },
55 | 'Variant Compare At Price': {
56 | width: 26.17,
57 | fill: 'a9d08f',
58 | },
59 | 'Variant SKU': {
60 | width: 14.17,
61 | fill: 'a9d08f',
62 | },
63 | 'Variant Barcode': {
64 | width: 18.17,
65 | fill: 'a9d08f',
66 | },
67 | 'Option1 Value': {
68 | width: 19.17,
69 | fill: 'a9d08f',
70 | },
71 | 'Option2 Value': {
72 | width: 19.17,
73 | fill: 'a9d08f',
74 | },
75 | 'Option3 Value': {
76 | width: 19.17,
77 | fill: 'a9d08f',
78 | },
79 | 'Variant Inventory Qty': {
80 | width: 23.17,
81 | fill: 'a9d08f',
82 | },
83 | 'Image ID': {
84 | width: 18.17,
85 | numFmt: '#',
86 | fill: 'fff2cb',
87 | },
88 | 'Image Position': {
89 | width: 18.17,
90 | fill: 'fff2cb',
91 | },
92 | 'Image Src': {
93 | width: 29.17,
94 | fill: 'fff2cb',
95 | },
96 | 'Image Width': {
97 | width: 15.17,
98 | fill: 'fff2cb',
99 | },
100 | 'Image Height': {
101 | width: 15.17,
102 | fill: 'fff2cb',
103 | },
104 | 'Image Alt Text': {
105 | width: 32,
106 | fill: 'fff2cb',
107 | },
108 | 'Row #': {
109 | width: 12.17,
110 | fill: 'cbcbcb',
111 | },
112 | 'Top Row': {
113 | width: 14.17,
114 | fill: 'cbcbcb',
115 | },
116 | 'Variant Command': {
117 | width: 19.17,
118 | fill: 'cbcbcb',
119 | },
120 | 'Image Command': {
121 | width: 19.17,
122 | fill: 'fff2cb',
123 | },
124 |
125 | 'Created At': {
126 | fill: 'e2efda',
127 | width: 20,
128 | },
129 | 'Updated At': {
130 | fill: 'e2efda',
131 | width: 20,
132 | },
133 | Published: {
134 | fill: 'e2efda',
135 | width: 14,
136 | },
137 | 'Published At': {
138 | fill: 'e2efda',
139 | width: 20,
140 | },
141 | 'Published Scope': {
142 | fill: 'e2efda',
143 | width: 20,
144 | },
145 | 'Template Suffix': {
146 | fill: 'e2efda',
147 | width: 20,
148 | },
149 | URL: {
150 | fill: 'e2efda',
151 | width: 32,
152 | },
153 | },
154 | 'Smart Collections': {
155 | ID: {
156 | width: 18,
157 | fill: 'ffe699',
158 | numFmt: '#',
159 | },
160 | Handle: {
161 | width: 34,
162 | fill: 'ffe699',
163 | },
164 | Command: {
165 | width: 12,
166 | fill: 'cbcbcb',
167 | },
168 | Title: {
169 | width: 36,
170 | fill: 'ffe699',
171 | },
172 | 'Body HTML': {
173 | width: 36,
174 | fill: 'ffe699',
175 | },
176 | 'Sort Order': {
177 | width: 18.17,
178 | fill: 'ffe699',
179 | },
180 | 'Template Suffix': {
181 | width: 18.17,
182 | fill: 'ffe699',
183 | },
184 | 'Updated At': {
185 | width: 28,
186 | fill: 'ffe699',
187 | },
188 | Published: {
189 | width: 14,
190 | fill: 'ffe699',
191 | },
192 | 'Published At': {
193 | width: 28,
194 | fill: 'ffe699',
195 | },
196 | 'Published Scope': {
197 | width: 18.17,
198 | fill: 'ffe699',
199 | },
200 | 'Image Src': {
201 | width: 36,
202 | fill: 'fff2cb',
203 | },
204 | 'Image Width': {
205 | width: 16,
206 | fill: 'fff2cb',
207 | },
208 | 'Image Height': {
209 | width: 16,
210 | fill: 'fff2cb',
211 | },
212 | 'Image Alt Text': {
213 | width: 34,
214 | fill: 'fff2cb',
215 | },
216 | 'Row #': {
217 | width: 12.17,
218 | fill: 'cbcbcb',
219 | },
220 | 'Top Row': {
221 | width: 14.17,
222 | fill: 'cbcbcb',
223 | },
224 | 'Must Match': {
225 | width: 16,
226 | fill: 'ffe699',
227 | },
228 | 'Rule: Product Column': {
229 | width: 24,
230 | fill: 'febf00',
231 | },
232 | 'Rule: Relation': {
233 | width: 16,
234 | fill: 'febf00',
235 | },
236 | 'Rule: Condition': {
237 | width: 22,
238 | fill: 'febf00',
239 | },
240 | },
241 | 'Custom Collections': {
242 | ID: {
243 | width: 18,
244 | fill: 'ffe699',
245 | numFmt: '#',
246 | },
247 | Handle: {
248 | width: 34,
249 | fill: 'ffe699',
250 | },
251 | Command: {
252 | width: 12,
253 | fill: 'cbcbcb',
254 | },
255 | Title: {
256 | width: 36,
257 | fill: 'ffe699',
258 | },
259 | 'Body HTML': {
260 | width: 36,
261 | fill: 'ffe699',
262 | },
263 | 'Sort Order': {
264 | width: 18.17,
265 | fill: 'ffe699',
266 | },
267 | 'Template Suffix': {
268 | width: 18.17,
269 | fill: 'ffe699',
270 | },
271 | 'Updated At': {
272 | width: 28,
273 | fill: 'ffe699',
274 | },
275 | Published: {
276 | width: 14,
277 | fill: 'ffe699',
278 | },
279 | 'Published At': {
280 | width: 28,
281 | fill: 'ffe699',
282 | },
283 | 'Published Scope': {
284 | width: 18.17,
285 | fill: 'ffe699',
286 | },
287 | 'Image Src': {
288 | width: 36,
289 | fill: 'fff2cb',
290 | },
291 | 'Image Width': {
292 | width: 16,
293 | fill: 'fff2cb',
294 | },
295 | 'Image Height': {
296 | width: 16,
297 | fill: 'fff2cb',
298 | },
299 | 'Image Alt Text': {
300 | width: 34,
301 | fill: 'fff2cb',
302 | },
303 | 'Row #': {
304 | width: 12.17,
305 | fill: 'cbcbcb',
306 | },
307 | 'Top Row': {
308 | width: 14.17,
309 | fill: 'cbcbcb',
310 | },
311 | 'Product: ID': {
312 | width: 18,
313 | fill: 'e2efda',
314 | numFmt: '#',
315 | },
316 | 'Product: Handle': {
317 | width: 32,
318 | fill: 'e2efda',
319 | },
320 | 'Product: Position': {
321 | width: 20,
322 | fill: 'e2efda',
323 | },
324 | 'Product: Command': {
325 | width: 20,
326 | fill: 'cbcbcb',
327 | },
328 | },
329 | Customers: {
330 | ID: {
331 | width: 16,
332 | fill: 'ddebf7',
333 | numFmt: '#',
334 | },
335 | Email: {
336 | width: 28,
337 | fill: 'ddebf7',
338 | },
339 | Command: {
340 | width: 12,
341 | fill: 'cbcbcb',
342 | },
343 | 'First Name': {
344 | width: 16,
345 | fill: 'ddebf7',
346 | },
347 | 'Last Name': {
348 | width: 16,
349 | fill: 'ddebf7',
350 | },
351 | Phone: {
352 | width: 16,
353 | fill: 'ddebf7',
354 | },
355 | State: {
356 | width: 12,
357 | fill: 'ddebf7',
358 | },
359 | 'Email Marketing: Status': {
360 | width: 26,
361 | fill: 'ddebf7',
362 | },
363 | 'Email Marketing: Level': {
364 | width: 26,
365 | fill: 'ddebf7',
366 | },
367 | 'Email Marketing: Updated At': {
368 | width: 32,
369 | fill: 'ddebf7',
370 | },
371 | 'SMS Marketing: Status': {
372 | width: 26,
373 | fill: 'ddebf7',
374 | },
375 | 'SMS Marketing: Level': {
376 | width: 26,
377 | fill: 'ddebf7',
378 | },
379 | 'SMS Marketing: Updated At': {
380 | width: 32,
381 | fill: 'ddebf7',
382 | },
383 | 'SMS Marketing: Source': {
384 | width: 26,
385 | fill: 'ddebf7',
386 | },
387 | 'Created At': {
388 | width: 20,
389 | fill: 'ddebf7',
390 | },
391 | 'Updated At': {
392 | width: 20,
393 | fill: 'ddebf7',
394 | },
395 | Note: {
396 | width: 32,
397 | fill: 'ddebf7',
398 | },
399 | 'Verified Email': {
400 | width: 14,
401 | fill: 'ddebf7',
402 | },
403 | 'Tax Exempt': {
404 | width: 14,
405 | fill: 'ddebf7',
406 | },
407 | Tags: {
408 | width: 26,
409 | fill: 'ddebf7',
410 | },
411 | 'Tags Command': {
412 | width: 16,
413 | fill: 'cbcbcb',
414 | },
415 | 'Total Spent': {
416 | width: 12,
417 | fill: 'c9ff00',
418 | },
419 | 'Total Orders': {
420 | width: 12,
421 | fill: 'c9ff00',
422 | },
423 | 'Send Account Activation Email': {
424 | width: 32,
425 | fill: 'ddebf7',
426 | },
427 | 'Send Welcome Email': {
428 | width: 26,
429 | fill: 'ddebf7',
430 | },
431 | Password: {
432 | width: 16,
433 | fill: 'ddebf7',
434 | },
435 | 'Multipass Identifier': {
436 | width: 20,
437 | fill: 'ddebf7',
438 | },
439 | 'Row #': {
440 | width: 10,
441 | fill: 'cbcbcb',
442 | },
443 | 'Top Row': {
444 | width: 10,
445 | fill: 'cbcbcb',
446 | },
447 |
448 | 'Address ID': {
449 | width: 16,
450 | fill: '9bc2e6',
451 | numFmt: '#',
452 | },
453 | 'Address Command': {
454 | width: 20,
455 | fill: '9bc2e6',
456 | },
457 | 'Address First Name': {
458 | width: 20,
459 | fill: '9bc2e6',
460 | },
461 | 'Address Last Name': {
462 | width: 20,
463 | fill: '9bc2e6',
464 | },
465 | 'Address Phone': {
466 | width: 18,
467 | fill: '9bc2e6',
468 | },
469 | 'Address Company': {
470 | width: 20,
471 | fill: '9bc2e6',
472 | },
473 | 'Address Line 1': {
474 | width: 20,
475 | fill: '9bc2e6',
476 | },
477 | 'Address Line 2': {
478 | width: 20,
479 | fill: '9bc2e6',
480 | },
481 | 'Address City': {
482 | width: 20,
483 | fill: '9bc2e6',
484 | },
485 | 'Address Province': {
486 | width: 20,
487 | fill: '9bc2e6',
488 | },
489 | 'Address Province Code': {
490 | width: 20,
491 | fill: '9bc2e6',
492 | },
493 | 'Address Country': {
494 | width: 20,
495 | fill: '9bc2e6',
496 | },
497 | 'Address Country Code': {
498 | width: 20,
499 | fill: '9bc2e6',
500 | },
501 | 'Address Zip': {
502 | width: 16,
503 | fill: '9bc2e6',
504 | },
505 | 'Address Is Default': {
506 | width: 20,
507 | fill: '9bc2e6',
508 | },
509 | },
510 | Orders: {
511 | // basic
512 | ID: {
513 | width: 18,
514 | fill: 'c9ff00',
515 | numFmt: '#',
516 | },
517 | Name: {
518 | width: 10,
519 | fill: 'c9ff00',
520 | },
521 | Command: {
522 | width: 12,
523 | fill: 'cbcbcb',
524 | },
525 | 'Send Receipt': {
526 | width: 14,
527 | fill: 'cbcbcb',
528 | },
529 | 'Inventory Behaviour': {
530 | width: 22,
531 | fill: 'cbcbcb',
532 | },
533 | Number: {
534 | width: 10,
535 | fill: 'c9ff00',
536 | },
537 | Phone: {
538 | width: 22,
539 | fill: 'c9ff00',
540 | },
541 | Email: {
542 | width: 22,
543 | fill: 'c9ff00',
544 | },
545 | Note: {
546 | width: 22,
547 | fill: 'c9ff00',
548 | },
549 | Tags: {
550 | width: 22,
551 | fill: 'c9ff00',
552 | },
553 | 'Tags Command': {
554 | width: 20,
555 | fill: 'cbcbcb',
556 | },
557 | 'Created At': {
558 | width: 12,
559 | fill: 'c9ff00',
560 | },
561 | 'Updated At': {
562 | width: 12,
563 | fill: 'c9ff00',
564 | },
565 | 'Cancelled At': {
566 | width: 14,
567 | fill: 'ffd966',
568 | },
569 | 'Cancel: Reason': {
570 | width: 21,
571 | fill: 'ffd966',
572 | },
573 | 'Cancel: Send Receipt': {
574 | width: 22,
575 | fill: 'ffd966',
576 | },
577 | 'Cancel: Refund': {
578 | width: 22,
579 | fill: 'ffd966',
580 | },
581 | 'Processed At': {
582 | width: 14,
583 | fill: 'c9ff00',
584 | },
585 | 'Closed At': {
586 | width: 12,
587 | fill: 'c9ff00',
588 | },
589 | Currency: {
590 | width: 10,
591 | fill: 'c9ff00',
592 | },
593 | Source: {
594 | width: 18,
595 | fill: 'c9ff00',
596 | },
597 | 'Physical Location': {
598 | width: 20,
599 | fill: 'c9ff00',
600 | },
601 | 'User ID': {
602 | width: 12,
603 | fill: 'c9ff00',
604 | },
605 | 'Checkout ID': {
606 | width: 18,
607 | fill: 'c9ff00',
608 | numFmt: '#',
609 | },
610 | 'Cart Token': {
611 | width: 12,
612 | fill: 'c9ff00',
613 | },
614 | Token: {
615 | width: 22,
616 | fill: 'c9ff00',
617 | },
618 | 'Order Status URL': {
619 | width: 22,
620 | fill: 'c9ff00',
621 | },
622 | 'Weight Total': {
623 | width: 14,
624 | fill: 'c9ff00',
625 | },
626 | 'Price: Total Line Items': {
627 | width: 24,
628 | fill: 'c9ff00',
629 | },
630 | 'Price: Subtotal': {
631 | width: 16,
632 | fill: 'c9ff00',
633 | },
634 | 'Tax 1: Title': {
635 | width: 14,
636 | fill: 'c9ff00',
637 | },
638 | 'Tax 1: Rate': {
639 | width: 14,
640 | fill: 'c9ff00',
641 | },
642 | 'Tax 1: Price': {
643 | width: 14,
644 | fill: 'c9ff00',
645 | },
646 |
647 | 'Tax 2: Title': {
648 | width: 14,
649 | fill: 'c9ff00',
650 | },
651 | 'Tax 2: Rate': {
652 | width: 14,
653 | fill: 'c9ff00',
654 | },
655 | 'Tax 2: Price': {
656 | width: 14,
657 | fill: 'c9ff00',
658 | },
659 |
660 | 'Tax 3: Title': {
661 | width: 14,
662 | fill: 'c9ff00',
663 | },
664 | 'Tax 3: Rate': {
665 | width: 14,
666 | fill: 'c9ff00',
667 | },
668 | 'Tax 3: Price': {
669 | width: 14,
670 | fill: 'c9ff00',
671 | },
672 |
673 | 'Tax 4: Title': {
674 | width: 14,
675 | fill: 'c9ff00',
676 | },
677 | 'Tax 4: Rate': {
678 | width: 14,
679 | fill: 'c9ff00',
680 | },
681 | 'Tax 4: Price': {
682 | width: 14,
683 | fill: 'c9ff00',
684 | },
685 |
686 | 'Tax 5: Title': {
687 | width: 14,
688 | fill: 'c9ff00',
689 | },
690 | 'Tax 5: Rate': {
691 | width: 14,
692 | fill: 'c9ff00',
693 | },
694 | 'Tax 5: Price': {
695 | width: 14,
696 | fill: 'c9ff00',
697 | },
698 | 'Tax: Included': {
699 | width: 14,
700 | fill: 'c9ff00',
701 | },
702 | 'Tax: Total': {
703 | width: 12,
704 | fill: 'c9ff00',
705 | },
706 | 'Price: Total Discount': {
707 | width: 22,
708 | fill: 'c9ff00',
709 | },
710 | 'Price: Total Shipping': {
711 | width: 22,
712 | fill: 'c9ff00',
713 | },
714 | 'Price: Total Refund': {
715 | width: 16,
716 | fill: 'c9ff00',
717 | },
718 | 'Price: Total Outstanding': {
719 | width: 16,
720 | fill: 'c9ff00',
721 | },
722 | 'Price: Current Total': {
723 | width: 16,
724 | fill: 'c9ff00',
725 | },
726 | 'Price: Total': {
727 | width: 16,
728 | fill: 'c9ff00',
729 | },
730 | 'Payment: Status': {
731 | width: 16,
732 | fill: 'c9ff00',
733 | },
734 | 'Payment: Processing Method': {
735 | width: 30,
736 | fill: 'c9ff00',
737 | },
738 | 'Order Fulfillment Status': {
739 | width: 24,
740 | fill: 'c9ff00',
741 | },
742 | 'Additional Details': {
743 | width: 30,
744 | fill: 'c9ff00',
745 | },
746 |
747 | // customer
748 | 'Customer: ID': {
749 | width: 22,
750 | fill: 'ddebf7',
751 | numFmt: '#',
752 | },
753 | 'Customer: Email': {
754 | width: 22,
755 | fill: 'ddebf7',
756 | },
757 | 'Customer: Phone': {
758 | width: 22,
759 | fill: 'ddebf7',
760 | },
761 | 'Customer: First Name': {
762 | width: 22,
763 | fill: 'ddebf7',
764 | },
765 | 'Customer: Last Name': {
766 | width: 22,
767 | fill: 'ddebf7',
768 | },
769 | 'Customer: Note': {
770 | width: 22,
771 | fill: 'ddebf7',
772 | },
773 | 'Customer: State': {
774 | width: 18,
775 | fill: 'ddebf7',
776 | },
777 | 'Customer: Tags': {
778 | width: 18,
779 | fill: 'ddebf7',
780 | },
781 | 'Customer: Accepts Marketing': {
782 | width: 30,
783 | fill: 'ddebf7',
784 | },
785 | 'Customer: Orders Count': {
786 | width: 24,
787 | fill: 'ddebf7',
788 | },
789 | 'Customer: Total Spent': {
790 | width: 20,
791 | fill: 'ddebf7',
792 | },
793 |
794 | // billing
795 | 'Billing: First Name': {
796 | width: 22,
797 | fill: '9bc2e6',
798 | },
799 | 'Billing: Last Name': {
800 | width: 22,
801 | fill: '9bc2e6',
802 | },
803 | 'Billing: Company': {
804 | width: 22,
805 | fill: '9bc2e6',
806 | },
807 | 'Billing: Phone': {
808 | width: 22,
809 | fill: '9bc2e6',
810 | },
811 | 'Billing: Address1': {
812 | width: 22,
813 | fill: '9bc2e6',
814 | },
815 | 'Billing: Address2': {
816 | width: 22,
817 | fill: '9bc2e6',
818 | },
819 | 'Billing: Zip': {
820 | width: 22,
821 | fill: '9bc2e6',
822 | },
823 | 'Billing: City': {
824 | width: 22,
825 | fill: '9bc2e6',
826 | },
827 | 'Billing: Province': {
828 | width: 22,
829 | fill: '9bc2e6',
830 | },
831 | 'Billing: Province Code': {
832 | width: 22,
833 | fill: '9bc2e6',
834 | },
835 | 'Billing: Country': {
836 | width: 18,
837 | fill: '9bc2e6',
838 | },
839 | 'Billing: Country Code': {
840 | width: 22,
841 | fill: '9bc2e6',
842 | },
843 |
844 | // shipping
845 | 'Shipping: First Name': {
846 | width: 22,
847 | fill: '9bc2e6',
848 | },
849 | 'Shipping: Last Name': {
850 | width: 22,
851 | fill: '9bc2e6',
852 | },
853 | 'Shipping: Company': {
854 | width: 22,
855 | fill: '9bc2e6',
856 | },
857 | 'Shipping: Phone': {
858 | width: 22,
859 | fill: '9bc2e6',
860 | },
861 | 'Shipping: Address1': {
862 | width: 22,
863 | fill: '9bc2e6',
864 | },
865 | 'Shipping: Address2': {
866 | width: 22,
867 | fill: '9bc2e6',
868 | },
869 | 'Shipping: Zip': {
870 | width: 22,
871 | fill: '9bc2e6',
872 | },
873 | 'Shipping: City': {
874 | width: 22,
875 | fill: '9bc2e6',
876 | },
877 | 'Shipping: Province': {
878 | width: 22,
879 | fill: '9bc2e6',
880 | },
881 | 'Shipping: Province Code': {
882 | width: 22,
883 | fill: '9bc2e6',
884 | },
885 | 'Shipping: Country': {
886 | width: 18,
887 | fill: '9bc2e6',
888 | },
889 | 'Shipping: Country Code': {
890 | width: 22,
891 | fill: '9bc2e6',
892 | },
893 |
894 | // browser
895 | 'Browser: IP': {
896 | width: 16,
897 | fill: 'ddebf7',
898 | },
899 | 'Browser: Width': {
900 | width: 18,
901 | fill: 'ddebf7',
902 | },
903 | 'Browser: Height': {
904 | width: 18,
905 | fill: 'ddebf7',
906 | },
907 | 'Browser: User Agent': {
908 | width: 22,
909 | fill: 'ddebf7',
910 | },
911 | 'Browser: Landing Page': {
912 | width: 22,
913 | fill: 'ddebf7',
914 | },
915 | 'Browser: Referrer': {
916 | width: 22,
917 | fill: 'ddebf7',
918 | },
919 | 'Browser: Referrer Domain': {
920 | width: 26,
921 | fill: 'ddebf7',
922 | },
923 | 'Browser: Search Keywords': {
924 | width: 26,
925 | fill: 'ddebf7',
926 | },
927 | 'Browser: Ad URL': {
928 | width: 22,
929 | fill: 'ddebf7',
930 | },
931 | 'Browser: UTM Source': {
932 | width: 22,
933 | fill: 'ddebf7',
934 | },
935 | 'Browser: UTM Medium': {
936 | width: 22,
937 | fill: 'ddebf7',
938 | },
939 | 'Browser: UTM Campaign': {
940 | width: 22,
941 | fill: 'ddebf7',
942 | },
943 | 'Browser: UTM Term': {
944 | width: 22,
945 | fill: 'ddebf7',
946 | },
947 | 'Browser: UTM Content': {
948 | width: 22,
949 | fill: 'ddebf7',
950 | },
951 |
952 | 'Row #': {
953 | width: 8,
954 | fill: 'cbcbcb',
955 | },
956 | 'Top Row': {
957 | width: 10,
958 | fill: 'cbcbcb',
959 | },
960 | 'Line: Type': {
961 | width: 16,
962 | fill: 'a9d08e',
963 | },
964 |
965 | // line item
966 | 'Line: ID': {
967 | width: 18,
968 | fill: 'a9d08e',
969 | numFmt: '#',
970 | },
971 | 'Line: Command': {
972 | width: 16,
973 | fill: 'cbcbcb',
974 | },
975 | 'Line: Product ID': {
976 | width: 18,
977 | fill: 'a9d08e',
978 | numFmt: '#',
979 | },
980 | 'Line: Product Handle': {
981 | width: 22,
982 | fill: 'a9d08e',
983 | },
984 | 'Line: Title': {
985 | width: 22,
986 | fill: 'a9d08e',
987 | },
988 | 'Line: Name': {
989 | width: 22,
990 | fill: 'a9d08e',
991 | },
992 | 'Line: Variant ID': {
993 | width: 18,
994 | fill: 'a9d08e',
995 | numFmt: '#',
996 | },
997 | 'Line: Variant Title': {
998 | width: 22,
999 | fill: 'a9d08e',
1000 | },
1001 | 'Line: SKU': {
1002 | width: 22,
1003 | fill: 'a9d08e',
1004 | },
1005 | 'Line: Quantity': {
1006 | width: 16,
1007 | fill: 'a9d08e',
1008 | },
1009 | 'Line: Price': {
1010 | width: 14,
1011 | fill: 'a9d08e',
1012 | },
1013 | 'Line: Discount': {
1014 | width: 16,
1015 | fill: 'a9d08e',
1016 | },
1017 | 'Line: Discount Allocation': {
1018 | width: 26,
1019 | fill: 'a9d08e',
1020 | },
1021 | 'Line: Discount per Item': {
1022 | width: 30,
1023 | fill: 'a9d08e',
1024 | },
1025 | 'Line: Total': {
1026 | width: 12,
1027 | fill: 'a9d08e',
1028 | },
1029 | 'Line: Grams': {
1030 | width: 12,
1031 | fill: 'a9d08e',
1032 | },
1033 | 'Line: Requires Shipping': {
1034 | width: 24,
1035 | fill: 'a9d08e',
1036 | },
1037 | 'Line: Vendor': {
1038 | width: 22,
1039 | fill: 'a9d08e',
1040 | },
1041 | 'Line: Properties': {
1042 | width: 22,
1043 | fill: 'a9d08e',
1044 | },
1045 | 'Line: Gift Card': {
1046 | width: 16,
1047 | fill: 'a9d08e',
1048 | },
1049 | 'Line: Force Gift Card': {
1050 | width: 22,
1051 | fill: 'cbcbcb',
1052 | },
1053 | 'Line: Taxable': {
1054 | width: 16,
1055 | fill: 'a9d08e',
1056 | },
1057 | 'Line: Tax Total': {
1058 | width: 18,
1059 | fill: 'a9d08e',
1060 | },
1061 | 'Line: Tax 1 Title': {
1062 | width: 18,
1063 | fill: 'a9d08e',
1064 | },
1065 | 'Line: Tax 1 Rate': {
1066 | width: 18,
1067 | fill: 'a9d08e',
1068 | },
1069 | 'Line: Tax 1 Price': {
1070 | width: 18,
1071 | fill: 'a9d08e',
1072 | },
1073 |
1074 | 'Line: Tax 2 Title': {
1075 | width: 18,
1076 | fill: 'a9d08e',
1077 | },
1078 | 'Line: Tax 2 Rate': {
1079 | width: 18,
1080 | fill: 'a9d08e',
1081 | },
1082 | 'Line: Tax 2 Price': {
1083 | width: 18,
1084 | fill: 'a9d08e',
1085 | },
1086 |
1087 | 'Line: Tax 3 Title': {
1088 | width: 18,
1089 | fill: 'a9d08e',
1090 | },
1091 | 'Line: Tax 3 Rate': {
1092 | width: 18,
1093 | fill: 'a9d08e',
1094 | },
1095 | 'Line: Tax 3 Price': {
1096 | width: 18,
1097 | fill: 'a9d08e',
1098 | },
1099 |
1100 | 'Line: Tax 4 Title': {
1101 | width: 18,
1102 | fill: 'a9d08e',
1103 | },
1104 | 'Line: Tax 4 Rate': {
1105 | width: 18,
1106 | fill: 'a9d08e',
1107 | },
1108 | 'Line: Tax 4 Price': {
1109 | width: 18,
1110 | fill: 'a9d08e',
1111 | },
1112 |
1113 | 'Line: Tax 5 Title': {
1114 | width: 18,
1115 | fill: 'a9d08e',
1116 | },
1117 | 'Line: Tax 5 Rate': {
1118 | width: 18,
1119 | fill: 'a9d08e',
1120 | },
1121 | 'Line: Tax 5 Price': {
1122 | width: 18,
1123 | fill: 'a9d08e',
1124 | },
1125 |
1126 | 'Line: Fulfillable Quantity': {
1127 | width: 24,
1128 | fill: 'a9d08e',
1129 | },
1130 | 'Line: Fulfillment Service': {
1131 | width: 24,
1132 | fill: 'a9d08e',
1133 | },
1134 | 'Line: Fulfillment Status': {
1135 | width: 24,
1136 | fill: 'a9d08e',
1137 | },
1138 |
1139 | 'Line: Pre Tax Price': {
1140 | width: 22,
1141 | fill: 'a9d08e',
1142 | },
1143 |
1144 | 'Shipping Origin: Name': {
1145 | width: 22,
1146 | fill: '9bc2e6',
1147 | },
1148 | 'Shipping Origin: Country Code': {
1149 | width: 26,
1150 | fill: '9bc2e6',
1151 | },
1152 | 'Shipping Origin: Province Code': {
1153 | width: 26,
1154 | fill: '9bc2e6',
1155 | },
1156 | 'Shipping Origin: City': {
1157 | width: 22,
1158 | fill: '9bc2e6',
1159 | },
1160 | 'Shipping Origin: Address 1': {
1161 | width: 26,
1162 | fill: '9bc2e6',
1163 | },
1164 | 'Shipping Origin: Address 2': {
1165 | width: 26,
1166 | fill: '9bc2e6',
1167 | },
1168 | 'Shipping Origin: Zip': {
1169 | width: 22,
1170 | fill: '9bc2e6',
1171 | },
1172 |
1173 | // refunds
1174 | 'Refund: ID': {
1175 | width: 16,
1176 | fill: 'ff896e',
1177 | numFmt: '#',
1178 | },
1179 | 'Refund: Created At': {
1180 | width: 20,
1181 | fill: 'ff896e',
1182 | },
1183 | 'Refund: Note': {
1184 | width: 22,
1185 | fill: 'ff896e',
1186 | },
1187 | 'Refund: Restock': {
1188 | width: 18,
1189 | fill: 'ff896e',
1190 | },
1191 | 'Refund: Restock Type': {
1192 | width: 26,
1193 | fill: 'ff896e',
1194 | },
1195 | 'Refund: Restock Location': {
1196 | width: 26,
1197 | fill: 'ff896e',
1198 | },
1199 | 'Refund: Send Receipt': {
1200 | width: 26,
1201 | fill: 'ff896e',
1202 | },
1203 | 'Refund: Generate Transaction': {
1204 | width: 26,
1205 | fill: 'ff896e',
1206 | },
1207 |
1208 | // transaction
1209 | 'Transaction: ID': {
1210 | width: 18,
1211 | fill: 'ffff00',
1212 | numFmt: '#',
1213 | },
1214 | 'Transaction: Kind': {
1215 | width: 20,
1216 | fill: 'ffff00',
1217 | },
1218 | 'Transaction: Processed At': {
1219 | width: 24,
1220 | fill: 'ffff00',
1221 | },
1222 | 'Transaction: Amount': {
1223 | width: 22,
1224 | fill: 'ffff00',
1225 | },
1226 | 'Transaction: Currency': {
1227 | width: 22,
1228 | fill: 'ffff00',
1229 | },
1230 | 'Transaction: Status': {
1231 | width: 22,
1232 | fill: 'ffff00',
1233 | },
1234 | 'Transaction: Message': {
1235 | width: 22,
1236 | fill: 'ffff00',
1237 | },
1238 | 'Transaction: Gateway': {
1239 | width: 22,
1240 | fill: 'ffff00',
1241 | },
1242 | 'Transaction: Force Gateway': {
1243 | width: 30,
1244 | fill: 'cbcbcb',
1245 | },
1246 | 'Transaction: Test': {
1247 | width: 22,
1248 | fill: 'ffff00',
1249 | },
1250 | 'Transaction: Authorization': {
1251 | width: 22,
1252 | fill: 'ffff00',
1253 | },
1254 | 'Transaction: Parent ID': {
1255 | width: 22,
1256 | fill: 'ffff00',
1257 | },
1258 | 'Transaction: Error Code': {
1259 | width: 22,
1260 | fill: 'ffff00',
1261 | },
1262 | 'Transaction: CC AVS Result': {
1263 | width: 22,
1264 | fill: 'ffff00',
1265 | },
1266 | 'Transaction: CC Bin': {
1267 | width: 22,
1268 | fill: 'ffff00',
1269 | },
1270 | 'Transaction: CC CVV Result': {
1271 | width: 22,
1272 | fill: 'ffff00',
1273 | },
1274 | 'Transaction: CC Number': {
1275 | width: 22,
1276 | fill: 'ffff00',
1277 | },
1278 | 'Transaction: CC Company': {
1279 | width: 22,
1280 | fill: 'ffff00',
1281 | },
1282 |
1283 | // risk
1284 | 'Risk: Source': {
1285 | width: 22,
1286 | fill: 'ff896e',
1287 | },
1288 | 'Risk: Score': {
1289 | width: 22,
1290 | fill: 'ff896e',
1291 | },
1292 | 'Risk: Recommendation': {
1293 | width: 30,
1294 | fill: 'ff896e',
1295 | },
1296 | 'Risk: Cause Cancel': {
1297 | width: 22,
1298 | fill: 'ff896e',
1299 | },
1300 | 'Risk: Message': {
1301 | width: 30,
1302 | fill: 'ff896e',
1303 | },
1304 |
1305 | // fulfillment
1306 | 'Fulfillment: ID': {
1307 | width: 18,
1308 | fill: 'e7e6e6',
1309 | numFmt: '#',
1310 | },
1311 | 'Fulfillment: Status': {
1312 | width: 20,
1313 | fill: 'e7e6e6',
1314 | },
1315 | 'Fulfillment: Created At': {
1316 | width: 22,
1317 | fill: 'e7e6e6',
1318 | },
1319 | 'Fulfillment: Updated At': {
1320 | width: 22,
1321 | fill: 'e7e6e6',
1322 | },
1323 | 'Fulfillment: Tracking Company': {
1324 | width: 30,
1325 | fill: 'e7e6e6',
1326 | },
1327 | 'Fulfillment: Location': {
1328 | width: 22,
1329 | fill: 'e7e6e6',
1330 | },
1331 | 'Fulfillment: Shipment Status': {
1332 | width: 30,
1333 | fill: 'e7e6e6',
1334 | },
1335 | 'Fulfillment: Tracking Number': {
1336 | width: 30,
1337 | fill: 'e7e6e6',
1338 | },
1339 | 'Fulfillment: Tracking URL': {
1340 | width: 26,
1341 | fill: 'e7e6e6',
1342 | },
1343 | 'Fulfillment: Send Receipt': {
1344 | width: 30,
1345 | fill: 'e7e6e6',
1346 | },
1347 | },
1348 | 'Metaobject Entries': {
1349 | "ID": {
1350 | width: 24,
1351 | fill: '9fffff',
1352 | },
1353 | "Handle": {
1354 | width: 24,
1355 | fill: '9fffff',
1356 | },
1357 | "Command": {
1358 | width: 12,
1359 | fill: 'cbcbcb',
1360 | },
1361 | "Display Name": {
1362 | width: 18,
1363 | fill: '9fffff',
1364 | },
1365 | "Status": {
1366 | width: 10,
1367 | fill: '9fffff',
1368 | },
1369 | "Updated At": {
1370 | width: 22,
1371 | fill: '9fffff',
1372 | },
1373 | "Definition: Handle": {
1374 | width: 22,
1375 | fill: '9fff9f',
1376 | },
1377 | "Definition: Name": {
1378 | width: 22,
1379 | fill: '9fff9f',
1380 | },
1381 | "Top Row": {
1382 | width: 14,
1383 | fill: 'cbcbcb',
1384 | },
1385 | "Row #": {
1386 | width: 12,
1387 | fill: 'cbcbcb',
1388 | },
1389 | "Field": {
1390 | width: 22,
1391 | fill: 'e3ffff',
1392 | },
1393 | "Value": {
1394 | width: 22,
1395 | fill: 'e3ffff',
1396 | },
1397 | },
1398 | 'Price Rules': {
1399 | "ID": {
1400 | width: 16,
1401 | fill: 'FFBF00',
1402 | numFmt: '#',
1403 | },
1404 | "Title": {
1405 | width: 26,
1406 | fill: 'FFBF00',
1407 | },
1408 | "Command": {
1409 | width: 12,
1410 | fill: 'cbcbcb',
1411 | },
1412 | "Code": {
1413 | width: 26,
1414 | fill: 'A8BF00',
1415 | },
1416 | "Used Count": {
1417 | width: 14,
1418 | fill: 'A8BF00',
1419 | },
1420 | "Discount Type": {
1421 | width: 22,
1422 | fill: 'FFBF00',
1423 | },
1424 | "Discount Value": {
1425 | width: 16,
1426 | fill: 'FFBF00',
1427 | },
1428 | "Minimum Purchase Amount": {
1429 | width: 28,
1430 | fill: 'FFBF00',
1431 | },
1432 | "Limit Total Times": {
1433 | width: 18,
1434 | fill: 'FFBF00',
1435 | },
1436 | "Limit Once Per Customer": {
1437 | width: 24,
1438 | fill: 'FFBF00',
1439 | },
1440 | "Limit Once Per Order": {
1441 | width: 24,
1442 | fill: 'FFBF00',
1443 | },
1444 | "Max Uses Per Order": {
1445 | width: 24,
1446 | fill: 'FFBF00',
1447 | },
1448 | "Minimum Quantity Of Items": {
1449 | width: 22,
1450 | fill: 'FFBF00',
1451 | },
1452 | "Status": {
1453 | width: 16,
1454 | fill: 'FFBF00',
1455 | },
1456 | "Starts At": {
1457 | width: 18,
1458 | fill: 'FFBF00',
1459 | },
1460 | "Ends At": {
1461 | width: 18,
1462 | fill: 'FFBF00',
1463 | },
1464 | "Updated At": {
1465 | width: 18,
1466 | fill: 'FFBF00',
1467 | },
1468 | "Free Shipping: Country Codes": {
1469 | width: 26,
1470 | fill: 'FFE699',
1471 | },
1472 | "Free Shipping: Over Amount": {
1473 | width: 26,
1474 | fill: 'FFE699',
1475 | },
1476 | "Customer Buys: Quantity": {
1477 | width: 22,
1478 | fill: 'DDEBF7',
1479 | },
1480 | "Customer Buys: Collections": {
1481 | width: 22,
1482 | fill: 'DDEBF7',
1483 | numFmt: '#',
1484 | },
1485 | "Customer Buys: Products": {
1486 | width: 22,
1487 | fill: 'DDEBF7',
1488 | numFmt: '#',
1489 | },
1490 | "Customer Buys: Variants": {
1491 | width: 22,
1492 | fill: 'DDEBF7',
1493 | numFmt: '#',
1494 | },
1495 | "Customer Gets: Quantity": {
1496 | width: 22,
1497 | fill: 'DDEBF7',
1498 | numFmt: '#',
1499 | },
1500 | "Applies To: Collections": {
1501 | width: 22,
1502 | fill: 'DDEBF7',
1503 | numFmt: '#',
1504 | },
1505 | "Applies To: Products": {
1506 | width: 22,
1507 | fill: 'DDEBF7',
1508 | numFmt: '#',
1509 | },
1510 | "Applies To: Variants": {
1511 | width: 22,
1512 | fill: 'DDEBF7',
1513 | numFmt: '#',
1514 | },
1515 | "Applies To: Customer Groups": {
1516 | width: 22,
1517 | fill: 'DDEBF7',
1518 | },
1519 | "Applies To: Customers": {
1520 | width: 22,
1521 | fill: 'DDEBF7',
1522 | numFmt: '#',
1523 | },
1524 | "Applies To: Customers Email": {
1525 | width: 26,
1526 | fill: 'DDEBF7',
1527 | },
1528 | 'Row #': {
1529 | width: 12.17,
1530 | fill: 'cbcbcb',
1531 | },
1532 | 'Top Row': {
1533 | width: 14.17,
1534 | fill: 'cbcbcb',
1535 | },
1536 | },
1537 | Pages: {
1538 | 'ID': {
1539 | width: 16,
1540 | fill: 'FFFF00',
1541 | },
1542 | 'Handle': {
1543 | width: 24,
1544 | fill: 'FFFF00',
1545 | },
1546 | 'Command': {
1547 | width: 12,
1548 | fill: 'cbcbcb',
1549 | },
1550 | 'Title': {
1551 | width: 24,
1552 | fill: 'FFFF00',
1553 | },
1554 | 'Author': {
1555 | width: 24,
1556 | fill: 'FFFF00',
1557 | },
1558 | 'Body HTML': {
1559 | width: 40,
1560 | fill: 'FFFF00',
1561 | },
1562 | 'Created At': {
1563 | width: 14,
1564 | fill: 'FFFF00',
1565 | },
1566 | 'Updated At': {
1567 | width: 14,
1568 | fill: 'FFFF00',
1569 | },
1570 | 'Published': {
1571 | width: 14,
1572 | fill: 'FFFF00',
1573 | },
1574 | 'Published At': {
1575 | width: 14,
1576 | fill: 'FFFF00',
1577 | },
1578 | 'Template Suffix': {
1579 | width: 18,
1580 | fill: 'FFFF00',
1581 | },
1582 | 'Row #': {
1583 | width: 12.17,
1584 | fill: 'cbcbcb',
1585 | },
1586 | 'Top Row': {
1587 | width: 14.17,
1588 | fill: 'cbcbcb',
1589 | },
1590 | },
1591 | Blogs: {
1592 | 'ID': {
1593 | width: 16,
1594 | fill: 'C9C6FF',
1595 | numFmt: '#',
1596 | },
1597 | 'Handle': {
1598 | width: 24,
1599 | fill: 'C9C6FF',
1600 | },
1601 | "Command": {
1602 | width: 12,
1603 | fill: 'cbcbcb',
1604 | },
1605 | 'Title': {
1606 | width: 24,
1607 | fill: 'C9C6FF',
1608 | },
1609 | 'Author': {
1610 | width: 14,
1611 | fill: 'C9C6FF',
1612 | },
1613 | 'Body HTML': {
1614 | width: 56,
1615 | fill: 'C9C6FF',
1616 | },
1617 | 'Summary HTML': {
1618 | width: 34,
1619 | fill: 'C9C6FF',
1620 | },
1621 | 'Tags': {
1622 | width: 20,
1623 | fill: 'C9C6FF',
1624 | },
1625 | 'Tags Command': {
1626 | width: 22,
1627 | fill: 'cbcbcb',
1628 | },
1629 | 'Created At': {
1630 | width: 24,
1631 | fill: 'C9C6FF',
1632 | },
1633 | 'Updated At': {
1634 | width: 24,
1635 | fill: 'C9C6FF',
1636 | },
1637 | 'Published': {
1638 | width: 14,
1639 | fill: 'C9C6FF',
1640 | },
1641 | 'Published At': {
1642 | width: 24,
1643 | fill: 'C9C6FF',
1644 | },
1645 | 'Template Suffix': {
1646 | width: 16,
1647 | fill: 'C9C6FF',
1648 | },
1649 | 'Image Src': {
1650 | width: 24,
1651 | fill: 'FFF2CC',
1652 | },
1653 | 'Image Width': {
1654 | width: 16,
1655 | fill: 'FFF2CC',
1656 | },
1657 | 'Image Height': {
1658 | width: 16,
1659 | fill: 'FFF2CC',
1660 | },
1661 | 'Image Alt Text': {
1662 | width: 26,
1663 | fill: 'FFF2CC',
1664 | },
1665 | 'Blog: ID': {
1666 | width: 16,
1667 | fill: '00FFFF',
1668 | },
1669 | 'Blog: Handle': {
1670 | width: 20,
1671 | fill: '00FFFF',
1672 | },
1673 | 'Blog: Title': {
1674 | width: 20,
1675 | fill: '00FFFF',
1676 | },
1677 | 'Blog: Commentable': {
1678 | width: 22,
1679 | fill: '00FFFF',
1680 | },
1681 | 'Blog: Feedburner URL': {
1682 | width: 26,
1683 | fill: '00FFFF',
1684 | },
1685 | 'Blog: Feedburner Path': {
1686 | width: 26,
1687 | fill: '00FFFF',
1688 | },
1689 | 'Blog: Template Suffix': {
1690 | width: 26,
1691 | fill: '00FFFF',
1692 | },
1693 | 'Blog: Created At': {
1694 | width: 26,
1695 | fill: '00FFFF',
1696 | },
1697 | 'Blog: Updated At': {
1698 | width: 26,
1699 | fill: '00FFFF',
1700 | },
1701 | }
1702 | };
1703 |
1704 | export const summaryHeader = [
1705 | // {
1706 | // header: 'Job ID',
1707 | // key: 'id',
1708 | // width: 14,
1709 | // style: { font: { name: 'Arial', size: 11, bold: false } },
1710 | // style_1: {
1711 | // font: { name: 'Arial', size: 11, bold: true },
1712 | // fill: {
1713 | // type: 'pattern',
1714 | // pattern: 'solid',
1715 | // fgColor: { argb: 'a8b1ff' },
1716 | // },
1717 | // },
1718 | // },
1719 | {
1720 | header: 'Items',
1721 | key: 'items',
1722 | width: 20,
1723 | style: { font: { name: 'Arial', size: 11, bold: false } },
1724 | style_1: {
1725 | font: { name: 'Arial', size: 11, bold: true },
1726 | fill: {
1727 | type: 'pattern',
1728 | pattern: 'solid',
1729 | fgColor: { argb: 'a8b1ff' },
1730 | },
1731 | },
1732 | },
1733 | {
1734 | header: 'Started At (UTC)',
1735 | key: 'start_at',
1736 | width: 24,
1737 | style: {
1738 | font: { name: 'Arial', size: 11, bold: false },
1739 | numFmt: 'yyyy-mm-dd hh:mm:ss',
1740 | },
1741 | style_1: {
1742 | font: { name: 'Arial', size: 11, bold: true },
1743 | fill: {
1744 | type: 'pattern',
1745 | pattern: 'solid',
1746 | fgColor: { argb: 'f8c6cd' },
1747 | },
1748 | },
1749 | },
1750 | {
1751 | header: 'Finished At (UTC)',
1752 | key: 'finish_at',
1753 | width: 24,
1754 | style: {
1755 | font: { name: 'Arial', size: 11, bold: false },
1756 | numFmt: 'yyyy-mm-dd hh:mm:ss',
1757 | },
1758 | style_1: {
1759 | font: { name: 'Arial', size: 11, bold: true },
1760 | fill: {
1761 | type: 'pattern',
1762 | pattern: 'solid',
1763 | fgColor: { argb: 'f8c6cd' },
1764 | },
1765 | },
1766 | },
1767 | {
1768 | header: 'Duration',
1769 | key: 'duration',
1770 | width: 14,
1771 | style: { font: { name: 'Arial', size: 11, bold: false } },
1772 | style_1: {
1773 | font: { name: 'Arial', size: 11, bold: true },
1774 | fill: {
1775 | type: 'pattern',
1776 | pattern: 'solid',
1777 | fgColor: { argb: 'f8c6cd' },
1778 | },
1779 | },
1780 | },
1781 | {
1782 | header: 'Seconds per Item',
1783 | key: 'per_seconds',
1784 | width: 20,
1785 | style: { font: { name: 'Arial', size: 11, bold: false } },
1786 | style_1: {
1787 | font: { name: 'Arial', size: 11, bold: true },
1788 | fill: {
1789 | type: 'pattern',
1790 | pattern: 'solid',
1791 | fgColor: { argb: 'f8c6cd' },
1792 | },
1793 | },
1794 | },
1795 | {
1796 | header: 'Exported',
1797 | key: 'exported',
1798 | width: 12,
1799 | style: { font: { name: 'Arial', size: 11, bold: false } },
1800 | style_1: {
1801 | font: { name: 'Arial', size: 11, bold: true },
1802 | fill: {
1803 | type: 'pattern',
1804 | pattern: 'solid',
1805 | fgColor: { argb: 'a8b1ff' },
1806 | },
1807 | },
1808 | },
1809 | {
1810 | header: 'Additional Details',
1811 | key: 'details',
1812 | width: 50,
1813 | style: { font: { name: 'Arial', size: 11, bold: false } },
1814 | style_1: {
1815 | font: { name: 'Arial', size: 11, bold: true },
1816 | fill: {
1817 | type: 'pattern',
1818 | pattern: 'solid',
1819 | fgColor: { argb: 'a8b1ff' },
1820 | },
1821 | },
1822 | },
1823 | {
1824 | header: 'Filter',
1825 | key: 'filter',
1826 | width: 50,
1827 | style: { font: { name: 'Arial', size: 11, bold: false } },
1828 | style_1: {
1829 | font: { name: 'Arial', size: 11, bold: true },
1830 | fill: {
1831 | type: 'pattern',
1832 | pattern: 'solid',
1833 | fgColor: { argb: 'a8b1ff' },
1834 | },
1835 | },
1836 | },
1837 | {
1838 | header: 'Advanced Columns',
1839 | key: 'columns',
1840 | width: 20,
1841 | style: { font: { name: 'Arial', size: 11, bold: false } },
1842 | style_1: {
1843 | font: { name: 'Arial', size: 11, bold: true },
1844 | fill: {
1845 | type: 'pattern',
1846 | pattern: 'solid',
1847 | fgColor: { argb: 'a8b1ff' },
1848 | },
1849 | },
1850 | },
1851 | ];
1852 |
--------------------------------------------------------------------------------